koios-sdk 0.1.1

A Rust SDK for the Koios Cardano API
Documentation
use crate::{
    error::Result,
    models::{
        block::{Block, BlockInfo, BlockTransaction, BlockTransactionCbor},
        transaction::TransactionInfo,
        BlockHashesRequest, BlockTxInfoRequest,
    },
    Client,
};

impl Client {
    /// Get summarized details about all blocks (paginated - latest first)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let blocks = client.get_blocks().await?;
    ///     println!("Latest blocks: {:?}", blocks);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_blocks(&self) -> Result<Vec<Block>> {
        self.get("/blocks").await
    }

    /// Get detailed information about specific blocks
    ///
    /// # Arguments
    ///
    /// * `block_hashes` - Vector of block hashes to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let block_hashes = vec![
    ///         "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e".to_string()
    ///     ];
    ///     let block_info = client.get_block_info(&block_hashes).await?;
    ///     println!("Block info: {:?}", block_info);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_block_info(&self, block_hashes: &[String]) -> Result<Vec<BlockInfo>> {
        let request = BlockHashesRequest {
            block_hashes: block_hashes.to_vec(),
        };
        self.post("/block_info", &request).await
    }

    /// Get a list of all transactions included in provided blocks
    ///
    /// # Arguments
    ///
    /// * `block_hashes` - Vector of block hashes to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let block_hashes = vec![
    ///         "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e".to_string()
    ///     ];
    ///     let block_txs = client.get_block_transactions(&block_hashes).await?;
    ///     println!("Block transactions: {:?}", block_txs);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_block_transactions(
        &self,
        block_hashes: &[String],
    ) -> Result<Vec<BlockTransaction>> {
        let request = BlockHashesRequest {
            block_hashes: block_hashes.to_vec(),
        };
        self.post("/block_txs", &request).await
    }

    /// Get raw CBOR data for all transactions within requested blocks
    ///
    /// # Arguments
    ///
    /// * `block_hashes` - Vector of block hashes to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let block_hashes = vec![
    ///         "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e".to_string()
    ///     ];
    ///     let tx_cbor = client.get_block_transaction_cbor(&block_hashes).await?;
    ///     println!("Transaction CBOR: {:?}", tx_cbor);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_block_transaction_cbor(
        &self,
        block_hashes: &[String],
    ) -> Result<Vec<BlockTransactionCbor>> {
        let request = BlockHashesRequest {
            block_hashes: block_hashes.to_vec(),
        };
        self.post("/block_tx_cbor", &request).await
    }

    /// Get detailed information about transactions for requested blocks
    ///
    /// # Arguments
    ///
    /// * `block_hashes` - Vector of block hashes to query
    /// * `options` - Optional parameters for customizing the response
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::models::BlockTxInfoRequest;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let block_hashes = vec![
    ///         "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e".to_string()
    ///     ];
    ///     let options = BlockTxInfoRequest {
    ///         block_hashes,
    ///         inputs: Some(true),
    ///         metadata: Some(true),
    ///         ..Default::default()
    ///     };
    ///     let tx_info = client.get_block_transaction_info(&options).await?;
    ///     println!("Transaction info: {:?}", tx_info);
    ///     Ok(())
    /// }
    /// ```
    #[deprecated(note = "This endpoint is deprecated in the Koios API")]
    pub async fn get_block_transaction_info(
        &self,
        options: &BlockTxInfoRequest,
    ) -> Result<Vec<TransactionInfo>> {
        self.post("/block_tx_info", options).await
    }
}

#[cfg(test)]
mod tests {
    use crate::Client;
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_get_blocks() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        let mock_response = json!([{
            "hash": "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e",
            "epoch_no": 321,
            "abs_slot": 53384091,
            "epoch_slot": 85691,
            "block_height": 7017300,
            "block_size": 4318,
            "block_time": 1630106091,
            "tx_count": 8,
            "vrf_key": "vrf_vk1gn7g0xjwhxhm9pv4m0pfz4qw8fj95h5qkkc9zhl02wsm6v0urq9qgug5fx",
            "op_cert_counter": 1,
            "proto_major": 6,
            "proto_minor": 0,
            "parent_hash": "43c66ecb78f5938d7a3bf2cef6b575acda9c86a7c0c27dd91cdcd9e2f0f6e683"
        }]);

        Mock::given(method("GET"))
            .and(path("/blocks"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response = client.get_blocks().await.unwrap();
        assert_eq!(response.len(), 1);
        assert_eq!(
            response[0].hash,
            "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e"
        );
    }

    // Add more tests for other endpoints...
}