alephium-web3 2.0.7

A Rust library to interact with the Alephium platform
Documentation
// Copyright 2018 - 2022 The Alephium Authors
// This file is part of the alephium project.

use crate::address::Address;
use crate::error::Result;
use reqwest::Client;
use serde::{Deserialize, Serialize};

/// Explorer provider for interacting with Alephium explorer
pub struct ExplorerProvider {
    base_url: String,
    client: Client,
    api_key: Option<String>,
}

impl ExplorerProvider {
    /// Create a new explorer provider
    pub fn new(base_url: impl Into<String>) -> Result<Self> {
        Ok(Self {
            base_url: base_url.into(),
            client: Client::new(),
            api_key: None,
        })
    }

    /// Create explorer provider with API key
    pub fn with_api_key(base_url: impl Into<String>, api_key: impl Into<String>) -> Result<Self> {
        Ok(Self {
            base_url: base_url.into(),
            client: Client::new(),
            api_key: Some(api_key.into()),
        })
    }

    /// Build request with optional API key
    fn build_request(&self, url: &str) -> reqwest::RequestBuilder {
        let mut req = self.client.get(url);
        if let Some(api_key) = &self.api_key {
            req = req.header("X-API-KEY", api_key);
        }
        req
    }

    /// Get address transactions
    pub async fn get_address_transactions(
        &self,
        address: &Address,
        page: Option<u32>,
    ) -> Result<AddressTransactions> {
        let page_num = page.unwrap_or(1);
        let url = format!(
            "{}/addresses/{}/transactions?page={}",
            self.base_url,
            address.to_base58(),
            page_num
        );
        let response = self.build_request(&url).send().await?;
        let transactions = response.json().await?;
        Ok(transactions)
    }

    /// Get address balance
    pub async fn get_address_balance(&self, address: &Address) -> Result<ExplorerAddressBalance> {
        let url = format!("{}/addresses/{}/balance", self.base_url, address.to_base58());
        let response = self.build_request(&url).send().await?;
        let balance = response.json().await?;
        Ok(balance)
    }

    /// Get address tokens
    pub async fn get_address_tokens(&self, address: &Address) -> Result<AddressTokens> {
        let url = format!("{}/addresses/{}/tokens", self.base_url, address.to_base58());
        let response = self.build_request(&url).send().await?;
        let tokens = response.json().await?;
        Ok(tokens)
    }

    /// Get transaction details
    pub async fn get_transaction(&self, tx_id: &str) -> Result<ExplorerTransaction> {
        let url = format!("{}/transactions/{}", self.base_url, tx_id);
        let response = self.build_request(&url).send().await?;
        let transaction = response.json().await?;
        Ok(transaction)
    }

    /// Get block details
    pub async fn get_block(&self, block_hash: &str) -> Result<ExplorerBlock> {
        let url = format!("{}/blocks/{}", self.base_url, block_hash);
        let response = self.build_request(&url).send().await?;
        let block = response.json().await?;
        Ok(block)
    }

    /// Get chart data
    pub async fn get_chart(&self, chart_type: &str, interval: &str) -> Result<ChartData> {
        let url = format!(
            "{}/charts/{}?interval-type={}",
            self.base_url, chart_type, interval
        );
        let response = self.build_request(&url).send().await?;
        let data = response.json().await?;
        Ok(data)
    }

    /// Search by query (address, transaction, block)
    pub async fn search(&self, query: &str) -> Result<SearchResult> {
        let url = format!("{}/utils/search?query={}", self.base_url, query);
        let response = self.build_request(&url).send().await?;
        let result = response.json().await?;
        Ok(result)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddressTransactions {
    pub total: u32,
    pub transactions: Vec<TransactionSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionSummary {
    pub hash: String,
    #[serde(rename = "blockHash")]
    pub block_hash: String,
    pub timestamp: u64,
    pub inputs: Vec<InputSummary>,
    pub outputs: Vec<OutputSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputSummary {
    pub address: Option<String>,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputSummary {
    pub address: String,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
    pub tokens: Option<Vec<TokenAmount>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenAmount {
    pub id: String,
    pub amount: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplorerAddressBalance {
    pub balance: String,
    #[serde(rename = "lockedBalance")]
    pub locked_balance: String,
    #[serde(rename = "txNumber")]
    pub tx_number: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddressTokens {
    pub tokens: Vec<AddressToken>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddressToken {
    pub id: String,
    pub amount: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplorerTransaction {
    pub hash: String,
    #[serde(rename = "blockHash")]
    pub block_hash: String,
    pub timestamp: u64,
    pub inputs: Vec<InputDetail>,
    pub outputs: Vec<OutputDetail>,
    #[serde(rename = "gasAmount")]
    pub gas_amount: u32,
    #[serde(rename = "gasPrice")]
    pub gas_price: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputDetail {
    #[serde(rename = "outputRef")]
    pub output_ref: OutputRefDetail,
    #[serde(rename = "unlockScript")]
    pub unlock_script: String,
    pub address: Option<String>,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputRefDetail {
    pub hint: i32,
    pub key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputDetail {
    #[serde(rename = "type")]
    pub output_type: String,
    pub address: String,
    #[serde(rename = "attoAlphAmount")]
    pub atto_alph_amount: String,
    pub tokens: Option<Vec<TokenAmount>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplorerBlock {
    pub hash: String,
    pub timestamp: u64,
    #[serde(rename = "chainFrom")]
    pub chain_from: u8,
    #[serde(rename = "chainTo")]
    pub chain_to: u8,
    pub height: u64,
    pub transactions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChartData {
    pub timestamps: Vec<u64>,
    pub values: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    #[serde(rename = "type")]
    pub result_type: String,
    pub value: serde_json::Value,
}