From f47207054679b6ab3cdb81fbaad9d4623654c3bf Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Fri, 26 Feb 2021 14:31:09 +1100 Subject: [PATCH] Remove `--send-btc` in favor of swapping the available balance If the current balance is 0, we wait until the user deposits money to the given address. After that, we simply swap the full balance. Not only does this simplify the interface by removing a parameter, but it also integrates the `deposit` command into the `buy-xmr` command. Syncing a wallet that is backed by electrum includes transactions that are part of the mempool when computing the balance. As such, waiting for a deposit is a very quick action because it allows us to build our lock transaction on top of the yet to be confirmed deposit transactions. This patch introduces another function to the `bitcoin::Wallet` that relies on the currently statically encoded fee rate. To make sure future developers don't forget to adjust both, we extract a function that "selects" a fee rate and return the constant from there. Fixes #196. --- swap/src/bin/swap_cli.rs | 34 +++++++++++++++++++++------------- swap/src/bitcoin/wallet.rs | 35 ++++++++++++++++++++++++++++++++++- swap/src/cli/command.rs | 10 ---------- 3 files changed, 55 insertions(+), 24 deletions(-) diff --git a/swap/src/bin/swap_cli.rs b/swap/src/bin/swap_cli.rs index c4fed8c1..76cbcadf 100644 --- a/swap/src/bin/swap_cli.rs +++ b/swap/src/bin/swap_cli.rs @@ -15,10 +15,11 @@ use anyhow::{Context, Result}; use prettytable::{row, Table}; use reqwest::Url; -use std::{path::Path, sync::Arc}; +use std::{path::Path, sync::Arc, time::Duration}; use structopt::StructOpt; use swap::{ bitcoin, + bitcoin::Amount, cli::{ command::{Arguments, Cancel, Command, Refund, Resume}, config::{ @@ -39,7 +40,7 @@ use swap::{ seed::Seed, trace::init_tracing, }; -use tracing::{error, info, warn}; +use tracing::{debug, error, info, warn}; use tracing_subscriber::filter::LevelFilter; use uuid::Uuid; @@ -95,7 +96,6 @@ async fn main() -> Result<()> { Command::BuyXmr { alice_peer_id, alice_addr, - send_bitcoin, } => { let (bitcoin_wallet, monero_wallet) = init_wallets( config, @@ -107,22 +107,30 @@ async fn main() -> Result<()> { ) .await?; - let swap_id = Uuid::new_v4(); + // TODO: Also wait for more funds if balance < dust + if bitcoin_wallet.balance().await? == Amount::ZERO { + debug!( + "Waiting for BTC at address {}", + bitcoin_wallet.new_address().await? + ); - info!( - "Swap buy XMR with {} started with ID {}", - send_bitcoin, swap_id - ); + while bitcoin_wallet.balance().await? == Amount::ZERO { + bitcoin_wallet.sync_wallet().await?; - info!( - "BTC deposit address: {}", - bitcoin_wallet.new_address().await? - ); + tokio::time::sleep(Duration::from_secs(1)).await; + } + + debug!("Received {}", bitcoin_wallet.balance().await?); + } + + let send_bitcoin = bitcoin_wallet.max_giveable().await?; + + info!("Swapping {} ...", send_bitcoin); let bob_factory = Builder::new( seed, db, - swap_id, + Uuid::new_v4(), Arc::new(bitcoin_wallet), Arc::new(monero_wallet), alice_addr, diff --git a/swap/src/bitcoin/wallet.rs b/swap/src/bitcoin/wallet.rs index 212c1bd9..466a5f4c 100644 --- a/swap/src/bitcoin/wallet.rs +++ b/swap/src/bitcoin/wallet.rs @@ -16,6 +16,7 @@ use bdk::{ miniscript::bitcoin::PrivateKey, FeeRate, }; +use bitcoin::Script; use reqwest::{Method, Url}; use serde::{Deserialize, Serialize}; use std::{path::Path, sync::Arc, time::Duration}; @@ -120,15 +121,47 @@ impl Wallet { let mut tx_builder = wallet.build_tx(); tx_builder.add_recipient(address.script_pubkey(), amount.as_sat()); - tx_builder.fee_rate(FeeRate::from_sat_per_vb(5.0)); // todo: make dynamic + tx_builder.fee_rate(self.select_feerate()); let (psbt, _details) = tx_builder.finish()?; Ok(psbt) } + /// Calculates the maximum "giveable" amount of this wallet. + /// + /// We define this as the maximum amount we can pay to a single output, + /// already accounting for the fees we need to spend to get the + /// transaction confirmed. + pub async fn max_giveable(&self) -> Result { + let wallet = self.inner.lock().await; + + let mut tx_builder = wallet.build_tx(); + + // create a dummy script to make the txbuilder pass + // we don't intend to send this transaction, we just want to know the max amount + // we can spend + let dummy_script = Script::default(); + tx_builder.set_single_recipient(dummy_script); + + tx_builder.drain_wallet(); + tx_builder.fee_rate(self.select_feerate()); + let (_, details) = tx_builder.finish()?; + + let max_giveable = details.sent - details.fees; + + Ok(Amount::from_sat(max_giveable)) + } + pub async fn get_network(&self) -> bitcoin::Network { self.inner.lock().await.network() } + + /// Selects an appropriate [`FeeRate`] to be used for getting transactions + /// confirmed within a reasonable amount of time. + fn select_feerate(&self) -> FeeRate { + // TODO: This should obviously not be a const :) + FeeRate::from_sat_per_vb(5.0) + } } #[async_trait] diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index 88348f21..728a329f 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -1,5 +1,3 @@ -use crate::bitcoin; -use anyhow::Result; use libp2p::{core::Multiaddr, PeerId}; use std::path::PathBuf; use uuid::Uuid; @@ -26,9 +24,6 @@ pub enum Command { #[structopt(long = "connect-addr")] alice_addr: Multiaddr, - - #[structopt(long = "send-btc", help = "Bitcoin amount as floating point nr without denomination (e.g. 1.25)", parse(try_from_str = parse_btc))] - send_bitcoin: bitcoin::Amount, }, History, Resume(Resume), @@ -85,8 +80,3 @@ pub enum Refund { force: bool, }, } - -fn parse_btc(str: &str) -> Result { - let amount = bitcoin::Amount::from_str_in(str, ::bitcoin::Denomination::Bitcoin)?; - Ok(amount) -}