JSPM

  • Created
  • Published
  • Downloads 793
  • Score
    100M100P100Q110265F
  • License MIT

React SDK for Pear Protocol Hyperliquid API integration

Package Exports

  • @pear-protocol/hyperliquid-sdk

Readme

@pear-protocol/hyperliquid-sdk

A React SDK for integrating with Pear Protocol's Hyperliquid trading API. This SDK provides React hooks, WebSocket connections, and utilities for building trading applications on the Hyperliquid perpetuals exchange.

Features

  • React Integration: Purpose-built React hooks for trading data and operations
  • Real-time Data: WebSocket connections for live market data and account updates
  • Authentication: EIP-712 signature and Privy wallet integration
  • Trading Operations: Position management, order placement, and portfolio tracking
  • Agent Wallets: Automated trading wallet creation and management
  • TypeScript Support: Full TypeScript definitions for all APIs and data structures

Installation

npm install @pear-protocol/hyperliquid-sdk
# or
yarn add @pear-protocol/hyperliquid-sdk

Peer Dependencies

This package requires React 18+ as a peer dependency:

npm install react react-dom

Quick Start

1. Provider Setup

Wrap your application with the PearHyperliquidProvider:

import { PearHyperliquidProvider } from '@pear-protocol/hyperliquid-sdk';

function App() {
  return (
    <PearHyperliquidProvider
      apiBaseUrl="https://api.pear.garden"
      wsUrl="wss://api.pear.garden/ws"
      clientId="your-app-name"
    >
      <TradingApp />
    </PearHyperliquidProvider>
  );
}

2. Authentication

Use the authentication hook to handle wallet connections:

import { usePearAuth } from '@pear-protocol/hyperliquid-sdk';

function LoginComponent() {
  const {
    isAuthenticated,
    getEip712,
    loginWithSignedMessage,
    logout
  } = usePearAuth();

  const handleWalletConnect = async (address: string, signMessage: Function) => {
    try {
      // Get EIP-712 message to sign
      const messageData = await getEip712(address);

      // Sign the message with user's wallet
      const signature = await signMessage(messageData.message);

      // Authenticate with Pear Protocol
      await loginWithSignedMessage(address, signature, messageData.timestamp);
    } catch (error) {
      console.error('Authentication failed:', error);
    }
  };

  if (isAuthenticated) {
    return <button onClick={logout}>Logout</button>;
  }

  return <WalletConnectButton onConnect={handleWalletConnect} />;
}

3. Trading Data

Access real-time trading data with built-in hooks:

import {
  useOpenPositions,
  useOpenOrders,
  useAccountSummary,
  usePearHyperliquid
} from '@pear-protocol/hyperliquid-sdk';

function TradingDashboard() {
  const { address, setAddress } = usePearHyperliquid();
  const { data: positions, isLoading: positionsLoading } = useOpenPositions();
  const { data: orders, isLoading: ordersLoading } = useOpenOrders();
  const { data: accountSummary } = useAccountSummary();

  // Set the address to track
  useEffect(() => {
    if (userWalletAddress) {
      setAddress(userWalletAddress);
    }
  }, [userWalletAddress, setAddress]);

  if (positionsLoading) return <div>Loading positions...</div>;

  return (
    <div>
      <h2>Account Summary</h2>
      <div>Total Value: ${accountSummary?.accountValue?.toFixed(2)}</div>

      <h2>Open Positions</h2>
      {positions?.map((position) => (
        <div key={position.coin}>
          {position.coin}: {position.szi} @ ${position.entryPx}
        </div>
      ))}

      <h2>Open Orders</h2>
      {orders?.map((order) => (
        <div key={order.oid}>
          {order.coin}: {order.sz} @ ${order.limitPx}
        </div>
      ))}
    </div>
  );
}

4. Position Management

Create and manage trading positions:

import { usePosition } from '@pear-protocol/hyperliquid-sdk';

function PositionManager() {
  const { createPosition, data: positions } = usePosition();

  const handleCreatePosition = async () => {
    try {
      const result = await createPosition({
        coin: 'ETH',
        side: 'long',
        size: 0.1,
        leverage: 10,
        orderType: 'market'
      });
      console.log('Position created:', result);
    } catch (error) {
      console.error('Failed to create position:', error);
    }
  };

  return (
    <div>
      <button onClick={handleCreatePosition}>
        Open ETH Long Position
      </button>

      {positions?.map((position) => (
        <PositionCard key={position.coin} position={position} />
      ))}
    </div>
  );
}

5. Agent Wallets

Manage automated trading wallets:

import { usePearAgentWallet } from '@pear-protocol/hyperliquid-sdk';

function AgentWalletManager() {
  const {
    agentWallet,
    isReady,
    loading,
    createAgentWallet,
    refreshAgentWalletStatus
  } = usePearAgentWallet();

  const handleCreateWallet = async () => {
    try {
      await createAgentWallet();
      console.log('Agent wallet created successfully');
    } catch (error) {
      console.error('Failed to create agent wallet:', error);
    }
  };

  if (loading) return <div>Loading agent wallet...</div>;

  if (!agentWallet.exists) {
    return (
      <button onClick={handleCreateWallet}>
        Create Agent Wallet
      </button>
    );
  }

  return (
    <div>
      <h3>Agent Wallet</h3>
      <div>Address: {agentWallet.address}</div>
      <div>Status: {agentWallet.status}</div>
      <button onClick={refreshAgentWalletStatus}>
        Refresh Status
      </button>
    </div>
  );
}

