1use std::cmp::Ordering;
4use std::fmt::Display;
5use std::str::FromStr;
6
7use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
8use data_encoding::BASE32HEX_NOPAD;
9use ethabi::ethereum_types::U256;
10use ibc::apps::transfer::types::Amount as IbcAmount;
11use namada_macros::BorshDeserializer;
12#[cfg(feature = "migrations")]
13use namada_migrations::*;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16
17use crate::arith::{self, checked, CheckedAdd, CheckedSub};
18use crate::dec::{Dec, POS_DECIMAL_PRECISION};
19use crate::storage;
20use crate::storage::{DbKeySeg, KeySeg};
21use crate::uint::{self, Uint, I256};
22
23#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
26#[derive(
27 Clone,
28 Copy,
29 Default,
30 BorshSerialize,
31 BorshDeserialize,
32 BorshDeserializer,
33 BorshSchema,
34 PartialEq,
35 Eq,
36 PartialOrd,
37 Ord,
38 Debug,
39 Hash,
40)]
41pub struct Amount {
42 raw: Uint,
43}
44
45pub const NATIVE_MAX_DECIMAL_PLACES: u8 = 6;
49
50pub const NATIVE_SCALE: u64 = 1_000_000;
54
55pub type Change = I256;
57
58impl Amount {
59 pub fn iter_words(self) -> impl Iterator<Item = u64> {
61 self.raw.0.into_iter()
62 }
63
64 pub const fn from_u64(x: u64) -> Self {
66 Self {
67 raw: Uint::from_u64(x),
68 }
69 }
70
71 pub const fn from_u128(value: u128) -> Self {
73 let mut ret = [0; 4];
74 #[allow(clippy::cast_possible_truncation)]
75 {
76 ret[0] = value as u64;
77 }
78 ret[1] = (value >> 64) as u64;
79 Self { raw: Uint(ret) }
80 }
81
82 pub fn change(&self) -> Change {
84 self.raw.try_into().unwrap()
85 }
86
87 pub fn spend(&mut self, amount: &Amount) -> Result<(), AmountError> {
89 self.raw = self
90 .raw
91 .checked_sub(amount.raw)
92 .ok_or(AmountError::Insufficient)?;
93 Ok(())
94 }
95
96 pub fn can_spend(&self, amount: &Amount) -> bool {
98 self.raw >= amount.raw
99 }
100
101 pub fn receive(&mut self, amount: &Amount) -> Result<(), AmountError> {
103 self.raw = self
104 .raw
105 .checked_add(amount.raw)
106 .ok_or(AmountError::Overflow)?;
107 Ok(())
108 }
109
110 pub fn native_whole(amount: u64) -> Self {
112 let raw = Uint::from(amount)
113 .checked_mul(Uint::from(NATIVE_SCALE))
114 .expect("u64 cannot overflow token amount");
115 Self { raw }
116 }
117
118 pub fn raw_amount(&self) -> Uint {
120 self.raw
121 }
122
123 pub fn max() -> Self {
125 Self {
126 raw: uint::MAX_VALUE,
127 }
128 }
129
130 pub fn max_signed() -> Self {
132 Self {
133 raw: uint::MAX_SIGNED_VALUE,
134 }
135 }
136
137 pub fn zero() -> Self {
139 Self::default()
140 }
141
142 pub fn is_zero(&self) -> bool {
144 self.raw == Uint::from(0)
145 }
146
147 pub fn is_positive(&self) -> bool {
149 !self.is_zero()
150 }
151
152 #[must_use]
155 pub fn checked_add(&self, amount: Amount) -> Option<Self> {
156 self.raw.checked_add(amount.raw).and_then(|result| {
157 if result <= uint::MAX_VALUE {
158 Some(Self { raw: result })
159 } else {
160 None
161 }
162 })
163 }
164
165 #[must_use]
168 pub fn checked_signed_add(&self, amount: Amount) -> Option<Self> {
169 self.raw.checked_add(amount.raw).and_then(|result| {
170 if result <= uint::MAX_SIGNED_VALUE {
171 Some(Self { raw: result })
172 } else {
173 None
174 }
175 })
176 }
177
178 #[must_use]
180 pub fn checked_sub(&self, amount: Amount) -> Option<Self> {
181 self.raw
182 .checked_sub(amount.raw)
183 .map(|result| Self { raw: result })
184 }
185
186 pub fn from_change(change: Change) -> Self {
188 Self { raw: change.abs() }
189 }
190
191 #[must_use]
193 pub fn checked_div(&self, amount: Amount) -> Option<Self> {
194 self.raw
195 .checked_div(amount.raw)
196 .map(|result| Self { raw: result })
197 }
198
199 #[must_use]
201 pub fn checked_mul<T>(&self, amount: T) -> Option<Self>
202 where
203 T: Into<Self>,
204 {
205 self.raw
206 .checked_mul(amount.into().raw)
207 .map(|result| Self { raw: result })
208 }
209
210 pub fn from_str(
212 string: impl AsRef<str>,
213 denom: impl Into<u8>,
214 ) -> Result<Amount, AmountParseError> {
215 DenominatedAmount::from_str(string.as_ref())?.scale(denom)
216 }
217
218 pub fn from_uint(
221 uint: impl Into<Uint>,
222 denom: impl Into<u8>,
223 ) -> Result<Self, AmountParseError> {
224 let denom = denom.into();
225 let uint = uint.into();
226 if denom == 0 {
227 return Ok(uint.into());
228 }
229 match Uint::from(10)
230 .checked_pow(Uint::from(denom))
231 .and_then(|scaling| scaling.checked_mul(uint))
232 {
233 Some(amount) => Ok(Self { raw: amount }),
234 None => Err(AmountParseError::ConvertToDecimal),
235 }
236 }
237
238 pub fn from_masp_denominated(val: u64, denom: MaspDigitPos) -> Self {
241 let mut raw = [0u64; 4];
242 raw[denom as usize] = val;
243 Self { raw: Uint(raw) }
244 }
245
246 pub fn from_masp_denominated_i128(
249 val: i128,
250 denom: MaspDigitPos,
251 ) -> Option<Self> {
252 #[allow(clippy::cast_sign_loss)]
253 #[allow(clippy::cast_possible_truncation)]
254 let lo = val as u64;
255 #[allow(clippy::cast_sign_loss)]
256 let hi = (val >> 64) as u64;
257 let lo_pos = denom as usize;
258 let hi_pos = lo_pos.checked_add(1)?;
259 let mut raw = [0u64; 4];
260 raw[lo_pos] = lo;
261 if hi != 0 && hi_pos >= 4 {
262 return None;
263 } else if hi != 0 {
264 raw[hi_pos] = hi;
265 }
266 Some(Self { raw: Uint(raw) })
267 }
268
269 pub fn to_string_native(&self) -> String {
271 DenominatedAmount {
272 amount: *self,
273 denom: NATIVE_MAX_DECIMAL_PLACES.into(),
274 }
275 .to_string_precise()
276 }
277
278 #[inline]
280 pub const fn native_denominated(self) -> DenominatedAmount {
281 DenominatedAmount::native(self)
282 }
283
284 pub fn from_string_precise(string: &str) -> Result<Self, AmountParseError> {
287 DenominatedAmount::from_str(string).map(|den| den.amount)
288 }
289
290 pub fn mul_ceil(&self, dec: Dec) -> Result<Self, arith::Error> {
293 let _ = checked!(Dec(I256::maximum()) - dec)?;
295
296 let tot = checked!(self.raw * dec.abs())?;
297 let denom = Uint::from(10u64.pow(u32::from(POS_DECIMAL_PRECISION)));
298 let floor_div = checked!(tot / denom)?;
299 let rem = checked!(tot % denom)?;
300 let raw = if !rem.is_zero() {
302 checked!(floor_div + Uint::one())?
303 } else {
304 floor_div
305 };
306 Ok(Self { raw })
307 }
308
309 pub fn mul_floor(&self, dec: Dec) -> Result<Self, arith::Error> {
312 let _ = checked!(Dec(I256::maximum()) - dec)?;
314
315 let raw = checked!(
316 (Uint::from(*self) * dec.0.abs())
317 / Uint::from(10u64.pow(u32::from(POS_DECIMAL_PRECISION)))
318 )?;
319 Ok(Self { raw })
320 }
321
322 pub fn sum<I: Iterator<Item = Self>>(mut iter: I) -> Option<Self> {
324 iter.try_fold(Amount::zero(), |acc, amt| acc.checked_add(amt))
325 }
326
327 pub fn checked_div_u64(self, rhs: u64) -> Option<Self> {
329 if rhs == 0 {
330 return None;
331 }
332 let raw = self.raw.checked_div(Uint::from(rhs))?;
333 Some(Self { raw })
334 }
335
336 pub fn u128_eucl_div_rem(
339 mut self,
340 (a, b): (u128, u128),
341 ) -> Option<(Amount, Amount)> {
342 let a = Uint::from(a);
343 let b = Uint::from(b);
344 let raw = (self.raw.checked_div(b))?.checked_mul(a)?;
345 let amt = Amount { raw };
346 self.raw = self.raw.checked_rem(b)?;
347 Some((amt, self))
348 }
349}
350
351impl CheckedAdd for Amount {
352 type Output = Amount;
353
354 fn checked_add(self, rhs: Self) -> Option<Self::Output> {
355 Amount::checked_add(&self, rhs)
356 }
357}
358
359impl CheckedAdd for &Amount {
360 type Output = Amount;
361
362 fn checked_add(self, rhs: Self) -> Option<Self::Output> {
363 self.checked_add(*rhs)
364 }
365}
366
367impl CheckedSub for Amount {
368 type Output = Amount;
369
370 fn checked_sub(self, amount: Self) -> Option<Self::Output> {
371 self.raw
372 .checked_sub(amount.raw)
373 .map(|result| Self { raw: result })
374 }
375}
376
377impl CheckedSub for &Amount {
378 type Output = Amount;
379
380 fn checked_sub(self, amount: Self) -> Option<Self::Output> {
381 self.raw
382 .checked_sub(amount.raw)
383 .map(|result| Amount { raw: result })
384 }
385}
386
387impl Display for Amount {
388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 write!(f, "{}", self.raw)
390 }
391}
392
393#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
397#[derive(
398 Debug,
399 Copy,
400 Clone,
401 Hash,
402 PartialEq,
403 Eq,
404 PartialOrd,
405 Ord,
406 BorshSerialize,
407 BorshDeserialize,
408 BorshDeserializer,
409 BorshSchema,
410 Serialize,
411 Deserialize,
412)]
413#[serde(transparent)]
414pub struct Denomination(pub u8);
415
416impl From<u8> for Denomination {
417 fn from(denom: u8) -> Self {
418 Self(denom)
419 }
420}
421
422impl From<Denomination> for u8 {
423 fn from(denom: Denomination) -> Self {
424 denom.0
425 }
426}
427
428#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
430#[derive(
431 Debug,
432 Copy,
433 Clone,
434 Hash,
435 PartialEq,
436 Eq,
437 BorshSerialize,
438 BorshDeserialize,
439 BorshDeserializer,
440 BorshSchema,
441)]
442pub struct DenominatedAmount {
443 amount: Amount,
445 denom: Denomination,
447}
448
449impl DenominatedAmount {
450 pub const fn new(amount: Amount, denom: Denomination) -> Self {
452 Self { amount, denom }
453 }
454
455 pub const fn native(amount: Amount) -> Self {
457 Self {
458 amount,
459 denom: Denomination(NATIVE_MAX_DECIMAL_PLACES),
460 }
461 }
462
463 #[inline]
465 pub fn is_zero(&self) -> bool {
466 self.amount.is_zero()
467 }
468
469 pub fn to_string_precise(&self) -> String {
474 let decimals = self.denom.0 as usize;
475 let mut string = self.amount.raw.to_string();
476 if decimals == 0 {
478 return string;
479 }
480 if string.len() > decimals {
481 #[allow(clippy::arithmetic_side_effects)]
483 let idx = string.len() - decimals;
484 string.insert(idx, '.');
485 } else {
486 for _ in string.len()..decimals {
487 string.insert(0, '0');
488 }
489 string.insert(0, '.');
490 string.insert(0, '0');
491 }
492 string
493 }
494
495 pub fn canonical(self) -> Self {
499 let mut value = self.amount.raw;
500 let ten = Uint::from(10);
501 let mut denom = self.denom.0;
502 for _ in 0..self.denom.0 {
503 let (div, rem) = value.div_mod(ten);
504 if rem == Uint::zero() {
505 value = div;
506 denom = denom.checked_sub(1).unwrap_or_default();
507 }
508 }
509 Self {
510 amount: Amount { raw: value },
511 denom: denom.into(),
512 }
513 }
514
515 pub fn increase_precision(
518 self,
519 denom: Denomination,
520 ) -> Result<Self, AmountParseError> {
521 if denom.0 < self.denom.0 {
522 return Err(AmountParseError::PrecisionDecrease);
523 }
524 #[allow(clippy::arithmetic_side_effects)]
526 let denom_diff = denom.0 - self.denom.0;
527 Uint::from(10)
528 .checked_pow(Uint::from(denom_diff))
529 .and_then(|scaling| self.amount.raw.checked_mul(scaling))
530 .map(|amount| Self {
531 amount: Amount { raw: amount },
532 denom,
533 })
534 .ok_or(AmountParseError::PrecisionOverflow)
535 }
536
537 pub fn redenominate(self, new_denom: u8) -> Self {
540 Self {
541 amount: self.amount,
542 denom: new_denom.into(),
543 }
544 }
545
546 pub fn scale(
549 self,
550 denom: impl Into<u8>,
551 ) -> Result<Amount, AmountParseError> {
552 self.increase_precision(Denomination(denom.into()))
553 .map(|x| x.amount)
554 }
555
556 pub fn checked_mul(&self, rhs: DenominatedAmount) -> Option<Self> {
558 let amount = self.amount.checked_mul(rhs.amount)?;
559 let denom = self.denom.0.checked_add(rhs.denom.0)?.into();
560 Some(Self { amount, denom })
561 }
562
563 pub fn checked_sub(&self, mut rhs: DenominatedAmount) -> Option<Self> {
565 let mut lhs = *self;
566 if lhs.denom < rhs.denom {
567 lhs = lhs.increase_precision(rhs.denom).ok()?;
568 } else {
569 rhs = rhs.increase_precision(lhs.denom).ok()?;
570 }
571 let amount = lhs.amount.checked_sub(rhs.amount)?;
572 Some(Self {
573 amount,
574 denom: lhs.denom,
575 })
576 }
577
578 pub fn checked_add(&self, mut rhs: DenominatedAmount) -> Option<Self> {
580 let mut lhs = *self;
581 if lhs.denom < rhs.denom {
582 lhs = lhs.increase_precision(rhs.denom).ok()?;
583 } else {
584 rhs = rhs.increase_precision(lhs.denom).ok()?;
585 }
586 let amount = lhs.amount.checked_add(rhs.amount)?;
587 Some(Self {
588 amount,
589 denom: lhs.denom,
590 })
591 }
592
593 pub const fn amount(&self) -> Amount {
595 self.amount
596 }
597
598 pub const fn denom(&self) -> Denomination {
600 self.denom
601 }
602}
603
604impl Display for DenominatedAmount {
605 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
606 let string = self.to_string_precise();
607 let string = if self.denom.0 > 0 {
608 string.trim_end_matches(['0'])
609 } else {
610 &string
611 };
612 let string = string.trim_end_matches(['.']);
613 f.write_str(string)
614 }
615}
616
617impl FromStr for DenominatedAmount {
618 type Err = AmountParseError;
619
620 fn from_str(s: &str) -> Result<Self, Self::Err> {
621 let precision = s.find('.').map(|pos| {
622 s.len()
623 .checked_sub(pos.checked_add(1).unwrap_or(pos))
624 .unwrap_or_default()
625 });
626 let digits = s
627 .chars()
628 .filter_map(|c| {
629 if c.is_numeric() {
630 c.to_digit(10).map(Uint::from)
631 } else {
632 None
633 }
634 })
635 .rev()
636 .collect::<Vec<_>>();
637 if digits.len() != s.len() && precision.is_none()
638 || digits.len() != s.len().checked_sub(1).unwrap_or_default()
639 && precision.is_some()
640 {
641 return Err(AmountParseError::NotNumeric);
642 }
643 if digits.len() > 77 {
644 return Err(AmountParseError::ScaleTooLarge(digits.len(), 77));
645 }
646 let mut value = Uint::default();
647 let ten = Uint::from(10);
648 for (pow, digit) in digits.into_iter().enumerate() {
649 value = ten
650 .checked_pow(Uint::from(pow))
651 .and_then(|scaling| scaling.checked_mul(digit))
652 .and_then(|scaled| value.checked_add(scaled))
653 .ok_or(AmountParseError::InvalidRange)?;
654 }
655 let denom = Denomination(
656 u8::try_from(precision.unwrap_or_default())
657 .map_err(|_e| AmountParseError::PrecisionOverflow)?,
658 );
659 Ok(Self {
660 amount: Amount { raw: value },
661 denom,
662 })
663 }
664}
665
666impl PartialOrd for DenominatedAmount {
667 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
668 Some(self.cmp(other))
669 }
670}
671
672impl Ord for DenominatedAmount {
673 fn cmp(&self, other: &Self) -> Ordering {
674 if self.denom < other.denom {
675 #[allow(clippy::arithmetic_side_effects)]
677 let diff = other.denom.0 - self.denom.0;
678 let (div, rem) =
679 other.amount.raw.div_mod(Uint::exp10(diff as usize));
680 let div_ceil = if rem.is_zero() {
681 div
682 } else {
683 div.checked_add(Uint::one()).unwrap_or(Uint::MAX)
684 };
685 let ord = self.amount.raw.cmp(&div_ceil);
686 if let Ordering::Equal = ord {
687 if rem.is_zero() {
688 Ordering::Equal
689 } else {
690 Ordering::Greater
691 }
692 } else {
693 ord
694 }
695 } else {
696 #[allow(clippy::arithmetic_side_effects)]
698 let diff = self.denom.0 - other.denom.0;
699 let (div, rem) =
700 self.amount.raw.div_mod(Uint::exp10(diff as usize));
701 let div_ceil = if rem.is_zero() {
702 div
703 } else {
704 div.checked_add(Uint::one()).unwrap_or(Uint::MAX)
705 };
706 let ord = div_ceil.cmp(&other.amount.raw);
707 if let Ordering::Equal = ord {
708 if rem.is_zero() {
709 Ordering::Equal
710 } else {
711 Ordering::Less
712 }
713 } else {
714 ord
715 }
716 }
717 }
718}
719
720impl serde::Serialize for Amount {
721 fn serialize<S>(
722 &self,
723 serializer: S,
724 ) -> std::result::Result<S::Ok, S::Error>
725 where
726 S: serde::Serializer,
727 {
728 let amount_string = self.raw.to_string();
729 serde::Serialize::serialize(&amount_string, serializer)
730 }
731}
732
733impl<'de> serde::Deserialize<'de> for Amount {
734 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
735 where
736 D: serde::Deserializer<'de>,
737 {
738 let amount_string: String =
739 serde::Deserialize::deserialize(deserializer)?;
740 let amt = DenominatedAmount::from_str(&amount_string).unwrap();
741 Ok(amt.amount)
742 }
743}
744
745impl serde::Serialize for DenominatedAmount {
746 fn serialize<S>(
747 &self,
748 serializer: S,
749 ) -> std::result::Result<S::Ok, S::Error>
750 where
751 S: serde::Serializer,
752 {
753 let amount_string = self.to_string_precise();
754 serde::Serialize::serialize(&amount_string, serializer)
755 }
756}
757
758impl<'de> serde::Deserialize<'de> for DenominatedAmount {
759 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
760 where
761 D: serde::Deserializer<'de>,
762 {
763 use serde::de::Error;
764 let amount_string: String =
765 serde::Deserialize::deserialize(deserializer)?;
766 Self::from_str(&amount_string).map_err(D::Error::custom)
767 }
768}
769
770impl From<Amount> for DenominatedAmount {
771 fn from(amount: Amount) -> Self {
772 DenominatedAmount::new(amount, 0.into())
773 }
774}
775
776impl From<u64> for Amount {
778 fn from(val: u64) -> Amount {
779 Amount {
780 raw: Uint::from(val),
781 }
782 }
783}
784
785impl From<Amount> for U256 {
786 fn from(amt: Amount) -> Self {
787 Self(amt.raw.0)
788 }
789}
790
791impl TryFrom<Dec> for Amount {
792 type Error = arith::Error;
793
794 fn try_from(dec: Dec) -> Result<Amount, Self::Error> {
795 let _ = checked!(Dec(I256::maximum()) - dec)?;
797
798 #[allow(clippy::arithmetic_side_effects)]
800 let raw = dec.0.abs() / Uint::exp10(POS_DECIMAL_PRECISION as usize);
801 Ok(Amount { raw })
802 }
803}
804
805impl TryFrom<Amount> for u128 {
806 type Error = std::io::Error;
807
808 fn try_from(value: Amount) -> Result<Self, Self::Error> {
809 let Uint(arr) = value.raw;
810 for word in arr.iter().skip(2) {
811 if *word != 0 {
812 return Err(std::io::Error::new(
813 std::io::ErrorKind::InvalidInput,
814 "Integer overflow when casting to u128",
815 ));
816 }
817 }
818 Ok(value.raw.low_u128())
819 }
820}
821
822impl KeySeg for Amount {
823 fn parse(string: String) -> super::storage::Result<Self>
824 where
825 Self: Sized,
826 {
827 let bytes = BASE32HEX_NOPAD.decode(string.as_ref()).map_err(|err| {
828 storage::Error::ParseKeySeg(format!(
829 "Failed parsing {} with {}",
830 string, err
831 ))
832 })?;
833 Ok(Amount {
834 raw: Uint::from_big_endian(&bytes),
835 })
836 }
837
838 fn raw(&self) -> String {
839 let buf = self.raw.to_big_endian();
840 BASE32HEX_NOPAD.encode(&buf)
841 }
842
843 fn to_db_key(&self) -> DbKeySeg {
844 DbKeySeg::StringSeg(self.raw())
845 }
846}
847
848#[allow(missing_docs)]
849#[derive(Error, Debug)]
850pub enum AmountParseError {
851 #[error(
852 "Error decoding token amount, too many decimal places: {0}. Maximum \
853 {1}"
854 )]
855 ScaleTooLarge(usize, u8),
856 #[error(
857 "Error decoding token amount, the value is not within invalid range."
858 )]
859 InvalidRange,
860 #[error("Error converting amount to decimal, number too large.")]
861 ConvertToDecimal,
862 #[error(
863 "Could not convert from string, expected an unsigned 256-bit integer."
864 )]
865 FromString,
866 #[error("Could not parse string as a correctly formatted number.")]
867 NotNumeric,
868 #[error("This amount cannot handle the requested precision in 256 bits.")]
869 PrecisionOverflow,
870 #[error("More precision given in the amount than requested.")]
871 PrecisionDecrease,
872}
873
874impl From<Amount> for Change {
875 fn from(amount: Amount) -> Self {
876 amount.raw.try_into().unwrap()
877 }
878}
879
880impl From<Change> for Amount {
881 fn from(change: Change) -> Self {
882 Amount { raw: change.abs() }
883 }
884}
885
886impl From<Amount> for Uint {
887 fn from(amount: Amount) -> Self {
888 amount.raw
889 }
890}
891
892impl From<Uint> for Amount {
893 fn from(raw: Uint) -> Self {
894 Self { raw }
895 }
896}
897
898#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
901#[derive(
902 Copy,
903 Clone,
904 Debug,
905 PartialEq,
906 Eq,
907 PartialOrd,
908 Ord,
909 Hash,
910 BorshSerialize,
911 BorshDeserialize,
912 BorshDeserializer,
913 BorshSchema,
914 Serialize,
915 Deserialize,
916)]
917#[repr(u8)]
918#[allow(missing_docs)]
919#[borsh(use_discriminant = true)]
920pub enum MaspDigitPos {
921 Zero = 0,
922 One,
923 Two,
924 Three,
925}
926
927impl TryFrom<u8> for MaspDigitPos {
928 type Error = &'static str;
929
930 fn try_from(denom: u8) -> Result<Self, Self::Error> {
931 match denom {
932 0 => Ok(Self::Zero),
933 1 => Ok(Self::One),
934 2 => Ok(Self::Two),
935 3 => Ok(Self::Three),
936 _ => Err("Possible MASP denominations must be between 0 and 3"),
937 }
938 }
939}
940
941impl MaspDigitPos {
942 pub fn iter() -> impl Iterator<Item = MaspDigitPos> {
944 [
945 MaspDigitPos::Zero,
946 MaspDigitPos::One,
947 MaspDigitPos::Two,
948 MaspDigitPos::Three,
949 ]
950 .into_iter()
951 }
952
953 pub fn denominate<'a>(&self, amount: impl Into<&'a Amount>) -> u64 {
955 let amount = amount.into();
956 amount.raw.0[*self as usize]
957 }
958}
959
960impl From<Amount> for IbcAmount {
961 fn from(amount: Amount) -> Self {
962 primitive_types::U256(amount.raw.0).into()
963 }
964}
965
966impl TryFrom<IbcAmount> for Amount {
967 type Error = AmountParseError;
968
969 fn try_from(amount: IbcAmount) -> Result<Self, Self::Error> {
970 let uint = Uint(primitive_types::U256::from(amount).0);
971 Self::from_uint(uint, 0)
972 }
973}
974
975impl From<DenominatedAmount> for IbcAmount {
976 fn from(amount: DenominatedAmount) -> Self {
977 amount.amount.into()
978 }
979}
980
981#[allow(missing_docs)]
982#[derive(Error, Debug)]
983pub enum AmountError {
984 #[error("Insufficient amount")]
985 Insufficient,
986 #[error("Amount overlofow")]
987 Overflow,
988}
989
990#[cfg(any(test, feature = "testing"))]
991#[allow(clippy::arithmetic_side_effects)]
993pub mod testing {
994 use proptest::prelude::*;
995
996 use super::*;
997
998 impl std::ops::Add for Amount {
999 type Output = Self;
1000
1001 fn add(self, rhs: Self) -> Self::Output {
1002 self.checked_add(rhs).unwrap()
1003 }
1004 }
1005
1006 impl std::ops::AddAssign for Amount {
1007 fn add_assign(&mut self, rhs: Self) {
1008 *self = self.checked_add(rhs).unwrap();
1009 }
1010 }
1011
1012 impl std::ops::Sub for Amount {
1013 type Output = Self;
1014
1015 fn sub(self, rhs: Self) -> Self::Output {
1016 self.checked_sub(rhs).unwrap()
1017 }
1018 }
1019
1020 impl std::ops::SubAssign for Amount {
1021 fn sub_assign(&mut self, rhs: Self) {
1022 *self = *self - rhs;
1023 }
1024 }
1025
1026 impl<T> std::ops::Mul<T> for Amount
1027 where
1028 T: Into<Self>,
1029 {
1030 type Output = Amount;
1031
1032 fn mul(self, rhs: T) -> Self::Output {
1033 self.checked_mul(rhs.into()).unwrap()
1034 }
1035 }
1036
1037 impl std::ops::Mul<Amount> for u64 {
1038 type Output = Amount;
1039
1040 fn mul(self, rhs: Amount) -> Self::Output {
1041 rhs * self
1042 }
1043 }
1044
1045 impl std::ops::Div<u64> for Amount {
1046 type Output = Self;
1047
1048 fn div(self, rhs: u64) -> Self::Output {
1049 Self {
1050 raw: self.raw / Uint::from(rhs),
1051 }
1052 }
1053 }
1054
1055 impl std::iter::Sum for Amount {
1056 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1057 iter.fold(Amount::zero(), |a, b| a + b)
1058 }
1059 }
1060
1061 prop_compose! {
1062 pub fn arb_denomination()(denom in 0u8..) -> Denomination {
1064 Denomination(denom)
1065 }
1066 }
1067
1068 prop_compose! {
1069 pub fn arb_denominated_amount()(
1071 amount in arb_amount(),
1072 denom in arb_denomination(),
1073 ) -> DenominatedAmount {
1074 DenominatedAmount::new(amount, denom)
1075 }
1076 }
1077
1078 pub fn arb_amount() -> impl Strategy<Value = Amount> {
1080 any::<u64>().prop_map(|val| Amount::from_uint(val, 0).unwrap())
1081 }
1082
1083 pub fn arb_amount_ceiled(max: u64) -> impl Strategy<Value = Amount> {
1085 (0..=max).prop_map(|val| Amount::from_uint(val, 0).unwrap())
1086 }
1087
1088 pub fn arb_amount_non_zero_ceiled(
1091 max: u64,
1092 ) -> impl Strategy<Value = Amount> {
1093 (1..=max).prop_map(|val| Amount::from_uint(val, 0).unwrap())
1094 }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use assert_matches::assert_matches;
1100
1101 use super::*;
1102
1103 #[test]
1104 fn test_token_display() {
1105 let max = Amount::from_uint(u64::MAX, 0).expect("Test failed");
1106 assert_eq!("18446744073709.551615", max.to_string_native());
1107 let max = DenominatedAmount {
1108 amount: max,
1109 denom: NATIVE_MAX_DECIMAL_PLACES.into(),
1110 };
1111 assert_eq!("18446744073709.551615", max.to_string());
1112
1113 let whole =
1114 Amount::from_uint(u64::MAX / NATIVE_SCALE * NATIVE_SCALE, 0)
1115 .expect("Test failed");
1116 assert_eq!("18446744073709.000000", whole.to_string_native());
1117 let whole = DenominatedAmount {
1118 amount: whole,
1119 denom: NATIVE_MAX_DECIMAL_PLACES.into(),
1120 };
1121 assert_eq!("18446744073709", whole.to_string());
1122
1123 let trailing_zeroes =
1124 Amount::from_uint(123000, 0).expect("Test failed");
1125 assert_eq!("0.123000", trailing_zeroes.to_string_native());
1126 let trailing_zeroes = DenominatedAmount {
1127 amount: trailing_zeroes,
1128 denom: NATIVE_MAX_DECIMAL_PLACES.into(),
1129 };
1130 assert_eq!("0.123", trailing_zeroes.to_string());
1131
1132 let zero = Amount::default();
1133 assert_eq!("0.000000", zero.to_string_native());
1134 let zero = DenominatedAmount {
1135 amount: zero,
1136 denom: NATIVE_MAX_DECIMAL_PLACES.into(),
1137 };
1138 assert_eq!("0", zero.to_string());
1139
1140 let amount = DenominatedAmount {
1141 amount: Amount::from_uint(1120, 0).expect("Test failed"),
1142 denom: 3u8.into(),
1143 };
1144 assert_eq!("1.12", amount.to_string());
1145 assert_eq!("1.120", amount.to_string_precise());
1146
1147 let amount = DenominatedAmount {
1148 amount: Amount::from_uint(1120, 0).expect("Test failed"),
1149 denom: 5u8.into(),
1150 };
1151 assert_eq!("0.0112", amount.to_string());
1152 assert_eq!("0.01120", amount.to_string_precise());
1153
1154 let amount = DenominatedAmount {
1155 amount: Amount::from_uint(200, 0).expect("Test failed"),
1156 denom: 0.into(),
1157 };
1158 assert_eq!("200", amount.to_string());
1159 assert_eq!("200", amount.to_string_precise());
1160 }
1161
1162 #[test]
1163 fn test_amount_checked_sub() {
1164 let max = Amount::native_whole(u64::MAX);
1165 let one = Amount::native_whole(1);
1166 let zero = Amount::native_whole(0);
1167
1168 assert_eq!(zero.checked_sub(zero), Some(zero));
1169 assert_eq!(zero.checked_sub(one), None);
1170 assert_eq!(zero.checked_sub(max), None);
1171
1172 assert_eq!(max.checked_sub(zero), Some(max));
1173 assert_eq!(max.checked_sub(one), Some(max - one));
1174 assert_eq!(max.checked_sub(max), Some(zero));
1175 }
1176
1177 #[test]
1178 fn test_serialization_round_trip() {
1179 let amount: Amount = serde_json::from_str(r#""1000000000""#).unwrap();
1180 assert_eq!(
1181 amount,
1182 Amount {
1183 raw: Uint::from(1000000000)
1184 }
1185 );
1186 let serialized = serde_json::to_string(&amount).unwrap();
1187 assert_eq!(serialized, r#""1000000000""#);
1188 }
1189
1190 #[test]
1191 fn test_amount_checked_add() {
1192 let max = Amount::max();
1193 let max_signed = Amount::max_signed();
1194 let one = Amount::native_whole(1);
1195 let zero = Amount::native_whole(0);
1196
1197 assert_eq!(zero.checked_add(zero), Some(zero));
1198 assert_eq!(zero.checked_signed_add(zero), Some(zero));
1199 assert_eq!(zero.checked_add(one), Some(one));
1200 assert_eq!(zero.checked_add(max - one), Some(max - one));
1201 assert_eq!(
1202 zero.checked_signed_add(max_signed - one),
1203 Some(max_signed - one)
1204 );
1205 assert_eq!(zero.checked_add(max), Some(max));
1206 assert_eq!(zero.checked_signed_add(max_signed), Some(max_signed));
1207
1208 assert_eq!(max.checked_add(zero), Some(max));
1209 assert_eq!(max.checked_signed_add(zero), None);
1210 assert_eq!(max.checked_add(one), None);
1211 assert_eq!(max.checked_add(max), None);
1212
1213 assert_eq!(max_signed.checked_add(zero), Some(max_signed));
1214 assert_eq!(max_signed.checked_add(one), Some(max_signed + one));
1215 assert_eq!(max_signed.checked_signed_add(max_signed), None);
1216 }
1217
1218 #[test]
1219 fn test_amount_from_string() {
1220 assert!(Amount::from_str("1.12", 1).is_err());
1221 assert!(Amount::from_str("0.0", 0).is_err());
1222 assert!(Amount::from_str("1.12", 80).is_err());
1223 assert!(Amount::from_str("1.12.1", 3).is_err());
1224 assert!(Amount::from_str("1.1a", 3).is_err());
1225 assert_eq!(
1226 Amount::zero(),
1227 Amount::from_str("0.0", 1).expect("Test failed")
1228 );
1229 assert_eq!(
1230 Amount::zero(),
1231 Amount::from_str(".0", 1).expect("Test failed")
1232 );
1233
1234 let amount = Amount::from_str("1.12", 3).expect("Test failed");
1235 assert_eq!(amount, Amount::from_uint(1120, 0).expect("Test failed"));
1236 let amount = Amount::from_str(".34", 3).expect("Test failed");
1237 assert_eq!(amount, Amount::from_uint(340, 0).expect("Test failed"));
1238 let amount = Amount::from_str("0.34", 3).expect("Test failed");
1239 assert_eq!(amount, Amount::from_uint(340, 0).expect("Test failed"));
1240 let amount = Amount::from_str("34", 1).expect("Test failed");
1241 assert_eq!(amount, Amount::from_uint(340, 0).expect("Test failed"));
1242 }
1243
1244 #[test]
1245 fn test_from_masp_denominated() {
1246 let uint = Uint([15u64, 16, 17, 18]);
1247 let original = Amount::from_uint(uint, 0).expect("Test failed");
1248 for denom in MaspDigitPos::iter() {
1249 let word = denom.denominate(&original);
1250 assert_eq!(word, denom as u64 + 15u64);
1251 let amount = Amount::from_masp_denominated(word, denom);
1252 let raw = Uint::from(amount).0;
1253 let mut expected = [0u64; 4];
1254 expected[denom as usize] = word;
1255 assert_eq!(raw, expected);
1256 }
1257 }
1258
1259 #[test]
1260 fn test_key_seg() {
1261 let original = Amount::from_uint(1234560000, 0).expect("Test failed");
1262 let key = original.raw();
1263 let amount = Amount::parse(key).expect("Test failed");
1264 assert_eq!(amount, original);
1265 }
1266
1267 #[test]
1268 fn test_amount_is_zero() {
1269 let zero = Amount::zero();
1270 assert!(zero.is_zero());
1271
1272 let non_zero = Amount::from_uint(1, 0).expect("Test failed");
1273 assert!(!non_zero.is_zero());
1274 }
1275
1276 #[test]
1277 fn test_token_amount_mul_ceil() {
1278 let one = Amount::from(1);
1279 let two = Amount::from(2);
1280 let three = Amount::from(3);
1281 let dec = Dec::from_str("0.34").unwrap();
1282 assert_eq!(one.mul_ceil(dec).unwrap(), one);
1283 assert_eq!(two.mul_ceil(dec).unwrap(), one);
1284 assert_eq!(three.mul_ceil(dec).unwrap(), two);
1285
1286 assert_matches!(one.mul_ceil(-dec), Err(_));
1287 assert_matches!(one.mul_ceil(-Dec::new(1, 12).unwrap()), Err(_));
1288 assert_matches!(
1289 Amount::native_whole(1).mul_ceil(-Dec::new(1, 12).unwrap()),
1290 Err(_)
1291 );
1292 }
1293
1294 #[test]
1295 fn test_token_amount_mul_floor() {
1296 let zero = Amount::zero();
1297 let one = Amount::from(1);
1298 let two = Amount::from(2);
1299 let three = Amount::from(3);
1300 let dec = Dec::from_str("0.34").unwrap();
1301 assert_eq!(one.mul_floor(dec).unwrap(), zero);
1302 assert_eq!(two.mul_floor(dec).unwrap(), zero);
1303 assert_eq!(three.mul_floor(dec).unwrap(), one);
1304
1305 assert_matches!(one.mul_floor(-dec), Err(_));
1306 assert_matches!(one.mul_floor(-Dec::new(1, 12).unwrap()), Err(_));
1307 assert_matches!(
1308 Amount::native_whole(1).mul_floor(-Dec::new(1, 12).unwrap()),
1309 Err(_)
1310 );
1311 }
1312
1313 #[test]
1314 fn test_denominateed_arithmetic() {
1315 let a = DenominatedAmount::new(10.into(), 3.into());
1316 let b = DenominatedAmount::new(10.into(), 2.into());
1317 let c = DenominatedAmount::new(110.into(), 3.into());
1318 let d = DenominatedAmount::new(90.into(), 3.into());
1319 let e = DenominatedAmount::new(100.into(), 5.into());
1320 let f = DenominatedAmount::new(100.into(), 3.into());
1321 let g = DenominatedAmount::new(0.into(), 3.into());
1322 assert_eq!(a.checked_add(b).unwrap(), c);
1323 assert_eq!(b.checked_sub(a).unwrap(), d);
1324 assert_eq!(a.checked_mul(b).unwrap(), e);
1325 assert!(a.checked_sub(b).is_none());
1326 assert_eq!(c.checked_sub(a).unwrap(), f);
1327 assert_eq!(c.checked_sub(c).unwrap(), g);
1328 }
1329
1330 #[test]
1331 fn test_denominated_amt_ord() {
1332 let denom_1 = DenominatedAmount {
1333 amount: Amount::from_uint(15, 0).expect("Test failed"),
1334 denom: 1.into(),
1335 };
1336 let denom_2 = DenominatedAmount {
1337 amount: Amount::from_uint(1500, 0).expect("Test failed"),
1338 denom: 3.into(),
1339 };
1340 assert_eq!(
1343 denom_1.partial_cmp(&denom_2).expect("Test failed"),
1344 Ordering::Equal
1345 );
1346 assert_eq!(
1347 denom_2.partial_cmp(&denom_1).expect("Test failed"),
1348 Ordering::Equal
1349 );
1350 assert_ne!(denom_1, denom_2);
1351
1352 let denom_1 = DenominatedAmount {
1353 amount: Amount::from_uint(15, 0).expect("Test failed"),
1354 denom: 1.into(),
1355 };
1356 let denom_2 = DenominatedAmount {
1357 amount: Amount::from_uint(1501, 0).expect("Test failed"),
1358 denom: 3.into(),
1359 };
1360 assert_eq!(
1361 denom_1.partial_cmp(&denom_2).expect("Test failed"),
1362 Ordering::Less
1363 );
1364 assert_eq!(
1365 denom_2.partial_cmp(&denom_1).expect("Test failed"),
1366 Ordering::Greater
1367 );
1368 let denom_1 = DenominatedAmount {
1369 amount: Amount::from_uint(15, 0).expect("Test failed"),
1370 denom: 1.into(),
1371 };
1372 let denom_2 = DenominatedAmount {
1373 amount: Amount::from_uint(1499, 0).expect("Test failed"),
1374 denom: 3.into(),
1375 };
1376 assert_eq!(
1377 denom_1.partial_cmp(&denom_2).expect("Test failed"),
1378 Ordering::Greater
1379 );
1380 assert_eq!(
1381 denom_2.partial_cmp(&denom_1).expect("Test failed"),
1382 Ordering::Less
1383 );
1384 }
1385
1386 #[test]
1387 fn test_token_amount_from_u128() {
1388 for val in [
1389 u128::MIN,
1390 u128::MIN + 1,
1391 u128::from(u64::MAX) - 1,
1392 u128::from(u64::MAX),
1393 u128::from(u64::MAX) + 1,
1394 u128::MAX - 1,
1395 u128::MAX,
1396 ] {
1397 let raw = Uint::from(val);
1398 let amount = Amount::from_u128(val);
1399 assert_eq!(raw, amount.raw);
1400 assert_eq!(amount.raw.as_u128(), val);
1401 }
1402 }
1403}