Skip to main content

alephium_web3/api/
explorer_provider.rs

1// Copyright 2018 - 2022 The Alephium Authors
2// This file is part of the alephium project.
3
4use crate::address::Address;
5use crate::error::Result;
6use reqwest::Client;
7use serde::{Deserialize, Serialize};
8
9/// Explorer provider for interacting with Alephium explorer
10pub struct ExplorerProvider {
11    base_url: String,
12    client: Client,
13    api_key: Option<String>,
14}
15
16impl ExplorerProvider {
17    /// Create a new explorer provider
18    pub fn new(base_url: impl Into<String>) -> Result<Self> {
19        Ok(Self {
20            base_url: base_url.into(),
21            client: Client::new(),
22            api_key: None,
23        })
24    }
25
26    /// Create explorer provider with API key
27    pub fn with_api_key(base_url: impl Into<String>, api_key: impl Into<String>) -> Result<Self> {
28        Ok(Self {
29            base_url: base_url.into(),
30            client: Client::new(),
31            api_key: Some(api_key.into()),
32        })
33    }
34
35    /// Build request with optional API key
36    fn build_request(&self, url: &str) -> reqwest::RequestBuilder {
37        let mut req = self.client.get(url);
38        if let Some(api_key) = &self.api_key {
39            req = req.header("X-API-KEY", api_key);
40        }
41        req
42    }
43
44    /// Get address transactions
45    pub async fn get_address_transactions(
46        &self,
47        address: &Address,
48        page: Option<u32>,
49    ) -> Result<AddressTransactions> {
50        let page_num = page.unwrap_or(1);
51        let url = format!(
52            "{}/addresses/{}/transactions?page={}",
53            self.base_url,
54            address.to_base58(),
55            page_num
56        );
57        let response = self.build_request(&url).send().await?;
58        let transactions = response.json().await?;
59        Ok(transactions)
60    }
61
62    /// Get address balance
63    pub async fn get_address_balance(&self, address: &Address) -> Result<ExplorerAddressBalance> {
64        let url = format!("{}/addresses/{}/balance", self.base_url, address.to_base58());
65        let response = self.build_request(&url).send().await?;
66        let balance = response.json().await?;
67        Ok(balance)
68    }
69
70    /// Get address tokens
71    pub async fn get_address_tokens(&self, address: &Address) -> Result<AddressTokens> {
72        let url = format!("{}/addresses/{}/tokens", self.base_url, address.to_base58());
73        let response = self.build_request(&url).send().await?;
74        let tokens = response.json().await?;
75        Ok(tokens)
76    }
77
78    /// Get transaction details
79    pub async fn get_transaction(&self, tx_id: &str) -> Result<ExplorerTransaction> {
80        let url = format!("{}/transactions/{}", self.base_url, tx_id);
81        let response = self.build_request(&url).send().await?;
82        let transaction = response.json().await?;
83        Ok(transaction)
84    }
85
86    /// Get block details
87    pub async fn get_block(&self, block_hash: &str) -> Result<ExplorerBlock> {
88        let url = format!("{}/blocks/{}", self.base_url, block_hash);
89        let response = self.build_request(&url).send().await?;
90        let block = response.json().await?;
91        Ok(block)
92    }
93
94    /// Get chart data
95    pub async fn get_chart(&self, chart_type: &str, interval: &str) -> Result<ChartData> {
96        let url = format!(
97            "{}/charts/{}?interval-type={}",
98            self.base_url, chart_type, interval
99        );
100        let response = self.build_request(&url).send().await?;
101        let data = response.json().await?;
102        Ok(data)
103    }
104
105    /// Search by query (address, transaction, block)
106    pub async fn search(&self, query: &str) -> Result<SearchResult> {
107        let url = format!("{}/utils/search?query={}", self.base_url, query);
108        let response = self.build_request(&url).send().await?;
109        let result = response.json().await?;
110        Ok(result)
111    }
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct AddressTransactions {
116    pub total: u32,
117    pub transactions: Vec<TransactionSummary>,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct TransactionSummary {
122    pub hash: String,
123    #[serde(rename = "blockHash")]
124    pub block_hash: String,
125    pub timestamp: u64,
126    pub inputs: Vec<InputSummary>,
127    pub outputs: Vec<OutputSummary>,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct InputSummary {
132    pub address: Option<String>,
133    #[serde(rename = "attoAlphAmount")]
134    pub atto_alph_amount: String,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct OutputSummary {
139    pub address: String,
140    #[serde(rename = "attoAlphAmount")]
141    pub atto_alph_amount: String,
142    pub tokens: Option<Vec<TokenAmount>>,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct TokenAmount {
147    pub id: String,
148    pub amount: String,
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct ExplorerAddressBalance {
153    pub balance: String,
154    #[serde(rename = "lockedBalance")]
155    pub locked_balance: String,
156    #[serde(rename = "txNumber")]
157    pub tx_number: u32,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct AddressTokens {
162    pub tokens: Vec<AddressToken>,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct AddressToken {
167    pub id: String,
168    pub amount: String,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct ExplorerTransaction {
173    pub hash: String,
174    #[serde(rename = "blockHash")]
175    pub block_hash: String,
176    pub timestamp: u64,
177    pub inputs: Vec<InputDetail>,
178    pub outputs: Vec<OutputDetail>,
179    #[serde(rename = "gasAmount")]
180    pub gas_amount: u32,
181    #[serde(rename = "gasPrice")]
182    pub gas_price: String,
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct InputDetail {
187    #[serde(rename = "outputRef")]
188    pub output_ref: OutputRefDetail,
189    #[serde(rename = "unlockScript")]
190    pub unlock_script: String,
191    pub address: Option<String>,
192    #[serde(rename = "attoAlphAmount")]
193    pub atto_alph_amount: String,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct OutputRefDetail {
198    pub hint: i32,
199    pub key: String,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct OutputDetail {
204    #[serde(rename = "type")]
205    pub output_type: String,
206    pub address: String,
207    #[serde(rename = "attoAlphAmount")]
208    pub atto_alph_amount: String,
209    pub tokens: Option<Vec<TokenAmount>>,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct ExplorerBlock {
214    pub hash: String,
215    pub timestamp: u64,
216    #[serde(rename = "chainFrom")]
217    pub chain_from: u8,
218    #[serde(rename = "chainTo")]
219    pub chain_to: u8,
220    pub height: u64,
221    pub transactions: Vec<String>,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225pub struct ChartData {
226    pub timestamps: Vec<u64>,
227    pub values: Vec<String>,
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct SearchResult {
232    #[serde(rename = "type")]
233    pub result_type: String,
234    pub value: serde_json::Value,
235}