Skip to content

Commit e50fcb6

Browse files
committed
add esplora_backend example.
1 parent ea2b9f5 commit e50fcb6

File tree

3 files changed

+193
-1
lines changed

3 files changed

+193
-1
lines changed

Cargo.toml

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ bitcoincore-rpc = { version = "0.15", optional = true }
4343

4444
# Platform-specific dependencies
4545
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
46-
tokio = { version = "1", features = ["rt"] }
46+
tokio = { version = "1", features = ["rt", "macros"] }
4747

4848
[target.'cfg(target_arch = "wasm32")'.dependencies]
4949
async-trait = "0.1"
@@ -124,6 +124,16 @@ name = "electrum_backend"
124124
path = "examples/electrum_backend.rs"
125125
required-features = ["electrum"]
126126

127+
[[example]]
128+
name = "esplora_backend_synchronous"
129+
path = "examples/esplora_backend_synchronous.rs"
130+
required-features = ["use-esplora-ureq"]
131+
132+
[[example]]
133+
name = "esplora_backend_asynchronous"
134+
path = "examples/esplora_backend_asynchronous.rs"
135+
required-features = ["use-esplora-reqwest", "reqwest-default-tls", "async-interface"]
136+
127137
[workspace]
128138
members = ["macros"]
129139
[package.metadata.docs.rs]
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
use std::str::FromStr;
2+
3+
use bdk::blockchain::Blockchain;
4+
use bdk::{
5+
blockchain::esplora::EsploraBlockchain,
6+
database::MemoryDatabase,
7+
template::Bip84,
8+
wallet::{export::FullyNodedExport, AddressIndex},
9+
KeychainKind, SyncOptions, Wallet,
10+
};
11+
use bitcoin::{
12+
util::bip32::{self, ExtendedPrivKey},
13+
Network,
14+
};
15+
16+
pub mod utils;
17+
18+
use crate::utils::tx::build_signed_tx;
19+
20+
/// This will create a wallet from an xpriv and get the balance by connecting to an Esplora server,
21+
/// using non blocking asynchronous calls with `reqwest`.
22+
/// If enough amount is available, this will send a transaction to an address.
23+
/// Otherwise, this will display a wallet address to receive funds.
24+
///
25+
/// This can be run with `cargo run --no-default-features --features="use-esplora-reqwest, reqwest-default-tls, async-interface" --example esplora_backend_asynchronous`
26+
/// in the root folder.
27+
#[tokio::main(flavor = "current_thread")]
28+
async fn main() {
29+
let network = Network::Signet;
30+
31+
let xpriv = "tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy";
32+
33+
let esplora_url = "https://explorer.bc-2.jp/api";
34+
35+
run(&network, esplora_url, xpriv).await;
36+
}
37+
38+
fn create_wallet(network: &Network, xpriv: &ExtendedPrivKey) -> Wallet<MemoryDatabase> {
39+
Wallet::new(
40+
Bip84(*xpriv, KeychainKind::External),
41+
Some(Bip84(*xpriv, KeychainKind::Internal)),
42+
*network,
43+
MemoryDatabase::default(),
44+
)
45+
.unwrap()
46+
}
47+
48+
async fn run(network: &Network, esplora_url: &str, xpriv: &str) {
49+
let xpriv = bip32::ExtendedPrivKey::from_str(xpriv).unwrap();
50+
51+
let blockchain = EsploraBlockchain::new(esplora_url, 20);
52+
53+
let wallet = create_wallet(network, &xpriv);
54+
55+
wallet
56+
.sync(&blockchain, SyncOptions::default())
57+
.await
58+
.unwrap();
59+
60+
let address = wallet.get_address(AddressIndex::New).unwrap().address;
61+
62+
println!("address: {}", address);
63+
64+
let balance = wallet.get_balance().unwrap();
65+
66+
println!("Available coins in BDK wallet : {} sats", balance);
67+
68+
if balance.confirmed > 10500 {
69+
// the wallet sends the amount to itself.
70+
let recipient_address = wallet
71+
.get_address(AddressIndex::New)
72+
.unwrap()
73+
.address
74+
.to_string();
75+
76+
let amount = 9359;
77+
78+
let tx = build_signed_tx(&wallet, &recipient_address, amount);
79+
80+
let _ = blockchain.broadcast(&tx);
81+
82+
println!("tx id: {}", tx.txid());
83+
} else {
84+
println!("Insufficient Funds. Fund the wallet with the address above");
85+
}
86+
87+
let export = FullyNodedExport::export_wallet(&wallet, "exported wallet", true)
88+
.map_err(ToString::to_string)
89+
.map_err(bdk::Error::Generic)
90+
.unwrap();
91+
92+
println!("------\nWallet Backup: {}", export.to_string());
93+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
use std::str::FromStr;
2+
3+
use bdk::blockchain::Blockchain;
4+
use bdk::{
5+
blockchain::esplora::EsploraBlockchain,
6+
database::MemoryDatabase,
7+
template::Bip84,
8+
wallet::{export::FullyNodedExport, AddressIndex},
9+
KeychainKind, SyncOptions, Wallet,
10+
};
11+
use bitcoin::{
12+
util::bip32::{self, ExtendedPrivKey},
13+
Network,
14+
};
15+
16+
pub mod utils;
17+
18+
use crate::utils::tx::build_signed_tx;
19+
20+
/// This will create a wallet from an xpriv and get the balance by connecting to an Esplora server,
21+
/// using blocking calls with `ureq`.
22+
/// If enough amount is available, this will send a transaction to an address.
23+
/// Otherwise, this will display a wallet address to receive funds.
24+
///
25+
/// This can be run with `cargo run --features=use-esplora-ureq --example esplora_backend_synchronous`
26+
/// in the root folder.
27+
fn main() {
28+
let network = Network::Signet;
29+
30+
let xpriv = "tprv8ZgxMBicQKsPcx5nBGsR63Pe8KnRUqmbJNENAfGftF3yuXoMMoVJJcYeUw5eVkm9WBPjWYt6HMWYJNesB5HaNVBaFc1M6dRjWSYnmewUMYy";
31+
32+
let esplora_url = "https://explorer.bc-2.jp/api";
33+
34+
run(&network, esplora_url, xpriv);
35+
}
36+
37+
fn create_wallet(network: &Network, xpriv: &ExtendedPrivKey) -> Wallet<MemoryDatabase> {
38+
Wallet::new(
39+
Bip84(*xpriv, KeychainKind::External),
40+
Some(Bip84(*xpriv, KeychainKind::Internal)),
41+
*network,
42+
MemoryDatabase::default(),
43+
)
44+
.unwrap()
45+
}
46+
47+
fn run(network: &Network, esplora_url: &str, xpriv: &str) {
48+
let xpriv = bip32::ExtendedPrivKey::from_str(xpriv).unwrap();
49+
50+
let blockchain = EsploraBlockchain::new(esplora_url, 20);
51+
52+
let wallet = create_wallet(network, &xpriv);
53+
54+
wallet.sync(&blockchain, SyncOptions::default()).unwrap();
55+
56+
let address = wallet.get_address(AddressIndex::New).unwrap().address;
57+
58+
println!("address: {}", address);
59+
60+
let balance = wallet.get_balance().unwrap();
61+
62+
println!("Available coins in BDK wallet : {} sats", balance);
63+
64+
if balance.confirmed > 10500 {
65+
// the wallet sends the amount to itself.
66+
let recipient_address = wallet
67+
.get_address(AddressIndex::New)
68+
.unwrap()
69+
.address
70+
.to_string();
71+
72+
let amount = 9359;
73+
74+
let tx = build_signed_tx(&wallet, &recipient_address, amount);
75+
76+
blockchain.broadcast(&tx).unwrap();
77+
78+
println!("tx id: {}", tx.txid());
79+
} else {
80+
println!("Insufficient Funds. Fund the wallet with the address above");
81+
}
82+
83+
let export = FullyNodedExport::export_wallet(&wallet, "exported wallet", true)
84+
.map_err(ToString::to_string)
85+
.map_err(bdk::Error::Generic)
86+
.unwrap();
87+
88+
println!("------\nWallet Backup: {}", export.to_string());
89+
}

0 commit comments

Comments
 (0)