#cardano #rate-limiting #sdk #api #builder-pattern #koios

bin+lib koios-sdk

A Rust SDK for the Koios Cardano API

2 releases

new 0.1.1 Jan 28, 2025
0.1.0 Jan 28, 2025

#678 in Web programming

Apache-2.0

240KB
5K SLoC

koios-sdk

A comprehensive Rust SDK for interacting with the Koios Cardano API. This SDK provides a strongly-typed, async interface for accessing Cardano blockchain data through Koios endpoints.

Crates.io Documentation License Tests Build Publish

Features

  • 🔄 Full coverage of Koios API endpoints
  • 🌐 Support for multiple networks (Mainnet, Preprod, Preview, Guild)
  • 🔒 Authentication support (JWT Bearer tokens)
  • ⚡ Built-in rate limiting
  • 🔄 Async/await support
  • 💪 Strong typing with comprehensive error handling
  • 📦 Zero-copy deserialization
  • 🛠️ Builder pattern for client configuration

Installation

Add this to your Cargo.toml:

[dependencies]
koios-sdk = "0.1.0"

Quick Start

use koios_sdk::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a client with default configuration (Mainnet)
    let client = Client::new()?;

    // Get the current tip of the blockchain
    let tip = client.get_tip().await?;
    println!("Current tip: {:?}", tip);

    Ok(())
}

Network Selection

use koios_sdk::{Client, Network};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Preprod network
    let client = Client::builder()
        .network(Network::Preprod)
        .build()?;

    // Get the current epoch info
    let epoch = client.get_epoch_info(None, None).await?;
    println!("Current epoch: {:?}", epoch);

    Ok(())
}

Authentication

use koios_sdk::ClientBuilder;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClientBuilder::new()
        .auth_token("your-jwt-token")
        .build()?;

    Ok(())
}

Advanced Configuration

use koios_sdk::ClientBuilder;
use governor::Quota;
use std::num::NonZeroU32;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ClientBuilder::new()
        .network(Network::Preview)
        .timeout(Duration::from_secs(30))
        .rate_limit(Quota::per_second(NonZeroU32::new(100).unwrap()))
        .build()?;

    Ok(())
}

Features

The SDK supports several optional features:

  • rustls-tls (default) - Uses rustls for TLS
  • native-tls - Uses native TLS implementation
  • full - Enables all optional features including base64 and hex encoding

Enable features in your Cargo.toml:

[dependencies]
koios-sdk = { version = "0.1.0", features = ["full"] }

Examples

Query Account Information

use koios_sdk::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new()?;
    
    let stake_addresses = vec![
        "stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7".to_string()
    ];
    
    let account_info = client.get_account_info(&stake_addresses).await?;
    println!("Account info: {:?}", account_info);
    
    Ok(())
}

Get Pool Information

use koios_sdk::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new()?;
    
    let pool_ids = vec![
        "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy".to_string()
    ];
    
    let pool_info = client.get_pool_info(&pool_ids).await?;
    println!("Pool info: {:?}", pool_info);
    
    Ok(())
}

API Coverage

The SDK provides comprehensive coverage of all Koios API endpoints, including:

Error Handling

The SDK provides detailed error types for handling various failure cases:

use koios_sdk::{Client, error::Error};

#[tokio::main]
async fn main() {
    let client = Client::new().unwrap();
    
    match client.get_tip().await {
        Ok(tip) => println!("Current tip: {:?}", tip),
        Err(Error::Api { status, message }) => {
            eprintln!("API error {}: {}", status, message);
        }
        Err(Error::RateLimit(wait_time)) => {
            eprintln!("Rate limited, retry after {} seconds", wait_time);
        }
        Err(e) => eprintln!("Other error: {}", e),
    }
}

Development

Building

To build the project:

# Debug build
cargo build

# Release build
cargo build --release

# Build with all features
cargo build --all-features

Testing

Run the test suite:

# Run all tests
cargo test

# Run tests with all features
cargo test --all-features

# Run specific test
cargo test test_name

# Run tests with output
cargo test -- --nocapture

Documentation

Generate and view the documentation:

# Generate documentation
cargo doc --no-deps

# Generate and open documentation in browser
cargo doc --no-deps --open

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Dependencies

~15–28MB
~398K SLoC