ostium-rust-sdk

Crates.ioostium-rust-sdk
lib.rsostium-rust-sdk
version0.1.0
created_at2025-05-26 08:16:16.82509+00
updated_at2025-05-26 08:16:16.82509+00
descriptionRust SDK for interacting with the Ostium trading platform on Arbitrum
homepage
repositoryhttps://github.com/ranger-finance/ostium-rust-sdk
max_upload_size
id1689102
size1,328,810
YK (yongkangc)

documentation

README

Ostium Rust SDK

A modern, type-safe Rust SDK for interacting with the Ostium trading platform on Arbitrum. Built with Alloy for robust Ethereum interactions and featuring async/await support.

CI Crates.io Documentation License: MIT

Features

  • 🦀 Pure Rust Implementation - Built with Rust for performance and safety
  • 🔐 Type-Safe Contract Interactions - Leveraging Alloy for Ethereum interactions
  • Async/Await Support - Built on Tokio for efficient async operations
  • 🌐 GraphQL Integration - Direct access to Ostium's GraphQL API
  • 🔧 Flexible Configuration - Support for mainnet, testnet, and custom networks
  • 📊 Comprehensive Trading Features - Full support for perpetual trading operations
  • 🛡️ Comprehensive error handling with detailed error types
  • 🌐 Multi-network support (Mainnet & Testnet)
  • 💰 Precise decimal arithmetic for financial calculations
  • 📚 Extensive documentation and examples

Installation

Add the SDK to your Cargo.toml:

[dependencies]
ostium-rust-sdk = "0.1.0"
tokio = { version = "1.0", features = ["full"] }
rust_decimal = "1.36"

Or using cargo:

cargo add ostium-rust-sdk

Quick Start

Basic Usage (Read-only)

use ostium_rust_sdk::{OstiumClient, Network};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a client connected to testnet
    let client = OstiumClient::new(Network::Testnet).await?;
    
    // Get available trading pairs
    let pairs = client.get_pairs().await?;
    println!("Available pairs: {}", pairs.len());
    
    // Get current price for BTC/USD
    let price = client.get_price("BTC/USD").await?;
    println!("BTC/USD: ${}", price.mark_price);
    
    // Check trading hours
    let hours = client.get_trading_hours("BTC/USD").await?;
    println!("Market open: {}", hours.is_open);
    
    Ok(())
}

Trading Operations

use ostium_rust_sdk::{
    OstiumClient, Network, OpenPositionParams, PositionSide
};
use rust_decimal_macros::dec;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a client with a private key for trading
    let client = OstiumClient::builder(Network::Testnet)
        .with_private_key("your_private_key_here")?
        .build()
        .await?;
    
    // Check account balance
    let balance = client.get_balance(None).await?;
    println!("USDC Balance: {}", balance.total);
    
    // Open a long position on BTC/USD
    let position_params = OpenPositionParams {
        symbol: "BTC/USD".to_string(),
        side: PositionSide::Long,
        size: dec!(0.01),           // 0.01 BTC
        leverage: dec!(5.0),        // 5x leverage
        take_profit: Some(dec!(55000)),
        stop_loss: Some(dec!(45000)),
        slippage_tolerance: dec!(0.01), // 1%
    };
    
    let tx_hash = client.open_position(position_params).await?;
    println!("Position opened: {}", tx_hash);
    
    Ok(())
}

Architecture

The SDK is organized into several key modules:

  • client - Main client interface and builder pattern
  • contracts - Smart contract wrappers (Trading, Storage, USDC)
  • config - Network configuration and endpoints
  • types - Core data structures and enums
  • error - Comprehensive error handling

Build System & ABI Management

The SDK uses an automated build script (build.rs) that ensures contract ABIs stay synchronized with the Ostium Python SDK:

  • Automatic ABI Fetching: Downloads the latest contract ABIs from the Ostium Python SDK
  • Python to JSON Conversion: Converts Python ABI format to JSON for use with Rust web3 libraries
  • Type-Safe Bindings: Generates Rust modules with ABI constants for compile-time safety
  • Smart Change Detection: Only updates files when ABIs have actually changed
  • Efficient Builds: Skips network requests during normal builds unless explicitly requested

Updating Contract ABIs

# Force update ABIs from Python SDK
cargo build --features update-contracts

# Or delete generated files to trigger update
rm -rf src/abi/generated && cargo build

The build script generates files in src/abi/generated/:

  • Individual contract modules (e.g., trading.rs, storage.rs)
  • Module organization file (mod.rs)
  • ABI constants accessible as {CONTRACT_NAME}_ABI

Contract Addresses

