@pear-protocol/hyperliquid-sdk 0.0.5 → 0.0.7-2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/clients/agentWallet.d.ts +3 -0
  2. package/dist/clients/auth.d.ts +14 -0
  3. package/dist/clients/hyperliquid.d.ts +25 -0
  4. package/dist/clients/notifications.d.ts +13 -0
  5. package/dist/clients/orders.d.ts +65 -0
  6. package/dist/clients/portfolio.d.ts +39 -0
  7. package/dist/clients/positions.d.ts +135 -0
  8. package/dist/clients/sync.d.ts +9 -0
  9. package/dist/clients/watchlist.d.ts +2 -0
  10. package/dist/hooks/index.d.ts +20 -2
  11. package/dist/hooks/useAccountSummary.d.ts +5 -0
  12. package/dist/hooks/useAgentWallet.d.ts +5 -0
  13. package/dist/hooks/useAllUserBalances.d.ts +9 -0
  14. package/dist/hooks/useAuth.d.ts +12 -0
  15. package/dist/hooks/useAutoSyncFills.d.ts +19 -0
  16. package/dist/hooks/useBasketCandles.d.ts +25 -0
  17. package/dist/hooks/useHistoricalPriceData.d.ts +11 -0
  18. package/dist/hooks/useMarketData.d.ts +12 -0
  19. package/dist/hooks/useNotifications.d.ts +16 -0
  20. package/dist/hooks/useOrders.d.ts +10 -0
  21. package/dist/hooks/usePerformanceOverlays.d.ts +14 -0
  22. package/dist/hooks/usePortfolio.d.ts +13 -0
  23. package/dist/hooks/usePosition.d.ts +13 -0
  24. package/dist/hooks/useSpotOrder.d.ts +13 -0
  25. package/dist/hooks/useTokenSelectionMetadata.d.ts +18 -0
  26. package/dist/hooks/useTrading.d.ts +6 -25
  27. package/dist/hooks/useTwap.d.ts +6 -0
  28. package/dist/hooks/useUserSelection.d.ts +3 -0
  29. package/dist/hooks/useWatchlist.d.ts +6 -0
  30. package/dist/hooks/useWebData.d.ts +30 -0
  31. package/dist/hyperliquid-websocket.d.ts +10 -0
  32. package/dist/index.d.ts +1301 -414
  33. package/dist/index.js +8290 -5579
  34. package/dist/provider.d.ts +11 -40
  35. package/dist/store/historicalPriceDataStore.d.ts +25 -0
  36. package/dist/store/hyperliquidDataStore.d.ts +31 -0
  37. package/dist/store/marketDataStore.d.ts +10 -0
  38. package/dist/store/tokenSelectionMetadataStore.d.ts +27 -0
  39. package/dist/store/userDataStore.d.ts +30 -0
  40. package/dist/store/userSelection.d.ts +27 -0
  41. package/dist/types.d.ts +617 -222
  42. package/dist/utils/account-summary-calculator.d.ts +17 -0
  43. package/dist/utils/basket-calculator.d.ts +24 -0
  44. package/dist/utils/chart-interval-mappers.d.ts +9 -0
  45. package/dist/utils/conflict-detector.d.ts +14 -0
  46. package/dist/utils/http.d.ts +26 -0
  47. package/dist/utils/position-processor.d.ts +2 -0
  48. package/dist/utils/position-validator.d.ts +61 -0
  49. package/dist/utils/symbol-translator.d.ts +40 -0
  50. package/dist/utils/token-metadata-extractor.d.ts +37 -0
  51. package/dist/websocket.d.ts +9 -0
  52. package/package.json +19 -6
  53. package/README.md +0 -230
  54. package/dist/client.d.ts +0 -43
  55. package/dist/hooks/useAddress.d.ts +0 -9
  56. package/dist/hyperliquid-service.d.ts +0 -75
  57. package/dist/index.esm.js +0 -5862
  58. package/dist/index.esm.js.map +0 -1
  59. package/dist/index.js.map +0 -1
  60. package/dist/migration-sdk.d.ts +0 -59
