@pear-protocol/hyperliquid-sdk 0.0.1 → 0.0.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 (2) hide show
  1. package/README.md +147 -182
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,265 +1,230 @@
1
- # Pear Hyperliquid SDK
1
+ # @pear-protocol/hyperliquid-sdk
2
2
 
3
- React SDK for Pear Protocol Hyperliquid API integration.
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
4
17
 
5
18
  ## Installation
6
19
 
7
20
  ```bash
8
21
  npm install @pear-protocol/hyperliquid-sdk
9
- # or
22
+ ```
23
+
24
+ or
25
+
26
+ ```bash
10
27
  yarn add @pear-protocol/hyperliquid-sdk
11
28
  ```
12
29
 
13
- ## Usage
30
+ ## Quick Start
14
31
 
15
- ### React Provider Setup
32
+ ### 1. Setup the Provider
16
33
 
17
- The SDK provides a React Provider that manages both the client and migration functions:
34
+ Wrap your application with the `PearHyperliquidProvider`:
18
35
 
19
- ```typescript
20
- import React from 'react';
36
+ ```tsx
21
37
  import { PearHyperliquidProvider } from '@pear-protocol/hyperliquid-sdk';
22
38
 
23
39
  function App() {
24
40
  return (
25
41
  <PearHyperliquidProvider
26
42
  config={{
27
- baseUrl: 'https://api.hyperliquid.xyz',
28
- timeout: 30000, // optional
29
- headers: { // optional
30
- 'Authorization': 'Bearer your-token'
31
- }
43
+ baseUrl: 'https://hl-v2.pearprotocol.io',
44
+ timeout: 30000, // Optional: Request timeout in ms
32
45
  }}
46
+ wsUrl="wss://hl-v2.pearprotocol.io/ws" // Optional: Custom WebSocket URL
33
47
  >
34
- <YourAppComponents />
48
+ <YourApp />
35
49
  </PearHyperliquidProvider>
36
50
  );
37
51
  }
38
52
  ```
39
53
 
40
- ### Using Migration Functions
54
+ ### 2. Use the Hooks
41
55
 
42
- The migration functions are provided directly by the PearHyperliquidProvider and accessed via hooks:
56
+ #### Address Management
43
57
 
44
- ```typescript
45
- import React from 'react';
46
- import { useMigrationHooks, SyncTradeHistoryDto } from '@pear-protocol/hyperliquid-sdk';
47
-
48
- function TradeHistoryMigration() {
49
- const { tradeHistory } = useMigrationHooks();
50
-
51
- const handleMigration = async () => {
52
- const payload: SyncTradeHistoryDto = {
53
- address: '0x1234567890abcdef1234567890abcdef12345678',
54
- data: {
55
- tradeHistoryId: 'trade-123',
56
- positionId: 'pos-123',
57
- address: '0x1234...abcd',
58
- externalFeePaid: 0.001,
59
- builderFeePaid: 0.0005,
60
- realizedPnl: 0.15,
61
- totalValue: 20000,
62
- entryRatio: 0.5,
63
- exitRatio: 0.5,
64
- leverage: 2,
65
- longAssets: [],
66
- shortAssets: [],
67
- createdAt: '2024-01-01T00:00:00.000Z'
68
- }
69
- };
70
-
71
- try {
72
- await tradeHistory.sync(payload);
73
- } catch (error) {
74
- console.error('Migration failed:', error);
75
- }
76
- };
58
+ ```tsx
59
+ import { useAddress } from '@pear-protocol/hyperliquid-sdk';
60
+
61
+ function LoginComponent() {
62
+ const { address, setAddress, clearAddress, isLoggedIn } = useAddress();
77
63
 
78
64
  return (
79
65
  <div>
80
- <button onClick={handleMigration} disabled={tradeHistory.loading}>
81
- {tradeHistory.loading ? 'Migrating...' : 'Migrate Trade History'}
82
- </button>
83
-
84
- {tradeHistory.error && (
85
- <div style={{ color: 'red' }}>
86
- Error: {tradeHistory.error.message}
66
+ {isLoggedIn ? (
67
+ <div>
68
+ <p>Logged in as: {address}</p>
69
+ <button onClick={clearAddress}>Logout</button>
87
70
  </div>
71
+ ) : (
72
+ <button onClick={() => setAddress('0x1234...')}>
73
+ Login
74
+ </button>
88
75
  )}
89
-
90
- {tradeHistory.data && (
91
- <div style={{ color: 'green' }}>
92
- Success: {tradeHistory.data.message}
93
- <br />
94
- Position ID: {tradeHistory.data.positionId}
95
- <br />
96
- Trade History ID: {tradeHistory.data.tradeHistoryId}
97
- </div>
98
- )}
99
-
100
- <button onClick={tradeHistory.reset}>Reset</button>
101
76
  </div>
102
77
  );
103
78
  }
104
79
  ```
105
80
 
106
- ### Using Generic SDK Functions
107
-
108
- For general SDK operations, use the generic hook:
109
-
110
- ```typescript
111
- import React from 'react';
112
- import { usePearHyperliquid } from '@pear-protocol/hyperliquid-sdk';
81
+ #### Trading Data
113
82
 
114
- function MyComponent() {
115
- const { client, setAuthToken, setHeaders, getBaseUrl } = usePearHyperliquid();
83
+ ```tsx
84
+ import {
85
+ useTradeHistories,
86
+ useOpenPositions,
87
+ useOpenOrders,
88
+ useAccountSummary
89
+ } from '@pear-protocol/hyperliquid-sdk';
116
90
 
117
- const handleAuth = () => {
118
- setAuthToken('new-bearer-token');
119
- };
91
+ function TradingDashboard() {
92
+ const tradeHistories = useTradeHistories();
93
+ const openPositions = useOpenPositions();
94
+ const openOrders = useOpenOrders();
95
+ const accountSummary = useAccountSummary();
120
96
 
121
97
  return (
122
98
  <div>
123
- <p>Base URL: {getBaseUrl()}</p>
124
- <button onClick={handleAuth}>Set Auth Token</button>
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
+ ))}
125
120
  </div>
126
121
  );
127
122
  }
128
123
  ```
129
124
 
130
- ### Direct Client Usage (Legacy)
125
+ ## API Reference
131
126
 
132
- You can still use the client directly without the provider:
127
+ ### Configuration
133
128
 
134
129
  ```typescript
135
- import { PearHyperliquidClient, SyncTradeHistoryDto } from '@pear-protocol/hyperliquid-sdk';
136
-
137
- const client = new PearHyperliquidClient({ baseUrl: 'https://api.hyperliquid.xyz' });
138
-
139
- const syncData: SyncTradeHistoryDto = {
140
- address: '0x1234567890abcdef1234567890abcdef12345678',
141
- data: {
142
- tradeHistoryId: 'trade-123',
143
- positionId: 'pos-123',
144
- address: '0x1234...abcd',
145
- externalFeePaid: 0.001,
146
- builderFeePaid: 0.0005,
147
- realizedPnl: 0.15,
148
- totalValue: 20000,
149
- entryRatio: 0.5,
150
- exitRatio: 0.5,
151
- leverage: 2,
152
- longAssets: [],
153
- shortAssets: [],
154
- createdAt: '2024-01-01T00:00:00.000Z'
155
- }
156
- };
157
-
158
- try {
159
- const response = await client.syncTradeHistory(syncData);
160
- console.log('Sync successful:', response.data);
161
- } catch (error) {
162
- console.error('Sync failed:', error);
130
+ interface PearHyperliquidConfig {
131
+ baseUrl: string;
132
+ timeout?: number;
133
+ headers?: Record<string, string>;
163
134
  }
164
135
  ```
165
136
 
166
- ## API Reference
137
+ ### Hooks
167
138
 
168
- ### PearHyperliquidProvider
139
+ #### `useAddress()`
140
+ Manages user address and login state.
169
141
 
170
- React Provider component that manages both the SDK client and migration functions.
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
171
147
 
172
- **Props:**
173
- - `config: PearHyperliquidConfig` - Configuration object
174
- - `baseUrl: string` - Base URL for the API (required)
175
- - `timeout?: number` - Request timeout in milliseconds (default: 30000)
176
- - `headers?: Record<string, string>` - Additional headers
148
+ #### `useTradeHistories()`
149
+ Returns paginated trade history data from WebSocket.
177
150
 
178
- **Provides:**
179
- - Client instance for API calls
180
- - Migration functions with state management
181
- - Context for all child hooks
151
+ #### `useOpenPositions()`
152
+ Returns array of current open positions from WebSocket.
182
153
 
183
- ### Hooks
154
+ #### `useOpenOrders()`
155
+ Returns array of current open orders from WebSocket.
184
156
 
185
- #### useMigrationHooks()
186
- Returns migration-specific operations managed by the provider. Must be used within `PearHyperliquidProvider`.
157
+ #### `useAccountSummary()`
158
+ Returns account summary including balance and margin information.
187
159
 
188
- **Returns:**
189
- - `tradeHistory.sync: (payload: SyncTradeHistoryDto) => Promise<ApiResponse<SyncTradeHistoryResponseDto>>`
190
- - `tradeHistory.loading: boolean` - Loading state
191
- - `tradeHistory.error: ApiErrorResponse | null` - Error state
192
- - `tradeHistory.data: SyncTradeHistoryResponseDto | null` - Response data
193
- - `tradeHistory.reset: () => void` - Reset state
160
+ ### Client Methods
194
161
 
195
- **Future migration operations:**
196
- - `openPositions.sync()` - Will be added for open positions migration
197
- - `closedPositions.sync()` - Will be added for closed positions migration
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
198
166
 
199
- #### usePearHyperliquid()
200
- Returns generic SDK utilities. Must be used within `PearHyperliquidProvider`.
167
+ ### WebSocket Channels
201
168
 
202
- **Returns:**
203
- - `client: PearHyperliquidClient` - Direct client access
204
- - `setAuthToken: (token: string) => void` - Set authorization header
205
- - `setHeaders: (headers: Record<string, string>) => void` - Update request headers
206
- - `getBaseUrl: () => string` - Get configured base URL
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
207
174
 
208
- #### usePearHyperliquidClient()
209
- Lower-level hook that returns the client instance directly.
175
+ ## TypeScript Support
210
176
 
211
- ### PearHyperliquidClient
177
+ The SDK includes comprehensive TypeScript definitions for all data structures:
212
178
 
213
- #### Methods
214
- - `getBaseUrl(): string` - Get the configured base URL
215
- - `setHeaders(headers: Record<string, string>): void` - Update request headers
216
- - `setAuthToken(token: string): void` - Set authorization header
217
- - `syncTradeHistory(payload: SyncTradeHistoryDto): Promise<ApiResponse<SyncTradeHistoryResponseDto>>` - Sync trade history
218
-
219
- ## Types
220
-
221
- All TypeScript types are exported from the main package:
222
- - `PearHyperliquidConfig`
223
- - `ApiResponse<T>`
224
- - `ApiErrorResponse`
225
- - `TradeHistoryAssetDataDto`
226
- - `TradeHistoryDataDto`
227
- - `SyncTradeHistoryDto`
228
- - `SyncTradeHistoryResponseDto`
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
+ ```
229
189
 
230
190
  ## Error Handling
231
191
 
232
- The SDK provides structured error handling with the `ApiErrorResponse` type:
192
+ The SDK provides structured error handling:
233
193
 
234
194
  ```typescript
235
- interface ApiErrorResponse {
236
- statusCode: number;
237
- message: string;
238
- error?: string;
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}`);
239
200
  }
