Skip to main content

smplx_sdk/provider/
core.rs

1use std::collections::HashMap;
2
3use electrsd::bitcoind::bitcoincore_rpc::Auth;
4
5use simplicityhl::elements::{Address, Script, Transaction, Txid};
6
7use crate::provider::SimplicityNetwork;
8use crate::transaction::UTXO;
9
10use super::error::ProviderError;
11
12pub const DEFAULT_FEE_RATE: f32 = 100.0;
13pub const DEFAULT_ESPLORA_TIMEOUT_SECS: u64 = 10;
14
15#[derive(Debug, Clone)]
16pub struct ProviderInfo {
17    pub esplora_url: String,
18    pub elements_url: Option<String>,
19    pub auth: Option<Auth>,
20}
21
22pub trait ProviderTrait {
23    fn get_network(&self) -> &SimplicityNetwork;
24
25    fn broadcast_transaction(&self, tx: &Transaction) -> Result<Txid, ProviderError>;
26
27    fn wait(&self, txid: &Txid) -> Result<(), ProviderError>;
28
29    fn fetch_tip_height(&self) -> Result<u32, ProviderError>;
30
31    fn fetch_tip_timestamp(&self) -> Result<u64, ProviderError>;
32
33    fn fetch_transaction(&self, txid: &Txid) -> Result<Transaction, ProviderError>;
34
35    fn fetch_address_utxos(&self, address: &Address) -> Result<Vec<UTXO>, ProviderError>;
36
37    fn fetch_scripthash_utxos(&self, script: &Script) -> Result<Vec<UTXO>, ProviderError>;
38
39    fn fetch_fee_estimates(&self) -> Result<HashMap<String, f64>, ProviderError>;
40
41    fn fetch_fee_rate(&self, target_blocks: u32) -> Result<f32, ProviderError> {
42        let estimates = self.fetch_fee_estimates()?;
43        let target_str = target_blocks.to_string();
44
45        if let Some(&rate) = estimates.get(&target_str) {
46            return Ok((rate * 1000.0) as f32); // Convert sat/vB to sats/kvb
47        }
48
49        let fallback_targets = [
50            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, 144, 504, 1008,
51        ];
52
53        for &target in fallback_targets.iter().filter(|&&t| t >= target_blocks) {
54            let key = target.to_string();
55
56            if let Some(&rate) = estimates.get(&key) {
57                return Ok((rate * 1000.0) as f32);
58            }
59        }
60
61        for &target in &fallback_targets {
62            let key = target.to_string();
63
64            if let Some(&rate) = estimates.get(&key) {
65                return Ok((rate * 1000.0) as f32);
66            }
67        }
68
69        Ok(DEFAULT_FEE_RATE)
70    }
71}