Skip to content

0xvasanth/lighter-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

22 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ Lighter RS - Rust SDK for Lighter Protocol

Rust License: MIT Tests

A production-ready Rust SDK for trading on Lighter Protocol - the lightning-fast order book DEX.

Build high-performance trading applications with the power of Rust and the speed of Lighter Protocol. Fully tested on mainnet with real transactions and comprehensive documentation to get you started in minutes.

โœจ What Makes This SDK Special

  • ๐Ÿ” Production-Grade Cryptography - Poseidon2 hashing & Schnorr signatures implemented
  • โšก Blazing Fast - Rust's zero-cost abstractions for maximum performance
  • ๐Ÿ›ก๏ธ Type-Safe - Catch errors at compile time, not runtime
  • โœ… Battle-Tested - 41 unit tests passing, verified on mainnet
  • ๐Ÿ“š Well-Documented - 120+ KB of guides, examples, and tutorials
  • ๐ŸŽฏ Easy to Use - Get started in 5 minutes with our quick start guide

๐ŸŒŸ Features

Core Trading Operations โœ…

  • ๐Ÿ“ˆ Market Orders - Open and close positions instantly
  • ๐ŸŽฏ Limit Orders - Place orders on the book
  • ๐Ÿ›‘ Stop Loss - Protect your positions
  • ๐Ÿ’ฐ Take Profit - Secure your gains
  • โœ๏ธ Modify Orders - Update price and size
  • โŒ Cancel Orders - Remove orders from book

Advanced Features

  • ๐Ÿ”„ Position Management - Full control over your positions
  • โš–๏ธ Leverage Control - Adjust leverage per market
  • ๐Ÿ’ธ Fund Transfers - Move funds between accounts
  • ๐ŸŠ Pool Operations - Create and manage liquidity pools
  • ๐Ÿ” API Key Management - Secure key handling

Developer Experience

  • ๐Ÿฆ€ Pure Rust - No FFI, no external dependencies for core logic
  • โšก Async/Await - Built on Tokio for high performance
  • ๐Ÿ” Tracing - Structured logging with tracing-subscriber
  • ๐Ÿ“ Type-Safe - Compile-time guarantees for correctness
  • ๐Ÿงช Well-Tested - 41 unit tests, 30+ examples
  • ๐ŸŽจ Clean API - Intuitive and easy to use

๐Ÿ“ฆ Installation

Add this to your Cargo.toml:

[dependencies]
lighter-rs = { git = "https://github.com/0xvasanth/lighter-rs" }
tokio = { version = "1.0", features = ["full"] }
dotenv = "0.15"

โšก Quick Start (5 Minutes!)

Step 1: Get API Credentials

  1. Visit app.lighter.xyz
  2. Connect your wallet
  3. Go to Settings โ†’ API Keys โ†’ Generate New
  4. Save your credentials securely

Step 2: Create .env File

LIGHTER_API_KEY=your-40-byte-hex-key-without-0x
LIGHTER_ACCOUNT_INDEX=your-account-index
LIGHTER_API_KEY_INDEX=4
LIGHTER_CHAIN_ID=304
LIGHTER_API_URL=https://mainnet.zklighter.elliot.ai

Step 3: Write Your First Trade

use dotenv::dotenv;
use lighter_rs::client::TxClient;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize tracing
    tracing_subscriber::fmt::init();
    dotenv().ok();

    // Create client
    let client = TxClient::new(
        &env::var("LIGHTER_API_URL")?,
        &env::var("LIGHTER_API_KEY")?,
        env::var("LIGHTER_ACCOUNT_INDEX")?.parse()?,
        env::var("LIGHTER_API_KEY_INDEX")?.parse()?,
        304, // Mainnet
    )?;

    // Open a tiny position (0.0001 ETH โ‰ˆ $0.30)
    let order = client.create_market_order(
        0,             // ETH market
        chrono::Utc::now().timestamp_millis(),
        100,           // 0.0001 ETH
        3_000_000_000, // $3000 mid price
        0,             // BUY
        false,
        None,
    ).await?;

    // Submit to Lighter
    match client.send_transaction(&order).await {
        Ok(response) if response.code == 200 => {
            tracing::info!("โœ… Order placed!");
            tracing::info!("Tx Hash: {:?}", response.tx_hash);
        }
        Ok(response) => {
            tracing::warn!("Error {}: {:?}", response.code, response.message);
        }
        Err(e) => {
            tracing::error!("Failed: {}", e);
        }
    }

    Ok(())
}

Step 4: Run It!

cargo run --example create_order

You should see:

โœ… Order placed!
Tx Hash: Some("abc123...")

Congratulations! ๐ŸŽ‰ You just traded on Lighter Protocol using Rust!

๐Ÿ“š Documentation

New to Lighter RS? Start here:

Need Help?

Want Deep Dive?

๐ŸŽฏ What Can You Build?

Trading Bots

// High-frequency trading bot
// Market making strategies
// Arbitrage systems
// Grid trading

DeFi Applications

// Automated liquidity provision
// Portfolio rebalancing
// Risk management systems

