Skip to main content

fedimint_walletv2_client/
cli.rs

1use std::{ffi, iter};
2
3use bitcoin::Address;
4use bitcoin::address::NetworkUnchecked;
5use clap::{Parser, Subcommand};
6use fedimint_api_client::api::FederationError;
7use fedimint_client_module::error::{ModuleLookupError, OperationLookupError};
8use fedimint_core::BitcoinAmountOrAll;
9use fedimint_core::core::Account;
10use fedimint_eventlog::EventLogId;
11use serde::Serialize;
12use serde_json::Value;
13
14use crate::{AwaitReceiveError, ReceiveError, SendError, WalletClientModule};
15
16#[derive(Parser, Serialize)]
17enum Opts {
18    /// Subcommands for operator to retrieve information about the wallet state.
19    #[command(subcommand)]
20    Info(InfoOpts),
21    /// Fetch the current fee required to send an onchain payment.
22    SendFee,
23    /// Fetch the current fee required to claim an onchain deposit (peg-in).
24    ReceiveFee,
25    /// Send an onchain payment.
26    Send {
27        address: Address<NetworkUnchecked>,
28        /// Value to send, or "all" to sweep the entire balance.
29        value: BitcoinAmountOrAll,
30        #[arg(long)]
31        fee: Option<bitcoin::Amount>,
32        #[arg(long, default_value_t = Account::Primary)]
33        account: Account,
34    },
35    /// Return the next unused receive address.
36    ///
37    /// To wait for a payment to this address, read the current event log
38    /// position with `dev next-event-log-id` *before* running this, then pass
39    /// that position to `await-receive`.
40    Receive {
41        #[arg(long, default_value_t = Account::Primary)]
42        account: Account,
43    },
44    /// Block until the next payment to an account is received, starting from
45    /// the given event log position. Returns the receive's final state and the
46    /// event log position to pass to the following `await-receive`.
47    AwaitReceive {
48        /// Event log position to start scanning from, as returned by
49        /// `dev next-event-log-id` or a prior `await-receive`.
50        position: EventLogId,
51        #[arg(long, default_value_t = Account::Primary)]
52        account: Account,
53    },
54}
55
56#[derive(Clone, Subcommand, Serialize)]
57enum InfoOpts {
58    /// Fetch the total value of bitcoin controlled by the federation.
59    TotalValue,
60    /// Fetch the consensus block count of the federation.
61    BlockCount,
62    /// Fetch the current consensus feerate.
63    Feerate,
64    /// Display the chain of pending bitcoin transactions.
65    PendingTxChain,
66    /// Display the chain of bitcoin transactions.
67    TxChain,
68}
69
70pub(crate) async fn handle_cli_command(
71    wallet: &WalletClientModule,
72    args: &[ffi::OsString],
73) -> Result<Value, CliCommandError> {
74    let opts = Opts::parse_from(iter::once(&ffi::OsString::from("walletv2")).chain(args.iter()));
75
76    let value = match opts {
77        Opts::Info(subcommand) => match subcommand {
78            InfoOpts::TotalValue => json(wallet.total_value().await?),
79            InfoOpts::BlockCount => json(wallet.block_count().await?),
80            InfoOpts::Feerate => json(wallet.feerate().await?),
81            InfoOpts::PendingTxChain => json(wallet.pending_tx_chain().await?),
82            InfoOpts::TxChain => json(wallet.tx_chain().await?),
83        },
84        Opts::SendFee => json(wallet.send_fee().await?),
85        Opts::ReceiveFee => json(wallet.receive_fee().await?),
86        Opts::Send {
87            address,
88            value,
89            fee,
90            account,
91        } => {
92            // Resolve the on-chain fee up front so the same value sizes the
93            // sweep and funds the send: the required feerate rises with each
94            // pending federation transaction, and a value computed against a
95            // stale fee would be rejected.
96            let fee = match fee {
97                Some(fee) => fee,
98                None => wallet.send_fee().await?,
99            };
100
101            let value = match value {
102                // The on-chain fee is only part of the cost of sending
103                // everything: funding the wallet output also incurs the
104                // federation's per-note fees.
105                BitcoinAmountOrAll::All => {
106                    let balance = wallet.client_ctx.get_balance_for_btc(account).await?;
107                    wallet.max_sendable_amount(account, balance, fee).await?
108                }
109                BitcoinAmountOrAll::Amount(value) => value,
110            };
111
112            json(
113                wallet
114                    .await_final_send_operation_state(
115                        wallet
116                            .send(account, address, value, Some(fee), serde_json::Value::Null)
117                            .await?,
118                    )
119                    .await?,
120            )
121        }
122        Opts::Receive { account } => json(wallet.receive(account).await?),
123        Opts::AwaitReceive { position, account } => {
124            json(wallet.await_receive(account, position).await?)
125        }
126    };
127
128    Ok(value)
129}
130
131fn json<T: Serialize>(value: T) -> Value {
132    serde_json::to_value(value).expect("JSON serialization failed")
133}
134
135/// A failure of a `walletv2` module command.
136#[derive(Debug, thiserror::Error)]
137pub(crate) enum CliCommandError {
138    /// The federation did not serve the request.
139    #[error(transparent)]
140    Federation(#[from] FederationError),
141
142    /// The payment could not be quoted or sent.
143    #[error(transparent)]
144    Send(#[from] SendError),
145
146    /// The receive fee could not be quoted.
147    #[error(transparent)]
148    Receive(#[from] ReceiveError),
149
150    /// The client's bitcoin balance could not be read.
151    #[error(transparent)]
152    Balance(#[from] ModuleLookupError),
153
154    /// The send operation could not be looked up.
155    #[error(transparent)]
156    OperationLookup(#[from] OperationLookupError),
157
158    /// The next receive could not be awaited.
159    #[error(transparent)]
160    AwaitReceive(#[from] AwaitReceiveError),
161}