spark_rust/wallet/handlers/
fees.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    error::SparkSdkError, signer::traits::SparkSigner,
5    wallet::internal_handlers::traits::ssp::SspInternalHandlers, SparkSdk,
6};
7
8/// Fee estimation data returned by Lightspark's Spark Service Provider. This is a generic struct that is used for Lightning, Cooperative Exit, and Leaves Swap fee estimations.
9#[derive(Debug, Serialize, Deserialize)]
10pub struct SparkFeeEstimate {
11    /// The estimated fees in sats.
12    pub fees: u64,
13}
14
15impl<S: SparkSigner + Send + Sync + Clone + 'static> SparkSdk<S> {
16    /// Estimates the fees for receiving a Lightning payment through the Spark Service Provider (SSP).
17    ///
18    /// This function calculates how much the SSP will charge for facilitating the receipt
19    /// of a Lightning payment of the specified amount. The fee is deducted from the received amount
20    /// before it is credited to your wallet.
21    ///
22    /// # Arguments
23    ///
24    /// * `amount` - The amount in satoshis you want to receive
25    ///
26    /// # Returns
27    ///
28    /// * `Ok(SparkFeeEstimate)` - Contains the estimated fees in satoshis
29    /// * `Err(SparkSdkError)` - If there was an error estimating the fees
30    ///
31    /// # Example
32    ///
33    /// ```
34    /// # use spark_rust::SparkSdk;
35    /// # async fn example(sdk: SparkSdk) -> Result<(), Box<dyn std::error::Error>> {
36    /// // Get fee estimate for receiving 50,000 satoshis
37    /// let amount = 50_000;
38    /// let fee_estimate = sdk.get_lightning_receive_fee_estimate(amount).await?;
39    /// println!("The SSP will charge {} sats for receiving {} sats", fee_estimate.fees, amount);
40    ///
41    /// // Calculate net amount after fees
42    /// let net_amount = amount - fee_estimate.fees;
43    /// println!("You'll receive {} sats after fees", net_amount);
44    /// # Ok(())
45    /// # }
46    /// ```
47    pub async fn get_lightning_receive_fee_estimate(
48        &self,
49        amount: u64,
50    ) -> Result<SparkFeeEstimate, SparkSdkError> {
51        self.get_lightning_receive_fee_estimate_with_ssp(amount)
52            .await
53    }
54
55    /// Estimates the fees for sending a Lightning payment through the Spark Service Provider (SSP).
56    ///
57    /// This function calculates how much the SSP will charge for facilitating a Lightning payment
58    /// to the destination specified in the invoice. The fee is in addition to the invoice amount
59    /// and is paid from your wallet.
60    ///
61    /// # Arguments
62    ///
63    /// * `invoice` - The Lightning invoice you want to pay
64    ///
65    /// # Returns
66    ///
67    /// * `Ok(SparkFeeEstimate)` - Contains the estimated fees in satoshis
68    /// * `Err(SparkSdkError)` - If there was an error estimating the fees
69    ///
70    /// # Example
71    ///
72    /// ```
73    /// # use spark_rust::SparkSdk;
74    /// # async fn example(sdk: SparkSdk) -> Result<(), Box<dyn std::error::Error>> {
75    /// // Get fee estimate for a Lightning invoice
76    /// let invoice = "lnbc1500n1p3zty3app5wkf0hagkc4egr8rl88msr4c5lp0ygt6gvzna5hdg4tpna65pzqdq0vehk7cnpwga5xzmnwvycqzpgxqyz5vqsp5v9ym7xsyf0qxqwzlmwjl3g0g9q2tg977h70hcheske9xlgfsggls9qyyssqtghx3qqpwm9zl4m398nm40wj8ryaz8v7v4rrdvczypdpy7qtc6rdrkklm9uxlkmtp3jf29yhqjw2vwmlp82y5ctft94k23cwgqd9llgy".to_string();
77    /// let fee_estimate = sdk.get_lightning_send_fee_estimate(invoice).await?;
78    /// println!("The SSP will charge {} sats for this Lightning payment", fee_estimate.fees);
79    ///
80    /// // Decide whether to proceed with payment based on fee amount
81    /// if fee_estimate.fees < 100 {
82    ///     println!("Fee is acceptable, proceeding with payment");
83    ///     // sdk.pay_lightning_invoice(&invoice).await?;
84    /// }
85    /// # Ok(())
86    /// # }
87    /// ```
88    pub async fn get_lightning_send_fee_estimate(
89        &self,
90        invoice: String,
91    ) -> Result<SparkFeeEstimate, SparkSdkError> {
92        self.get_lightning_send_fee_estimate_with_ssp(invoice).await
93    }
94
95    /// Estimates the fees for withdrawing funds from Spark to an on-chain Bitcoin address.
96    ///
97    /// This function calculates how much the SSP will charge for facilitating the withdrawal
98    /// of specific leaves from the Spark network to an on-chain Bitcoin address. The fee is
99    /// deducted from the withdrawn amount.
100    ///
101    /// # Arguments
102    ///
103    /// * `leaf_ids` - The specific leaf IDs you want to withdraw
104    /// * `on_chain_address` - The Bitcoin address where you want to receive the funds
105    ///
106    /// # Returns
107    ///
108    /// * `Ok(SparkFeeEstimate)` - Contains the estimated fees in satoshis
109    /// * `Err(SparkSdkError)` - If there was an error estimating the fees
110    ///
111    /// # Example
112    ///
113    /// ```
114    /// # use spark_rust::SparkSdk;
115    /// # use bitcoin::Address;
116    /// # use std::str::FromStr;
117    /// # async fn example(sdk: SparkSdk) -> Result<(), Box<dyn std::error::Error>> {
118    /// // Identify the leaves you want to withdraw
119    /// let leaf_ids = vec!["leaf_id_1".to_string(), "leaf_id_2".to_string()];
120    ///
121    /// // Specify the Bitcoin address to receive funds
122    /// let onchain_address = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string();
123    ///
124    /// // Get fee estimate before withdrawing
125    /// let fee_estimate = sdk.get_cooperative_exit_fee_estimate(leaf_ids.clone(), onchain_address.clone()).await?;
126    /// println!("Estimated withdrawal fee: {} satoshis", fee_estimate.fees);
127    ///
128    /// // Decide whether to proceed with the withdrawal based on the fee
129    /// if fee_estimate.fees < 1000 {
130    ///     // Fee is acceptable, proceed with withdrawal
131    ///     let bitcoin_address = Address::from_str(&onchain_address)?;
132    ///     // sdk.withdraw(&bitcoin_address, None).await?;
133    /// }
134    /// # Ok(())
135    /// # }
136    /// ```
137    pub async fn get_cooperative_exit_fee_estimate(
138        &self,
139        leaf_ids: Vec<String>,
140        on_chain_address: String,
141    ) -> Result<SparkFeeEstimate, SparkSdkError> {
142        self.get_cooperative_exit_fee_estimate_with_ssp(leaf_ids, on_chain_address)
143            .await
144    }
145
146    /// Estimates the fees for optimizing your wallet's leaf structure by swapping leaves with the SSP.
147    ///
148    /// This function calculates how much the SSP will charge for facilitating a leaves swap
149    /// operation. Leaf swaps are used to optimize your wallet's UTXO structure or to obtain
150    /// specific denominations needed for transfers.
151    ///
152    /// # Arguments
153    ///
154    /// * `total_amount_sats` - The total amount in satoshis that will be involved in the swap
155    ///
156    /// # Returns
157    ///
158    /// * `Ok(SparkFeeEstimate)` - Contains the estimated fees in satoshis
159    /// * `Err(SparkSdkError)` - If there was an error estimating the fees
160    ///
161    /// # Example
162    ///
163    /// ```
164    /// # use spark_rust::SparkSdk;
165    /// # async fn example(sdk: SparkSdk) -> Result<(), Box<dyn std::error::Error>> {
166    /// // Total amount to be swapped
167    /// let total_amount_sats = 100_000;
168    ///
169    /// // Get fee estimate before swapping leaves
170    /// let fee_estimate = sdk.get_leaves_swap_fee_estimate(total_amount_sats).await?;
171    /// println!("Estimated swap fee: {} satoshis", fee_estimate.fees);
172    ///
173    /// // Decide whether to proceed with the swap based on the fee
174    /// if fee_estimate.fees < total_amount_sats * 0.005 { // Less than 0.5% fee
175    ///     // Fee is acceptable, proceed with swap
176    ///     let target_amount = 80_000; // The specific denomination you need
177    ///     // sdk.request_leaves_swap(target_amount).await?;
178    /// }
179    /// # Ok(())
180    /// # }
181    /// ```
182    pub async fn get_leaves_swap_fee_estimate(
183        &self,
184        total_amount_sats: u64,
185    ) -> Result<SparkFeeEstimate, SparkSdkError> {
186        self.get_leaves_swap_fee_estimate_with_ssp(total_amount_sats)
187            .await
188    }
189}