@pear-protocol/hyperliquid-sdk 0.0.24 → 0.0.28

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.
package/README.md CHANGED
@@ -1,35 +1,35 @@
1
1
  # @pear-protocol/hyperliquid-sdk
2
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.
3
+ 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.
9
4
 
10
5
  ## Features
11
6
 
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
7
+ - **React Integration**: Purpose-built React hooks for trading data and operations
8
+ - **Real-time Data**: WebSocket connections for live market data and account updates
9
+ - **Authentication**: EIP-712 signature and Privy wallet integration
10
+ - **Trading Operations**: Position management, order placement, and portfolio tracking
11
+ - **Agent Wallets**: Automated trading wallet creation and management
12
+ - **TypeScript Support**: Full TypeScript definitions for all APIs and data structures
17
13
 
18
14
  ## Installation
19
15
 
20
16
  ```bash
21
17
  npm install @pear-protocol/hyperliquid-sdk
18
+ # or
19
+ yarn add @pear-protocol/hyperliquid-sdk
22
20
  ```
23
21
 
24
- or
22
+ ### Peer Dependencies
23
+
24
+ This package requires React 18+ as a peer dependency:
25
25
 
26
26
  ```bash
27
- yarn add @pear-protocol/hyperliquid-sdk
27
+ npm install react react-dom
28
28
  ```
29
29
 
30
30
  ## Quick Start
31
31
 
32
- ### 1. Setup the Provider
32
+ ### 1. Provider Setup
33
33
 
34
34
  Wrap your application with the `PearHyperliquidProvider`:
35
35
 
@@ -39,82 +39,97 @@ import { PearHyperliquidProvider } from '@pear-protocol/hyperliquid-sdk';
39
39
  function App() {
40
40
  return (
41
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
42
+ apiBaseUrl="https://api.pear.garden"
43
+ wsUrl="wss://api.pear.garden/ws"
44
+ clientId="your-app-name"
47
45
  >
48
- <YourApp />
46
+ <TradingApp />
49
47
  </PearHyperliquidProvider>
50
48
  );
51
49
  }
52
50
  ```
53
51
 
54
- ### 2. Use the Hooks
52
+ ### 2. Authentication
55
53
 
56
- #### Address Management
54
+ Use the authentication hook to handle wallet connections:
57
55
 
58
56
  ```tsx
59
- import { useAddress } from '@pear-protocol/hyperliquid-sdk';
57
+ import { usePearAuth } from '@pear-protocol/hyperliquid-sdk';
60
58
 
61
59
  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
- );
60
+ const {
61
+ isAuthenticated,
62
+ getEip712,
63
+ loginWithSignedMessage,
64
+ logout
65
+ } = usePearAuth();
66
+
67
+ const handleWalletConnect = async (address: string, signMessage: Function) => {
68
+ try {
69
+ // Get EIP-712 message to sign
70
+ const messageData = await getEip712(address);
71
+
72
+ // Sign the message with user's wallet
73
+ const signature = await signMessage(messageData.message);
74
+
75
+ // Authenticate with Pear Protocol
76
+ await loginWithSignedMessage(address, signature, messageData.timestamp);
77
+ } catch (error) {
78
+ console.error('Authentication failed:', error);
79
+ }
80
+ };
81
+
82
+ if (isAuthenticated) {
83
+ return <button onClick={logout}>Logout</button>;
84
+ }
85
+
86
+ return <WalletConnectButton onConnect={handleWalletConnect} />;
78
87
  }
79
88
  ```
80
89
 
81
- #### Trading Data
90
+ ### 3. Trading Data
91
+
92
+ Access real-time trading data with built-in hooks:
82
93
 
83
94
  ```tsx
84
- import {
85
- useTradeHistories,
86
- useOpenPositions,
87
- useOpenOrders,
88
- useAccountSummary
95
+ import {
96
+ useOpenPositions,
97
+ useOpenOrders,
98
+ useAccountSummary,
99
+ usePearHyperliquid
89
100
  } from '@pear-protocol/hyperliquid-sdk';
90
101
 
91
102
  function TradingDashboard() {
92
- const tradeHistories = useTradeHistories();
93
- const openPositions = useOpenPositions();
94
- const openOrders = useOpenOrders();
95
- const accountSummary = useAccountSummary();
103
+ const { address, setAddress } = usePearHyperliquid();
104
+ const { data: positions, isLoading: positionsLoading } = useOpenPositions();
105
+ const { data: orders, isLoading: ordersLoading } = useOpenOrders();
106
+ const { data: accountSummary } = useAccountSummary();
107
+
108
+ // Set the address to track
109
+ useEffect(() => {
110
+ if (userWalletAddress) {
111
+ setAddress(userWalletAddress);
112
+ }
113
+ }, [userWalletAddress, setAddress]);
114
+
115
+ if (positionsLoading) return <div>Loading positions...</div>;
96
116
 
97
117
  return (
98
118
  <div>
99
119
  <h2>Account Summary</h2>
100
- {accountSummary && (
101
- <div>
102
- <p>Balance: {accountSummary.balance}</p>
103
- <p>Margin Used: {accountSummary.marginUsed}</p>
104
- </div>
105
- )}
120
+ <div>Total Value: ${accountSummary?.accountValue?.toFixed(2)}</div>
106
121
 
107
122
  <h2>Open Positions</h2>
108
- {openPositions?.map(position => (
123
+ {positions?.map((position) => (
109
124
  <div key={position.coin}>
110
- <p>{position.coin}: {position.szi} @ {position.entryPx}</p>
125
+ {position.coin}: {position.szi} @ ${position.entryPx}
111
126
  </div>
112
127
  ))}
113
128
 
114
129
  <h2>Open Orders</h2>
115
- {openOrders?.map(order => (
130
+ {orders?.map((order) => (
116
131
  <div key={order.oid}>
117
- <p>{order.coin}: {order.sz} @ {order.limitPx}</p>
132
+ {order.coin}: {order.sz} @ ${order.limitPx}
118
133
  </div>
119
134
  ))}
120
135
  </div>
@@ -122,109 +137,291 @@ function TradingDashboard() {
122
137
  }
123
138
  ```
124
139
 
125
- ## API Reference
140
+ ### 4. Position Management
141
+
142
+ Create and manage trading positions:
143
+
144
+ ```tsx
145
+ import { usePosition } from '@pear-protocol/hyperliquid-sdk';
146
+
147
+ function PositionManager() {
148
+ const { createPosition, data: positions } = usePosition();
149
+
150
+ const handleCreatePosition = async () => {
151
+ try {
152
+ const result = await createPosition({
153
+ coin: 'ETH',
154
+ side: 'long',
155
+ size: 0.1,
156
+ leverage: 10,
157
+ orderType: 'market'
158
+ });
159
+ console.log('Position created:', result);
160
+ } catch (error) {
161
+ console.error('Failed to create position:', error);
162
+ }
163
+ };
126
164
 
127
- ### Configuration
165
+ return (
166
+ <div>
167
+ <button onClick={handleCreatePosition}>
168
+ Open ETH Long Position
169
+ </button>
128
170
 
129
- ```typescript
130
- interface PearHyperliquidConfig {
131
- baseUrl: string;
132
- timeout?: number;
133
- headers?: Record<string, string>;
171
+ {positions?.map((position) => (
172
+ <PositionCard key={position.coin} position={position} />
173
+ ))}
174
+ </div>
175
+ );
134
176
  }
135
177
  ```
136
178
 
137
- ### Hooks
179
+ ### 5. Agent Wallets
138
180
 
139
- #### `useAddress()`
140
- Manages user address and login state.
181
+ Manage automated trading wallets:
141
182
 
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
183
+ ```tsx
184
+ import { usePearAgentWallet } from '@pear-protocol/hyperliquid-sdk';
185
+
186
+ function AgentWalletManager() {
187
+ const {
188
+ agentWallet,
189
+ isReady,
190
+ loading,
191
+ createAgentWallet,
192
+ refreshAgentWalletStatus
193
+ } = usePearAgentWallet();
194
+
195
+ const handleCreateWallet = async () => {
196
+ try {
197
+ await createAgentWallet();
198
+ console.log('Agent wallet created successfully');
199
+ } catch (error) {
200
+ console.error('Failed to create agent wallet:', error);
201
+ }
202
+ };
203
+
204
+ if (loading) return <div>Loading agent wallet...</div>;
205
+
206
+ if (!agentWallet.exists) {
207
+ return (
208
+ <button onClick={handleCreateWallet}>
209
+ Create Agent Wallet
210
+ </button>
211
+ );
212
+ }
147
213
 
148
- #### `useTradeHistories()`
149
- Returns paginated trade history data from WebSocket.
214
+ return (
215
+ <div>
216
+ <h3>Agent Wallet</h3>
217
+ <div>Address: {agentWallet.address}</div>
218
+ <div>Status: {agentWallet.status}</div>
219
+ <button onClick={refreshAgentWalletStatus}>
220
+ Refresh Status
221
+ </button>
222
+ </div>
223
+ );
224
+ }
225
+ ```
150
226
 
151
- #### `useOpenPositions()`
152
- Returns array of current open positions from WebSocket.
227
+ ## Advanced Usage
153
228
 
154
- #### `useOpenOrders()`
155
- Returns array of current open orders from WebSocket.
229
+ ### WebSocket Connections
156
230
 
157
- #### `useAccountSummary()`
158
- Returns account summary including balance and margin information.
231
+ The SDK automatically manages WebSocket connections for real-time data:
159
232
 
160
- ### Client Methods
233
+ ```tsx
234
+ import { useHyperliquidWebSocket, useHyperliquidNativeWebSocket } from '@pear-protocol/hyperliquid-sdk';
161
235
 
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
236
+ function WebSocketStatus() {
237
+ const { isConnected, lastError } = useHyperliquidWebSocket({
238
+ wsUrl: 'wss://api.pear.garden/ws',
239
+ address: userAddress
240
+ });
166
241
 
167
- ### WebSocket Channels
242
+ const {
243
+ isConnected: nativeConnected
244
+ } = useHyperliquidNativeWebSocket({
245
+ address: userAddress
246
+ });
168
247
 
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
248
+ return (
249
+ <div>
250
+ <div>Pear API: {isConnected ? 'Connected' : 'Disconnected'}</div>
251
+ <div>Hyperliquid: {nativeConnected ? 'Connected' : 'Disconnected'}</div>
252
+ {lastError && <div>Error: {lastError}</div>}
253
+ </div>
254
+ );
255
+ }
256
+ ```
174
257
 
175
- ## TypeScript Support
258
+ ### Historical Data
176
259
 
177
- The SDK includes comprehensive TypeScript definitions for all data structures:
260
+ Access historical price data and performance metrics:
178
261
 
179
- ```typescript
180
- import type {
181
- PearHyperliquidConfig,
182
- TradeHistoryV1Dto,
183
- OpenPositionDto,
184
- OpenLimitOrderDto,
185
- AccountSummaryResponseDto,
186
- // ... and many more
262
+ ```tsx
263
+ import {
264
+ useHistoricalPriceData,
265
+ useBasketCandles,
266
+ useHistoricalPriceDataStore
187
267
  } from '@pear-protocol/hyperliquid-sdk';
188
- ```
189
268
 
190
- ## Error Handling
269
+ function ChartComponent() {
270
+ const { data: priceData } = useHistoricalPriceData({
271
+ tokens: ['ETH', 'BTC'],
272
+ range: '1D'
273
+ });
191
274
 
192
- The SDK provides structured error handling:
275
+ const { data: candleData } = useBasketCandles({
276
+ tokens: [{ symbol: 'ETH', weight: 0.6 }, { symbol: 'BTC', weight: 0.4 }],
277
+ interval: '1h',
278
+ startTime: Date.now() - 24 * 60 * 60 * 1000
279
+ });
193
280
 
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}`);
281
+ return (
282
+ <div>
283
+ {/* Render your charts here */}
284
+ </div>
285
+ );
200
286
  }
201
287
  ```
202
288
 
203
- ## Requirements
289
+ ### Utilities
290
+
291
+ The SDK includes utility functions for calculations and data processing:
292
+
293
+ ```tsx
294
+ import {
295
+ AccountSummaryCalculator,
296
+ ConflictDetector,
297
+ TokenMetadataExtractor,
298
+ calculateWeightedRatio
299
+ } from '@pear-protocol/hyperliquid-sdk';
204
300
 
205
- - React >= 16.8.0
206
- - Node.js >= 16.0.0
301
+ // Calculate account metrics
302
+ const calculator = new AccountSummaryCalculator(positions, marketData);
303
+ const accountValue = calculator.getTotalAccountValue();
207
304
 
208
- ## Development
305
+ // Detect token conflicts
306
+ const detector = new ConflictDetector();
307
+ const conflicts = detector.detectConflicts(tokenSelections);
209
308
 
210
- ```bash
211
- # Install dependencies
212
- npm install
309
+ // Extract token metadata
310
+ const extractor = new TokenMetadataExtractor();
311
+ const metadata = extractor.extractMetadata(tokenData);
312
+ ```
313
+
314
+ ## Configuration
315
+
316
+ ### Environment Setup
317
+
318
+ The SDK supports different environments through configuration:
319
+
320
+ ```tsx
321
+ // Development
322
+ <PearHyperliquidProvider
323
+ apiBaseUrl="http://localhost:3000"
324
+ wsUrl="ws://localhost:3000/ws"
325
+ >
326
+
327
+ // Production
328
+ <PearHyperliquidProvider
329
+ apiBaseUrl="https://api.pear.garden"
330
+ wsUrl="wss://api.pear.garden/ws"
331
+ >
332
+
333
+ // Beta
334
+ <PearHyperliquidProvider
335
+ apiBaseUrl="https://beta-api.pear.garden"
336
+ wsUrl="wss://beta-api.pear.garden/ws"
337
+ >
338
+ ```
339
+
340
+ ### Authentication Methods
213
341
 
214
- # Build the package
215
- npm run build
342
+ The SDK supports multiple authentication methods:
216
343
 
217
- # Run in development mode (watch)
218
- npm run dev
344
+ ```tsx
345
+ // EIP-712 signature (recommended)
346
+ await loginWithSignedMessage(address, signature, timestamp);
219
347
 
220
- # Type check
221
- npm run type-check
348
+ // Privy integration
349
+ await loginWithPrivyToken(address, appId, privyAccessToken);
222
350
  ```
223
351
 
352
+ ## API Reference
353
+
354
+ ### Core Hooks
355
+
356
+ - `usePearHyperliquid()` - Access the main context
357
+ - `usePearAuth()` - Authentication state and methods
358
+ - `usePearAgentWallet()` - Agent wallet management
359
+
360
+ ### Trading Hooks
361
+
362
+ - `useOpenPositions()` - Get open positions with real-time updates
363
+ - `useOpenOrders()` - Get open orders
364
+ - `useAccountSummary()` - Account summary with calculated metrics
365
+ - `useTradeHistories()` - Historical trade data
366
+ - `usePosition()` - Position management operations
367
+
368
+ ### Data Hooks
369
+
370
+ - `useWebData()` - Market data from Hyperliquid
371
+ - `useHistoricalPriceData()` - Historical price charts
372
+ - `useBasketCandles()` - Basket/portfolio candle data
373
+ - `useTokenSelectionMetadata()` - Token metadata and conflicts
374
+
375
+ ### WebSocket Hooks
376
+
377
+ - `useHyperliquidWebSocket()` - Pear API WebSocket connection
378
+ - `useHyperliquidNativeWebSocket()` - Direct Hyperliquid WebSocket
379
+
380
+ ## TypeScript Support
381
+
382
+ The SDK is fully typed with TypeScript. All hooks, utilities, and data structures include comprehensive type definitions:
383
+
384
+ ```tsx
385
+ import type {
386
+ OpenPositionDto,
387
+ AccountSummaryResponseDto,
388
+ AgentWalletState,
389
+ WebSocketConnectionState,
390
+ CandleData
391
+ } from '@pear-protocol/hyperliquid-sdk';
392
+ ```
393
+
394
+ ## Error Handling
395
+
396
+ The SDK provides comprehensive error handling:
397
+
398
+ ```tsx
399
+ const { error, authError } = usePearAuth();
400
+ const { agentWalletError } = usePearAgentWallet();
401
+ const { lastError } = useHyperliquidWebSocket();
402
+
403
+ // Handle authentication errors
404
+ if (authError) {
405
+ console.error('Auth failed:', authError);
406
+ }
407
+
408
+ // Handle connection errors
409
+ if (lastError) {
410
+ console.error('WebSocket error:', lastError);
411
+ }
412
+ ```
413
+
414
+ ## Contributing
415
+
416
+ This SDK is part of the Pear Protocol ecosystem. For issues, feature requests, or contributions, please visit the [GitHub repository](https://github.com/pear-protocol/hyperliquid).
417
+
224
418
  ## License
225
419
 
226
- MIT License - see [LICENSE](LICENSE) file for details.
420
+ MIT License - see LICENSE file for details.
227
421
 
228
422
  ## Support
229
423
 
230
- For questions and support, please contact the Pear Protocol team.
424
+ For technical support and questions:
425
+ - GitHub Issues: [pear-protocol/hyperliquid](https://github.com/pear-protocol/hyperliquid/issues)
426
+ - Documentation: [docs.pear.garden](https://docs.pear.garden)
427
+ - Discord: [Pear Protocol Community](https://discord.gg/pear-protocol)
@@ -0,0 +1,3 @@
1
+ import type { ApiResponse, GetAgentWalletResponseDto, CreateAgentWalletResponseDto } from '../types';
2
+ export declare function getAgentWallet(baseUrl: string, accessToken: string): Promise<ApiResponse<GetAgentWalletResponseDto>>;
3
+ export declare function createAgentWallet(baseUrl: string, accessToken: string): Promise<ApiResponse<CreateAgentWalletResponseDto>>;
@@ -0,0 +1,14 @@
1
+ import type { ApiResponse, GetEIP712MessageResponse, AuthenticateRequest, AuthenticateResponse, RefreshTokenResponse, LogoutResponse } from '../types';
2
+ export declare function getEIP712Message(baseUrl: string, address: string, clientId: string): Promise<ApiResponse<GetEIP712MessageResponse>>;
3
+ export declare function authenticate(baseUrl: string, body: AuthenticateRequest): Promise<ApiResponse<AuthenticateResponse>>;
4
+ /**
5
+ * Convenience wrapper for Privy access token authentication
6
+ */
7
+ export declare function authenticateWithPrivy(baseUrl: string, params: {
8
+ address: string;
9
+ clientId: string;
10
+ appId: string;
11
+ accessToken: string;
12
+ }): Promise<ApiResponse<AuthenticateResponse>>;
13
+ export declare function refreshToken(baseUrl: string, refreshTokenVal: string): Promise<ApiResponse<RefreshTokenResponse>>;
14
+ export declare function logout(baseUrl: string, refreshTokenVal: string): Promise<ApiResponse<LogoutResponse>>;
@@ -0,0 +1,9 @@
1
+ import type { ApiResponse, CandleInterval, CandleData, ExternalFillDto } from '../types';
2
+ /**
3
+ * Fetch historical candle data from HyperLiquid API
4
+ */
5
+ export declare const fetchHistoricalCandles: (coin: string, startTime: number, endTime: number, interval: CandleInterval) => Promise<ApiResponse<CandleData[]>>;
6
+ /**
7
+ * Retrieve recent user fills from HyperLiquid and map to ExternalFillDto[]
8
+ */
9
+ export declare const fetchUserFillsFromHyperliquid: (user: string, aggregateByTime?: boolean) => Promise<ApiResponse<ExternalFillDto[]>>;
@@ -0,0 +1,24 @@
1
+ import type { ApiResponse } from '../types';
2
+ export interface AdjustOrderRequestInput {
3
+ limitRatio?: number;
4
+ usdValue?: number;
5
+ }
6
+ export interface AdjustOrderResponseDto {
7
+ orderId: string;
8
+ limitRatio: number;
9
+ usdValue: number;
10
+ updatedAt: string;
11
+ }
12
+ export declare function adjustOrder(baseUrl: string, accessToken: string, orderId: string, payload: AdjustOrderRequestInput): Promise<ApiResponse<AdjustOrderResponseDto>>;
13
+ export interface CancelOrderResponseDto {
14
+ orderId: string;
15
+ status: string;
16
+ cancelledAt: string;
17
+ }
18
+ export declare function cancelOrder(baseUrl: string, accessToken: string, orderId: string): Promise<ApiResponse<CancelOrderResponseDto>>;
19
+ export interface CancelTwapResponseDto {
20
+ orderId: string;
21
+ status: string;
22
+ cancelledAt: string;
23
+ }
24
+ export declare function cancelTwapOrder(baseUrl: string, accessToken: string, orderId: string): Promise<ApiResponse<CancelTwapResponseDto>>;