Skip to main content

Crate hypersdk

Crate hypersdk 

Source
Expand description

§hypersdk

A comprehensive Rust SDK for interacting with the Hyperliquid protocol.

Hyperliquid is a high-performance decentralized exchange with two main components:

  • HyperCore: The native L1 chain with perpetual and spot markets
  • HyperEVM: An Ethereum-compatible layer for DeFi integrations

§Quick Navigation

ModuleDescriptionCommon Use Cases
hypercoreL1 trading & dataPlace orders, query markets, stream data
hypercore::httpHTTP API clientAccount queries, order placement
hypercore::wsWebSocket streamingReal-time market data, order updates
hypercore::typesCore type definitionsOrders, trades, candles, subscriptions
hypercore::signingSignature utilitiesSign actions, recover addresses
hyperevm::morphoMorpho lendingQuery APY, lending positions
hyperevm::uniswapUniswap V3Pool prices, liquidity positions

§Features

  • Full HyperCore API support (HTTP and WebSocket)
  • Trading operations (orders, cancellations, modifications)
  • Real-time market data via WebSocket subscriptions
  • Asset transfers between perps, spot, and EVM
  • HyperEVM contract interactions (Morpho, Uniswap)
  • Type-safe EIP-712 signing for all operations
  • Accurate price tick rounding for orders
  • HIP-3 support for multi-DEX perpetuals
  • Multi-signature transaction support

§Getting Started

§Installation

Add to your Cargo.toml:

[dependencies]
hypersdk = "0.1"
rust_decimal = "1.39"
tokio = { version = "1", features = ["full"] }
anyhow = "1"

§Your First Query

use hypersdk::hypercore;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = hypercore::mainnet();
    let markets = client.perps().await?;

    for market in markets {
        println!("{}: {}x leverage", market.name, market.max_leverage);
    }
    Ok(())
}

§Placing an Order

use hypersdk::hypercore::{self, types::*, PrivateKeySigner};
use rust_decimal::dec;

let client = hypercore::mainnet();
let signer: PrivateKeySigner = "your_private_key".parse()?;

let order = BatchOrder {
    orders: vec![OrderRequest {
        asset: 0, // BTC
        is_buy: true,
        limit_px: dec!(50000),
        sz: dec!(0.1),
        reduce_only: false,
        order_type: OrderTypePlacement::Limit {
            tif: TimeInForce::Gtc,
        },
        cloid: Default::default(),
    }],
    grouping: OrderGrouping::Na,
};

let nonce = chrono::Utc::now().timestamp_millis() as u64;
let result = client.place(&signer, order, nonce, None, None).await?;

§WebSocket Subscriptions

use hypersdk::hypercore::{self, types::*, ws::Event};
use futures::StreamExt;

let mut ws = hypercore::mainnet_ws();

// Subscribe to market data
ws.subscribe(Subscription::Trades { coin: "BTC".into() });
ws.subscribe(Subscription::L2Book { coin: "ETH".into() });
ws.subscribe(Subscription::Candle {
    coin: "BTC".into(),
    interval: "15m".into()
});

// Process incoming events
while let Some(event) = ws.next().await {
    let Event::Message(msg) = event else { continue };
    match msg {
        Incoming::Trades(trades) => {
            for trade in trades {
                println!("Trade: {} @ {}", trade.sz, trade.px);
            }
        }
        Incoming::L2Book(book) => {
            println!("Book update for {}", book.coin);
        }
        Incoming::Candle(candle) => {
            println!("Candle: O:{} H:{} L:{} C:{}",
                candle.open, candle.high, candle.low, candle.close);
        }
        _ => {}
    }
}

§Architecture Overview

┌─────────────────────────────────────────────────┐
│                   hypersdk                      │
├─────────────────────┬───────────────────────────┤
│    HyperCore L1     │      HyperEVM             │
├─────────────────────┼───────────────────────────┤
│ • HTTP Client       │ • Morpho (Lending)        │
│ • WebSocket Client  │ • Uniswap V3 (DEX)        │
│ • Order Management  │ • ERC-20 Interactions     │
│ • Market Data       │                           │
│ • Transfers         │                           │
│ • EIP-712 Signing   │                           │
└─────────────────────┴───────────────────────────┘

§Architecture Decisions

§Why impl Future instead of async fn?

The SDK uses impl Future<Output = Result<...>> + Send + 'static for many methods instead of the more common async fn. This allows you to spawn futures directly:

// Direct spawning works!
tokio::spawn(client.place(order));

// Or deferred spawning
let future = client.place(order);
tokio::spawn(async move { future.await });

With async fn, the compiler cannot guarantee the future is Send + 'static when it captures &self, preventing use with tokio::spawn. See the README for detailed explanation with playground links.

§High-Precision Decimals

All prices and quantities use rust_decimal::Decimal for precise financial calculations. This avoids floating-point rounding errors that are critical in trading applications.

§Zero-Copy WebSocket

The SDK uses yawc for WebSocket connections, providing:

  • Zero-copy message parsing
  • Per-message deflate compression
  • Automatic reconnection with subscription management

§Testing

Use testnet for development and testing:

use hypersdk::hypercore;

let client = hypercore::testnet();
let mut ws = hypercore::testnet_ws();

§Examples

The examples/ directory contains comprehensive examples covering:

  • Market data queries and WebSocket streaming
  • Order placement, modification, and cancellation
  • Asset transfers between perps, spot, and EVM
  • Multi-signature transactions
  • HyperEVM interactions (Morpho, Uniswap)

§Modules

Modules§

hypercore
HyperCore L1 chain interactions.
hyperevm
HyperEVM Ethereum-compatible layer.

Macros§

address
Re-exported Ethereum address type from Alloy.
dec
Re-exported decimal type from rust_decimal.

Structs§

Address
Re-exported Ethereum address type from Alloy.
Decimal
Re-exported decimal type from rust_decimal.

Type Aliases§

U160
Re-exported Ethereum address type from Alloy.
U256
Re-exported Ethereum address type from Alloy.