240
201
  ```
241
202
 
242
- Errors are automatically intercepted and transformed into this format.
203
+ ## Requirements
243
204
 
244
- ## Architecture
205
+ - React >= 16.8.0
206
+ - Node.js >= 16.0.0
245
207
 
246
- The SDK follows a provider-centric architecture where:
208
+ ## Development
247
209
 
248
- 1. **PearHyperliquidProvider** manages both the client instance and migration functions
249
- 2. **Migration functions** are provided as part of the provider context with built-in state management
250
- 3. **Hooks** access the provider context and must be used within the provider
251
- 4. **State management** for migrations (loading, error, data) is handled automatically by the provider
210
+ ```bash
211
+ # Install dependencies
212
+ npm install
252
213
 
253
- This ensures that migration functions are properly integrated with React's component lifecycle and state management.
214
+ # Build the package
215
+ npm run build
254
216
 
255
- ## Future Migration Operations
217
+ # Run in development mode (watch)
218
+ npm run dev
256
219
 
257
- The provider is designed to be extensible. Future versions will include additional migration functions:
258
- - Open positions migration
259
- - Closed positions migration
260
- - Account data migration
261
- - Additional migration utilities
220
+ # Type check
221
+ npm run type-check
222
+ ```
262
223
 
263
224
  ## License
264
225
 
265
- MIT
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "type": "module",
5
5
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
6
6
  "main": "dist/index.js",