1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use crate::batch;
use crate::batch::BatchOutputType;
use crate::wallet::BoardingWallet;
use crate::wallet::OnchainWallet;
use crate::Client;
use crate::Error;
use crate::KeyProvider;
use crate::SwapStorage;
use ark_core::ArkAddress;
use bitcoin::Address;
use bitcoin::Amount;
use bitcoin::OutPoint;
use bitcoin::SignedAmount;
use rand::CryptoRng;
use rand::Rng;
impl<B, W, S, K> Client<B, W, S, K>
where
B: crate::Blockchain,
W: BoardingWallet + OnchainWallet,
S: SwapStorage + 'static,
K: KeyProvider,
{
/// Estimates the fee to collaboratively redeem VTXOs to an on-chain Bitcoin address.
///
/// This function calculates the expected fee for moving funds from the Ark protocol
/// back to a standard on-chain Bitcoin address through a collaborative redemption process.
/// The fee is estimated by creating a simulated intent and querying the Ark server.
///
/// # Arguments
///
/// * `rng` - A random number generator for creating the intent
/// * `to_address` - The on-chain Bitcoin address to send funds to
/// * `to_amount` - The amount to send to the destination address
///
/// # Returns
///
/// Returns the estimated fee as a [`SignedAmount`]. The fee will be deducted from
/// the total available balance when performing the actual redemption.
///
/// # Errors
///
/// Returns an error if:
/// - The available balance is insufficient for the requested amount
/// - Failed to fetch VTXOs or boarding inputs
/// - Failed to communicate with the Ark server
pub async fn estimate_onchain_fees<R>(
&self,
rng: &mut R,
to_address: Address,
to_amount: Amount,
) -> Result<SignedAmount, Error>
where
R: Rng + CryptoRng + Clone,
{
let (change_address, _) = self.get_offchain_address()?;
let (boarding_inputs, vtxo_inputs, total_amount) = self
.fetch_commitment_transaction_inputs(crate::utils::unix_now()?)
.await?;
let change_amount = total_amount.checked_sub(to_amount).ok_or_else(|| {
Error::coin_select(format!(
"cannot afford to send {to_amount}, only have {total_amount}"
))
})?;
tracing::info!(
%to_address,
gross_amount = %to_amount,
change_address = %change_address.encode(),
%change_amount,
?boarding_inputs,
"Estimating fee to collaboratively redeem outputs"
);
let intent = self.prepare_intent(
&mut rng.clone(),
boarding_inputs,
vtxo_inputs,
BatchOutputType::OffBoard {
to_address,
to_amount,
change_address,
change_amount,
},
batch::PrepareIntentKind::EstimateFee,
)?;
let amount = self.network_client().estimate_fees(intent.intent).await?;
Ok(amount)
}
/// Estimates the fee to join the next batch and settle funds to an Ark address.
///
/// This function calculates the expected fee for consolidating all available VTXOs
/// and boarding outputs into fresh VTXOs through the Ark batch process. The full
/// available balance will be used, with fees deducted from the resulting VTXO.
///
/// Use this to estimate fees before calling [`settle`](crate::Client::settle) or
/// similar batch operations.
///
/// # Arguments
///
/// * `rng` - A random number generator for creating the intent
/// * `to_address` - The Ark address to receive the settled funds
///
/// # Returns
///
/// Returns the estimated fee as a [`SignedAmount`]. This fee will be deducted from
/// the total available balance when joining the actual batch.
///
/// # Errors
///
/// Returns an error if:
/// - Failed to fetch VTXOs or boarding inputs
/// - Failed to communicate with the Ark server
pub async fn estimate_batch_fees<R>(
&self,
rng: &mut R,
to_address: ArkAddress,
) -> Result<SignedAmount, Error>
where
R: Rng + CryptoRng + Clone,
{
let (boarding_inputs, vtxo_inputs, total_amount) = self
.fetch_commitment_transaction_inputs(crate::utils::unix_now()?)
.await?;
tracing::info!(
%to_address,
gross_amount = %total_amount,
?boarding_inputs,
"Estimating fee to board outputs"
);
let intent = self.prepare_intent(
&mut rng.clone(),
boarding_inputs,
vtxo_inputs,
BatchOutputType::Board {
to_address,
to_amount: total_amount,
},
batch::PrepareIntentKind::EstimateFee,
)?;
let amount = self.network_client().estimate_fees(intent.intent).await?;
Ok(amount)
}
/// Estimates the fee to collaboratively redeem specific VTXOs to an on-chain Bitcoin address.
///
/// This function is similar to [`estimate_onchain_fees`](Self::estimate_onchain_fees), but
/// allows you to specify exactly which VTXOs to use as inputs instead of using automatic
/// coin selection. This is useful when you want to estimate fees for redeeming specific
/// UTXOs.
///
/// # Arguments
///
/// * `rng` - A random number generator for creating the intent
/// * `input_vtxos` - An iterator of [`OutPoint`]s specifying which VTXOs to use as inputs
/// * `to_address` - The on-chain Bitcoin address to send funds to
/// * `to_amount` - The amount to send to the destination address
///
/// # Returns
///
/// Returns the estimated fee as a [`SignedAmount`]. The fee will be deducted from
/// the total input amount, with any remainder going to change.
///
/// # Errors
///
/// Returns an error if:
/// - No matching VTXO outpoints are found
/// - The total input amount is insufficient for the requested amount plus fees
/// - Failed to fetch VTXOs
/// - Failed to communicate with the Ark server
pub async fn estimate_onchain_fees_vtxo_selection<R>(
&self,
rng: &mut R,
input_vtxos: impl Iterator<Item = OutPoint> + Clone,
to_address: Address,
to_amount: Amount,
) -> Result<SignedAmount, Error>
where
R: Rng + CryptoRng + Clone,
{
let (change_address, _) = self.get_offchain_address()?;
let vtxo_inputs = self
.selected_batch_settleable_vtxo_inputs(input_vtxos)
.await?;
if vtxo_inputs.is_empty() {
return Err(Error::ad_hoc("no matching VTXO outpoints found"));
}
let total_input_amount = vtxo_inputs
.iter()
.fold(Amount::ZERO, |acc, vtxo| acc + vtxo.amount());
let change_amount = total_input_amount.checked_sub(to_amount).ok_or_else(|| {
Error::coin_select(format!(
"cannot afford to send {to_amount}, only have {total_input_amount}"
))
})?;
tracing::info!(
%to_address,
%to_amount,
%total_input_amount,
change_address = %change_address.encode(),
%change_amount,
num_vtxos = vtxo_inputs.len(),
"Estimating fee to collaboratively redeem selected VTXOs"
);
let intent = self.prepare_intent(
&mut rng.clone(),
vec![], // No boarding inputs when using specific VTXOs
vtxo_inputs,
BatchOutputType::OffBoard {
to_address,
to_amount,
change_address,
change_amount,
},
batch::PrepareIntentKind::EstimateFee,
)?;
let amount = self.network_client().estimate_fees(intent.intent).await?;
Ok(amount)
}
/// Estimates the fee to join the next batch with specific VTXOs and settle to an Ark address.
///
/// This function is similar to [`estimate_batch_fees`](Self::estimate_batch_fees), but allows
/// you to specify exactly which VTXOs to use as inputs instead of using all available VTXOs.
/// This is useful when you want to estimate fees for settling specific UTXOs into fresh VTXOs.
///
/// # Arguments
///
/// * `rng` - A random number generator for creating the intent
/// * `input_vtxos` - An iterator of [`OutPoint`]s specifying which VTXOs to use as inputs
/// * `to_address` - The Ark address to receive the settled funds
///
/// # Returns
///
/// Returns the estimated fee as a [`SignedAmount`]. The fee will be deducted from
/// the total input amount when joining the actual batch.
///
/// # Errors
///
/// Returns an error if:
/// - No matching VTXO outpoints are found
/// - Failed to fetch VTXOs
/// - Failed to communicate with the Ark server
pub async fn estimate_batch_fees_vtxo_selection<R>(
&self,
rng: &mut R,
input_vtxos: impl Iterator<Item = OutPoint> + Clone,
to_address: ArkAddress,
) -> Result<SignedAmount, Error>
where
R: Rng + CryptoRng + Clone,
{
let vtxo_inputs = self
.selected_batch_settleable_vtxo_inputs(input_vtxos)
.await?;
if vtxo_inputs.is_empty() {
return Err(Error::ad_hoc("no matching VTXO outpoints found"));
}
let total_input_amount = vtxo_inputs
.iter()
.fold(Amount::ZERO, |acc, vtxo| acc + vtxo.amount());
tracing::info!(
%to_address,
%total_input_amount,
num_vtxos = vtxo_inputs.len(),
"Estimating fee to settle selected VTXOs"
);
let intent = self.prepare_intent(
&mut rng.clone(),
vec![], // No boarding inputs when using specific VTXOs
vtxo_inputs,
BatchOutputType::Board {
to_address,
to_amount: total_input_amount,
},
batch::PrepareIntentKind::EstimateFee,
)?;
let amount = self.network_client().estimate_fees(intent.intent).await?;
Ok(amount)
}
}