Skip to content

0xBoji/hyperliquid-swift-sdk

Repository files navigation

πŸš€ Hyperliquid Swift SDK

A complete Swift SDK for the Hyperliquid decentralized exchange.

Current Version: v1.6.0 🎯

Swift Platform License Version Code style: SwiftFormat Lint: SwiftLint

✨ Features

  • πŸ” Complete Trading API: Place orders, cancel orders, manage positions
  • πŸ“Š Real-time Market Data: Prices, order books, trade history
  • πŸ’° Account Management: Portfolio tracking, balance queries, user state
  • πŸ’Έ Transfer Operations: USD, spot tokens, sub-accounts, vault transfers
  • πŸ”§ Advanced Features: Multi-sig, token delegation, bridge operations
  • πŸ”’ EIP-712 Signing: Secure transaction signing with Ethereum standards
  • ⚑️ Type Safety: Full Swift type system with Codable support
  • 🎯 Async/Await: Modern Swift concurrency support
  • 🌐 Multi-Environment: Testnet and Mainnet support
  • πŸ›‘οΈ Enterprise Grade: Production-ready cryptography and error handling
  • πŸ› οΈ Development Tools: Makefile, SwiftLint, SwiftFormat for code quality

βœ… Implemented Feature Checklist

  • Trading
    • Limit/Market orders, Modify, Cancel, Schedule cancel
    • Bulk orders and Batch modify orders
    • Cancel by client order ID, Cancel all orders
  • Market Data & Queries
    • All mids, L2 order book, Candle snapshot
    • Meta, MetaAndAssetCtxs, SpotMeta, SpotMetaAndAssetCtxs
    • User/Spot state, Open/Frontend open orders, User fills (+by time)
    • Funding history, User funding history, User fees
    • Query order by oid/cloid, Referral state
    • Perp dex list, Multi‑sig signers, Perp deploy auction status
    • Sub‑accounts query (raw JSON)
  • Account Management
    • Update leverage, Update isolated margin, Set referrer
  • Sub Accounts
    • Create sub account
  • Transfer Operations
    • USD class transfer, USD transfer, Spot transfer
    • Sub account transfer, Vault USD transfer, Send asset
    • Sub account spot transfer, Approve agent
  • Advanced Features
    • Token delegate, Withdraw from bridge
    • Approve builder fee, Convert to multi-sig user
    • Multi-sig operations, Use big blocks
  • Real‑time
    • WebSocket subscriptions
  • Development Tools
    • Makefile with common commands
    • SwiftLint configuration
    • SwiftFormat configuration
    • Constants for easy customization
    • Error types (ClientError, ServerError, NetworkError)
    • Market making strategy example

πŸ›£οΈ Future Features

  • Map querySubAccounts β†’ strong models (with nested UserState)
  • More examples and docs for new APIs
  • TPSL helpers and risk utilities
  • CI matrix expansion (macOS versions, optional Linux build-only)
  • Transfer/withdraw operations kept off by default for mobile safety (opt‑in discussion)

πŸ“¦ Installation

Swift Package Manager

Add to your Package.swift:

dependencies: [
    .package(url: "https://github.com/0xboji/hyperliquid-swift-sdk.git", from: "1.0.0")
]

πŸš€ Quick Start

import HyperliquidSwift

// Initialize client
let client = try HyperliquidClient(
    privateKeyHex: "your_private_key_here",
    environment: .testnet
)

// Get market data
let prices = try await client.getAllMids()
print("BTC Price: \(prices["BTC"] ?? 0)")

// Place a limit order
let response = try await client.limitBuy(
    coin: "ETH",
    sz: Decimal(0.1),
    px: Decimal(3000.0),
    reduceOnly: false
)

πŸ› οΈ Development Tools

Makefile Commands

# Build the package
make build

# Run tests
make test

# Run linting
make lint

# Format code
make format

# Clean build artifacts
make clean

# Install dependencies
make install

# Generate documentation
make docs

# Run all examples
make examples

# Run security checks
make security

Code Quality

The SDK includes:

  • SwiftLint: Code linting with custom rules
  • SwiftFormat: Automatic code formatting
  • Constants: Easy customization points
  • Error Types: Comprehensive error handling

πŸ“– API Reference

πŸ“Š Market Data

// Get all market prices
let prices = try await client.getAllMids()

// Get exchange metadata
let meta = try await client.getMeta()

