Skip to content

Commit

Permalink
Merge pull request #244 from KnowWhoami/taker_test
Browse files Browse the repository at this point in the history
write integration test for taker cli app.
  • Loading branch information
mojoX911 authored Oct 5, 2024
2 parents b7f7dc3 + 3d39c73 commit 32255dd
Show file tree
Hide file tree
Showing 8 changed files with 332 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src/bin/directory-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ fn send_rpc_req(req: &RpcMsgReq) {
}

fn main() {
setup_logger();
setup_logger(log::LevelFilter::Info);
let cli = App::parse();

match cli.command {
Expand Down
2 changes: 1 addition & 1 deletion src/bin/directoryd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ struct Cli {
}

fn main() {
setup_logger();
setup_logger(log::LevelFilter::Info);

let args = Cli::parse();

Expand Down
2 changes: 1 addition & 1 deletion src/bin/maker-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ enum Commands {
}

fn main() -> Result<(), MakerError> {
setup_logger();
setup_logger(log::LevelFilter::Info);
let cli = App::parse();

match cli.command {
Expand Down
2 changes: 1 addition & 1 deletion src/bin/makerd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ struct Cli {
}

fn main() -> std::io::Result<()> {
setup_logger();
setup_logger(log::LevelFilter::Info);

let args = Cli::parse();

Expand Down
101 changes: 88 additions & 13 deletions src/bin/taker.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
use std::path::PathBuf;

use bitcoin::Amount;
use bitcoin::{Address, Amount};
use bitcoind::bitcoincore_rpc::{json::ListUnspentResultEntry, Auth};
use clap::Parser;
use coinswap::{
taker::{SwapParams, Taker, TakerBehavior},
utill::{
parse_proxy_auth, read_bitcoin_network_string, read_connection_network_string, setup_logger,
},
wallet::RPCConfig,
wallet::{Destination, RPCConfig, SendAmount},
};
use log::LevelFilter;
use std::{path::PathBuf, str::FromStr};

/// taker-cli is a command line app to use taker client API's.
#[derive(Parser, Debug)]
#[clap(version = option_env ! ("CARGO_PKG_VERSION").unwrap_or("unknown"),
author = option_env ! ("CARGO_PKG_AUTHORS").unwrap_or(""))]
struct Cli {
/// Optional Connection Network Type
#[clap(long, default_value = "clearnet",possible_values = &["tor","clearnet"])]
network: String,
#[clap(long, default_value = "clearnet",short= 'c', possible_values = &["tor","clearnet"])]
connection_type: String,
/// Optional DNS data directory. Default value : "~/.coinswap/taker"
#[clap(long, short = 'd')]
data_directory: Option<PathBuf>,
Expand All @@ -35,15 +35,18 @@ struct Cli {
pub auth: (String, String),
/// Sets the full node network, this should match with the network of the running node.
#[clap(
name = "NETWORK",
long,
short = 'n',
short = 'b',
default_value = "regtest", possible_values = &["regtest", "signet", "mainnet"]
)]
pub rpc_network: String,
pub bitcoin_network: String,
/// Sets the taker wallet's name. If the wallet file already exists at data-directory, it will load that wallet.
#[clap(name = "WALLET", long, short = 'w', default_value = "taker")]
pub wallet_name: String,
/// Sets the verbosity level of logs.
/// Default: Determined by the command passed.
#[clap(long, short = 'v', possible_values = &["off", "error", "warn", "info", "debug", "trace"])]
pub verbosity: Option<String>,
/// Sets the maker count to initiate coinswap with.
#[clap(name = "maker_count", default_value = "2")]
pub maker_count: usize,
Expand Down Expand Up @@ -82,17 +85,28 @@ enum Commands {
TotalBalance,
/// Returns a new address
GetNewAddress,
/// Send to an external wallet address.
SendToAddress {
#[clap(name = "address")]
address: String,
/// Amount to be sent (in sats)
#[clap(name = "amount")]
amount: u64,
/// Fee of a Tx(in sats)
#[clap(name = "fee")]
fee: u64,
},
/// Sync the offer book
SyncOfferBook,
/// Initiate the coinswap process
DoCoinswap,
}

fn main() {
setup_logger();
let args = Cli::parse();
let rpc_network = read_bitcoin_network_string(&args.rpc_network).unwrap();
let connection_type = read_connection_network_string(&args.network).unwrap();

let rpc_network = read_bitcoin_network_string(&args.bitcoin_network).unwrap();
let connection_type = read_connection_network_string(&args.connection_type).unwrap();
let rpc_config = RPCConfig {
url: args.rpc,
auth: Auth::UserPass(args.auth.0, args.auth.1),
Expand All @@ -117,11 +131,27 @@ fn main() {
)
.unwrap();

// Determines the log level based on the verbosity argument or the command.
//
// If verbosity is provided, it converts the string to a `LevelFilter`.
// Otherwise, the log level is set based on the command.
let log_level = match args.verbosity {
Some(level) => LevelFilter::from_str(&level).unwrap(),
None => match args.command {
Commands::DoCoinswap | Commands::SyncOfferBook | Commands::SendToAddress { .. } => {
log::LevelFilter::Info
}
_ => log::LevelFilter::Off,
},
};

setup_logger(log_level);

match args.command {
Commands::SeedUtxo => {
let utxos: Vec<ListUnspentResultEntry> = taker
.get_wallet()
.list_live_contract_spend_info(None)
.list_descriptor_utxo_spend_info(None)
.unwrap()
.iter()
.map(|(l, _)| l.clone())
Expand Down Expand Up @@ -168,6 +198,51 @@ fn main() {
let address = taker.get_wallet_mut().get_next_external_address().unwrap();
println!("{:?}", address);
}
Commands::SendToAddress {
address,
amount,
fee,
} => {
// NOTE:
//
// Currently, we take `fee` instead of `fee_rate` because we cannot calculate the fee for a
// transaction that hasn't been created yet when only a `fee_rate` is provided.
//
// As a result, the user must supply the fee as a parameter, and the function will return the
// transaction hex and the calculated `fee_rate`.
// This allows the user to infer what fee is needed for a successful transaction.
//
// This approach will be improved in the future BDK integration.

let fee = Amount::from_sat(fee);

let amount = Amount::from_sat(amount);

let coins_to_spend = taker.get_wallet().coin_select(amount + fee).unwrap();

let destination =
Destination::Address(Address::from_str(&address).unwrap().assume_checked());

let tx = taker
.get_wallet_mut()
.spend_from_wallet(
fee,
SendAmount::Amount(amount),
destination,
&coins_to_spend,
)
.unwrap();

// Derive fee rate from given `fee` argument.
let calculated_fee_rate = fee / (tx.weight());

println!(
"transaction_hex : {:?}",
bitcoin::consensus::encode::serialize_hex(&tx)
);
println!("Calculated FeeRate : {:#}", calculated_fee_rate);
}

Commands::SyncOfferBook => {
taker.sync_offerbook(args.maker_count).unwrap();
}
Expand Down
12 changes: 5 additions & 7 deletions src/utill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use bitcoin::{
},
Network, PublicKey, ScriptBuf, WitnessProgram, WitnessVersion,
};
use log::LevelFilter;
use log4rs::{
append::{console::ConsoleAppender, file::FileAppender},
config::{Appender, Logger, Root},
Expand Down Expand Up @@ -120,7 +121,8 @@ pub fn seed_phrase_to_unique_id(seed: &str) -> String {
}

/// Setup function that will only run once, even if called multiple times.
pub fn setup_logger() {
/// Takes log level to set the desired logging verbosity
pub fn setup_logger(filter: LevelFilter) {
Once::new().call_once(|| {
env::set_var("RUST_LOG", "coinswap=info");
let taker_log_dir = get_taker_dir().join("debug.log");
Expand All @@ -139,7 +141,7 @@ pub fn setup_logger() {
.logger(
Logger::builder()
.appender("taker")
.build("coinswap::taker", log::LevelFilter::Info),
.build("coinswap::taker", filter),
)
.logger(
Logger::builder()
Expand All @@ -151,11 +153,7 @@ pub fn setup_logger() {
.appender("directory")
.build("coinswap::market", log::LevelFilter::Info),
)
.build(
Root::builder()
.appender("stdout")
.build(log::LevelFilter::Info),
)
.build(Root::builder().appender("stdout").build(filter))
.unwrap();
log4rs::init_config(config).unwrap();
});
Expand Down
Loading

0 comments on commit 32255dd

Please sign in to comment.