[−][src]Module bdk::wallet::coin_selection
Coin selection
This module provides the trait CoinSelectionAlgorithm
that can be implemented to
define custom coin selection algorithms.
The coin selection algorithm is not globally part of a Wallet
, instead it
is selected whenever a Wallet::create_tx
call is made, through
the use of the TxBuilder
structure, specifically with
TxBuilder::coin_selection
method.
The DefaultCoinSelectionAlgorithm
selects the default coin selection algorithm that
TxBuilder
uses, if it's not explicitly overridden.
Example
#[derive(Debug)] struct AlwaysSpendEverything; impl CoinSelectionAlgorithm for AlwaysSpendEverything { fn coin_select( &self, utxos: Vec<UTXO>, _use_all_utxos: bool, fee_rate: FeeRate, amount_needed: u64, input_witness_weight: usize, fee_amount: f32, ) -> Result<CoinSelectionResult, bdk::Error> { let selected_amount = utxos.iter().fold(0, |acc, utxo| acc + utxo.txout.value); let all_utxos_selected = utxos .into_iter() .map(|utxo| { ( TxIn { previous_output: utxo.outpoint, ..Default::default() }, utxo.txout.script_pubkey, ) }) .collect::<Vec<_>>(); let additional_weight = all_utxos_selected.iter().fold(0, |acc, (txin, _)| { acc + serialize(txin).len() * 4 + input_witness_weight }); let additional_fees = additional_weight as f32 * fee_rate.as_sat_vb() / 4.0; if (fee_amount + additional_fees).ceil() as u64 + amount_needed > selected_amount { return Err(bdk::Error::InsufficientFunds); } Ok(CoinSelectionResult { txin: all_utxos_selected, selected_amount, fee_amount: fee_amount + additional_fees, }) } } // create wallet, sync, ... let to_address = Address::from_str("2N4eQYCbKUHCCTUjBJeHcJp9ok6J2GZsTDt").unwrap(); let (psbt, details) = wallet.create_tx( TxBuilder::with_recipients(vec![(to_address.script_pubkey(), 50_000)]) .coin_selection(AlwaysSpendEverything), )?; // inspect, sign, broadcast, ...
Structs
CoinSelectionResult | Result of a successful coin selection |
DumbCoinSelection | Simple and dumb coin selection |
Traits
CoinSelectionAlgorithm | Trait for generalized coin selection algorithms |
Type Definitions
DefaultCoinSelectionAlgorithm | Default coin selection algorithm used by |