npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hypersignals/hyperliquid-privy-sdk

v0.4.1

Published

Unified Hyperliquid SDK with Privy integration for web, mobile, and backend

Readme

@hypersignals/hyperliquid-privy-sdk

A unified TypeScript SDK for trading on Hyperliquid with Privy wallet integration. Works seamlessly across React Web, React Native/Expo, and Node.js backend with a consistent API.

npm version License: MIT

Features

  • Universal API - Same methods work across web, mobile, and backend
  • Type-Safe - Full TypeScript support with comprehensive types
  • Privy Integration - Built-in support for Privy embedded wallets
  • Headless Signing - No UI popups (optional)
  • Delegated Wallets - Backend can trade on behalf of users (with permission)
  • Complete Trading Suite - Limit, market, trigger orders, TP/SL, TWAP, leverage management
  • Tree Shakeable - Import only what you need
  • Resilient Connection - Automatic REST fallback when WebSocket fails, with background recovery

Installation

npm install @hypersignals/hyperliquid-privy-sdk

Peer Dependencies

For React Web:

npm install @privy-io/react-auth

For React Native/Expo:

npm install @privy-io/expo

For Backend (Node.js): No additional dependencies needed!

Documentation

Quick Start

React Web Example (Simplified API)

// 1. Wrap your app with SDK provider (in layout/root)
import { usePrivy } from '@privy-io/react-auth';
import { HyperliquidSDKProvider } from '@hypersignals/hyperliquid-privy-sdk/web';

function Layout({ children }) {
  const { ready, wallets, signTypedData } = usePrivy();

  return (
    <HyperliquidSDKProvider
      ready={ready}
      signTypedData={signTypedData}
      wallets={wallets}
      isTestnet={false}
      builder={true}
      environment="prod"
    >
      {children}
    </HyperliquidSDKProvider>
  );
}

// 2. Use SDK in your components
import { useHyperliquidClient } from '@hypersignals/hyperliquid-privy-sdk/web';

function TradingComponent() {
  const { client, isReady } = useHyperliquidClient();

  // Place market order with TP/SL (builder fee automatically applied)
  const buyETH = async () => {
    if (!isReady || !client) return;

    const result = await client.placeSymbolOrder({
      symbol: 'ETH',        // Symbol-based (no asset IDs!)
      side: 'buy',
      orderType: 'market',
      quantity: '0.1',
      slippage: 0.05,       // Auto price calculation
      takeProfit: { triggerPrice: '4200' },
      stopLoss: { triggerPrice: '3800' },
    });

    if (result.status === 'ok') {
      console.log('Order placed with TP/SL!');
    }
  };

  return <button onClick={buyETH}>Buy ETH</button>;
}

📖 See WEB_USAGE.md for complete examples and all features

React Native/Expo Example

import { HyperliquidClient } from '@hypersignals/hyperliquid-privy-sdk';
import { useSignTypedData, useWallets } from '@privy-io/expo';

// EXACT SAME CODE AS REACT WEB! 🎉

Backend (Node.js/Telegram Bot) Example

import { createServerClient } from '@hypersignals/hyperliquid-privy-sdk/server';

// Create backend client (builder fees automatically applied)
const client = createServerClient({
  userId: 'did:privy:...',
  walletAddress: '0x...',
  appId: process.env.PRIVY_APP_ID,
  appSecret: process.env.PRIVY_APP_SECRET,
});

// Place order using symbol-based API
const result = await client.placeSymbolOrder({
  symbol: 'ETH',
  side: 'buy',
  orderType: 'market',
  quantity: '0.1',
  slippage: 0.05,
});

console.log('Order placed:', result);

Builder Fees

The SDK automatically includes a 5 basis point (0.05%) builder fee on all orders by default. This supports platform development and maintenance.

Default Configuration

  • Builder Address: 0x8af3545a3988b7A46f96F9F1AE40c0e64Fa493C2
  • Builder Fee: 5 basis points (0.05%)
  • Applied to: All order types automatically

Customization (Optional)

See BUILDER_FEES.md for:

  • How to disable builder fees
  • How to use custom builder address and fee
  • How to integrate with backend API for dynamic configuration

Example:

<HyperliquidSDKProvider
  ready={ready}
  signTypedData={signTypedData}
  wallets={wallets}
  builder={false}  // Disable builder fees
>
  {children}
</HyperliquidSDKProvider>

API Reference

Order Methods

placeLimitOrder(params)

Place a limit order.