@@ -0,0 +1,17 @@
1
+ import type { AccountSummaryResponseDto, ClearinghouseState, ExtraAgent, PlatformAccountSummaryResponseDto } from "../types";
2
+ /**
3
+ * Account summary calculation utility class
4
+ */
5
+ export declare class AccountSummaryCalculator {
6
+ private clearinghouseState;
7
+ constructor(clearinghouseState: ClearinghouseState | null);
8
+ /**
9
+ * Calculate account summary from real-time clearinghouse state and platform orders
10
+ */
11
+ calculateAccountSummary(platformAccountSummary: PlatformAccountSummaryResponseDto | null, registeredAgentWallets: ExtraAgent[]): AccountSummaryResponseDto | null;
12
+ getClearinghouseState(): ClearinghouseState | null;
13
+ /**
14
+ * Check if real-time data is available
15
+ */
16
+ hasRealTimeData(): boolean;
17
+ }
@@ -0,0 +1,24 @@
1
+ import type { CandleData, TokenSelection } from '../types';
2
+ /**
3
+ * Create efficient timestamp-based lookup maps for candle data
4
+ */
5
+ export declare const createCandleLookups: (tokenCandles: Record<string, CandleData[]>) => Record<string, Map<number, CandleData>>;
6
+ /**
7
+ * Calculate weighted ratio for a specific price type (open, high, low, close)
8
+ * Uses the formula: LONG_PRODUCT * SHORT_PRODUCT
9
+ * Where LONG_PRODUCT = ∏(PRICE^(WEIGHT/100)) for long tokens
10
+ * And SHORT_PRODUCT = ∏(PRICE^-(WEIGHT/100)) for short tokens
11
+ *
12
+ * Optimized version that uses Map lookups instead of Array.find()
13
+ */
14
+ export declare const calculateWeightedRatio: (longTokens: TokenSelection[], shortTokens: TokenSelection[], candleLookups: Record<string, Map<number, CandleData>>, timestamp: number, priceType: "o" | "h" | "l" | "c") => number;
15
+ /**
16
+ * Get all unique timestamps where ALL required symbols have data
17
+ * Optimized version that uses Map lookups
18
+ */
19
+ export declare const getCompleteTimestamps: (candleLookups: Record<string, Map<number, CandleData>>, requiredSymbols: string[]) => number[];
20
+ /**
21
+ * Compute basket candles from individual token candles using weighted ratios
22
+ * Optimized version that creates lookup maps once and reuses them
23
+ */
24
+ export declare const computeBasketCandles: (longTokens: TokenSelection[], shortTokens: TokenSelection[], tokenCandles: Record<string, CandleData[]>) => CandleData[];
@@ -0,0 +1,9 @@
1
+ import type { CandleInterval } from '../types';
2
+ /**
3
+ * Maps TradingView ResolutionString to CandleInterval
4
+ */
5
+ export declare function mapTradingViewIntervalToCandleInterval(interval: string): CandleInterval;
6
+ /**
7
+ * Maps CandleInterval to TradingView ResolutionString
8
+ */
9
+ export declare function mapCandleIntervalToTradingViewInterval(interval: CandleInterval): string;
@@ -0,0 +1,14 @@
1
+ import type { TokenSelection, TokenConflict, RawPositionDto } from '../types';
2
+ /**
3
+ * Detects conflicts between selected tokens and existing positions
4
+ */
5
+ export declare class ConflictDetector {
6
+ /**
7
+ * Detects conflicts between token selections and open positions
8
+ * @param longTokens - Selected long tokens
9
+ * @param shortTokens - Selected short tokens
10
+ * @param openPositions - Current open positions from API
11
+ * @returns Array of detected conflicts
12
+ */
13
+ static detectConflicts(longTokens: TokenSelection[], shortTokens: TokenSelection[], openPositions: RawPositionDto[] | null): TokenConflict[];
14
+ }
@@ -0,0 +1,26 @@
1
+ import type { AxiosInstance } from 'axios';
2
+ import { ApiErrorResponse } from '../types';
3
+ export declare function toApiError(error: unknown): ApiErrorResponse;
4
+ export declare function joinUrl(baseUrl: string, path: string): string;
5
+ /**
6
+ * Shared Axios instance with interceptors.
7
+ * - Request: inject Authorization headers from buildAuthHeaders when absent
8
+ * - Response: on 401, clear tokens and emit a logout event
9
+ */
10
+ export declare const apiClient: AxiosInstance;
11
+ /**
12
+ * Attach auth-aware Axios interceptors to `apiClient`.
13
+ * - Request: adds `Authorization: Bearer <accessToken>` for requests to `apiBaseUrl`.
14
+ * - Response: if a request returns 401, attempts token refresh and retries the request.
15
+ * If the 401 came from the refresh endpoint (or refresh fails/returns 401), calls `logout()`.
16
+ *
17
+ */
18
+ export declare function addAuthInterceptors(params: {
19
+ apiBaseUrl: string;
20
+ getAccessToken: () => string | null;
21
+ refreshTokens: () => Promise<{
22
+ accessToken: string;
23
+ refreshToken: string;
24
+ } | any>;
25
+ logout: () => Promise<void> | void;
26
+ }): () => void;
@@ -0,0 +1,2 @@
1
+ import { OpenPositionDto, RawPositionDto, ClearinghouseState, WsAllMidsData } from "../types";
2
+ export declare const buildPositionValue: (rawPositions: RawPositionDto[], clearinghouseState: ClearinghouseState, allMids: WsAllMidsData) => OpenPositionDto[];
@@ -0,0 +1,61 @@
1
+ import type { PairAssetInput } from "../clients/positions";
2
+ /**
3
+ * Minimum USD value required per asset when creating a position
4
+ */
5
+ export declare const MINIMUM_ASSET_USD_VALUE = 11;
6
+ /**
7
+ * Maximum number of assets allowed per leg (long or short) in a position
8
+ */
9
+ export declare const MAX_ASSETS_PER_LEG = 15;
10
+ /**
11
+ * Validation error for minimum position size
12
+ */
13
+ export declare class MinimumPositionSizeError extends Error {
14
+ assetName: string;
15
+ assetValue: number;
16
+ minimumRequired: number;
17
+ constructor(assetName: string, assetValue: number, minimumRequired: number);
18
+ }
19
+ /**
20
+ * Validation error for exceeding maximum assets per leg
21
+ */
22
+ export declare class MaxAssetsPerLegError extends Error {
23
+ leg: "long" | "short";
24
+ assetCount: number;
25
+ maxAllowed: number;
26
+ constructor(leg: "long" | "short", assetCount: number, maxAllowed: number);
27
+ }
28
+ /**
29
+ * Validates that each leg doesn't exceed the maximum number of assets
30
+ * @param longAssets Array of long assets
31
+ * @param shortAssets Array of short assets
32
+ * @throws MaxAssetsPerLegError if any leg exceeds the maximum allowed assets
33
+ */
34
+ export declare function validateMaxAssetsPerLeg(longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): void;
35
+ /**
36
+ * Validates that each asset in a position has at least the minimum USD value
37
+ * @param usdValue Total USD value for the position
38
+ * @param longAssets Array of long assets with weights
39
+ * @param shortAssets Array of short assets with weights
40
+ * @throws MinimumPositionSizeError if any asset has less than the minimum USD value
41
+ */
42
+ export declare function validateMinimumAssetSize(usdValue: number, longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): void;
43
+ /**
44
+ * Calculates the minimum USD value required for a position based on the number of assets
45
+ * @param longAssets Array of long assets
46
+ * @param shortAssets Array of short assets
47
+ * @returns The minimum total USD value required
48
+ */
49
+ export declare function calculateMinimumPositionValue(longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): number;
50
+ /**
51
+ * Validates and provides a user-friendly error message with suggestions
52
+ * @param usdValue Total USD value for the position
53
+ * @param longAssets Array of long assets with weights
54
+ * @param shortAssets Array of short assets with weights
55
+ * @returns Validation result with success flag and optional error message
56
+ */
57
+ export declare function validatePositionSize(usdValue: number, longAssets?: PairAssetInput[], shortAssets?: PairAssetInput[]): {
58
+ valid: boolean;
59
+ error?: string;
60
+ minimumRequired?: number;
61
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Convert a full/prefixed symbol (e.g., "xyz:XYZ100") to a display symbol (e.g., "XYZ100").
3
+ */
4
+ export declare function toDisplaySymbol(symbol: string): string;
5
+ /**
6
+ * Convert a display symbol back to backend form using a provided map.
7
+ * If mapping is missing, returns the original symbol.
8
+ * For multi-market assets, returns the first available market.
9
+ * @param displaySymbol e.g., "TSLA"
10
+ * @param hip3Assets map of display -> all full market names (e.g., "TSLA" -> ["xyz:TSLA", "flx:TSLA"])
11
+ */
12
+ export declare function toBackendSymbol(displaySymbol: string, hip3Assets: Map<string, string[]>): string;
13
+ /**
14
+ * Convert a display symbol to backend form for a specific market prefix.
15
+ * This is useful when an asset is available on multiple markets (e.g., xyz:TSLA and flx:TSLA).
16
+ * @param displaySymbol e.g., "TSLA"
17
+ * @param marketPrefix e.g., "xyz" or "flx"
18
+ * @param hip3Assets map of display -> all full market names
19
+ * @returns Full market name if found, null if prefix not specified for multi-market asset, otherwise displaySymbol with prefix
20
+ */
21
+ export declare function toBackendSymbolWithMarket(displaySymbol: string, marketPrefix: string | undefined, hip3Assets: Map<string, string[]>): string | null;
22
+ /**
23
+ * Get all available markets for a display symbol.
24
+ * @param displaySymbol e.g., "TSLA"
25
+ * @param hip3Assets map of display -> all full market names
26
+ * @returns Array of full market names, e.g., ["xyz:TSLA", "flx:TSLA"]
27
+ */
28
+ export declare function getAvailableMarkets(displaySymbol: string, hip3Assets: Map<string, string[]>): string[];
29
+ /**
30
+ * Extract the market prefix from a full market name.
31
+ * @param fullSymbol e.g., "xyz:TSLA"
32
+ * @returns The prefix (e.g., "xyz") or undefined if no prefix
33
+ */
34
+ export declare function getMarketPrefix(fullSymbol: string): string | undefined;
35
+ /**
36
+ * Check if a symbol is a HIP-3 market (has a prefix).
37
+ * @param symbol e.g., "xyz:TSLA" or "TSLA"
38
+ * @returns true if the symbol has a market prefix
39
+ */
40
+ export declare function isHip3Market(symbol: string): boolean;
@@ -0,0 +1,37 @@
1
+ import type { WsAllMidsData, TokenMetadata, ActiveAssetData, UniverseAsset, WebData3AssetCtx } from '../types';
2
+ /**
3
+ * Extracts token metadata from aggregated WebData3 contexts and AllMids data
4
+ */
5
+ export declare class TokenMetadataExtractor {
6
+ /**
7
+ * Extracts comprehensive token metadata
8
+ * @param symbol - Token symbol (base symbol without prefix, e.g., "TSLA")
9
+ * @param perpMetaAssets - Aggregated universe assets (flattened across dexes)
10
+ * @param finalAssetContexts - Aggregated asset contexts (flattened across dexes)
11
+ * @param allMids - AllMids data containing current prices
12
+ * @param activeAssetData - Optional active asset data containing leverage information
13
+ * @param marketPrefix - Optional market prefix (e.g., "xyz", "flx") for HIP3 multi-market assets
14
+ * @returns TokenMetadata or null if token not found
15
+ */
16
+ static extractTokenMetadata(symbol: string, perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null, marketPrefix?: string | null): TokenMetadata | null;
17
+ /**
18
+ * Extracts metadata for multiple tokens
19
+ * @param tokens - Array of token objects with symbol and optional marketPrefix
20
+ * @param perpMetaAssets - Aggregated universe assets
21
+ * @param finalAssetContexts - Aggregated asset contexts
22
+ * @param allMids - AllMids data
23
+ * @param activeAssetData - Optional active asset data containing leverage information
24
+ * @returns Record of unique key to TokenMetadata. Key is "{prefix}:{symbol}" for HIP3 assets, or just "{symbol}" otherwise
25
+ */
26
+ static extractMultipleTokensMetadata(tokens: Array<{
27
+ symbol: string;
28
+ marketPrefix?: string | null;
29
+ }>, perpMetaAssets: UniverseAsset[] | null, finalAssetContexts: WebData3AssetCtx[] | null, allMids: WsAllMidsData | null, activeAssetData?: Record<string, ActiveAssetData> | null): Record<string, TokenMetadata | null>;
30
+ /**
31
+ * Checks if token data is available in aggregated universe assets
32
+ * @param symbol - Token symbol
33
+ * @param perpMetaAssets - Aggregated universe assets
34
+ * @returns boolean indicating if token exists in universe
35
+ */
36
+ static isTokenAvailable(symbol: string, perpMetaAssets: UniverseAsset[] | null): boolean;
37
+ }
@@ -0,0 +1,9 @@
1
+ export interface UseHyperliquidWebSocketProps {
2
+ wsUrl: string;
3
+ address: string | null;
4
+ enabled?: boolean;
5
+ }
6
+ export declare const useHyperliquidWebSocket: ({ wsUrl, address, enabled, }: UseHyperliquidWebSocketProps) => {
7
+ isConnected: boolean;
8
+ lastError: string | null;
9
+ };
package/package.json CHANGED
@@ -1,36 +1,48 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.5",
3
+ "version": "0.0.72.2",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
+ "type": "module",
5
6
  "main": "dist/index.js",
6
- "module": "dist/index.esm.js",
7
+ "module": "dist/index.js",
7
8
  "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
8
15
  "files": [
9
16
  "dist"
10
17
  ],
11
18
  "scripts": {
12
19
  "build": "rollup -c",
13
20
  "dev": "rollup -c -w",
21
+ "copy-watch": "nodemon --watch dist --exec \"npm run copy-to-node-modules\"",
22
+ "copy-to-node-modules": "cp -r dist/* ../node_modules/@pear-protocol/hyperliquid-sdk/dist/",
14
23
  "type-check": "tsc --noEmit",
15
24
  "clean": "rimraf dist"
16
25
  },
17
26
  "dependencies": {
18
- "@nktkas/hyperliquid": "^0.22.1",
19
27
  "axios": "^1.6.0",
20
- "react-use-websocket": "^4.8.1"
28
+ "zustand": "^5.0.9"
21
29
  },
22
30
  "peerDependencies": {
23
- "react": ">=16.8.0"
31
+ "react": "^18.0.0",
32
+ "react-dom": "^18.0.0"
24
33
  },
25
34
  "devDependencies": {
26
35
  "@rollup/plugin-commonjs": "^25.0.0",
27
36
  "@rollup/plugin-node-resolve": "^15.0.0",
37
+ "@rollup/plugin-terser": "^0.4.4",
28
38
  "@rollup/plugin-typescript": "^11.0.0",
29
39
  "@types/react": "^18.0.0",
30
- "react": "^18.0.0",
40
+ "concurrently": "^9.2.1",
41
+ "esbuild": "^0.25.9",
31
42
  "rimraf": "^5.0.0",
32
43
  "rollup": "^3.0.0",
33
44
  "rollup-plugin-dts": "^6.0.0",
45
+ "rollup-plugin-esbuild": "^6.2.1",
34
46
  "tslib": "^2.6.0",
35
47
  "typescript": "^5.0.0"
36
48
  },
@@ -53,5 +65,6 @@
53
65
  "registry": "https://registry.npmjs.org",
54
66
  "access": "public"
55
67
  },
68
+ "sideEffects": false,
56
69
  "private": false
57
70
  }
package/README.md DELETED
@@ -1,230 +0,0 @@
1
- # @pear-protocol/hyperliquid-sdk
2
-
3
- > React SDK for Pear Protocol Hyperliquid API integration
4
-
5
- [![npm version](https://badge.fury.io/js/%40pear-protocol%2Fhyperliquid-sdk.svg)](https://badge.fury.io/js/%40pear-protocol%2Fhyperliquid-sdk)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
-
8
- A comprehensive React SDK for integrating with Pear Protocol's Hyperliquid trading platform. This SDK provides React hooks, TypeScript support, real-time WebSocket connections, and migration utilities for seamless integration.
9
-
10
- ## Features
11
-
12
- - 🚀 **React Hooks**: Easy-to-use hooks for trading data and account management
13
- - 🔌 **Real-time WebSocket**: Live updates for positions, orders, and trade history
14
- - 📝 **TypeScript**: Full TypeScript support with comprehensive type definitions
15
- - 🔄 **Migration Tools**: Built-in SDK for migrating trading data
16
- - 📱 **Responsive**: Works with React 16.8+ and modern React patterns
17
-
18
- ## Installation
19
-
20
- ```bash
21
- npm install @pear-protocol/hyperliquid-sdk
22
- ```
23
-
24
- or
25
-
26
- ```bash
27
- yarn add @pear-protocol/hyperliquid-sdk
28
- ```
29
-
30
- ## Quick Start
31
-
32
- ### 1. Setup the Provider
33
-
34
- Wrap your application with the `PearHyperliquidProvider`:
35
-
36
- ```tsx
37
- import { PearHyperliquidProvider } from '@pear-protocol/hyperliquid-sdk';
38
-
39
- function App() {
40
- return (
41
- <PearHyperliquidProvider
42
- config={{
43
- baseUrl: 'https://hl-v2.pearprotocol.io',
44
- timeout: 30000, // Optional: Request timeout in ms
45
- }}
46
- wsUrl="wss://hl-v2.pearprotocol.io/ws" // Optional: Custom WebSocket URL
47
- >
48
- <YourApp />
49
- </PearHyperliquidProvider>
50
- );
51
- }
52
- ```
53
-
54
- ### 2. Use the Hooks
55
-
56
- #### Address Management
57
-
58
- ```tsx
59
- import { useAddress } from '@pear-protocol/hyperliquid-sdk';
60
-
61
- function LoginComponent() {
62
- const { address, setAddress, clearAddress, isLoggedIn } = useAddress();
63
-
64
- return (
65
- <div>
66
- {isLoggedIn ? (
67
- <div>
68
- <p>Logged in as: {address}</p>
69
- <button onClick={clearAddress}>Logout</button>
70
- </div>
71
- ) : (
72
- <button onClick={() => setAddress('0x1234...')}>
73
- Login
74
- </button>
75
- )}
76
- </div>
77
- );
78
- }
79
- ```
80
-
81
- #### Trading Data
82
-
83
- ```tsx
84
- import {
85
- useTradeHistories,
86
- useOpenPositions,
87
- useOpenOrders,
88
- useAccountSummary
89
- } from '@pear-protocol/hyperliquid-sdk';
90
-
91
- function TradingDashboard() {
92
- const tradeHistories = useTradeHistories();
93
- const openPositions = useOpenPositions();
94
- const openOrders = useOpenOrders();
95
- const accountSummary = useAccountSummary();
96
-
97
- return (
98
- <div>
99
- <h2>Account Summary</h2>
100
- {accountSummary && (
101
- <div>
102
- <p>Balance: {accountSummary.balance}</p>
103
- <p>Margin Used: {accountSummary.marginUsed}</p>
104
- </div>
105
- )}
106
-
107
- <h2>Open Positions</h2>
108
- {openPositions?.map(position => (
109
- <div key={position.coin}>
110
- <p>{position.coin}: {position.szi} @ {position.entryPx}</p>
111
- </div>
112
- ))}
113
-
114
- <h2>Open Orders</h2>
115
- {openOrders?.map(order => (
116
- <div key={order.oid}>
117
- <p>{order.coin}: {order.sz} @ {order.limitPx}</p>
118
- </div>
119
- ))}
120
- </div>
121
- );
122
- }
123
- ```
124
-
125
- ## API Reference
126
-
127
- ### Configuration
128
-
129
- ```typescript
130
- interface PearHyperliquidConfig {
131
- baseUrl: string;
132
- timeout?: number;
133
- headers?: Record<string, string>;
134
- }
135
- ```
136
-
137
- ### Hooks
138
-
139
- #### `useAddress()`
140
- Manages user address and login state.
141
-
142
- **Returns:**
143
- - `address: string | null` - Current user address
144
- - `setAddress: (address: string | null) => void` - Set user address
145
- - `clearAddress: () => void` - Clear current address
146
- - `isLoggedIn: boolean` - Whether user is logged in
147
-
148
- #### `useTradeHistories()`
149
- Returns paginated trade history data from WebSocket.
150
-
151
- #### `useOpenPositions()`
152
- Returns array of current open positions from WebSocket.
153
-
154
- #### `useOpenOrders()`
155
- Returns array of current open orders from WebSocket.
156
-
157
- #### `useAccountSummary()`
158
- Returns account summary including balance and margin information.
159
-
160
- ### Client Methods
161
-
162
- The `PearHyperliquidClient` provides methods for:
163
- - `syncTradeHistories(data: SyncTradeHistoryDto)` - Sync trade history
164
- - `syncOpenPositions(data: SyncOpenPositionDto)` - Sync open positions
165
- - `syncOpenOrders(data: SyncOpenOrderDto)` - Sync open orders
166
-
167
- ### WebSocket Channels
168
-
169
- The SDK automatically subscribes to these channels when an address is set:
170
- - `trade-histories` - Real-time trade history updates
171
- - `open-positions` - Real-time position updates
172
- - `open-orders` - Real-time order updates
173
- - `account-summary` - Real-time account summary updates
174
-
175
- ## TypeScript Support
176
-
177
- The SDK includes comprehensive TypeScript definitions for all data structures:
178
-
179
- ```typescript
180
- import type {
181
- PearHyperliquidConfig,
182
- TradeHistoryV1Dto,
183
- OpenPositionDto,
184
- OpenLimitOrderDto,
185
- AccountSummaryResponseDto,
186
- // ... and many more
187
- } from '@pear-protocol/hyperliquid-sdk';
188
- ```
189
-
190
- ## Error Handling
191
-
192
- The SDK provides structured error handling:
193
-
194
- ```typescript
195
- try {
196
- await client.syncTradeHistories(data);
197
- } catch (error) {
198
- // Error is typed as ApiErrorResponse
199
- console.error(`API Error ${error.statusCode}: ${error.message}`);
200
- }
201
- ```
202
-
203
- ## Requirements
204
-
205
- - React >= 16.8.0
206
- - Node.js >= 16.0.0
207
-
208
- ## Development
209
-
210
- ```bash
211
- # Install dependencies
212
- npm install
213
-
214
- # Build the package
215
- npm run build
216
-
217
- # Run in development mode (watch)
218
- npm run dev
219
-
220
- # Type check
221
- npm run type-check
222
- ```
223
-
224
- ## License
225
-
226
- MIT License - see [LICENSE](LICENSE) file for details.
227
-
228
- ## Support
229
-
230
- For questions and support, please contact the Pear Protocol team.
package/dist/client.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import { PearHyperliquidConfig, ApiResponse, SyncTradeHistoryDto, SyncTradeHistoryResponseDto, SyncOpenPositionDto, SyncOpenPositionResponseDto, SyncOpenOrderDto, SyncOpenOrderResponseDto } from './types';
2
- /**
3
- * Main SDK client for Pear Protocol Hyperliquid API integration
4
- */
5
- export declare class PearHyperliquidClient {
6
- private httpClient;
7
- private baseUrl;
8
- constructor(config: PearHyperliquidConfig);
9
- /**
10
- * Get the configured base URL
11
- */
12
- getBaseUrl(): string;
13
- /**
14
- * Update request headers
15
- */
16
- setHeaders(headers: Record<string, string>): void;
17
- /**
18
- * Set authorization header
19
- */
20
- setAuthToken(token: string): void;
21
- /**
22
- * Make a generic HTTP request
23
- */
24
- private makeRequest;
25
- /**
26
- * Sync trade history data from old database structure to new database format
27
- * @param payload - Trade history data with user address
28
- * @returns Promise with sync result
29
- */
30
- syncTradeHistory(payload: SyncTradeHistoryDto): Promise<ApiResponse<SyncTradeHistoryResponseDto>>;
31
- /**
32
- * Sync open positions data from old database structure to new database format
33
- * @param payload - Open positions data with user address
34
- * @returns Promise with sync result
35
- */
36
- syncOpenPositions(payload: SyncOpenPositionDto): Promise<ApiResponse<SyncOpenPositionResponseDto>>;
37
- /**
38
- * Sync open orders data from old database structure to new database format
39
- * @param payload - Open orders data with user address
40
- * @returns Promise with sync result
41
- */
42
- syncOpenOrders(payload: SyncOpenOrderDto): Promise<ApiResponse<SyncOpenOrderResponseDto>>;
43
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Hook to manage address (login/logout functionality)
3
- */
4
- export declare const useAddress: () => {
5
- address: string | null;
6
- setAddress: (address: string | null) => void;
7
- clearAddress: () => void;
8
- isLoggedIn: boolean;
9
- };
@@ -1,75 +0,0 @@
1
- import * as hl from '@nktkas/hyperliquid';
2
- export interface AllAssetInformation {
3
- universe: hl.PerpsUniverse;
4
- assetsCtx: hl.PerpsAssetCtx;
5
- }
6
- /**
7
- * Hyperliquid service client for direct API communication
8
- */
9
- export declare class HyperliquidService {
10
- private infoClient;
11
- private subsClient?;
12
- private wsTransport?;
13
- private allMidsData;
14
- private webData2;
15
- private assetBySymbol;
16
- private allAssetsCache;
17
- constructor(wsUrl?: string, isTestnet?: boolean);
18
- private initializeWebSocket;
19
- /**
20
- * Refresh asset cache when webData2 updates
21
- */
22
- private refreshAssetCache;
23
- /**
24
- * Get asset information by symbol - O(1) lookup
25
- */
26
- getAssetInfo(symbol: string): hl.PerpsUniverse | null;
27
- /**
28
- * Get asset context by symbol - O(1) lookup
29
- */
30
- getAssetCtx(symbol: string): hl.PerpsAssetCtx | null;
31
- /**
32
- * Get asset index by symbol - O(1) lookup
33
- */
34
- getAssetIndex(symbol: string): number | null;
35
- /**
36
- * Get all assets with caching
37
- */
38
- getAllAssets(): AllAssetInformation[];
39
- /**
40
- * Get current market price for an asset
41
- */
42
- getMarketPrice(symbol: string): number;
43
- /**
44
- * Get optimal decimal places for an asset
45
- */
46
- getOptimalDecimal(symbol: string): number;
47
- /**
48
- * Get user's open positions from Hyperliquid
49
- */
50
- getUserPositions(address: string): Promise<hl.AssetPosition[]>;
51
- /**
52
- * Get user's account summary from Hyperliquid
53
- */
54
- getAccountSummary(address: string): Promise<hl.PerpsClearinghouseState | null>;
55
- /**
56
- * Get user's open orders from Hyperliquid
57
- */
58
- getUserOrders(address: string): Promise<any[]>;
59
- /**
60
- * Update the user address for webData2 subscription
61
- */
62
- updateUserAddress(address: string | null): void;
63
- /**
64
- * Get the info client instance
65
- */
66
- getInfoClient(): hl.InfoClient;
67
- /**
68
- * Check if WebSocket is connected
69
- */
70
- isWebSocketConnected(): boolean;
71
- /**
72
- * Clean up resources
73
- */
74
- cleanup(): Promise<void>;
75
- }