From 60e0b9382c1ef7795fc3a146af335d265c8e88b2 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Mon, 8 Feb 2021 15:24:32 +1100 Subject: [PATCH] Introduced from float API for Monero quantities --- Cargo.lock | 5 +++-- swap/Cargo.toml | 2 +- swap/src/monero.rs | 14 ++++++++++++-- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8a3e61d6..8e218318 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2885,10 +2885,11 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.9.0" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5c739ba050709eae138f053356d27ff818d71fe54ce5a8d9f4c7a660bfb6684" +checksum = "e3e5a94e2006dd60c603d8481c65b665b4b6694f78d23e15869ad10eb883e36e" dependencies = [ + "arrayvec", "num-traits", "serde", ] diff --git a/swap/Cargo.toml b/swap/Cargo.toml index 5cb515da..34bf5ecb 100644 --- a/swap/Cargo.toml +++ b/swap/Cargo.toml @@ -40,7 +40,7 @@ pem = "0.8" prettytable-rs = "0.8" rand = "0.7" reqwest = { version = "0.11", default-features = false } -rust_decimal = "1.8" +rust_decimal = "1.10" serde = { version = "1", features = ["derive"] } serde_cbor = "0.11" serde_derive = "1.0" diff --git a/swap/src/monero.rs b/swap/src/monero.rs index 9d7bdec9..bc40b4a0 100644 --- a/swap/src/monero.rs +++ b/swap/src/monero.rs @@ -15,6 +15,7 @@ use rust_decimal::{ }; use serde::{Deserialize, Serialize}; use std::{ + convert::TryFrom, fmt::Display, ops::{Add, Mul, Sub}, str::FromStr, @@ -88,13 +89,22 @@ impl Amount { self.0 } + pub fn from_monero(amount: f64) -> Result { + let decimal = Decimal::try_from(amount)?; + Self::from_decimal(decimal) + } + pub fn parse_monero(amount: &str) -> Result { let decimal = Decimal::from_str(amount)?; + Self::from_decimal(decimal) + } + + fn from_decimal(amount: Decimal) -> Result { let piconeros_dec = - decimal.mul(Decimal::from_u64(PICONERO_OFFSET).expect("constant to fit into u64")); + amount.mul(Decimal::from_u64(PICONERO_OFFSET).expect("constant to fit into u64")); let piconeros = piconeros_dec .to_u64() - .ok_or_else(|| OverflowError(amount.to_owned()))?; + .ok_or_else(|| OverflowError(amount.to_string()))?; Ok(Amount(piconeros)) } }