await client.placeLimitOrder({
  asset: 0,          // Asset ID (0=BTC, 1=ETH, etc.)
  isBuy: true,       // true=long, false=short
  price: '30000',    // Limit price
  size: '0.1',       // Order size
  reduceOnly: false, // Only reduce position
  timeInForce: 'Gtc', // 'Gtc', 'Ioc', or 'Alo'
  clientOrderId: '0x...', // Optional client order ID
});

placeMarketOrder(params)

Place a market order (executed immediately with IoC).

await client.placeMarketOrder({
  asset: 0,
  isBuy: true,
  price: '30000',    // Current market price (still required by API)
  size: '0.1',
  reduceOnly: false,
});

placeTriggerOrder(params)

Place a trigger order (stop loss or take profit).

await client.placeTriggerOrder({
  asset: 0,
  isBuy: false,
  size: '0.1',
  triggerPrice: '29000', // Trigger when price hits this
  limitPrice: '28900',   // Optional: limit price when triggered (omit for market)
  reduceOnly: true,
  tpsl: 'sl',           // 'tp' or 'sl'
});

placeTpSlOrder(params)

Place both TP and SL orders for a position.

await client.placeTpSlOrder({
  asset: 0,
  size: '0.1',
  isLong: true,        // Closing a long position
  takeProfit: {
    triggerPrice: '35000',
    limitPrice: '34900', // Optional
  },
  stopLoss: {
    triggerPrice: '28000',
    limitPrice: '27900', // Optional
  },
});

batchOrders(params)

Place multiple orders in a single transaction.

await client.batchOrders({
  orders: [
    {
      asset: 0,
      isBuy: true,
      price: '30000',
      size: '0.01',
      reduceOnly: false,
      orderType: 'limit',
      timeInForce: 'Gtc',
    },
    {
      asset: 0,
      isBuy: false,
      price: '31000',
      size: '0.01',
      reduceOnly: false,
      orderType: 'limit',
      timeInForce: 'Gtc',
    },
    {
      asset: 1, // ETH
      isBuy: true,
      price: '2000',
      size: '0.1',
      reduceOnly: false,
      orderType: 'limit',
      timeInForce: 'Gtc',
    },
  ],
  grouping: 'na', // 'na' | 'normalTpsl' | 'positionTpsl'
});

modifyOrder(params)

Modify an existing order.

await client.modifyOrder({
  orderId: 123,
  order: {
    asset: 0,
    isBuy: true,
    price: '31000',    // New price
    size: '0.2',       // New size
    reduceOnly: false,
    timeInForce: 'Gtc',
  },
});

batchModifyOrders(params)

Modify multiple orders in a single transaction.

await client.batchModifyOrders({
  modifies: [
    {
      orderId: 123,
      order: {
        asset: 0,
        isBuy: true,
        price: '31000',
        size: '0.2',
        reduceOnly: false,
        timeInForce: 'Gtc',
      },
    },
    {
      orderId: 456,
      order: {
        asset: 1,
        isBuy: false,
        price: '2100',
        size: '0.15',
        reduceOnly: false,
        timeInForce: 'Gtc',
      },
    },
  ],
});

cancelOrders(params)

Cancel orders by ID.

await client.cancelOrders({
  cancels: [
    { asset: 0, orderId: 123 },
    { asset: 1, orderId: 456 },
  ],
});

cancelAllOrders(asset?)

Cancel all orders (optionally for a specific asset).

await client.cancelAllOrders(0); // Cancel all BTC orders
await client.cancelAllOrders();  // Cancel all orders

Leverage & Margin Methods

updateLeverage(params)

Set leverage and margin mode.

await client.updateLeverage({
  asset: 0,
  isCross: true,    // true=cross, false=isolated
  leverage: 5,      // 1-50x
});

setMarginMode(params)

Helper to set margin mode.

await client.setMarginMode({
  asset: 0,
  mode: 'cross',    // 'cross' or 'isolated'
  leverage: 5,
});

updateIsolatedMargin(params)

Add or remove margin from isolated position.

await client.updateIsolatedMargin({
  asset: 0,
  isBuy: true,      // Long or short side
  amountUsd: 100,   // Positive to add, negative to remove
});

TWAP Methods

placeTwapOrder(params)

Place a TWAP (Time-Weighted Average Price) order.

await client.placeTwapOrder({
  asset: 0,
  isBuy: true,
  size: '1.0',
  durationMinutes: 60,  // Spread over 1 hour
  randomizeTiming: true,
  reduceOnly: false,
});

cancelTwapOrder(params)

Cancel a TWAP order.

await client.cancelTwapOrder({
  asset: 0,
  twapId: 1,
});