// Get metadata with asset contexts
let metaAndCtxs = try await client.getMetaAndAssetCtxs()

// Get spot market metadata
let spotMeta = try await client.getSpotMeta()

// Get spot metadata with asset contexts
let spotMetaAndCtxs = try await client.getSpotMetaAndAssetCtxs()

// Get user state
let userState = try await client.getUserState()

πŸ’Ή Trading Operations

// Place limit buy order
let buyResponse = try await client.limitBuy(
    coin: "ETH",
    sz: Decimal(0.1),
    px: Decimal(3000.0),
    reduceOnly: false
)

// Place limit sell order
let sellResponse = try await client.limitSell(
    coin: "ETH",
    sz: Decimal(0.1),
    px: Decimal(3500.0),
    reduceOnly: false
)

// Place market orders
let marketBuy = try await client.marketBuy(coin: "ETH", sz: Decimal(0.1))
let marketSell = try await client.marketSell(coin: "BTC", sz: Decimal(0.01))

// Cancel single order
let cancelResponse = try await client.cancelOrder(coin: "ETH", oid: 12345)

// Cancel all orders for a coin
let cancelAllETH = try await client.cancelAllOrders(coin: "ETH")

// Cancel all orders across all coins
let cancelAll = try await client.cancelAllOrders()

// Modify existing order
let modifyResponse = try await client.modifyOrder(
    oid: 12345,
    coin: "ETH",
    newPrice: Decimal(3200.0),
    newSize: Decimal(0.05)
)

πŸ“ˆ Account Information

// Get open orders
let openOrders = try await client.getOpenOrders()

// Get enhanced frontend open orders (with trigger conditions)
let frontendOrders = try await client.getFrontendOpenOrders(address: userAddress)

// Get user fills
let fills = try await client.getUserFills()

// Get user fills by time range
let recentFills = try await client.getUserFillsByTime(
    startTime: Date().addingTimeInterval(-86400), // 24 hours ago
    endTime: Date()
)

// Get user fees and trading volume
let userFees = try await client.getUserFees(address: userAddress)

// Get user funding history
let fundingHistory = try await client.getUserFunding(
    user: userAddress,
    startTime: Int(Date().addingTimeInterval(-86400).timeIntervalSince1970 * 1000),
    endTime: Int(Date().timeIntervalSince1970 * 1000)
)

// Get funding rate history for a specific coin
let btcFunding = try await client.getFundingHistory(
    coin: "BTC",
    startTime: Int(Date().addingTimeInterval(-86400).timeIntervalSince1970 * 1000)
)

// Query referral state
let referralState = try await client.queryReferralState(user: userAddress)

// Query sub accounts
let subAccounts = try await client.querySubAccounts(user: userAddress)

πŸ’Έ Transfer Operations

// Transfer USDC between spot and perp wallets
let spotToPerp = try await client.usdClassTransfer(amount: Decimal(100.0), toPerp: true)
let perpToSpot = try await client.usdClassTransfer(amount: Decimal(100.0), toPerp: false)

// Transfer USDC to another address
let usdTransfer = try await client.usdTransfer(
    amount: Decimal(50.0),
    destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45"
)

// Transfer spot tokens
let spotTransfer = try await client.spotTransfer(
    amount: Decimal(10.0),
    destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    token: "PURR:0xc4bf3f870c0e9465323c0b6ed28096c2"
)

// Transfer to/from sub account
let subAccountDeposit = try await client.subAccountTransfer(
    subAccountUser: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    isDeposit: true,
    usd: Decimal(25.0)
)

// Vault USD transfer (institutional trading)
let vaultDeposit = try await client.vaultUsdTransfer(
    vaultAddress: "0xa15099a30bbf2e68942d6f4c43d70d04faeab0a0",
    isDeposit: true,
    usd: 5_000_000 // $5 in micro-USD
)

πŸ”§ Advanced Features

// Token delegation to validator
let delegate = try await client.tokenDelegate(
    validator: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    wei: 1000000000000000000, // 1 token in wei
    isUndelegate: false
)

// Withdraw from bridge
let withdraw = try await client.withdrawFromBridge(
    amount: Decimal(10.0),
    destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45"
)

// Convert to multi-signature user
let convertToMultiSig = try await client.convertToMultiSigUser(
    authorizedUsers: [
        "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
        "0xa15099a30bbf2e68942d6f4c43d70d04faeab0a0"
    ],
    threshold: 2
)

// Enable big blocks for better performance
let bigBlocks = try await client.useBigBlocks(enable: true)

// Send asset between DEXs
let assetTransfer = try await client.sendAsset(
    destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    sourceDex: "",
    destinationDex: "spot",
    token: "USDC",
    amount: Decimal(10.0)
)

// Sub account spot transfer
let subSpotTransfer = try await client.subAccountSpotTransfer(
    subAccountUser: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    isDeposit: true,
    token: "USDC",
    amount: Decimal(5.0)
)

// Approve agent for automated trading
let agentApproval = try await client.approveAgent(
    agentAddress: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
    agentName: "TradingBot"
)

πŸ’‘ Examples

Run the included examples:

# Market data and account queries
swift run BasicUsage

# Basic trading tutorial
swift run TradingExample

# Advanced trading operations (market orders, cancel all, modify)
swift run AdvancedTradingExample

# Market making strategy (similar to Python SDK's basic_adding.py)
swift run MarketMakingExample

# New Info API methods (fees, funding, referrals, sub accounts)
swift run NewMethodsExample

# Transfer operations (USD, spot tokens, sub accounts)
swift run TransferExample

# Multi-signature operations
swift run ConvertToMultiSigExample
swift run MultiSigOrderExample

# Builder fees and routing
swift run BuilderFeeExample

# Performance optimization
swift run UseBigBlocksExample

# TPSL (Take Profit/Stop Loss) orders
swift run TPSLOrdersExample

# Bulk cancellation and order expiration
swift run BulkCancelExample

# Validator management operations
swift run ValidatorManagementExample

# Token and asset deployment
swift run DeploymentExample

# Agent wallet management
swift run AgentManagementExample

# Advanced deployment operations
swift run AdvancedDeploymentExample

# Advanced spot token operations
swift run AdvancedSpotOperationsExample

πŸ“‹ Example Categories

  • Core Trading: Basic usage, advanced trading, market orders, TPSL orders
  • Market Making: Automated liquidity provision strategy
  • Account Management: Leverage, margin, referrals, sub-accounts
  • Transfer Operations: USD, spot tokens, sub-accounts, vault transfers
  • Advanced Features: Multi-sig, builder fees, big blocks, token delegation
  • Order Management: Bulk cancellation, order expiration, advanced cancellation
  • Validator Operations: Validator registration, profile management, signer operations
  • Deployment Operations: Spot token and perpetual asset deployment, genesis operations
  • Agent Management: Agent wallet creation and approval for automated trading
  • Real-time Data: WebSocket subscriptions and market data streaming

Each example corresponds to similar functionality in the Python SDK examples, ensuring consistency across implementations.

πŸ“‹ Changelog

