From 1251681cfdb2528477602c32194bdcac1f8314e9 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 16 Oct 2020 12:42:47 +1100 Subject: [PATCH] Calculate amounts from BTC --- swap/src/alice.rs | 39 ++++++++++++++++++++++++++++++--------- swap/src/lib.rs | 8 ++++++-- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/swap/src/alice.rs b/swap/src/alice.rs index 80ddc09c..aebd9b3f 100644 --- a/swap/src/alice.rs +++ b/swap/src/alice.rs @@ -13,7 +13,7 @@ mod messenger; use self::messenger::*; use crate::{ - monero, + bitcoin, monero, network::{ peer_tracker::{self, PeerTracker}, request_response::{AliceToBob, TIMEOUT}, @@ -31,14 +31,8 @@ pub async fn swap(listen: Multiaddr) -> Result<()> { match swarm.next().await { BehaviourOutEvent::Request(messenger::BehaviourOutEvent::Btc { btc, channel }) => { debug!("Got request from Bob to swap {}", btc); - let params = SwapParams { - btc, - // TODO: Do a real calculation. - xmr: monero::Amount::from_piconero(10), - }; - - let msg = AliceToBob::Amounts(params); - swarm.send(channel, msg); + let p = calculate_amounts(btc); + swarm.send(channel, AliceToBob::Amounts(p)); } other => panic!("unexpected event: {:?}", other), } @@ -137,3 +131,30 @@ impl Default for Alice { } } } + +fn calculate_amounts(btc: bitcoin::Amount) -> SwapParams { + const XMR_PER_BTC: u64 = 100; // TODO: Get this from an exchange. + + // XMR uses 12 zerose BTC uses 8. + let picos = (btc.as_sat() * 10000) * XMR_PER_BTC; + let xmr = monero::Amount::from_piconero(picos); + + SwapParams { btc, xmr } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ONE_BTC: u64 = 100_000_000; + const HUNDRED_XMR: u64 = 100_000_000_000_000; + + #[test] + fn one_bitcoin_equals_a_hundred_moneroj() { + let btc = bitcoin::Amount::from_sat(ONE_BTC); + let want = monero::Amount::from_piconero(HUNDRED_XMR); + + let SwapParams { xmr: got, .. } = calculate_amounts(btc); + assert_eq!(got, want); + } +} diff --git a/swap/src/lib.rs b/swap/src/lib.rs index f9ba9a32..11f688d6 100644 --- a/swap/src/lib.rs +++ b/swap/src/lib.rs @@ -43,7 +43,7 @@ pub mod monero { use serde::{Deserialize, Serialize}; use std::fmt; - #[derive(Copy, Clone, Debug, Serialize, Deserialize)] + #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Amount(u64); impl Amount { @@ -76,7 +76,7 @@ pub mod bitcoin { use serde::{Deserialize, Serialize}; use std::fmt; - #[derive(Copy, Clone, Debug, Serialize, Deserialize)] + #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Amount(u64); impl Amount { @@ -92,6 +92,10 @@ pub mod bitcoin { pub fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) } + + pub fn as_sat(&self) -> u64 { + self.0 + } } impl fmt::Display for Amount {