Analytics Tools

// Order flow analysis
// Market data collection
// Position tracking

The possibilities are endless! This SDK gives you the building blocks to create any trading application you can imagine.

๐Ÿ’ก Common Use Cases

Open and Close Positions

// Open long position
let open = client.create_market_order(
    0, timestamp, 100, 3_000_000_000, 0, false, None
).await?;

// Close position (important: use reduce_only=true!)
let close = client.create_market_order(
    0, timestamp, 100, 3_000_000_000, 1, true, None
).await?;

Set Stop Loss Protection

use lighter_rs::types::CreateOrderTxReq;
use lighter_rs::constants::*;

let stop_loss = CreateOrderTxReq {
    market_index: 0,
    client_order_index: chrono::Utc::now().timestamp_millis(),
    base_amount: 100,
    price: 2_900_000_000,          // Execution price
    is_ask: 1,                     // SELL
    order_type: ORDER_TYPE_STOP_LOSS,
    time_in_force: TIME_IN_FORCE_IMMEDIATE_OR_CANCEL,  // Required for stop loss
    reduce_only: 1,
    trigger_price: 2_950_000_000,  // Trigger at $2950
    order_expiry: future_timestamp,
};

let tx = client.create_order(&stop_loss, None).await?;
client.send_transaction(&tx).await?;

Place and Cancel Limit Orders

// Place limit order
let limit = client.create_limit_order(
    market_index, timestamp, amount, price, is_ask, false, None
).await?;

client.send_transaction(&limit).await?;

// Cancel it later
let cancel = CancelOrderTxReq {
    market_index: 0,
    index: order_client_order_index,
};

let cancel_tx = client.cancel_order(&cancel, None).await?;
client.send_transaction(&cancel_tx).await?;

๐Ÿ› ๏ธ Development

Running Tests

# Run all unit tests (41 tests)
cargo test

# Run specific example
cargo run --example create_order

# Run with logging
RUST_LOG=debug cargo run --example create_order

Building

# Development build
cargo build

# Optimized release build
cargo build --release

# Generate documentation
cargo doc --open

Code Quality

# Format code
cargo fmt

# Run linter
cargo clippy

# Run all checks
cargo test && cargo clippy && cargo fmt --check

๐Ÿค Contributing

We welcome contributions from everyone! Whether you're fixing a bug, adding a feature, or improving documentation, your help makes this project better.

How to Contribute

  1. ๐Ÿด Fork the repository
  2. ๐ŸŒฟ Create a feature branch (git checkout -b feature/amazing-feature)
  3. โœจ Make your changes
  4. โœ… Run tests (cargo test)
  5. ๐Ÿ“ Commit your changes (git commit -m 'Add amazing feature')
  6. ๐Ÿš€ Push to branch (git push origin feature/amazing-feature)
  7. ๐ŸŽ‰ Open a Pull Request

Contribution Ideas

Good First Issues:

  • ๐Ÿ“ Improve documentation
  • ๐Ÿ› Fix typos or formatting
  • ๐Ÿงช Add more test cases
  • ๐Ÿ“‹ Create new examples
  • ๐ŸŒ Add support for more markets

Advanced Contributions:

  • ๐Ÿ” Enhance cryptographic implementations
  • โšก Performance optimizations
  • ๐ŸŽจ API improvements
  • ๐Ÿงฎ Additional transaction types
  • ๐Ÿ“Š Analytics features

Every contribution matters! Even small improvements help make this SDK better for everyone.

๐ŸŒŸ Community

Join our growing community of Rust developers building on Lighter Protocol!

๐Ÿ† Project Status

  • โœ… Core Trading: Fully functional on mainnet
  • โœ… Cryptography: Complete Poseidon2 + Schnorr implementation
  • โœ… Tests: 41 unit tests, all passing
  • โœ… Documentation: 120+ KB comprehensive guides
  • โœ… Examples: 30+ working examples
  • โœ… Mainnet Verified: 11+ successful transactions

Status: Production-ready for market order trading! ๐ŸŽ‰

๐Ÿ” Security

Private Key Safety:

  • Never commit private keys to version control
  • Use environment variables (.env file)
  • The .env file is in .gitignore by default
  • Regenerate keys if accidentally exposed

Audit Status: This SDK uses goldilocks-crypto and poseidon-hash crates for cryptography. While these are ports from the official lighter-go implementation, they have not been independently audited. Use appropriate caution in production.

๐Ÿ“– Learn More

About Lighter Protocol:

Other SDKs:

๐Ÿ’ Acknowledgments

Built with โค๏ธ by the Rust community for the Lighter Protocol ecosystem.

Special thanks to:

  • The Lighter Protocol team for building an amazing DEX
  • Contributors to goldilocks-crypto and poseidon-hash crates
  • Everyone who has tested, reported issues, or contributed code

๐Ÿ“„ License

MIT License - See LICENSE for details.


Ready to build the future of decentralized trading? ๐Ÿš€

Start with our Quick Start Guide above, explore the examples, and join our community!

Happy Trading! ๐Ÿ“ˆ

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages