|
|
@@ -0,0 +1,557 @@
|
|
|
+//! [`Amount`]: a [`Cent`] that knows which asset it is denominated in
|
|
|
+//! (ADR-0028).
|
|
|
+
|
|
|
+use std::convert::Infallible;
|
|
|
+use std::error::Error;
|
|
|
+use std::fmt;
|
|
|
+use std::sync::Arc;
|
|
|
+
|
|
|
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
|
+
|
|
|
+use crate::asset::Asset;
|
|
|
+use crate::ids::AssetId;
|
|
|
+use kuatia_money::{Cent, OverflowError, ParseDecimalError};
|
|
|
+
|
|
|
+/// A quantity of one asset.
|
|
|
+///
|
|
|
+/// A bare [`Cent`] adds to and compares with any other, so nothing stopped a
|
|
|
+/// caller holding two balances from summing dollars into euros. Carrying the
|
|
|
+/// asset makes that a rejected operation instead of a wrong number, and gives
|
|
|
+/// a decimal string somewhere to learn its precision from.
|
|
|
+///
|
|
|
+/// Built only through conversion, so an amount cannot exist without a
|
|
|
+/// registered asset behind it. The value comes first and the asset second, the
|
|
|
+/// way the money reads aloud. Integers are minor units and a string is the
|
|
|
+/// decimal form at the asset's own scale: `(500, usd)` is five dollars, and so
|
|
|
+/// is `("5.00", usd)`.
|
|
|
+#[derive(Clone)]
|
|
|
+pub struct Amount {
|
|
|
+ asset: Arc<Asset>,
|
|
|
+ value: Cent,
|
|
|
+}
|
|
|
+
|
|
|
+impl Amount {
|
|
|
+ /// Nothing, of one asset. The identity for [`checked_add`](Self::checked_add).
|
|
|
+ pub fn zero(asset: Arc<Asset>) -> Self {
|
|
|
+ Self {
|
|
|
+ asset,
|
|
|
+ value: Cent::ZERO,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The asset this is denominated in.
|
|
|
+ pub fn asset(&self) -> &Arc<Asset> {
|
|
|
+ &self.asset
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The asset's id, which is what storage and the content address carry.
|
|
|
+ pub fn asset_id(&self) -> AssetId {
|
|
|
+ self.asset.id
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The value in minor units, as a plain integer. The widest money backing
|
|
|
+ /// is 128 bits, so this is lossless whichever one is compiled in.
|
|
|
+ pub fn minor_units(&self) -> i128 {
|
|
|
+ self.value.minor_units()
|
|
|
+ }
|
|
|
+
|
|
|
+ pub(crate) fn cent(&self) -> Cent {
|
|
|
+ self.value
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Whether this is a positive, negative or zero quantity.
|
|
|
+ pub fn is_positive(&self) -> bool {
|
|
|
+ self.value.is_positive()
|
|
|
+ }
|
|
|
+
|
|
|
+ /// True when the quantity is below zero, which an account permitting
|
|
|
+ /// overdraft may hold.
|
|
|
+ pub fn is_negative(&self) -> bool {
|
|
|
+ self.value.is_negative()
|
|
|
+ }
|
|
|
+
|
|
|
+ /// True when the quantity is nothing.
|
|
|
+ pub fn is_zero(&self) -> bool {
|
|
|
+ self.value.is_zero()
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Add two amounts of the same asset. Mismatched assets are rejected, which
|
|
|
+ /// is the whole reason this type exists.
|
|
|
+ pub fn checked_add(&self, rhs: &Self) -> Result<Self, AmountError> {
|
|
|
+ self.same_asset(rhs)?;
|
|
|
+ Ok(Self {
|
|
|
+ asset: Arc::clone(&self.asset),
|
|
|
+ value: self.value.checked_add(rhs.value)?,
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Subtract an amount of the same asset.
|
|
|
+ pub fn checked_sub(&self, rhs: &Self) -> Result<Self, AmountError> {
|
|
|
+ self.same_asset(rhs)?;
|
|
|
+ Ok(Self {
|
|
|
+ asset: Arc::clone(&self.asset),
|
|
|
+ value: self.value.checked_sub(rhs.value)?,
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Negate, keeping the asset.
|
|
|
+ pub fn checked_neg(&self) -> Result<Self, AmountError> {
|
|
|
+ Ok(Self {
|
|
|
+ asset: Arc::clone(&self.asset),
|
|
|
+ value: self.value.checked_neg()?,
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Sum amounts that must all be of `asset`. The asset is a parameter rather
|
|
|
+ /// than taken from the first item, so an empty sum still has one.
|
|
|
+ pub fn checked_sum(
|
|
|
+ asset: Arc<Asset>,
|
|
|
+ iter: impl IntoIterator<Item = Self>,
|
|
|
+ ) -> Result<Self, AmountError> {
|
|
|
+ let mut total = Self::zero(asset);
|
|
|
+ for item in iter {
|
|
|
+ total = total.checked_add(&item)?;
|
|
|
+ }
|
|
|
+ Ok(total)
|
|
|
+ }
|
|
|
+
|
|
|
+ fn same_asset(&self, rhs: &Self) -> Result<(), AmountError> {
|
|
|
+ if self.asset.id == rhs.asset.id {
|
|
|
+ return Ok(());
|
|
|
+ }
|
|
|
+ Err(AmountError::AssetMismatch {
|
|
|
+ left: self.asset.id,
|
|
|
+ right: rhs.asset.id,
|
|
|
+ })
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Equality is by asset id and value. Two reads of the same asset are the same
|
|
|
+/// asset, so comparing the registry metadata would make equality depend on when
|
|
|
+/// each side was loaded.
|
|
|
+impl PartialEq for Amount {
|
|
|
+ fn eq(&self, other: &Self) -> bool {
|
|
|
+ self.asset.id == other.asset.id && self.value == other.value
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl Eq for Amount {}
|
|
|
+
|
|
|
+impl fmt::Debug for Amount {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ write!(f, "Amount({} {})", self.value, self.asset.code)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Formats at the asset's own scale and names it by code, so an amount cannot
|
|
|
+/// be printed at the wrong precision. Grouping separators are a locale
|
|
|
+/// decision and stay with the caller.
|
|
|
+impl fmt::Display for Amount {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ write!(
|
|
|
+ f,
|
|
|
+ "{} {}",
|
|
|
+ self.asset.scale().format(self.value),
|
|
|
+ self.asset.code
|
|
|
+ )
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// The serialized form carries the whole asset, not just its id, so an amount
|
|
|
+/// read back needs no registry to be whole again (ADR-0029). That is what makes
|
|
|
+/// a stored posting self-describing and its decode infallible.
|
|
|
+///
|
|
|
+/// The content address is the exception: it hashes the asset's id and the value
|
|
|
+/// alone, so a transfer's identity does not move when a code or a symbol is
|
|
|
+/// written differently.
|
|
|
+#[derive(Serialize, Deserialize)]
|
|
|
+#[serde(rename = "Amount")]
|
|
|
+struct AmountWire {
|
|
|
+ asset: Asset,
|
|
|
+ value: Cent,
|
|
|
+}
|
|
|
+
|
|
|
+impl Serialize for Amount {
|
|
|
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
|
+ AmountWire {
|
|
|
+ asset: Asset::clone(&self.asset),
|
|
|
+ value: self.value,
|
|
|
+ }
|
|
|
+ .serialize(serializer)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl<'de> Deserialize<'de> for Amount {
|
|
|
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
|
+ let wire = AmountWire::deserialize(deserializer)?;
|
|
|
+ Ok(Self {
|
|
|
+ asset: Arc::new(wire.asset),
|
|
|
+ value: wire.value,
|
|
|
+ })
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Why an amount could not be built or combined.
|
|
|
+#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
+pub enum AmountError {
|
|
|
+ /// Two amounts of different assets were combined. Each asset is its own
|
|
|
+ /// conservation boundary, so there is no sum to give.
|
|
|
+ AssetMismatch {
|
|
|
+ /// Asset of the left operand.
|
|
|
+ left: AssetId,
|
|
|
+ /// Asset of the right operand.
|
|
|
+ right: AssetId,
|
|
|
+ },
|
|
|
+ /// The result left the range the money backing can hold.
|
|
|
+ Overflow,
|
|
|
+ /// The decimal string did not parse at the asset's scale.
|
|
|
+ Parse(ParseDecimalError),
|
|
|
+}
|
|
|
+
|
|
|
+impl fmt::Display for AmountError {
|
|
|
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
+ match self {
|
|
|
+ Self::AssetMismatch { left, right } => {
|
|
|
+ write!(f, "asset mismatch: {left:?} and {right:?}")
|
|
|
+ }
|
|
|
+ Self::Overflow => write!(f, "monetary amount overflow"),
|
|
|
+ Self::Parse(e) => write!(f, "amount: {e}"),
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl Error for AmountError {
|
|
|
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
|
|
|
+ match self {
|
|
|
+ Self::Parse(e) => Some(e),
|
|
|
+ Self::AssetMismatch { .. } | Self::Overflow => None,
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl From<OverflowError> for AmountError {
|
|
|
+ fn from(_: OverflowError) -> Self {
|
|
|
+ Self::Overflow
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl From<ParseDecimalError> for AmountError {
|
|
|
+ fn from(e: ParseDecimalError) -> Self {
|
|
|
+ Self::Parse(e)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Lets an infallible conversion satisfy a bound that accepts a fallible one,
|
|
|
+/// so `(asset, Cent)` and `(asset, "5.00")` reach the same builder method.
|
|
|
+impl From<Infallible> for AmountError {
|
|
|
+ fn from(never: Infallible) -> Self {
|
|
|
+ match never {}
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// Build an amount of an asset from the asset's side: `usd.amount("100.00")?`,
|
|
|
+/// for a caller holding the asset rather than assembling a tuple.
|
|
|
+///
|
|
|
+/// Implemented for both [`Asset`] and `Arc<Asset>`, so it works on whatever a
|
|
|
+/// caller has: a handle from [`Ledger::asset`](../../kuatia/ledger/struct.Ledger.html)
|
|
|
+/// or a row from a listing. The `Arc` receiver shares the one row; the `Asset`
|
|
|
+/// one clones it, which costs the two strings and nothing in identity, since an
|
|
|
+/// amount compares by asset id.
|
|
|
+///
|
|
|
+/// This is a trait, so it has to be in scope. `kuatia::prelude::*` and
|
|
|
+/// `kuatia_core::*` both bring it. Not named `new`, which would read as
|
|
|
+/// constructing an [`Asset`].
|
|
|
+pub trait Denominate {
|
|
|
+ /// An amount of this asset, in whichever form the value is already in.
|
|
|
+ fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
|
|
|
+ where
|
|
|
+ Amount: TryFrom<(V, Arc<Asset>)>,
|
|
|
+ <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>;
|
|
|
+}
|
|
|
+
|
|
|
+impl Denominate for Arc<Asset> {
|
|
|
+ fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
|
|
|
+ where
|
|
|
+ Amount: TryFrom<(V, Arc<Asset>)>,
|
|
|
+ <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>,
|
|
|
+ {
|
|
|
+ Amount::try_from((value, Arc::clone(self))).map_err(Into::into)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl Denominate for Asset {
|
|
|
+ fn amount<V>(&self, value: V) -> Result<Amount, AmountError>
|
|
|
+ where
|
|
|
+ Amount: TryFrom<(V, Arc<Asset>)>,
|
|
|
+ <Amount as TryFrom<(V, Arc<Asset>)>>::Error: Into<AmountError>,
|
|
|
+ {
|
|
|
+ Amount::try_from((value, Arc::new(self.clone()))).map_err(Into::into)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl From<(Cent, Arc<Asset>)> for Amount {
|
|
|
+ fn from((value, asset): (Cent, Arc<Asset>)) -> Self {
|
|
|
+ Self { asset, value }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl From<(Cent, &Arc<Asset>)> for Amount {
|
|
|
+ fn from((value, asset): (Cent, &Arc<Asset>)) -> Self {
|
|
|
+ Self::from((value, Arc::clone(asset)))
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// The value comes first, the way the money reads aloud: `("50.00", usd)`.
|
|
|
+/// Each conversion comes in two shapes, one taking the asset handle and one
|
|
|
+/// taking a reference to it, so a caller passing the same asset to several
|
|
|
+/// movements does not clone it at every call.
|
|
|
+macro_rules! amount_conversions {
|
|
|
+ (infallible $($value:ty),+) => {
|
|
|
+ $(
|
|
|
+ impl From<($value, Arc<Asset>)> for Amount {
|
|
|
+ fn from((value, asset): ($value, Arc<Asset>)) -> Self {
|
|
|
+ Self { asset, value: Cent::from(value) }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ impl From<($value, &Arc<Asset>)> for Amount {
|
|
|
+ fn from((value, asset): ($value, &Arc<Asset>)) -> Self {
|
|
|
+ Self::from((value, Arc::clone(asset)))
|
|
|
+ }
|
|
|
+ }
|
|
|
+ )+
|
|
|
+ };
|
|
|
+}
|
|
|
+
|
|
|
+amount_conversions!(infallible i64, i32, u32, u8, i8);
|
|
|
+
|
|
|
+impl TryFrom<(i128, Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((value, asset): (i128, Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ Ok(Self {
|
|
|
+ asset,
|
|
|
+ value: Cent::try_from(value)?,
|
|
|
+ })
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl TryFrom<(i128, &Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((value, asset): (i128, &Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ Self::try_from((value, Arc::clone(asset)))
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl TryFrom<(&str, Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((text, asset): (&str, Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ let value = asset.scale().parse(text)?;
|
|
|
+ Ok(Self { asset, value })
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl TryFrom<(&str, &Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((text, asset): (&str, &Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ Self::try_from((text, Arc::clone(asset)))
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl TryFrom<(String, Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((text, asset): (String, Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ Self::try_from((text.as_str(), asset))
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+impl TryFrom<(String, &Arc<Asset>)> for Amount {
|
|
|
+ type Error = AmountError;
|
|
|
+
|
|
|
+ fn try_from((text, asset): (String, &Arc<Asset>)) -> Result<Self, Self::Error> {
|
|
|
+ Self::try_from((text.as_str(), Arc::clone(asset)))
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ fn usd() -> Arc<Asset> {
|
|
|
+ Arc::new(Asset::new(AssetId::new(1), "USD", "$", 2))
|
|
|
+ }
|
|
|
+
|
|
|
+ fn btc() -> Arc<Asset> {
|
|
|
+ Arc::new(Asset::new(AssetId::new(3), "BTC", "\u{20bf}", 8))
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The same digits mean different quantities at different scales, which is
|
|
|
+ /// the reason a string cannot be parsed without its asset.
|
|
|
+ #[test]
|
|
|
+ fn integers_are_minor_units_and_strings_are_decimal() {
|
|
|
+ let from_int = Amount::from((500, usd()));
|
|
|
+ let from_str = Amount::try_from(("5.00", usd())).unwrap();
|
|
|
+ assert_eq!(from_int, from_str);
|
|
|
+ assert_eq!(from_int.minor_units(), 500);
|
|
|
+ assert_eq!(
|
|
|
+ Amount::try_from(("5.00", btc())).unwrap().minor_units(),
|
|
|
+ 500_000_000
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn a_string_finer_than_the_asset_is_refused() {
|
|
|
+ let err = Amount::try_from(("5.001", usd())).unwrap_err();
|
|
|
+ assert!(matches!(err, AmountError::Parse(_)));
|
|
|
+ assert!(Amount::try_from(("5.001", btc())).is_ok());
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn mismatched_assets_do_not_combine() {
|
|
|
+ let dollars = Amount::from((500, usd()));
|
|
|
+ let coins = Amount::from((500, btc()));
|
|
|
+ assert_eq!(
|
|
|
+ dollars.checked_add(&coins),
|
|
|
+ Err(AmountError::AssetMismatch {
|
|
|
+ left: AssetId::new(1),
|
|
|
+ right: AssetId::new(3),
|
|
|
+ })
|
|
|
+ );
|
|
|
+ assert_eq!(
|
|
|
+ coins.checked_sub(&dollars),
|
|
|
+ Err(AmountError::AssetMismatch {
|
|
|
+ left: AssetId::new(3),
|
|
|
+ right: AssetId::new(1),
|
|
|
+ })
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn same_asset_arithmetic_keeps_the_asset() {
|
|
|
+ let sum = Amount::from((500, usd()))
|
|
|
+ .checked_add(&Amount::from((250, usd())))
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(sum, Amount::from((750, usd())));
|
|
|
+ assert_eq!(sum.asset_id(), AssetId::new(1));
|
|
|
+ assert_eq!(sum.checked_neg().unwrap().minor_units(), -750);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The asset is a parameter so an empty sum still has one, and a stray
|
|
|
+ /// asset in the middle is caught rather than added.
|
|
|
+ #[test]
|
|
|
+ fn checked_sum_carries_the_asset_through_an_empty_run() {
|
|
|
+ assert_eq!(
|
|
|
+ Amount::checked_sum(usd(), Vec::new()).unwrap(),
|
|
|
+ Amount::zero(usd())
|
|
|
+ );
|
|
|
+ assert_eq!(
|
|
|
+ Amount::checked_sum(
|
|
|
+ usd(),
|
|
|
+ [Amount::from((100, usd())), Amount::from((25, usd()))]
|
|
|
+ )
|
|
|
+ .unwrap(),
|
|
|
+ Amount::from((125, usd()))
|
|
|
+ );
|
|
|
+ assert!(
|
|
|
+ Amount::checked_sum(
|
|
|
+ usd(),
|
|
|
+ [Amount::from((100, usd())), Amount::from((1, btc()))]
|
|
|
+ )
|
|
|
+ .is_err()
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn i128_out_of_range_is_an_overflow() {
|
|
|
+ assert_eq!(
|
|
|
+ Amount::try_from((650i128, usd())).unwrap(),
|
|
|
+ Amount::from((650, usd()))
|
|
|
+ );
|
|
|
+ if let Some(beyond) = i128::from(i64::MAX).checked_add(1) {
|
|
|
+ let too_big = Amount::try_from((beyond, usd()));
|
|
|
+ #[cfg(not(feature = "i128"))]
|
|
|
+ assert_eq!(too_big, Err(AmountError::Overflow));
|
|
|
+ #[cfg(feature = "i128")]
|
|
|
+ assert!(too_big.is_ok());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn display_uses_the_asset_scale_and_code() {
|
|
|
+ assert_eq!(Amount::from((65_000, usd())).to_string(), "650.00 USD");
|
|
|
+ assert_eq!(
|
|
|
+ Amount::from((150_000_000, btc())).to_string(),
|
|
|
+ "1.50000000 BTC"
|
|
|
+ );
|
|
|
+ assert_eq!(
|
|
|
+ format!("{:?}", Amount::from((65_000, usd()))),
|
|
|
+ "Amount(65000 USD)"
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ /// A reference reaches the same conversions, so a caller passing one asset
|
|
|
+ /// to several movements does not clone the handle at every call.
|
|
|
+ #[test]
|
|
|
+ fn a_reference_to_the_asset_converts_too() {
|
|
|
+ let usd = usd();
|
|
|
+ let from_ref = Amount::try_from(("5.00", &usd)).unwrap();
|
|
|
+ assert_eq!(from_ref, Amount::from((500, &usd)));
|
|
|
+ assert_eq!(from_ref, Amount::from((Cent::from(500), usd.clone())));
|
|
|
+ assert_eq!(Amount::try_from((500i128, &usd)).unwrap(), from_ref);
|
|
|
+ assert_eq!(
|
|
|
+ Amount::try_from((String::from("5.00"), &usd)).unwrap(),
|
|
|
+ from_ref
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ /// `usd.amount(..)` is the same conversion from the other side, for a caller
|
|
|
+ /// holding the asset rather than building a tuple. It reads the same whether
|
|
|
+ /// the caller holds the shared handle or a row of its own.
|
|
|
+ #[test]
|
|
|
+ fn denominate_builds_from_the_asset() {
|
|
|
+ let usd = usd();
|
|
|
+ assert_eq!(usd.amount("5.00").unwrap(), Amount::from((500, &usd)));
|
|
|
+ assert_eq!(usd.amount(500).unwrap(), Amount::from((500, &usd)));
|
|
|
+ assert_eq!(
|
|
|
+ usd.amount(Cent::from(500)).unwrap(),
|
|
|
+ Amount::from((500, &usd))
|
|
|
+ );
|
|
|
+ assert!(matches!(usd.amount("5.001"), Err(AmountError::Parse(_))));
|
|
|
+
|
|
|
+ // A bare row works too, which is what a caller holds after listing the
|
|
|
+ // registry; an amount compares by asset id, so the two agree.
|
|
|
+ let row = Asset::new(AssetId::new(1), "USD", "$", 2);
|
|
|
+ assert_eq!(row.amount("5.00").unwrap(), usd.amount("5.00").unwrap());
|
|
|
+ assert_eq!(row.amount(500).unwrap(), Amount::from((500, &usd)));
|
|
|
+ }
|
|
|
+
|
|
|
+ /// A fraction shorter than the asset's scale is padded, not rejected: a
|
|
|
+ /// two-decimal asset reads "100.0" as ten thousand minor units.
|
|
|
+ #[test]
|
|
|
+ fn a_short_fraction_pads_to_the_scale() {
|
|
|
+ assert_eq!(usd().amount("100.0").unwrap().minor_units(), 10_000);
|
|
|
+ assert_eq!(usd().amount("100").unwrap().minor_units(), 10_000);
|
|
|
+ assert_eq!(btc().amount("1.5").unwrap().minor_units(), 150_000_000);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The asset travels with the value, so a stored amount decodes without a
|
|
|
+ /// registry and cannot come back at the wrong scale.
|
|
|
+ #[test]
|
|
|
+ fn round_trips_through_serde_carrying_its_asset() {
|
|
|
+ let amount = Amount::from((650, usd()));
|
|
|
+ let json = serde_json::to_string(&amount).unwrap();
|
|
|
+ assert_eq!(
|
|
|
+ json,
|
|
|
+ r#"{"asset":{"id":1,"code":"USD","symbol":"$","decimals":2},"value":"650"}"#
|
|
|
+ );
|
|
|
+
|
|
|
+ let back: Amount = serde_json::from_str(&json).unwrap();
|
|
|
+ assert_eq!(back, amount);
|
|
|
+ assert_eq!(back.asset().decimals, 2);
|
|
|
+ assert_eq!(back.to_string(), "6.50 USD");
|
|
|
+ }
|
|
|
+}
|