Schedule Cancel (Dead Man's Switch)

scheduleCancel(timeMs?)

Schedule automatic cancellation of all orders.

// Cancel all orders in 1 hour
await client.scheduleCancel(Date.now() + 3600000);

// Remove scheduled cancel
await client.removeScheduledCancel();

DEX Abstraction (HIP-3)

getDexAbstractionState(userAddress?)

Check if DEX fee abstraction is enabled for a wallet.

// Check current user's DEX abstraction status
const status = await client.getDexAbstractionState();

if (status === true) {
  console.log('DEX abstraction is enabled');
} else if (status === false) {
  console.log('DEX abstraction is disabled');
} else {
  console.log('DEX abstraction is not set');
}

// Check another user's status
const otherUserStatus = await client.getDexAbstractionState('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb');

enableAgentDexAbstraction()

Enable DEX fee abstraction using Agent signing.

const result = await client.enableAgentDexAbstraction();

if (result.status === 'ok') {
  console.log('DEX abstraction enabled successfully!');
} else {
  console.error('Failed to enable:', result.message);
}

Note: Once enabled via Agent, DEX abstraction cannot be disabled. This is by design in Hyperliquid's HIP-3 implementation.

Backend-Specific Features

Getting Delegated Wallets

import { HyperliquidBackendClient } from '@hypersignals/hyperliquid-privy-sdk/backend';

const client = new HyperliquidBackendClient({
  privy: { appId: '...', appSecret: '...', walletId: '...' },
});

// Get all delegated wallets for a user
const wallets = await client.getUserDelegatedWallets('privy-user-id');
console.log(wallets);
// [{ address: '0x...', walletId: 'prv_...', chainType: 'ethereum' }]

Delegated Wallet Setup (Required for Backend)

For backend trading, users must first delegate their wallet:

Frontend: Delegate Wallet

import { useDelegatedActions, useWallets } from '@privy-io/react-auth';

function DelegateButton() {
  const { delegateWallet } = useDelegatedActions();
  const { wallets } = useWallets();

  const handleDelegate = async () => {
    await delegateWallet({
      address: wallets[0].address,
      chainType: 'ethereum',
    });
    // User sees Privy modal to approve delegation
  };

  return <button onClick={handleDelegate}>Delegate Wallet</button>;
}

Asset IDs

Common asset IDs (use these in the asset parameter):

import { ASSET_IDS } from '@hypersignals/hyperliquid-privy-sdk';

ASSET_IDS.BTC   // 0
ASSET_IDS.ETH   // 1
ASSET_IDS.SOL   // 2
ASSET_IDS.ARB   // 3
ASSET_IDS.AVAX  // 4

Error Handling

try {
  await client.placeLimitOrder({ ... });
} catch (error) {
  if (error instanceof Error) {
    console.error('Order failed:', error.message);
    // Common errors:
    // - "Insufficient margin"
    // - "Invalid price"
    // - "User rejected the request"
    // - "Request timeout after 30000ms"
  }
}

Connection Resilience

The SDK automatically handles WebSocket connection issues:

  • WebSocket errors (connection failed, network issues) → Automatically falls back to REST API
  • API errors (insufficient margin, invalid price) → Thrown as exceptions (no fallback)
  • Background recovery → WebSocket reconnects automatically in the background
  • Automatic switch back → When WebSocket recovers, SDK switches back from REST

You can check the current transport state:

const { client } = useHyperliquidClient();

// Check if currently using REST fallback
if (client?.isUsingRestFallback()) {
  console.log('Using REST API (WebSocket recovering in background)');
}

Advanced Usage

Custom Timeout

import { HyperliquidClient } from '@hypersignals/hyperliquid-privy-sdk';
import { HyperliquidAPIClient } from '@hypersignals/hyperliquid-privy-sdk/core/utils/api';

// Default timeout is 30 seconds
// For custom timeout, you'll need to extend the client

Testing with Testnet

<HyperliquidSDKProvider
  ready={ready}
  signTypedData={signTypedData}
  wallets={wallets}
  isTestnet={true}  // Use Hyperliquid testnet
>
  {children}
</HyperliquidSDKProvider>

TypeScript Support

Full TypeScript support with comprehensive types:

import type {
  OrderResponse,
  SuccessResponse,
  CancelResponse,
  LimitOrderParams,
  MarketOrderParams,
  TriggerOrderParams,
} from '@hypersignals/hyperliquid-privy-sdk';

Examples

See the examples directory for complete implementations:

Development

# Install dependencies
npm install

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Build
npm run build

# Lint
npm run lint

# Type check
npm run typecheck

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © HyperSignals

Support

Acknowledgments