Skip to main content

alephium_web3/api/
node_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 crate::transaction::{Transaction, UnsignedTransaction};
7use reqwest::Client;
8use serde::{Deserialize, Serialize};
9
10/// Node provider for interacting with Alephium node
11pub struct NodeProvider {
12    pub base_url: String,
13    client: Client,
14    api_key: Option<String>,
15}
16
17impl NodeProvider {
18    /// Create a new node provider
19    pub fn new(base_url: impl Into<String>) -> Result<Self> {
20        Ok(Self {
21            base_url: base_url.into(),
22            client: Client::new(),
23            api_key: None,
24        })
25    }
26
27    /// Create a new node provider with API key
28    pub fn with_api_key(base_url: impl Into<String>, api_key: impl Into<String>) -> Result<Self> {
29        Ok(Self {
30            base_url: base_url.into(),
31            client: Client::new(),
32            api_key: Some(api_key.into()),
33        })
34    }
35
36    /// Build request with optional API key
37    fn build_request(&self, url: &str) -> reqwest::RequestBuilder {
38        let mut req = self.client.get(url);
39        if let Some(api_key) = &self.api_key {
40            req = req.header("X-API-KEY", api_key);
41        }
42        req
43    }
44
45    /// Build POST request with optional API key
46    fn build_post_request(&self, url: &str) -> reqwest::RequestBuilder {
47        let mut req = self.client.post(url);
48        if let Some(api_key) = &self.api_key {
49            req = req.header("X-API-KEY", api_key);
50        }
51        req
52    }
53
54    /// Get node info
55    pub async fn get_node_info(&self) -> Result<NodeInfo> {
56        let url = format!("{}/infos/node", self.base_url);
57        let response = self.build_request(&url).send().await?;
58        let info = response.json().await?;
59        Ok(info)
60    }
61
62    /// Get blockchain info
63    pub async fn get_blockchain_info(&self) -> Result<BlockchainInfo> {
64        let url = format!("{}/blockflow", self.base_url);
65        let response = self.build_request(&url).send().await?;
66        let info = response.json().await?;
67        Ok(info)
68    }
69
70    /// Get address balance
71    pub async fn get_address_balance(&self, address: &Address) -> Result<AddressBalance> {
72        let url = format!("{}/addresses/{}/balance", self.base_url, address.to_base58());
73        let response = self.build_request(&url).send().await?;
74        let balance = response.json().await?;
75        Ok(balance)
76    }
77
78    /// Get address group
79    pub async fn get_address_group(&self, address: &Address) -> Result<AddressGroup> {
80        let url = format!("{}/addresses/{}/group", self.base_url, address.to_base58());
81        let response = self.build_request(&url).send().await?;
82        let group = response.json().await?;
83        Ok(group)
84    }
85
86    /// Get UTXOs for an address
87    pub async fn get_address_utxos(&self, address: &Address) -> Result<AddressUtxos> {
88        let url = format!("{}/addresses/{}/utxos", self.base_url, address.to_base58());
89        let response = self.build_request(&url).send().await?;
90        let utxos = response.json().await?;
91        Ok(utxos)
92    }
93
94    /// Get transaction status
95    pub async fn get_transaction_status(&self, tx_id: &str) -> Result<TransactionStatus> {
96        let url = format!("{}/transactions/status", self.base_url);
97        let body = serde_json::json!({ "txId": tx_id });
98        let response = self.build_post_request(&url).json(&body).send().await?;
99        let status = response.json().await?;
100        Ok(status)
101    }
102
103    /// Submit a signed transaction
104    pub async fn submit_transaction(&self, tx: &Transaction) -> Result<SubmitResult> {
105        let url = format!("{}/transactions/submit", self.base_url);
106        let body = serde_json::json!({
107            "unsignedTx": serde_json::to_string(&tx.unsigned)?,
108            "signature": tx.input_signatures.first().ok_or_else(|| {
109                crate::error::Error::InvalidTransaction("No signatures".to_string())
110            })?
111        });
112        let response = self.build_post_request(&url).json(&body).send().await?;
113        let result = response.json().await?;
114        Ok(result)
115    }
116
117    /// Build transfer transaction
118    pub async fn build_transfer_transaction(
119        &self,
120        params: BuildTransferTxParams,
121    ) -> Result<UnsignedTransaction> {
122        let url = format!("{}/transactions/build", self.base_url);
123        let response = self.build_post_request(&url).json(&params).send().await?;
124        let result: BuildTransferTxResponse = response.json().await?;
125        Ok(result.unsigned_tx)
126    }
127
128    /// Compile contract
129    pub async fn compile_contract(&self, code: &str) -> Result<CompileResult> {
130        let url = format!("{}/contracts/compile-contract", self.base_url);
131        let body = serde_json::json!({ "code": code });
132        let response = self.build_post_request(&url).json(&body).send().await?;
133        let result = response.json().await?;
134        Ok(result)
135    }
136
137    /// Compile script
138    pub async fn compile_script(&self, code: &str) -> Result<CompileResult> {
139        let url = format!("{}/contracts/compile-script", self.base_url);
140        let body = serde_json::json!({ "code": code });
141        let response = self.build_post_request(&url).json(&body).send().await?;
142        let result = response.json().await?;
143        Ok(result)
144    }
145
146    /// Get contract events
147    pub async fn get_contract_events(&self, contract_address: &Address) -> Result<ContractEvents> {
148        let url = format!(
149            "{}/contracts/{}/events",
150            self.base_url,
151            contract_address.to_base58()
152        );
153        let response = self.build_request(&url).send().await?;
154        let events = response.json().await?;
155        Ok(events)
156    }
157
158    /// Call contract method (read-only)
159    pub async fn call_contract(&self, params: CallContractParams) -> Result<CallContractResult> {
160        let url = format!("{}/contracts/call-contract", self.base_url);
161        let response = self.build_post_request(&url).json(&params).send().await?;
162        let result = response.json().await?;
163        Ok(result)
164    }
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct NodeInfo {
169    pub version: String,
170    #[serde(rename = "buildInfo")]
171    pub build_info: BuildInfo,
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct BuildInfo {
176    #[serde(rename = "releaseVersion")]
177    pub release_version: String,
178    pub commit: String,
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct BlockchainInfo {
183    #[serde(rename = "currentHeight")]
184    pub current_height: u64,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct AddressBalance {
189    #[serde(rename = "balance")]
190    pub balance: String,
191    #[serde(rename = "lockedBalance")]
192    pub locked_balance: String,
193    #[serde(rename = "utxoNum")]
194    pub utxo_num: u32,
195}
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct AddressGroup {
199    pub group: u8,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct AddressUtxos {
204    pub utxos: Vec<Utxo>,
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct Utxo {
209    pub ref_: OutputRef,
210    #[serde(rename = "amount")]
211    pub amount: String,
212    #[serde(rename = "tokens", skip_serializing_if = "Option::is_none")]
213    pub tokens: Option<Vec<Token>>,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct OutputRef {
218    pub hint: i32,
219    pub key: String,
220}
221
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct Token {
224    pub id: String,
225    pub amount: String,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct TransactionStatus {
230    #[serde(rename = "type")]
231    pub status_type: String,
232    #[serde(rename = "blockHash")]
233    pub block_hash: Option<String>,
234    #[serde(rename = "txIndex")]
235    pub tx_index: Option<u32>,
236    #[serde(rename = "chainConfirmations")]
237    pub chain_confirmations: Option<u32>,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
241pub struct SubmitResult {
242    #[serde(rename = "txId")]
243    pub tx_id: String,
244    #[serde(rename = "fromGroup")]
245    pub from_group: u8,
246    #[serde(rename = "toGroup")]
247    pub to_group: u8,
248}
249
250#[derive(Debug, Clone, Serialize, Deserialize)]
251pub struct BuildTransferTxParams {
252    #[serde(rename = "fromPublicKey")]
253    pub from_public_key: String,
254    pub destinations: Vec<Destination>,
255    #[serde(rename = "gasAmount", skip_serializing_if = "Option::is_none")]
256    pub gas_amount: Option<u32>,
257    #[serde(rename = "gasPrice", skip_serializing_if = "Option::is_none")]
258    pub gas_price: Option<String>,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct Destination {
263    pub address: String,
264    #[serde(rename = "attoAlphAmount")]
265    pub atto_alph_amount: String,
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub tokens: Option<Vec<Token>>,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct BuildTransferTxResponse {
272    #[serde(rename = "unsignedTx")]
273    pub unsigned_tx: UnsignedTransaction,
274    #[serde(rename = "gasAmount")]
275    pub gas_amount: u32,
276    #[serde(rename = "gasPrice")]
277    pub gas_price: String,
278}
279
280#[derive(Debug, Clone, Serialize, Deserialize)]
281pub struct CompileResult {
282    pub bytecode: String,
283    #[serde(rename = "bytecodeDebugPatch", skip_serializing_if = "Option::is_none")]
284    pub bytecode_debug_patch: Option<String>,
285    #[serde(rename = "codeHash")]
286    pub code_hash: String,
287    #[serde(rename = "fields")]
288    pub fields: CompileFields,
289    #[serde(rename = "functions")]
290    pub functions: Vec<CompileFunction>,
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct CompileFields {
295    pub names: Vec<String>,
296    pub types: Vec<String>,
297    #[serde(rename = "isMutable")]
298    pub is_mutable: Vec<bool>,
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct CompileFunction {
303    pub name: String,
304    #[serde(rename = "usePreapprovedAssets")]
305    pub use_preapproved_assets: bool,
306    #[serde(rename = "useContractAssets")]
307    pub use_contract_assets: bool,
308    #[serde(rename = "isPublic")]
309    pub is_public: bool,
310    #[serde(rename = "paramNames")]
311    pub param_names: Vec<String>,
312    #[serde(rename = "paramTypes")]
313    pub param_types: Vec<String>,
314    #[serde(rename = "returnTypes")]
315    pub return_types: Vec<String>,
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct ContractEvents {
320    pub events: Vec<ContractEvent>,
321}
322
323#[derive(Debug, Clone, Serialize, Deserialize)]
324pub struct ContractEvent {
325    #[serde(rename = "blockHash")]
326    pub block_hash: String,
327    #[serde(rename = "txId")]
328    pub tx_id: String,
329    #[serde(rename = "eventIndex")]
330    pub event_index: i32,
331    pub fields: Vec<EventField>,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct EventField {
336    #[serde(rename = "type")]
337    pub field_type: String,
338    pub value: serde_json::Value,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
342pub struct CallContractParams {
343    pub group: u8,
344    pub address: String,
345    #[serde(rename = "methodIndex")]
346    pub method_index: u32,
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub args: Option<Vec<serde_json::Value>>,
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
352pub struct CallContractResult {
353    pub returns: Vec<ReturnValue>,
354    #[serde(rename = "gasUsed")]
355    pub gas_used: u32,
356}
357
358#[derive(Debug, Clone, Serialize, Deserialize)]
359pub struct ReturnValue {
360    #[serde(rename = "type")]
361    pub value_type: String,
362    pub value: serde_json::Value,
363}