v1.6.1 - Development Tools & Market Making πŸ› οΈ

  • βœ… Development Tools: Added Makefile, SwiftLint, SwiftFormat
  • βœ… Constants: Added Constants.swift for easy customization
  • βœ… Error Types: Added ClientError, ServerError, NetworkError
  • βœ… Market Making: Added MarketMakingExample (similar to Python SDK's basic_adding.py)
  • βœ… Code Quality: Comprehensive linting and formatting rules
  • βœ… Documentation: Updated README with development tools section

v1.6.0 (Latest) - Beyond 100% - Advanced Spot Operations πŸš€

  • βœ… Freeze Operations: spotDeployEnableFreezePrivilege, spotDeployFreezeUser, spotDeployRevokeFreezePrivilege
  • βœ… Hyperliquidity: spotDeployRegisterHyperliquidity for automated market making
  • βœ… Fee Management: spotDeploySetDeployerTradingFeeShare for revenue sharing
  • βœ… Advanced Example: AdvancedSpotOperationsExample with compliance features
  • βœ… 105% Coverage: Now exceeds Python SDK baseline (105/100 methods)
  • βœ… Compliance Ready: Complete regulatory and freeze management tools
  • 🎯 MILESTONE: First SDK to exceed Python SDK feature coverage

v1.5.0 - 100% Feature Parity Achievement πŸŽ‰

  • βœ… Agent Management: approveAgent for automated trading wallet creation
  • βœ… Advanced Deployment: spotDeployGenesis, spotDeployRegisterSpot, spotDeployUserGenesis
  • βœ… Oracle Management: perpDeploySetOracle for perpetual price feeds
  • βœ… Complete Examples: AgentManagementExample and AdvancedDeploymentExample
  • βœ… 100% Feature Parity: All 100/100 methods implemented
  • βœ… Production Complete: Full compatibility with Python SDK
  • 🎯 MILESTONE: First mobile SDK with complete Hyperliquid API coverage

v1.4.0 - Infrastructure & Deployment Operations

  • βœ… Validator Management: changeValidatorProfile for validator configuration updates
  • βœ… Signer Operations: cSignerUnjailSelf and cSignerJailSelf for network participation
  • βœ… Spot Deployment: spotDeployRegisterToken for new token registration
  • βœ… Perpetual Deployment: perpDeployRegisterAsset for new asset registration
  • βœ… New Examples: ValidatorManagementExample and DeploymentExample
  • βœ… 98% Feature Parity: 95/97 methods implemented
  • βœ… Infrastructure Ready: Complete validator and deployment support

v1.3.0 - Advanced Trading Features

  • βœ… TPSL Orders: stopLossOrder and takeProfitOrder for automated risk management
  • βœ… Bulk Cancellation: bulkCancelByCloid for efficient order management
  • βœ… Order Expiration: setExpiresAfter for automated order lifecycle
  • βœ… Validator Operations: registerValidator and unregisterValidator
  • βœ… New Examples: TPSLOrdersExample and BulkCancelExample
  • βœ… 96% Feature Parity: 88/92 methods implemented
  • βœ… Enhanced Testing: Comprehensive test coverage for all new methods

v1.2.0 - Multi-Sig and Advanced Features

  • βœ… Multi-signature user conversion and operations
  • βœ… Builder fee approval and routing
  • βœ… Big blocks configuration
  • βœ… Token delegation and bridge operations

v1.1.0 - Core Foundation

  • βœ… Complete trading operations (limit, market, cancel, modify)
  • βœ… Transfer operations and account management
  • βœ… Real-time WebSocket support
  • βœ… Comprehensive market data queries

πŸ§ͺ Testing

The SDK includes comprehensive tests covering all functionality:

# Run all tests
swift test

# Build only (faster verification)
swift build

# Run specific test suites
swift test --filter NewMethodsTests
swift test --filter HyperliquidClientTests

Test Coverage

  • Method Signatures: Verify all methods exist with correct signatures
  • Parameter Validation: Test parameter handling and validation
  • Error Handling: Ensure proper error propagation
  • Integration Tests: Test real API interactions (when configured)
  • Mock Tests: Unit tests with mocked responses

The test suite ensures compatibility with the Python SDK and validates all newly implemented methods.

Example Output:

πŸš€ Hyperliquid Swift SDK - Basic Usage Examples
==================================================

πŸ“ˆ Market Summary
=================
Active Markets: 1441

πŸ“Š Account Summary
==================
Address: 0x1234...7890
Account Value: $8.199509
Total Margin Used: $0
Positions: 0
Open Orders: 0

βš™οΈ Configuration

Create Examples/config.json:

{
    "private_key": "your_private_key_hex",
    "environment": "testnet"
}

πŸ”§ Requirements

  • iOS 13.0+ / macOS 10.15+
  • Swift 5.5+
  • Xcode 13.0+

πŸ“š Dependencies

πŸ—οΈ Architecture

HyperliquidSwift/
β”œβ”€β”€ Models/           # Data models and types
β”œβ”€β”€ Services/         # Core services
β”‚   β”œβ”€β”€ CryptoService.swift    # EIP-712 signing
β”‚   β”œβ”€β”€ HTTPClient.swift       # Network layer
β”‚   └── TradingService.swift   # Trading operations
β”œβ”€β”€ Utils/            # Utilities and helpers
β”‚   β”œβ”€β”€ Constants.swift        # Global constants
β”‚   β”œβ”€β”€ ErrorTypes.swift       # Error handling
β”‚   └── Validation.swift       # Input validation
└── HyperliquidClient.swift    # Main client interface

πŸ” Security

  • EIP-712 compliant transaction signing
  • secp256k1 elliptic curve cryptography
  • Keccak256 hashing for Ethereum compatibility
  • Private key never leaves your application

πŸ§ͺ Testing

swift test

πŸ“„ License

MIT License - see LICENSE file for details.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ’¬ Support

πŸŽ‰ Acknowledgments

Built with ❀️ for the Hyperliquid community.


Ready to trade on Hyperliquid with Swift? Let's go! πŸš€

About

A proper Swift SDK for Hyperliquid. Clean API, great docs, works perfectly in Xcode!

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published