titan_client/http/
client_async_impl.rs

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use bitcoin::Txid;
use reqwest::{header::HeaderMap, Client as AsyncReqwestClient};
use std::str::FromStr;
use titan_types::*;

use crate::Error;

use super::TitanApiAsync;

#[derive(Clone)]
pub struct AsyncClient {
    /// The async HTTP client from `reqwest`.
    http_client: AsyncReqwestClient,
    /// The base URL for all endpoints (e.g. http://localhost:3030).
    base_url: String,
}

impl AsyncClient {
    /// Creates a new `AsyncClient` for the given `base_url`.
    pub fn new(base_url: &str) -> Self {
        Self {
            http_client: AsyncReqwestClient::new(),
            base_url: base_url.trim_end_matches('/').to_string(),
        }
    }

    async fn call_text(&self, path: &str) -> Result<String, Error> {
        let url = format!("{}{}", self.base_url, path);
        let response = self.http_client.get(&url).send().await?;
        if response.status().is_success() {
            Ok(response.text().await?)
        } else {
            Err(Error::TitanError(response.status(), response.text().await?))
        }
    }

    async fn call_bytes(&self, path: &str) -> Result<Vec<u8>, Error> {
        let url = format!("{}{}", self.base_url, path);
        let response = self.http_client.get(&url).send().await?;
        if response.status().is_success() {
            Ok(response.bytes().await?.to_vec())
        } else {
            Err(Error::TitanError(response.status(), response.text().await?))
        }
    }

    async fn post_text(&self, path: &str, body: String) -> Result<String, Error> {
        let url = format!("{}{}", self.base_url, path);
        let response = self.http_client.post(&url).body(body).send().await?;
        if response.status().is_success() {
            Ok(response.text().await?)
        } else {
            Err(Error::TitanError(response.status(), response.text().await?))
        }
    }

    async fn delete(&self, path: &str) -> Result<(), Error> {
        let url = format!("{}{}", self.base_url, path);
        let response = self.http_client.delete(&url).send().await?;
        if response.status().is_success() {
            Ok(())
        } else {
            Err(Error::TitanError(response.status(), response.text().await?))
        }
    }
}

#[async_trait::async_trait]
impl TitanApiAsync for AsyncClient {
    async fn get_status(&self) -> Result<Status, Error> {
        let text = self.call_text("/status").await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_tip(&self) -> Result<BlockTip, Error> {
        let text = self.call_text("/tip").await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_block(&self, query: &query::Block) -> Result<Block, Error> {
        let text = self.call_text(&format!("/block/{}", query)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_block_hash_by_height(&self, height: u64) -> Result<String, Error> {
        self.call_text(&format!("/block/{}/hash", height)).await
    }

    async fn get_block_txids(&self, query: &query::Block) -> Result<Vec<String>, Error> {
        let text = self.call_text(&format!("/block/{}/txids", query)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_address(&self, address: &str) -> Result<AddressData, Error> {
        let text = self.call_text(&format!("/address/{}", address)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_transaction(&self, txid: &str) -> Result<Transaction, Error> {
        let text = self.call_text(&format!("/tx/{}", txid)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_transaction_raw(&self, txid: &str) -> Result<Vec<u8>, Error> {
        self.call_bytes(&format!("/tx/{}/raw", txid)).await
    }

    async fn get_transaction_hex(&self, txid: &str) -> Result<String, Error> {
        self.call_text(&format!("/tx/{}/hex", txid)).await
    }

    async fn get_transaction_status(&self, txid: &str) -> Result<TransactionStatus, Error> {
        let text = self.call_text(&format!("/tx/{}/status", txid)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn send_transaction(&self, tx_hex: String) -> Result<Txid, Error> {
        let text = self.post_text("/tx/broadcast", tx_hex).await?;
        Txid::from_str(&text).map_err(Error::from)
    }

    async fn get_output(&self, outpoint: &str) -> Result<TxOutEntry, Error> {
        let text = self.call_text(&format!("/output/{}", outpoint)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_inscription(&self, inscription_id: &str) -> Result<(HeaderMap, Vec<u8>), Error> {
        let url = format!("{}/inscription/{}", self.base_url, inscription_id);
        let resp = self.http_client.get(&url).send().await?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::TitanError(status, body));
        }
        let headers = resp.headers().clone();
        let bytes = resp.bytes().await?.to_vec();
        Ok((headers, bytes))
    }

    async fn get_runes(
        &self,
        pagination: Option<Pagination>,
    ) -> Result<PaginationResponse<RuneResponse>, Error> {
        let mut path = "/runes".to_string();
        if let Some(p) = pagination {
            path = format!("{}?skip={}&limit={}", path, p.skip, p.limit);
        }
        let text = self.call_text(&path).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_rune(&self, rune: &str) -> Result<RuneResponse, Error> {
        let text = self.call_text(&format!("/rune/{}", rune)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_rune_transactions(
        &self,
        rune: &str,
        pagination: Option<Pagination>,
    ) -> Result<PaginationResponse<Txid>, Error> {
        let mut path = format!("/rune/{}/transactions", rune);
        if let Some(p) = pagination {
            path = format!("{}?skip={}&limit={}", path, p.skip, p.limit);
        }
        let text = self.call_text(&path).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_mempool_txids(&self) -> Result<Vec<Txid>, Error> {
        let text = self.call_text("/mempool/txids").await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn get_subscription(&self, id: &str) -> Result<Subscription, Error> {
        let text = self.call_text(&format!("/subscription/{}", id)).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn list_subscriptions(&self) -> Result<Vec<Subscription>, Error> {
        let text = self.call_text("/subscriptions").await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn add_subscription(&self, subscription: &Subscription) -> Result<Subscription, Error> {
        let text = self.post_text("/subscription", serde_json::to_string(subscription)?).await?;
        serde_json::from_str(&text).map_err(Error::from)
    }

    async fn delete_subscription(&self, id: &str) -> Result<(), Error> {
        self.delete(&format!("/subscription/{}", id)).await
    }
}