hypersdk Rust SDK for Hyperliquid

repository·main·Indexed 41 days ago

https://github.com/infinitefield/hypersdk

A comprehensive Rust SDK (v0.2.15) for interacting with the Hyperliquid protocol, supporting the native HyperCore L1 (perpetuals and spot) and the HyperEVM layer (including Morpho and Uniswap integrations). Includes the hypecli command-line tool for managing Foundry-compatible keystores, placing orders, querying market data, and handling P2P multi-signature transactions and gossip priority bidding.

Tokens
41.2K
Snippets
126
Records
176
Agent score
50%

What's inside hypersdk

  1. Use asset name formats for trading

    main

    Hyperliquid uses specific string formats to identify assets depending on the market type:

    FormatExampleDescription
    SYMBOLBTC, ETHPerpetual on Hyperliquid DEX
    BASE/QUOTEPURR/USDCSpot market
    dex:SYMBOLxyz:BTCPerpetual on a specific HIP-3 DEX

    To trade on a third-party exchange, always prefix the asset with the DEX name and a colon (e.g., xyz:BTC).

  2. Understanding the Async Design: `impl Future` vs `async`

    main

    The SDK uses impl Future<Output = Result<...>> + Send + 'static instead of the async keyword for many methods.

    Why? When a function captures &self, the Rust compiler cannot guarantee that the object will live long enough to satisfy the 'static requirement needed for tokio::spawn. By explicitly returning impl Future, the SDK ensures that the returned future is Send and 'static, allowing you to spawn tasks directly without lifetime errors.

    Usage Pattern:

    // Direct spawning (fire and forget) works because the future is 'static
    tokio::spawn(client.place());
    
    // Or deferred spawning
    let future = client.place();
    tokio::spawn(async move {
        let res = future.await;
        match res {
            ...
        }
    })
  3. How P2P Multi-Signature works

    main

    The multisig feature allows coordinating transactions using decentralized peer-to-peer gossip via the Iroh protocol, requiring no centralized server.

    Workflow

    1. Initiation: The initiator creates a proposal and waits for signers to connect.
    2. Discovery: Signers find each other via mDNS (local), DNS (n0 relay), or direct connection via an endpoint ticket.
    3. Signing: Authorized signers review the transaction details and cryptographically sign them.
    4. Submission: Once the threshold is met, the transaction is submitted.

    Initiating a transaction

    hypecli multisig send-asset \
      --multi-sig-addr 0xYourMultiSigWallet... \
      --chain Mainnet \
      --to 0xRecipient... \
      --token USDC \
      --amount 100 \
      --keystore my-wallet

    Signing a transaction

    Signers use the connection endpoint provided by the initiator:

    hypecli multisig sign \
      --multi-sig-addr 0xYourMultiSigWallet... \
      --chain Mainnet \
      --connect endpoint... \
      --keystore another-wallet

    Signer Authentication Options:

    • --private-key 0x...: Direct hex private key.
    • --keystore filename: Foundry keystore (prompts for password).
    • No flag: Automatically searches for connected Ledger devices.
    hypecli multisig send-asset --multi-sig-addr 0xYourMultiSigWallet... --chain Mainnet --to 0xRecipient... --token USDC --amount 100 --keystore my-wallet
  4. Security best practices for Hyperliquid agents

    main

    When managing agent payments on Hyperliquid, follow these security guidelines:

    • Use encrypted keystores: Never store plaintext private keys.
    • Use API wallets for bots: Create API wallets at https://app.hyperliquid.xyz/API. These allow trading but prevent fund withdrawals, limiting damage if a key is compromised.
    • Keep minimal balances: Only maintain the funds necessary for near-term operations.
  5. How Gossip Priority (Dutch Auction) works

    main

    Hyperliquid's gossip network uses 5 Dutch auction slots (indices 0–4) to provide read-priority ordering. Winning a slot allows your node to receive transaction data faster than non-winners.

    Priority Levels

    Lower slot indices provide higher priority (faster data access):

    • Slot 0: ~50ms faster than no-bid nodes
    • Slot 1: ~40ms faster
    • Slot 2: ~30ms faster
    • Slot 3: ~20ms faster
    • Slot 4: ~10ms faster

    Bidding Mechanism

    • You bid using --max (your ceiling), but you pay the live currentGas price at the time of mining.
    • Any difference between the currentGas and your --max is automatically refunded.
    • Winning bid amounts are burned from your spot HYPE balance.
    • If currentGas >= --max, the bid is skipped.

    Commands

    Check current auction status and prices:

    hypecli prio status

    Place a bid for a specific slot:

    hypecli prio bid \
      --keystore if_dev \
      --ip 52.196.250.75 \
      --max 1 \
      --slot 0
    hypecli prio status
  6. Manage Foundry-compatible keystores

    main

    The hypecli account command manages keystores stored in ~/.foundry/keystores/. These are compatible with Foundry's cast tool. You can reference a keystore in other commands using the --keystore flag.

    Create a new keystore

    Creates a new keystore with a random private key. You will be prompted to enter and confirm a password.

    hypecli account create --name my-wallet

    List available keystores

    hypecli account list
    hypecli account create --name my-wallet
  7. Query market data (Perps, Spot, and DEXes)

    main

    Use these commands to explore available trading pairs and markets on Hyperliquid and HIP-3 DEXes.

    List HIP-3 DEXes

    List all available HIP-3 perpetual DEXes:

    hypecli dexes

    List Perpetual Markets

    List perpetual markets from Hyperliquid or a specific HIP-3 DEX:

    # List all Hyperliquid perpetual markets
    hypecli perps
    
    # List perpetual markets from a specific HIP-3 DEX
    hypecli perps --dex xyz

    List Spot Markets

    List all spot trading pairs:

    hypecli spot
  8. Run HyperCore examples

    main

    HyperCore examples are categorized by complexity.

    Beginner (Read-only)

    Use these to explore market data and queries without needing a private key.

    • list-markets: List perpetual markets (leverage, tick size).
    • list-tokens: List spot tokens.
    • list-hip3: Query HIP-3 DEXes.
    • websocket: Real-time trades, order books, and user events.
    • websocket-user-events: Real-time userEvents, TWAP, etc. (requires --user <address>).
    • websocket-candles: Real-time OHLCV data.
    • vault_details: Vault performance metrics.
    • user_vault_equities: User vault deposits.
    • user_role: Query address roles (User, Vault, Agent, SubAccount).

    Intermediate (State-changing)

    Requires a private key.

    • send_order: Place a limit order.
    • send_usd: Transfer USDC between perpetual balances.
    • transfer_to_evm / transfer_from_evm: Cross-chain transfers.
    • transfer_to_perps / transfer_to_spot: Move assets between balance types.
    • vault_transfer: Deposit/withdraw from a vault.
    • subaccounts: List subaccounts.
    • approve-agent: Approve an API agent.

    Advanced (Complex Flows)

    • multisig_order: Orders with multiple signers.
    • multisig_send_usd: Multi-sig USDC transfer.
    • multisig_send_asset: Multi-sig asset transfer between DEXes.
    • multisig-approve-agent: Multi-sig agent approval.
    • buy_and_transfer: Order -> Fill -> Transfer to EVM.
    • priority-fee-bid: Bid on gossip priority Dutch auction.
    cargo run --example list-markets
    cargo run --example send_order
    cargo run --example websocket-user-events -- --user 0xYourAddress
  9. Set up a Hyperliquid wallet with hypecli

    main

    To manage funds, you must create an encrypted keystore. Keystores are stored in ~/.foundry/keystores/ and are compatible with Foundry tools. When you create an account, the CLI will display your Hyperliquid address, which you should use to receive payments.

    Use hypecli account create to initialize a new wallet and hypecli account list to view existing ones.

    # Create a new wallet with encrypted keystore
    hypecli account create --name default --password yourpassword
    
    # List available keystores
    hypecli account list
  10. Setup environment variables for private keys

    main

    The SDK typically requires a private key to be provided via an environment variable. You can set this in your shell or use a .env file for local development.

    Shell:

    export PRIVATE_KEY="your_private_key_here"

    .env file:

    PRIVATE_KEY=your_private_key_here
  11. Set up Hypersdk environment variables

    main

    Most state-changing examples (trading, transfers, etc.) require a private key. You can provide this by setting the PRIVATE_KEY environment variable or by creating a .env file in your project root.

    Environment Variable:

    export PRIVATE_KEY="your_private_key_here"

    Using a .env file:

    PRIVATE_KEY=your_private_key_here
    export PRIVATE_KEY="your_private_key_here"
    # OR
    PRIVATE_KEY=your_private_key_here