Mainnet (Arbitrum One)

  • USDC: 0xaf88d065e77c8cC2239327C5EDb3A432268e5831
  • Trading: 0x6D0bA1f9996DBD8885827e1b2e8f6593e7702411
  • Storage: 0xcCd5891083A8acD2074690F65d3024E7D13d66E7

Testnet (Arbitrum Sepolia)

  • USDC: 0xe73B11Fb1e3eeEe8AF2a23079A4410Fe1B370548
  • Trading: 0x2A9B9c988393f46a2537B0ff11E98c2C15a95afe
  • Storage: 0x0b9F5243B29938668c9Cfbd7557A389EC7Ef88b8

API Reference

Client Creation

// Simple client (read-only)
let client = OstiumClient::new(Network::Testnet).await?;

// Client with private key (for trading)
let client = OstiumClient::builder(Network::Testnet)
    .with_private_key("0x...")?
    .build()
    .await?;

// Custom configuration
let client = OstiumClient::builder(Network::Testnet)
    .with_rpc_url("https://custom-rpc.com")?
    .with_private_key("0x...")?
    .build()
    .await?;

Trading Operations

// Open position
let params = OpenPositionParams { /* ... */ };
let tx_hash = client.open_position(params).await?;

// Close position
let params = ClosePositionParams {
    position_id: "trader:pair:index".to_string(),
    size: None, // Close entire position
    slippage_tolerance: dec!(0.01),
};
let tx_hash = client.close_position(params).await?;

// Update take profit and stop loss
let params = UpdateTPSLParams {
    position_id: "trader:pair:index".to_string(),
    take_profit: Some(dec!(60000)),
    stop_loss: Some(dec!(40000)),
};
let tx_hash = client.update_tp_sl(params).await?;

Market Data

// Get trading pairs
let pairs = client.get_pairs().await?;

// Get price data
let price = client.get_price("BTC/USD").await?;

// Check trading hours
let hours = client.get_trading_hours("BTC/USD").await?;

Account Management

// Get balance
let balance = client.get_balance(None).await?; // Uses signer address
let balance = client.get_balance(Some(address)).await?; // Specific address

// Get positions
let positions = client.get_positions(None).await?;

// Get orders
let orders = client.get_orders(None).await?;

Examples

Run the included examples:

# Basic usage (read-only operations)
cargo run --example basic_usage

# Price fetching and API testing
cargo run --example price_test

# Account management (balance, positions, orders)
cargo run --example account_test

# Trading operations (requires OSTIUM_PRIVATE_KEY env var)
export OSTIUM_PRIVATE_KEY=your_private_key_here
cargo run --example trading

# Contract interaction testing
cargo run --example contract_test

Error Handling

The SDK provides comprehensive error handling with detailed error types:

use ostium_rust_sdk::{OstiumError, Result};

match client.open_position(params).await {
    Ok(tx_hash) => println!("Success: {}", tx_hash),
    Err(OstiumError::Network(msg)) => println!("Network error: {}", msg),
    Err(OstiumError::Contract(msg)) => println!("Contract error: {}", msg),
    Err(OstiumError::Wallet(msg)) => println!("Wallet error: {}", msg),
    Err(OstiumError::Validation(msg)) => println!("Validation error: {}", msg),
    Err(e) => println!("Other error: {}", e),
}

Development Status

✅ Completed Features

  • Network configuration and client setup
  • Contract interfaces (Trading, Storage, USDC)
  • Type-safe contract interactions with Alloy
  • Error handling and validation
  • Basic trading operations (open, close, update TP/SL)
  • Account balance queries
  • GraphQL client foundation
  • Comprehensive examples and documentation

🚧 In Progress

  • Complete GraphQL schema implementation
  • Position and order history queries
  • Real-time price feeds and WebSocket support
  • Advanced order types (limit, stop orders)
  • Batch operations and transaction optimization

📋 Planned Features

  • Portfolio analytics and PnL calculations
  • Risk management utilities
  • Integration tests with testnet
  • Performance optimizations
  • Additional utility functions

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.

Development Setup

# Clone the repository
git clone https://github.com/ranger-finance/ostium-rust-sdk.git
cd ostium-rust-sdk

# Install dependencies
cargo build

# Run tests
cargo test

# Run examples
cargo run --example basic_usage

Security

  • Never commit private keys to version control
  • Use environment variables for sensitive data
  • Always test on testnet before mainnet
  • Keep dependencies updated

License

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

Support


Disclaimer: This SDK is for educational and development purposes. Always conduct thorough testing before using in production environments. Trading involves risk, and you should never trade with funds you cannot afford to lose.

Commit count: 0

cargo fmt