Advanced Usage

WebSocket Connections

The SDK automatically manages WebSocket connections for real-time data:

import { useHyperliquidWebSocket, useHyperliquidNativeWebSocket } from '@pear-protocol/hyperliquid-sdk';

function WebSocketStatus() {
  const { isConnected, lastError } = useHyperliquidWebSocket({
    wsUrl: 'wss://api.pear.garden/ws',
    address: userAddress
  });

  const {
    isConnected: nativeConnected
  } = useHyperliquidNativeWebSocket({
    address: userAddress
  });

  return (
    <div>
      <div>Pear API: {isConnected ? 'Connected' : 'Disconnected'}</div>
      <div>Hyperliquid: {nativeConnected ? 'Connected' : 'Disconnected'}</div>
      {lastError && <div>Error: {lastError}</div>}
    </div>
  );
}

Historical Data

Access historical price data and performance metrics:

import {
  useHistoricalPriceData,
  useBasketCandles,
  useHistoricalPriceDataStore
} from '@pear-protocol/hyperliquid-sdk';

function ChartComponent() {
  const { data: priceData } = useHistoricalPriceData({
    tokens: ['ETH', 'BTC'],
    range: '1D'
  });

  const { data: candleData } = useBasketCandles({
    tokens: [{ symbol: 'ETH', weight: 0.6 }, { symbol: 'BTC', weight: 0.4 }],
    interval: '1h',
    startTime: Date.now() - 24 * 60 * 60 * 1000
  });

  return (
    <div>
      {/* Render your charts here */}
    </div>
  );
}

Utilities

The SDK includes utility functions for calculations and data processing:

import {
  AccountSummaryCalculator,
  ConflictDetector,
  TokenMetadataExtractor,
  calculateWeightedRatio
} from '@pear-protocol/hyperliquid-sdk';

// Calculate account metrics
const calculator = new AccountSummaryCalculator(positions, marketData);
const accountValue = calculator.getTotalAccountValue();

// Detect token conflicts
const detector = new ConflictDetector();
const conflicts = detector.detectConflicts(tokenSelections);

// Extract token metadata
const extractor = new TokenMetadataExtractor();
const metadata = extractor.extractMetadata(tokenData);

Configuration

Environment Setup

The SDK supports different environments through configuration:

// Development
<PearHyperliquidProvider
  apiBaseUrl="http://localhost:3000"
  wsUrl="ws://localhost:3000/ws"
>

// Production
<PearHyperliquidProvider
  apiBaseUrl="https://api.pear.garden"
  wsUrl="wss://api.pear.garden/ws"
>

// Beta
<PearHyperliquidProvider
  apiBaseUrl="https://beta-api.pear.garden"
  wsUrl="wss://beta-api.pear.garden/ws"
>

Authentication Methods

The SDK supports multiple authentication methods:

// EIP-712 signature (recommended)
await loginWithSignedMessage(address, signature, timestamp);

// Privy integration
await loginWithPrivyToken(address, appId, privyAccessToken);

API Reference

Core Hooks

  • usePearHyperliquid() - Access the main context
  • usePearAuth() - Authentication state and methods
  • usePearAgentWallet() - Agent wallet management

Trading Hooks

  • useOpenPositions() - Get open positions with real-time updates
  • useOpenOrders() - Get open orders
  • useAccountSummary() - Account summary with calculated metrics
  • useTradeHistories() - Historical trade data
  • usePosition() - Position management operations

Data Hooks

  • useWebData() - Market data from Hyperliquid
  • useHistoricalPriceData() - Historical price charts
  • useBasketCandles() - Basket/portfolio candle data
  • useTokenSelectionMetadata() - Token metadata and conflicts

WebSocket Hooks

  • useHyperliquidWebSocket() - Pear API WebSocket connection
  • useHyperliquidNativeWebSocket() - Direct Hyperliquid WebSocket

TypeScript Support

The SDK is fully typed with TypeScript. All hooks, utilities, and data structures include comprehensive type definitions:

import type {
  OpenPositionDto,
  AccountSummaryResponseDto,
  AgentWalletState,
  WebSocketConnectionState,
  CandleData
} from '@pear-protocol/hyperliquid-sdk';

Error Handling

The SDK provides comprehensive error handling:

const { error, authError } = usePearAuth();
const { agentWalletError } = usePearAgentWallet();
const { lastError } = useHyperliquidWebSocket();

// Handle authentication errors
if (authError) {
  console.error('Auth failed:', authError);
}

// Handle connection errors
if (lastError) {
  console.error('WebSocket error:', lastError);
}

Contributing

This SDK is part of the Pear Protocol ecosystem. For issues, feature requests, or contributions, please visit the GitHub repository.

License

MIT License - see LICENSE file for details.

Support

For technical support and questions: