smplx_sdk_test/provider/core.rs
1use std::collections::HashMap;
2
3#[cfg(feature = "provider")]
4use bitcoincore_rpc::Auth;
5
6use simplicityhl::elements::{Address, Script, Transaction, Txid};
7
8use crate::provider::SimplicityNetwork;
9use crate::transaction::{TxReceipt, UTXO};
10
11use super::error::ProviderError;
12
13/// The fallback default fee rate (in sats/kvb) to use when dynamic estimates fail.
14pub const DEFAULT_FEE_RATE: f32 = 100.0;
15/// The standard timeout duration (in seconds) applied to Esplora REST API requests.
16pub const DEFAULT_ESPLORA_TIMEOUT_SECS: u64 = 10;
17
18/// Contains foundational configuration elements required for initializing a generic blockchain provider.
19#[cfg(feature = "provider")]
20#[derive(Debug, Clone)]
21pub struct ProviderInfo {
22 /// URL of the target Esplora REST service.
23 pub esplora_url: String,
24 /// URL of the target direct `elementsd` or `bitcoind` RPC interface.
25 pub elements_url: Option<String>,
26 /// Authentication settings (e.g. cookie or username/password) for the RPC backend.
27 pub auth: Option<Auth>,
28}
29
30/// Baseline traits detailing required interaction methods between the SDK client and the underlying blockchain node or API.
31pub trait ProviderTrait {
32 /// Retrieves the network configured for this provider.
33 fn get_network(&self) -> &SimplicityNetwork;
34
35 /// Attempts to broadcast a fully compiled transaction to the configured backend.
36 ///
37 /// # Errors
38 /// Returns a `ProviderError` if network transmission fails, or if the backend explicitly rejects the transaction.
39 fn broadcast_transaction(&self, tx: &Transaction) -> Result<TxReceipt<'_>, ProviderError>;
40
41 /// Blocks and repeatedly polls the network until the specified transaction receives its first confirmation.
42 ///
43 /// # Errors
44 /// Returns a `ProviderError` if the network fails or the designated timeout elapses without confirmation.
45 fn wait(&self, txid: &Txid) -> Result<(), ProviderError>;
46
47 /// Retrieves the current block height of the network tip.
48 ///
49 /// # Errors
50 /// Returns a `ProviderError` if the backend request fails or the returned height cannot be parsed.
51 fn fetch_tip_height(&self) -> Result<u32, ProviderError>;
52
53 /// Retrieves the current block hash of the network tip.
54 ///
55 /// # Errors
56 /// Returns a `ProviderError` if the backend request fails or the returned block hash cannot be parsed.
57 fn fetch_tip_block_hash(&self) -> Result<String, ProviderError>;
58
59 /// Retrieves the block timestamp representing network consensus clock tip.
60 ///
61 /// # Errors
62 /// Returns a `ProviderError` if the hash query, subsequent block query, or block parsing fails.
63 fn fetch_tip_timestamp(&self) -> Result<u64, ProviderError>;
64
65 /// Retrieves the block hash at a specific block height.
66 ///
67 /// # Errors
68 /// Returns a `ProviderError` if the passed block height does not exist or the returned hash cannot be parsed.
69 fn fetch_block_hash_at_height(&self, block_height: u32) -> Result<String, ProviderError>;
70
71 /// Retrieves the transaction IDs for a specific block hash.
72 ///
73 /// # Errors
74 /// Returns a `ProviderError` if the passed block hash does not exist or the returned data cannot be parsed.
75 fn fetch_block_txids(&self, block_hash: &str) -> Result<Vec<Txid>, ProviderError>;
76
77 /// Retrieves the serialized transaction payload given its hex transaction ID.
78 ///
79 /// # Errors
80 /// Returns a `ProviderError` if the node fails to locate the transaction or serialization fails.
81 fn fetch_transaction(&self, txid: &Txid) -> Result<Transaction, ProviderError>;
82
83 /// Fetches all active unspent transaction outputs correlated to a particular public `Address`.
84 ///
85 /// # Errors
86 /// Returns a `ProviderError` if the backend request fails or if UTXO parsing fails.
87 fn fetch_address_utxos(&self, address: &Address) -> Result<Vec<UTXO>, ProviderError>;
88
89 /// Fetches all active unspent transaction outputs correlated to a given custom `Script` mapping.
90 ///
91 /// # Errors
92 /// Returns a `ProviderError` if the backend request fails or if UTXO parsing fails.
93 fn fetch_scripthash_utxos(&self, script: &Script) -> Result<Vec<UTXO>, ProviderError>;
94
95 /// Fetches network fee estimation models based on varying target confirmation block delays.
96 ///
97 /// # Errors
98 /// Returns a `ProviderError` if the REST request fails or the resulting mappings fail to parse cleanly.
99 fn fetch_fee_estimates(&self) -> Result<HashMap<String, f64>, ProviderError>;
100
101 /// Attempts to extract the specific fee rate (in sats/kvb) necessary for the transaction to be confirmed within `target_blocks`.
102 ///
103 /// # Errors
104 /// Passes along `ProviderError` if `fetch_fee_estimates` fails.
105 #[allow(clippy::cast_possible_truncation)]
106 fn fetch_fee_rate(&self, target_blocks: u32) -> Result<f32, ProviderError> {
107 let estimates = self.fetch_fee_estimates()?;
108 let target_str = target_blocks.to_string();
109
110 if let Some(&rate) = estimates.get(&target_str) {
111 return Ok((rate * 1000.0) as f32); // Convert sat/vB to sats/kvb
112 }
113
114 let fallback_targets = [
115 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,
116 ];
117
118 for &target in fallback_targets.iter().filter(|&&t| t >= target_blocks) {
119 let key = target.to_string();
120
121 if let Some(&rate) = estimates.get(&key) {
122 return Ok((rate * 1000.0) as f32);
123 }
124 }
125
126 for &target in &fallback_targets {
127 let key = target.to_string();
128
129 if let Some(&rate) = estimates.get(&key) {
130 return Ok((rate * 1000.0) as f32);
131 }
132 }
133
134 Ok(DEFAULT_FEE_RATE)
135 }
136}