Skip to content

Instantly share code, notes, and snippets.

@danielabrozzoni
Created July 4, 2023 22:14
Show Gist options
  • Save danielabrozzoni/20e22d4842ff924a0996d395ca06f626 to your computer and use it in GitHub Desktop.
Save danielabrozzoni/20e22d4842ff924a0996d395ca06f626 to your computer and use it in GitHub Desktop.
Cubo+ BDK example
use bdk::{Wallet, SyncOptions, FeeRate, SignOptions};
use bdk::wallet::AddressIndex;
use bdk::database::MemoryDatabase;
use bdk::blockchain::ElectrumBlockchain;
use bdk::electrum_client::Client;
use bdk::bitcoin::{self, Address};
use std::str::FromStr;
use bdk::blockchain::Blockchain;
fn main() -> Result<(), bdk::Error> {
// Create the wallet
let wallet = Wallet::new(
"tr(tprv8ZgxMBicQKsPdaBPm4xUDLQCNujS9gh8EnEY8j9jCh5VRV1YUjJFphfRoCAmcE6uC1m3S7ZPejG1DkDsfS3YhbRbi2kTThxzsSFyQEqbFGA/*)",
None,
bitcoin::Network::Testnet,
MemoryDatabase::default(),
)?;
// Generate an address
let address = wallet.get_address(AddressIndex::New)?;
println!("This is your wallet address: {}", address);
let client = Client::new("ssl://electrum.blockstream.info:60002")?;
let blockchain = ElectrumBlockchain::from(client);
wallet.sync(&blockchain, SyncOptions::default())?;
// Receive money (= going on a faucet and pasting the address)
// on a single sig BIP32 wallet
// We did it yay
// See the balance
let balance = wallet.get_balance()?;
println!("This is you wallet balance: {:?}", balance);
// Spend everything
// 1. Create a transaction
let mut builder = wallet.build_tx();
let address = Address::from_str("tb1qw2c3lxufxqe2x9s4rdzh65tpf4d7fssjgh8nv6").unwrap();
builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(FeeRate::from_sat_per_vb(2.0))
.enable_rbf();
let (mut psbt, tx_details) = builder.finish()?;
println!("This is our PSBT: {}", psbt);
println!("Details about our transaction: {:?}", tx_details);
// 2. Sign a transaction
let finalized = wallet.sign(&mut psbt, SignOptions::default())?;
println!("Is my psbt final? {}", finalized);
println!("This is our PSBT: {}", psbt);
let tx = psbt.extract_tx();
println!("My Bitcoin transaction: {}", bitcoin::consensus::encode::serialize_hex(&tx));
let txid = tx.txid();
println!("Txid: {}", txid);
// 3. Broadcast the transaction
blockchain.broadcast(&tx)?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment