Skip to main content

qualia_client_core/wallet/
chronik.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize)]
4pub struct ChronikUtxo {
5    pub outpoint: Outpoint,
6    pub block_height: i32,
7    pub is_coinbase: bool,
8    pub value: i64,
9    #[serde(default)]
10    pub slp_meta: Option<SlpMeta>,
11    #[serde(default)]
12    pub slp_token: Option<SlpToken>,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct Outpoint {
17    pub txid: String,
18    pub out_idx: u32,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct SlpMeta {
23    pub token_type: String,
24    pub tx_type: String,
25    pub token_id: String,
26    pub group_token_id: Option<String>,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct SlpToken {
31    pub amount: String,
32    pub is_mint_baton: bool,
33}
34
35pub struct ChronikClient {
36    pub base_url: String,
37    client: reqwest::blocking::Client,
38}
39
40impl ChronikClient {
41    /// Creates a new instance.
42    pub fn new(base_url: &str) -> Self {
43        Self {
44            base_url: base_url.to_string(),
45            client: reqwest::blocking::Client::new(),
46        }
47    }
48
49    /// Fetches utxos-p2pkh.
50    pub fn fetch_utxos_p2pkh(&self, hash160_hex: &str) -> Result<Vec<ChronikUtxo>, String> {
51        let url = format!("{}/script/p2pkh/{}/utxos", self.base_url, hash160_hex);
52        let resp = self.client.get(&url).send().map_err(|e| e.to_string())?;
53
54        if !resp.status().is_success() {
55            return Err(format!("Chronik API error: {}", resp.status()));
56        }
57
58        #[derive(Deserialize)]
59        struct ScriptUtxos {
60            utxos: Vec<ChronikUtxo>,
61        }
62
63        let result: Vec<ScriptUtxos> = resp.json().map_err(|e| e.to_string())?;
64
65        let mut all_utxos = Vec::new();
66        for script_utxo in result {
67            all_utxos.extend(script_utxo.utxos);
68        }
69        Ok(all_utxos)
70    }
71
72    /// Broadcasts a transaction.
73    pub fn broadcast_tx(&self, raw_tx_hex: &str) -> Result<String, String> {
74        let url = format!("{}/broadcast-tx", self.base_url);
75
76        let resp = self
77            .client
78            .post(&url)
79            .header("Content-Type", "text/plain")
80            .body(raw_tx_hex.to_string())
81            .send()
82            .map_err(|e| e.to_string())?;
83
84        if !resp.status().is_success() {
85            let err_text = resp.text().unwrap_or_default();
86            return Err(format!("Broadcast failed: {}", err_text));
87        }
88
89        #[derive(Deserialize)]
90        struct BroadcastResponse {
91            txid: String,
92        }
93
94        let res: BroadcastResponse = resp.json().map_err(|e| e.to_string())?;
95        Ok(res.txid)
96    }
97
98    /// Fetch transaction history for a P2PKH script hash.
99    /// Returns the most recent transactions (up to `page_size`, default 25).
100    pub fn fetch_tx_history_p2pkh(
101        &self,
102        hash160_hex: &str,
103        page: u32,
104        page_size: u32,
105    ) -> Result<ChronikTxHistoryPage, String> {
106        let url = format!(
107            "{}/script/p2pkh/{}/history?page={}&page_size={}",
108            self.base_url, hash160_hex, page, page_size
109        );
110        let resp = self.client.get(&url).send().map_err(|e| e.to_string())?;
111
112        if !resp.status().is_success() {
113            return Err(format!("Chronik history API error: {}", resp.status()));
114        }
115
116        let result: ChronikTxHistoryPage = resp.json().map_err(|e| e.to_string())?;
117        Ok(result)
118    }
119}
120
121/// A page of transaction history from Chronik.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124pub struct ChronikTxHistoryPage {
125    #[serde(default)]
126    pub txs: Vec<ChronikTx>,
127    #[serde(default)]
128    pub num_pages: u32,
129    #[serde(default)]
130    pub num_txs: u32,
131}
132
133/// A transaction returned by Chronik's history endpoint.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135#[serde(rename_all = "camelCase")]
136pub struct ChronikTx {
137    pub txid: String,
138    #[serde(default)]
139    pub version: i32,
140    #[serde(default)]
141    pub inputs: Vec<ChronikTxIO>,
142    #[serde(default)]
143    pub outputs: Vec<ChronikTxIO>,
144    #[serde(default)]
145    pub block: Option<ChronikBlock>,
146    #[serde(default)]
147    pub time_first_seen: i64,
148    #[serde(default)]
149    pub size: u32,
150    #[serde(default)]
151    pub is_coinbase: bool,
152}
153
154/// An input or output in a Chronik transaction.
155#[derive(Debug, Clone, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157pub struct ChronikTxIO {
158    #[serde(default)]
159    pub value: i64,
160    #[serde(default)]
161    pub output_script: String,
162    #[serde(default)]
163    pub slp_meta: Option<SlpMeta>,
164    #[serde(default)]
165    pub slp_token: Option<SlpToken>,
166}
167
168/// Block info for a confirmed transaction.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct ChronikBlock {
172    pub height: i32,
173    #[serde(default)]
174    pub hash: String,
175    #[serde(default)]
176    pub timestamp: i64,
177}