bdkffi/tx_builder.rs
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 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
use crate::bitcoin::{Amount, FeeRate, Input, OutPoint, Psbt, Script, Txid};
use crate::error::{AddForeignUtxoError, CreateTxError};
use crate::types::{LockTime, ScriptAmount};
use crate::wallet::Wallet;
use bdk_wallet::bitcoin::absolute::LockTime as BdkLockTime;
use bdk_wallet::bitcoin::amount::Amount as BdkAmount;
use bdk_wallet::bitcoin::psbt::Input as BdkInput;
use bdk_wallet::bitcoin::script::PushBytesBuf;
use bdk_wallet::bitcoin::Psbt as BdkPsbt;
use bdk_wallet::bitcoin::ScriptBuf as BdkScriptBuf;
use bdk_wallet::bitcoin::{OutPoint as BdkOutPoint, Sequence, Weight as BdkWeight};
use bdk_wallet::KeychainKind;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::sync::Arc;
type ChangeSpendPolicy = bdk_wallet::ChangeSpendPolicy;
/// A `TxBuilder` is created by calling `build_tx` on a wallet. After assigning it, you set options on it until finally
/// calling `finish` to consume the builder and generate the transaction.
#[derive(Clone, uniffi::Object)]
pub struct TxBuilder {
add_global_xpubs: bool,
recipients: Vec<(BdkScriptBuf, BdkAmount)>,
utxos: Vec<BdkOutPoint>,
unspendable: Vec<BdkOutPoint>,
internal_policy_path: Option<BTreeMap<String, Vec<usize>>>,
external_policy_path: Option<BTreeMap<String, Vec<usize>>>,
change_policy: ChangeSpendPolicy,
manually_selected_only: bool,
fee_rate: Option<FeeRate>,
fee_absolute: Option<Arc<Amount>>,
drain_wallet: bool,
drain_to: Option<BdkScriptBuf>,
sequence: Option<u32>,
data: Vec<u8>,
current_height: Option<u32>,
locktime: Option<LockTime>,
allow_dust: bool,
version: Option<i32>,
exclude_unconfirmed: bool,
exclude_below_confirmations: Option<u32>,
only_witness_utxo: bool,
foreign_utxos: Vec<(BdkOutPoint, BdkInput, BdkWeight)>,
}
#[allow(clippy::new_without_default)]
#[uniffi::export]
impl TxBuilder {
#[uniffi::constructor]
pub fn new() -> Self {
TxBuilder {
add_global_xpubs: false,
recipients: Vec::new(),
utxos: Vec::new(),
unspendable: Vec::new(),
internal_policy_path: None,
external_policy_path: None,
change_policy: ChangeSpendPolicy::ChangeAllowed,
manually_selected_only: false,
fee_rate: None,
fee_absolute: None,
drain_wallet: false,
drain_to: None,
sequence: None,
data: Vec::new(),
current_height: None,
locktime: None,
allow_dust: false,
version: None,
exclude_unconfirmed: false,
exclude_below_confirmations: None,
only_witness_utxo: false,
foreign_utxos: Vec::new(),
}
}
/// Fill-in the `PSBT_GLOBAL_XPUB` field with the extended keys contained in both the external and internal
/// descriptors.
///
/// This is useful for offline signers that take part to a multisig. Some hardware wallets like BitBox and ColdCard
/// are known to require this.
pub fn add_global_xpubs(&self) -> Arc<Self> {
Arc::new(TxBuilder {
add_global_xpubs: true,
..self.clone()
})
}
/// Exclude outpoints whose enclosing transaction is unconfirmed.
/// This is a shorthand for exclude_below_confirmations(1).
pub fn exclude_unconfirmed(&self) -> Arc<Self> {
Arc::new(TxBuilder {
exclude_unconfirmed: true,
..self.clone()
})
}
/// Excludes any outpoints whose enclosing transaction has fewer than `min_confirms`
/// confirmations.
///
/// `min_confirms` is the minimum number of confirmations a transaction must have in order for
/// its outpoints to remain spendable.
/// - Passing `0` will include all transactions (no filtering).
/// - Passing `1` will exclude all unconfirmed transactions (equivalent to
/// `exclude_unconfirmed`).
/// - Passing `6` will only allow outpoints from transactions with at least 6 confirmations.
///
/// If you chain this with other filtering methods, the final set of unspendable outpoints will
/// be the union of all filters.
pub fn exclude_below_confirmations(&self, min_confirms: u32) -> Arc<Self> {
Arc::new(TxBuilder {
exclude_below_confirmations: Some(min_confirms),
..self.clone()
})
}
/// Add a recipient to the internal list of recipients.
pub fn add_recipient(&self, script: &Script, amount: Arc<Amount>) -> Arc<Self> {
let mut recipients: Vec<(BdkScriptBuf, BdkAmount)> = self.recipients.clone();
recipients.append(&mut vec![(script.0.clone(), amount.0)]);
Arc::new(TxBuilder {
recipients,
..self.clone()
})
}
/// Replace the recipients already added with a new list of recipients.
pub fn set_recipients(&self, recipients: Vec<ScriptAmount>) -> Arc<Self> {
let recipients = recipients
.iter()
.map(|script_amount| (script_amount.script.0.clone(), script_amount.amount.0)) //;
.collect();
Arc::new(TxBuilder {
recipients,
..self.clone()
})
}
/// Add a utxo to the internal list of unspendable utxos.
///
/// It’s important to note that the "must-be-spent" utxos added with `TxBuilder::add_utxo` have priority over this.
pub fn add_unspendable(&self, unspendable: OutPoint) -> Arc<Self> {
let mut unspendable_vec: Vec<BdkOutPoint> = self.unspendable.clone();
unspendable_vec.push(unspendable.into());
Arc::new(TxBuilder {
unspendable: unspendable_vec,
..self.clone()
})
}
/// Replace the internal list of unspendable utxos with a new list.
///
/// It’s important to note that the "must-be-spent" utxos added with `TxBuilder::add_utxo` have priority over these.
pub fn unspendable(&self, unspendable: Vec<OutPoint>) -> Arc<Self> {
let new_unspendable_vec: Vec<BdkOutPoint> =
unspendable.into_iter().map(BdkOutPoint::from).collect();
Arc::new(TxBuilder {
unspendable: new_unspendable_vec,
..self.clone()
})
}
/// Add a utxo to the internal list of utxos that must be spent.
///
/// These have priority over the "unspendable" utxos, meaning that if a utxo is present both in the "utxos" and the
/// "unspendable" list, it will be spent.
pub fn add_utxo(&self, outpoint: OutPoint) -> Arc<Self> {
self.add_utxos(vec![outpoint])
}
/// Add the list of outpoints to the internal list of UTXOs that must be spent.
//
// If an error occurs while adding any of the UTXOs then none of them are added and the error is returned.
//
// These have priority over the “unspendable” utxos, meaning that if a utxo is present both in the “utxos” and the “unspendable” list, it will be spent.
pub fn add_utxos(&self, outpoints: Vec<OutPoint>) -> Arc<Self> {
let mut utxos: Vec<BdkOutPoint> = self.utxos.clone();
utxos.extend(outpoints.into_iter().map(BdkOutPoint::from));
Arc::new(TxBuilder {
utxos,
..self.clone()
})
}
/// The TxBuilder::policy_path is a complex API. See the Rust docs for complete information: https://docs.rs/bdk_wallet/latest/bdk_wallet/struct.TxBuilder.html#method.policy_path
pub fn policy_path(
&self,
policy_path: HashMap<String, Vec<u64>>,
keychain: KeychainKind,
) -> Arc<Self> {
let mut updated_self = self.clone();
let to_update = match keychain {
KeychainKind::Internal => &mut updated_self.internal_policy_path,
KeychainKind::External => &mut updated_self.external_policy_path,
};
*to_update = Some(
policy_path
.into_iter()
.map(|(key, value)| (key, value.into_iter().map(|x| x as usize).collect()))
.collect::<BTreeMap<String, Vec<usize>>>(),
);
Arc::new(updated_self)
}
/// Set a specific `ChangeSpendPolicy`. See `TxBuilder::do_not_spend_change` and `TxBuilder::only_spend_change` for
/// some shortcuts. This method assumes the presence of an internal keychain, otherwise it has no effect.
pub fn change_policy(&self, change_policy: ChangeSpendPolicy) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy,
..self.clone()
})
}
/// Do not spend change outputs.
///
/// This effectively adds all the change outputs to the "unspendable" list. See `TxBuilder::unspendable`. This method
/// assumes the presence of an internal keychain, otherwise it has no effect.
pub fn do_not_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::ChangeForbidden,
..self.clone()
})
}
/// Only spend change outputs.
///
/// This effectively adds all the non-change outputs to the "unspendable" list. See `TxBuilder::unspendable`. This
/// method assumes the presence of an internal keychain, otherwise it has no effect.
pub fn only_spend_change(&self) -> Arc<Self> {
Arc::new(TxBuilder {
change_policy: ChangeSpendPolicy::OnlyChange,
..self.clone()
})
}
/// Only spend utxos added by `TxBuilder::add_utxo`.
///
/// The wallet will not add additional utxos to the transaction even if they are needed to make the transaction valid.
pub fn manually_selected_only(&self) -> Arc<Self> {
Arc::new(TxBuilder {
manually_selected_only: true,
..self.clone()
})
}
/// Set a custom fee rate.
///
/// This method sets the mining fee paid by the transaction as a rate on its size. This means that the total fee paid
/// is equal to fee_rate times the size of the transaction. Default is 1 sat/vB in accordance with Bitcoin Core’s
/// default relay policy.
///
/// Note that this is really a minimum feerate – it’s possible to overshoot it slightly since adding a change output
/// to drain the remaining excess might not be viable.
pub fn fee_rate(&self, fee_rate: &FeeRate) -> Arc<Self> {
Arc::new(TxBuilder {
fee_rate: Some(fee_rate.clone()),
..self.clone()
})
}
/// Set an absolute fee The `fee_absolute` method refers to the absolute transaction fee in `Amount`. If anyone sets
/// both the `fee_absolute` method and the `fee_rate` method, the `FeePolicy` enum will be set by whichever method was
/// called last, as the `FeeRate` and `FeeAmount` are mutually exclusive.
///
/// Note that this is really a minimum absolute fee – it’s possible to overshoot it slightly since adding a change output to drain the remaining excess might not be viable.
pub fn fee_absolute(&self, fee_amount: Arc<Amount>) -> Arc<Self> {
Arc::new(TxBuilder {
fee_absolute: Some(fee_amount),
..self.clone()
})
}
/// Spend all the available inputs. This respects filters like `TxBuilder::unspendable` and the change policy.
pub fn drain_wallet(&self) -> Arc<Self> {
Arc::new(TxBuilder {
drain_wallet: true,
..self.clone()
})
}
/// Sets the address to drain excess coins to.
///
/// Usually, when there are excess coins they are sent to a change address generated by the wallet. This option
/// replaces the usual change address with an arbitrary script_pubkey of your choosing. Just as with a change output,
/// if the drain output is not needed (the excess coins are too small) it will not be included in the resulting
/// transaction. The only difference is that it is valid to use `drain_to` without setting any ordinary recipients
/// with `add_recipient` (but it is perfectly fine to add recipients as well).
///
/// If you choose not to set any recipients, you should provide the utxos that the transaction should spend via
/// `add_utxos`. `drain_to` is very useful for draining all the coins in a wallet with `drain_wallet` to a single
/// address.
pub fn drain_to(&self, script: &Script) -> Arc<Self> {
Arc::new(TxBuilder {
drain_to: Some(script.0.clone()),
..self.clone()
})
}
/// Set an exact `nSequence` value.
///
/// This can cause conflicts if the wallet’s descriptors contain an "older" (`OP_CSV`) operator and the given
/// `nsequence` is lower than the CSV value.
pub fn set_exact_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(TxBuilder {
sequence: Some(nsequence),
..self.clone()
})
}
/// Add data as an output using `OP_RETURN`.
pub fn add_data(&self, data: Vec<u8>) -> Arc<Self> {
Arc::new(TxBuilder {
data,
..self.clone()
})
}
/// Set the current blockchain height.
///
/// This will be used to:
///
/// 1. Set the `nLockTime` for preventing fee sniping. Note: This will be ignored if you manually specify a
/// `nlocktime` using `TxBuilder::nlocktime`.
///
/// 2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at `current_height`,
/// we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs,
/// manually add them using `TxBuilder::add_utxos`.
/// In both cases, if you don’t provide a current height, we use the last sync height.
pub fn current_height(&self, height: u32) -> Arc<Self> {
Arc::new(TxBuilder {
current_height: Some(height),
..self.clone()
})
}
/// Use a specific nLockTime while creating the transaction.
///
/// This can cause conflicts if the wallet’s descriptors contain an "after" (`OP_CLTV`) operator.
pub fn nlocktime(&self, locktime: LockTime) -> Arc<Self> {
Arc::new(TxBuilder {
locktime: Some(locktime),
..self.clone()
})
}
/// Set whether or not the dust limit is checked.
///
/// Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.
pub fn allow_dust(&self, allow_dust: bool) -> Arc<Self> {
Arc::new(TxBuilder {
allow_dust,
..self.clone()
})
}
/// Build a transaction with a specific version.
///
/// The version should always be greater than 0 and greater than 1 if the wallet's descriptors contain an "older"
/// (`OP_CSV`) operator.
pub fn version(&self, version: i32) -> Arc<Self> {
Arc::new(TxBuilder {
version: Some(version),
..self.clone()
})
}
/// Only Fill-in the [`psbt::Input::witness_utxo`](bitcoin::psbt::Input::witness_utxo) field
/// when spending from SegWit descriptors.
///
/// This reduces the size of the PSBT, but some signers might reject them due to the lack of
/// the `non_witness_utxo`.
pub fn only_witness_utxo(&self) -> Arc<Self> {
Arc::new(TxBuilder {
only_witness_utxo: true,
..self.clone()
})
}
/// Add a foreign UTXO i.e. a UTXO not known by this wallet.
///
/// Foreign UTXOs are not prioritized over local UTXOs. If a local UTXO is added to the
/// manually selected list, it will replace any conflicting foreign UTXOs. However, a foreign
/// UTXO cannot replace a conflicting local UTXO.
///
/// There might be cases where the UTXO belongs to the wallet but it doesn't have knowledge of
/// it. This is possible if the wallet is not synced or its not being use to track
/// transactions. In those cases is the responsibility of the user to add any possible local
/// UTXOs through the [`TxBuilder::add_utxo`] method.
/// A manually added local UTXO will always have greater precedence than a foreign UTXO. No
/// matter if it was added before or after the foreign UTXO.
///
/// At a minimum to add a foreign UTXO we need:
///
/// 1. `outpoint`: To add it to the raw transaction.
/// 2. `psbt_input`: To know the value.
/// 3. `satisfaction_weight`: To know how much weight/vbytes the input will add to the
/// transaction for fee calculation.
///
/// There are several security concerns about adding foreign UTXOs that application
/// developers should consider. First, how do you know the value of the input is correct? If a
/// `non_witness_utxo` is provided in the `psbt_input` then this method implicitly verifies the
/// value by checking it against the transaction. If only a `witness_utxo` is provided then this
/// method doesn't verify the value but just takes it as a given -- it is up to you to check
/// that whoever sent you the `input_psbt` was not lying!
///
/// Secondly, you must somehow provide `satisfaction_weight` of the input. Depending on your
/// application it may be important that this be known precisely. If not, a malicious
/// counterparty may fool you into putting in a value that is too low, giving the transaction a
/// lower than expected feerate. They could also fool you into putting a value that is too high
/// causing you to pay a fee that is too high. The party who is broadcasting the transaction can
/// of course check the real input weight matches the expected weight prior to broadcasting.
///
/// To guarantee the `max_weight_to_satisfy` is correct, you can require the party providing the
/// `psbt_input` provide a miniscript descriptor for the input so you can check it against the
/// `script_pubkey` and then ask it for the [`max_weight_to_satisfy`].
///
/// This is an **EXPERIMENTAL** feature, API and other major changes are expected.
///
/// In order to use [`Wallet::calculate_fee`] or [`Wallet::calculate_fee_rate`] for a
/// transaction created with foreign UTXO(s) you must manually insert the corresponding
/// TxOut(s) into the tx graph using the [`Wallet::insert_txout`] function.
///
/// # Errors
///
/// This method returns errors in the following circumstances:
///
/// 1. The `psbt_input` does not contain a `witness_utxo` or `non_witness_utxo`.
/// 2. The data in `non_witness_utxo` does not match what is in `outpoint`.
///
/// Note unless you set [`only_witness_utxo`] any non-taproot `psbt_input` you pass to this
/// method must have `non_witness_utxo` set otherwise you will get an error when [`finish`]
/// is called.
///
/// [`only_witness_utxo`]: Self::only_witness_utxo
/// [`finish`]: Self::finish
/// [`max_weight_to_satisfy`]: miniscript::Descriptor::max_weight_to_satisfy
pub fn add_foreign_utxo(
&self,
outpoint: OutPoint,
psbt_input: Input,
satisfaction_weight: u64,
) -> Result<Arc<Self>, AddForeignUtxoError> {
let bdk_outpoint: BdkOutPoint = outpoint.into();
let bdk_input: BdkInput = psbt_input.try_into()?;
let bdk_weight = BdkWeight::from_wu(satisfaction_weight);
let mut foreign_utxos = self.foreign_utxos.clone();
foreign_utxos.push((bdk_outpoint, bdk_input, bdk_weight));
Ok(Arc::new(TxBuilder {
foreign_utxos,
..self.clone()
}))
}
/// Finish building the transaction.
///
/// Uses the thread-local random number generator (rng).
///
/// Returns a new `Psbt` per BIP174.
///
/// WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this
/// method before closing the wallet. See `Wallet::reveal_next_address`.
pub fn finish(&self, wallet: &Arc<Wallet>) -> Result<Arc<Psbt>, CreateTxError> {
// TODO: I had to change the wallet here to be mutable. Why is that now required with the 1.0 API?
let mut wallet = wallet.get_wallet();
let mut tx_builder = wallet.build_tx();
if self.add_global_xpubs {
tx_builder.add_global_xpubs();
}
for (script, amount) in &self.recipients {
tx_builder.add_recipient(script.clone(), *amount);
}
if let Some(policy_path) = &self.external_policy_path {
tx_builder.policy_path(policy_path.clone(), KeychainKind::External);
}
if let Some(policy_path) = &self.internal_policy_path {
tx_builder.policy_path(policy_path.clone(), KeychainKind::Internal);
}
tx_builder.change_policy(self.change_policy);
if !self.utxos.is_empty() {
tx_builder
.add_utxos(&self.utxos)
.map_err(CreateTxError::from)?;
}
if !self.unspendable.is_empty() {
tx_builder.unspendable(self.unspendable.clone());
}
if self.manually_selected_only {
tx_builder.manually_selected_only();
}
if let Some(fee_rate) = &self.fee_rate {
tx_builder.fee_rate(fee_rate.0);
}
if let Some(fee_amount) = &self.fee_absolute {
tx_builder.fee_absolute(fee_amount.0);
}
if self.drain_wallet {
tx_builder.drain_wallet();
}
if let Some(script) = &self.drain_to {
tx_builder.drain_to(script.clone());
}
if let Some(sequence) = self.sequence {
tx_builder.set_exact_sequence(Sequence(sequence));
}
if !&self.data.is_empty() {
let push_bytes = PushBytesBuf::try_from(self.data.clone())?;
tx_builder.add_data(&push_bytes);
}
if let Some(height) = self.current_height {
tx_builder.current_height(height);
}
if let Some(locktime) = &self.locktime {
let bdk_locktime: BdkLockTime = locktime.try_into()?;
tx_builder.nlocktime(bdk_locktime);
}
if self.allow_dust {
tx_builder.allow_dust(self.allow_dust);
}
if let Some(version) = self.version {
tx_builder.version(version);
}
if self.exclude_unconfirmed {
tx_builder.exclude_unconfirmed();
}
if let Some(min_confirms) = self.exclude_below_confirmations {
tx_builder.exclude_below_confirmations(min_confirms);
}
if self.only_witness_utxo {
tx_builder.only_witness_utxo();
}
for (outpoint, input, weight) in &self.foreign_utxos {
tx_builder
.add_foreign_utxo(*outpoint, input.clone(), *weight)
.map_err(AddForeignUtxoError::from)?;
}
let psbt = tx_builder.finish().map_err(CreateTxError::from)?;
Ok(Arc::new(psbt.into()))
}
}
/// A `BumpFeeTxBuilder` is created by calling `build_fee_bump` on a wallet. After assigning it, you set options on it
/// until finally calling `finish` to consume the builder and generate the transaction.
#[derive(Clone, uniffi::Object)]
pub struct BumpFeeTxBuilder {
txid: Arc<Txid>,
fee_rate: Arc<FeeRate>,
sequence: Option<u32>,
current_height: Option<u32>,
locktime: Option<LockTime>,
allow_dust: bool,
version: Option<i32>,
}
#[uniffi::export]
impl BumpFeeTxBuilder {
#[uniffi::constructor]
pub fn new(txid: Arc<Txid>, fee_rate: Arc<FeeRate>) -> Self {
BumpFeeTxBuilder {
txid,
fee_rate,
sequence: None,
current_height: None,
locktime: None,
allow_dust: false,
version: None,
}
}
/// Set an exact `nSequence` value.
///
/// This can cause conflicts if the wallet’s descriptors contain an "older" (`OP_CSV`) operator and the given
/// `nsequence` is lower than the CSV value.
pub fn set_exact_sequence(&self, nsequence: u32) -> Arc<Self> {
Arc::new(BumpFeeTxBuilder {
sequence: Some(nsequence),
..self.clone()
})
}
/// Set the current blockchain height.
///
/// This will be used to:
///
/// 1. Set the `nLockTime` for preventing fee sniping. Note: This will be ignored if you manually specify a
/// `nlocktime` using `TxBuilder::nlocktime`.
///
/// 2. Decide whether coinbase outputs are mature or not. If the coinbase outputs are not mature at `current_height`,
/// we ignore them in the coin selection. If you want to create a transaction that spends immature coinbase inputs,
/// manually add them using `TxBuilder::add_utxos`.
/// In both cases, if you don’t provide a current height, we use the last sync height.
pub fn current_height(&self, height: u32) -> Arc<Self> {
Arc::new(BumpFeeTxBuilder {
current_height: Some(height),
..self.clone()
})
}
/// Use a specific nLockTime while creating the transaction.
///
/// This can cause conflicts if the wallet’s descriptors contain an "after" (`OP_CLTV`) operator.
pub fn nlocktime(&self, locktime: LockTime) -> Arc<Self> {
Arc::new(BumpFeeTxBuilder {
locktime: Some(locktime),
..self.clone()
})
}
/// Set whether the dust limit is checked.
///
/// Note: by avoiding a dust limit check you may end up with a transaction that is non-standard.
pub fn allow_dust(&self, allow_dust: bool) -> Arc<Self> {
Arc::new(BumpFeeTxBuilder {
allow_dust,
..self.clone()
})
}
/// Build a transaction with a specific version.
///
/// The version should always be greater than 0 and greater than 1 if the wallet’s descriptors contain an "older"
/// (`OP_CSV`) operator.
pub fn version(&self, version: i32) -> Arc<Self> {
Arc::new(BumpFeeTxBuilder {
version: Some(version),
..self.clone()
})
}
/// Finish building the transaction.
///
/// Uses the thread-local random number generator (rng).
///
/// Returns a new `Psbt` per BIP174.
///
/// WARNING: To avoid change address reuse you must persist the changes resulting from one or more calls to this
/// method before closing the wallet. See `Wallet::reveal_next_address`.
pub fn finish(&self, wallet: &Arc<Wallet>) -> Result<Arc<Psbt>, CreateTxError> {
let mut wallet = wallet.get_wallet();
let mut tx_builder = wallet
.build_fee_bump(self.txid.0)
.map_err(CreateTxError::from)?;
tx_builder.fee_rate(self.fee_rate.0);
if let Some(sequence) = self.sequence {
tx_builder.set_exact_sequence(Sequence(sequence));
}
if let Some(height) = self.current_height {
tx_builder.current_height(height);
}
if let Some(locktime) = &self.locktime {
let bdk_locktime: BdkLockTime = locktime.try_into()?;
tx_builder.nlocktime(bdk_locktime);
}
if self.allow_dust {
tx_builder.allow_dust(self.allow_dust);
}
if let Some(version) = self.version {
tx_builder.version(version);
}
let psbt: BdkPsbt = tx_builder.finish()?;
Ok(Arc::new(psbt.into()))
}
}
/// Policy regarding the use of change outputs when creating a transaction.
#[uniffi::remote(Enum)]
pub enum ChangeSpendPolicy {
/// Use both change and non-change outputs (default).
#[default]
ChangeAllowed,
/// Only use change outputs (see [`bdk_wallet::TxBuilder::only_spend_change`]).
OnlyChange,
/// Only use non-change outputs (see [`bdk_wallet::TxBuilder::do_not_spend_change`]).
ChangeForbidden,
}