Skip to content

Commit

Permalink
Merge pull request #21 from Mystic-Nayy/main
Browse files Browse the repository at this point in the history
Docs :add documentation for all public functions and modules
  • Loading branch information
raduciobanu22 authored Feb 4, 2025
2 parents 7a4a60f + 01cfe14 commit 1b06285
Show file tree
Hide file tree
Showing 5 changed files with 280 additions and 113 deletions.
100 changes: 82 additions & 18 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,25 @@ use anyhow::Result;
use std::env;
use url::Url;

/// Enum representing different networks for the client to interact with.
#[derive(Clone, Debug)]
pub enum Network {
Development,
Testnet,
Mainnet,
Custom(String),
Development, // Represents the development network.
Testnet, // Represents the testnet network.
Mainnet, // Represents the mainnet network.
Custom(String), // Represents a custom network, specified by a URL.
}

impl Network {
/// Returns the base URL for the network.
///
/// # Arguments
///
/// * `self` - A reference to the network instance.
///
/// # Returns
///
/// A string containing the base URL of the network.
pub fn base_url(&self) -> String {
match self {
Network::Development => {
Expand Down Expand Up @@ -42,28 +52,54 @@ impl Default for Network {
}
}

/// Struct representing a client that interacts with the Alephium node network.
#[derive(Clone, Debug)]
pub struct Client {
inner: reqwest::Client,
base_url: String,
inner: reqwest::Client, // The inner HTTP client used for requests.
base_url: String, // The base URL for making requests to the node network.
}

impl Client {
/// Creates a new `Client` instance for interacting with a specified network.
///
/// # Arguments
///
/// * `network` - The network to connect to.
///
/// # Returns
///
/// A new `Client` instance.
pub fn new(network: Network) -> Self {
Self { inner: reqwest::Client::new(), base_url: network.base_url() }
}

// List blocks on the given time interval.
// GET:/blockflow/blocks
/// List blocks on the given time interval.
///
/// # Arguments
///
/// * `from_ts` - The starting timestamp for the block query.
/// * `to_ts` - The ending timestamp for the block query.
///
/// # Returns
///
/// A `Result` containing a `BlocksPerTimestampRange` structure, or an error if the request fails.
pub async fn get_blocks(&self, from_ts: u64, to_ts: u64) -> Result<BlocksPerTimestampRange> {
let endpoint = format!("blockflow/blocks?fromTs={}&toTs={}", from_ts, to_ts);
let url = Url::parse(&format!("{}/{}", self.base_url, endpoint))?;
let response = self.inner.get(url).send().await?.json().await?;
Ok(response)
}

// List blocks with events on the given time interval.
// GET:/blockflow/blocks-with-events
/// List blocks with events on the given time interval.
///
/// # Arguments
///
/// * `from_ts` - The starting timestamp for the block and event query.
/// * `to_ts` - The ending timestamp for the block and event query.
///
/// # Returns
///
/// A `Result` containing a `BlocksAndEventsPerTimestampRange` structure, or an error if the request fails.
pub async fn get_blocks_and_events(
&self,
from_ts: u64,
Expand All @@ -75,17 +111,31 @@ impl Client {
Ok(response)
}

// Get a block with hash.
// GET:/blockflow/blocks/{block_hash}
/// Get a block by its hash.
///
/// # Arguments
///
/// * `block_hash` - The hash of the block to retrieve.
///
/// # Returns
///
/// A `Result` containing a `BlockEntry` structure, or an error if the request fails.
pub async fn get_block(&self, block_hash: &BlockHash) -> Result<BlockEntry> {
let endpoint = format!("blockflow/blocks/{}", block_hash);
let url = Url::parse(&format!("{}/{}", self.base_url, endpoint))?;
let response = self.inner.get(url).send().await?.json().await?;
Ok(response)
}

// Get a block and events with hash.
// GET:/blockflow/blocks-with-events/{block_hash}
/// Get a block with events by its hash.
///
/// # Arguments
///
/// * `block_hash` - The hash of the block to retrieve along with events.
///
/// # Returns
///
/// A `Result` containing a `BlockAndEvents` structure, or an error if the request fails.
pub async fn get_block_and_events_by_hash(
&self,
block_hash: &BlockHash,
Expand All @@ -96,17 +146,31 @@ impl Client {
Ok(response)
}

// Get block header.
// GET:/blockflow/headers/{block_hash}
/// Get the header of a block by its hash.
///
/// # Arguments
///
/// * `block_hash` - The hash of the block to retrieve the header for.
///
/// # Returns
///
/// A `Result` containing a `BlockHeaderEntry` structure, or an error if the request fails.
pub async fn get_block_header(&self, block_hash: &BlockHash) -> Result<BlockHeaderEntry> {
let endpoint = format!("blockflow/headers/{}", block_hash);
let url = Url::parse(&format!("{}/{}", self.base_url, endpoint))?;
let response = self.inner.get(url).send().await?.json().await?;
Ok(response)
}

// Get transaction details.
// GET:/transactions/details/{txId}
/// Get transaction details by transaction ID.
///
/// # Arguments
///
/// * `tx_id` - The ID of the transaction to retrieve.
///
/// # Returns
///
/// A `Result` containing a `Transaction` structure, or an error if the request fails.
pub async fn get_transaction(&self, tx_id: &str) -> Result<Transaction> {
let endpoint = format!("transactions/details/{}", tx_id);
let url = Url::parse(&format!("{}/{}", self.base_url, endpoint))?;
Expand Down
11 changes: 9 additions & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@ use std::error::Error;
pub type DbPool = r2d2::Pool<r2d2::ConnectionManager<PgConnection>>;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
pub type DbError = Box<dyn Error + Send + Sync + 'static>;

/// Initializes and returns a connection pool for the PostgreSQL database.
///
/// # Panics
/// This function panics if the `DATABASE_URL` environment variable is missing
/// or if the connection pool cannot be created.
pub fn initialize_db_pool() -> DbPool {
let database_url = env::var("DATABASE_URL").expect("missing DATABASE_URL in .env");
let manager = r2d2::ConnectionManager::<PgConnection>::new(database_url);
r2d2::Pool::builder().build(manager).expect("Failed to create pool")
}

/// Runs pending database migrations.
///
/// # Errors
/// Returns an error if the migration process fails.
pub fn run_migrations(
connection: &mut impl MigrationHarness<diesel::pg::Pg>,
) -> Result<(), DbError> {
Expand Down
15 changes: 13 additions & 2 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ use serde::{Deserialize, Serialize};
#[derive(Queryable, Selectable, Insertable, Debug, Clone, Serialize, AsChangeset)]
#[diesel(table_name = crate::schema::blocks)]
#[diesel(check_for_backend(diesel::pg::Pg))]

/// Represents a block in the blockchain.
///
/// A block contains information related to its position within the blockchain, the transactions it contains,
/// and other associated metadata. The `Block` struct is used to interact with the `blocks` table in the database.
pub struct Block {
pub hash: String,
pub timestamp: NaiveDateTime,
Expand All @@ -24,7 +29,10 @@ pub struct Block {
pub parent_hash: Option<String>,
pub uncles: serde_json::Value,
}

/// Represents an event related to a blockchain transaction.
///
/// An event is tied to a specific transaction and contract address, with additional metadata in `fields`
/// that can vary depending on the event's nature. The `Event` struct interacts with the `events` table.
#[derive(Queryable, Selectable, Insertable, Debug, Clone, AsChangeset)]
#[diesel(table_name = crate::schema::events)]
#[diesel(check_for_backend(diesel::pg::Pg))]
Expand All @@ -34,7 +42,10 @@ pub struct Event {
pub event_index: i32,
pub fields: serde_json::Value,
}

/// Represents a blockchain transaction.
///
/// A transaction includes metadata such as its hash, script execution status, input and output details,
/// and signatures associated with the transaction. The `Transaction` struct interacts with the `transactions` table.
#[derive(Queryable, Selectable, Insertable, Debug, Clone, Serialize, Deserialize, AsChangeset)]
#[diesel(table_name = crate::schema::transactions)]
#[diesel(check_for_backend(diesel::pg::Pg))]
Expand Down
Loading

0 comments on commit 1b06285

Please sign in to comment.