Skip to main content

fedimint_wallet_client/
cli.rs

1use std::str::FromStr as _;
2use std::{ffi, iter};
3
4use bitcoin::address::NetworkUnchecked;
5use clap::Parser;
6use fedimint_api_client::api::FederationError;
7use fedimint_client_module::error::{ModuleLookupError, TransactionSubmitError};
8use fedimint_core::BitcoinAmountOrAll;
9use fedimint_core::core::{Account, OperationId};
10use fedimint_core::encoding::Encodable;
11use futures::StreamExt;
12use serde::Serialize;
13use tracing::{debug, info};
14
15use super::WalletClientModule;
16use crate::api::WalletFederationApi;
17use crate::client_db::TweakIdx;
18use crate::{
19    DepositAddressError, MaxWithdrawableAmountError, PegInError, SubscribeWithdrawError,
20    WithdrawFeesError, WithdrawState,
21};
22
23#[derive(Parser, Serialize)]
24enum Opts {
25    /// Await a deposit on a given deposit address
26    AwaitDeposit {
27        addr: Option<String>,
28        #[arg(long)]
29        operation_id: Option<OperationId>,
30        #[arg(long)]
31        tweak_idx: Option<TweakIdx>,
32        /// Await more than just one deposit
33        #[arg(long, default_value = "1")]
34        num: usize,
35    },
36    GetConsensusBlockCount,
37    /// Returns the Bitcoin RPC kind
38    GetBitcoinRpcKind {
39        peer_id: u16,
40    },
41    /// Returns the Bitcoin RPC kind and URL, if authenticated
42    GetBitcoinRpcConfig,
43
44    NewDepositAddress,
45    /// Withdraw funds from the federation
46    Withdraw {
47        #[clap(long)]
48        amount: BitcoinAmountOrAll,
49        #[clap(long)]
50        address: bitcoin::Address<NetworkUnchecked>,
51    },
52    /// Trigger wallet address check (in the background)
53    RecheckDepositAddress {
54        addr: Option<bitcoin::Address<NetworkUnchecked>>,
55        #[arg(long)]
56        operation_id: Option<OperationId>,
57        #[arg(long)]
58        tweak_idx: Option<TweakIdx>,
59    },
60}
61
62async fn await_deposit(
63    module: &WalletClientModule,
64    addr: Option<String>,
65    operation_id: Option<OperationId>,
66    tweak_idx: Option<TweakIdx>,
67    num: usize,
68) -> Result<(), CliCommandError> {
69    if u32::from(addr.is_some())
70        + u32::from(operation_id.is_some())
71        + u32::from(tweak_idx.is_some())
72        != 1
73    {
74        return Err(CliCommandError::SelectorCount);
75    }
76    if let Some(tweak_idx) = tweak_idx {
77        module.await_num_deposits(tweak_idx, num).await?;
78    } else if let Some(operation_id) = operation_id {
79        module
80            .await_num_deposits_by_operation_id(operation_id, num)
81            .await?;
82    } else if let Some(addr) = addr {
83        if addr.len() == 64 {
84            eprintln!(
85                "Interpreting addr as an operation_id for backward compatibility. \
86                Use `--operation-id` from now on."
87            );
88            let operation_id = OperationId::from_str(&addr)?;
89            module
90                .await_num_deposits_by_operation_id(operation_id, num)
91                .await?;
92        } else {
93            let addr = bitcoin::Address::from_str(&addr)?;
94            module.await_num_deposits_by_address(addr, num).await?;
95        }
96    } else {
97        unreachable!()
98    }
99    Ok(())
100}
101
102async fn withdraw(
103    module: &WalletClientModule,
104    amount: BitcoinAmountOrAll,
105    address: bitcoin::Address<NetworkUnchecked>,
106) -> Result<serde_json::Value, CliCommandError> {
107    let address = address.require_network(module.get_network())?;
108    let (amount, fees) = match amount {
109        // The on-chain fee is only part of the cost of withdrawing everything:
110        // funding the peg-out output also incurs the federation's per-note
111        // fees. The returned fees are quoted at the returned amount, so they
112        // must be used together.
113        BitcoinAmountOrAll::All => {
114            let balance = module
115                .client_ctx
116                .get_balance_for_btc(Account::Primary)
117                .await?;
118            module.max_withdrawable_amount(&address, balance).await?
119        }
120        BitcoinAmountOrAll::Amount(amount) => {
121            (amount, module.get_withdraw_fees(&address, amount).await?)
122        }
123    };
124    let absolute_fees = fees.amount();
125
126    info!("Attempting withdraw with fees: {fees:?}");
127
128    let operation_id = module.withdraw(&address, amount, fees, ()).await?;
129
130    let mut updates = module
131        .subscribe_withdraw_updates(operation_id)
132        .await?
133        .into_stream();
134
135    while let Some(update) = updates.next().await {
136        debug!(?update, "Withdraw state update");
137
138        match update {
139            WithdrawState::Succeeded(txid) => {
140                return Ok(serde_json::json!({
141                    "txid": txid.consensus_encode_to_hex(),
142                    "fees_sat": absolute_fees.to_sat(),
143                }));
144            }
145            WithdrawState::Failed(e) => {
146                return Err(CliCommandError::WithdrawFailed(e));
147            }
148            WithdrawState::Created => {}
149        }
150    }
151
152    unreachable!("Update stream ended without outcome");
153}
154
155pub(crate) async fn handle_cli_command(
156    module: &WalletClientModule,
157    args: &[ffi::OsString],
158) -> Result<serde_json::Value, CliCommandError> {
159    let opts = Opts::parse_from(iter::once(&ffi::OsString::from("wallet")).chain(args.iter()));
160
161    let res = match opts {
162        Opts::AwaitDeposit {
163            operation_id,
164            num,
165            addr,
166            tweak_idx,
167        } => {
168            await_deposit(module, addr, operation_id, tweak_idx, num).await?;
169            serde_json::Value::Bool(true)
170        }
171        Opts::GetBitcoinRpcKind { peer_id } => {
172            let kind = module
173                .module_api
174                .fetch_bitcoin_rpc_kind(peer_id.into())
175                .await?;
176            serde_json::to_value(kind).expect("JSON serialization failed")
177        }
178        Opts::GetBitcoinRpcConfig => {
179            let auth = module
180                .admin_auth
181                .clone()
182                .ok_or(CliCommandError::AdminAuthNotSet)?;
183            serde_json::to_value(module.module_api.fetch_bitcoin_rpc_config(auth).await?)
184                .expect("JSON serialization failed")
185        }
186        Opts::GetConsensusBlockCount => {
187            serde_json::to_value(module.module_api.fetch_consensus_block_count().await?)
188                .expect("JSON serialization failed")
189        }
190        Opts::RecheckDepositAddress {
191            addr,
192            operation_id,
193            tweak_idx,
194        } => {
195            if u32::from(addr.is_some())
196                + u32::from(operation_id.is_some())
197                + u32::from(tweak_idx.is_some())
198                != 1
199            {
200                return Err(CliCommandError::SelectorCount);
201            }
202            if let Some(tweak_idx) = tweak_idx {
203                module.recheck_pegin_address(tweak_idx).await?;
204            } else if let Some(operation_id) = operation_id {
205                module.recheck_pegin_address_by_op_id(operation_id).await?;
206            } else if let Some(addr) = addr {
207                module.recheck_pegin_address_by_address(addr).await?;
208            } else {
209                unreachable!()
210            }
211            serde_json::Value::Bool(true)
212        }
213        Opts::NewDepositAddress => {
214            let deposit_address = module.allocate_deposit_address_expert_only(()).await?;
215            serde_json::json! {
216                {
217                    "address": deposit_address.address,
218                    "operation_id": deposit_address.operation_id,
219                    "tweak_idx": deposit_address.tweak_idx.0
220                }
221            }
222        }
223        Opts::Withdraw { amount, address } => return withdraw(module, amount, address).await,
224    };
225
226    Ok(res)
227}
228
229/// A failure of a `wallet` module command.
230#[derive(Debug, thiserror::Error)]
231pub(crate) enum CliCommandError {
232    /// Not exactly one of the address, operation id and tweak index was
233    /// given.
234    #[error("One and only one of the selector arguments must be set")]
235    SelectorCount,
236
237    /// The deposits could not be awaited or rechecked.
238    #[error(transparent)]
239    PegIn(#[from] PegInError),
240
241    /// The argument is not a valid operation id.
242    #[error(transparent)]
243    OperationId(#[from] fedimint_core::hex::FromHexError),
244
245    /// The address is not valid, or not for the federation's network.
246    #[error(transparent)]
247    Address(#[from] bitcoin::address::ParseError),
248
249    /// The client's bitcoin balance could not be read.
250    #[error(transparent)]
251    Balance(#[from] ModuleLookupError),
252
253    /// The largest withdrawable amount could not be computed.
254    #[error(transparent)]
255    MaxWithdrawable(#[from] MaxWithdrawableAmountError),
256
257    /// The withdrawal fees could not be quoted.
258    #[error(transparent)]
259    WithdrawFees(#[from] WithdrawFeesError),
260
261    /// The withdrawal transaction could not be submitted.
262    #[error(transparent)]
263    Withdraw(#[from] TransactionSubmitError),
264
265    /// The withdrawal's updates could not be followed.
266    #[error(transparent)]
267    SubscribeWithdraw(#[from] SubscribeWithdrawError),
268
269    /// The withdrawal failed.
270    #[error("Withdraw failed: {0}")]
271    WithdrawFailed(String),
272
273    /// The federation did not serve the request.
274    #[error(transparent)]
275    Federation(#[from] FederationError),
276
277    /// The client has no admin credentials, which reading the Bitcoin RPC
278    /// config needs.
279    #[error("Admin auth not set")]
280    AdminAuthNotSet,
281
282    /// A deposit address could not be allocated.
283    #[error(transparent)]
284    DepositAddress(#[from] DepositAddressError),
285}