@pear-protocol/hyperliquid-sdk 0.0.1

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 ADDED
@@ -0,0 +1,265 @@
1
+ # Pear Hyperliquid SDK
2
+
3
+ React SDK for Pear Protocol Hyperliquid API integration.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @pear-protocol/hyperliquid-sdk
9
+ # or
10
+ yarn add @pear-protocol/hyperliquid-sdk
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### React Provider Setup
16
+
17
+ The SDK provides a React Provider that manages both the client and migration functions:
18
+
19
+ ```typescript
20
+ import React from 'react';
21
+ import { PearHyperliquidProvider } from '@pear-protocol/hyperliquid-sdk';
22
+
23
+ function App() {
24
+ return (
25
+ <PearHyperliquidProvider
26
+ config={{
27
+ baseUrl: 'https://api.hyperliquid.xyz',
28
+ timeout: 30000, // optional
29
+ headers: { // optional
30
+ 'Authorization': 'Bearer your-token'
31
+ }
32
+ }}
33
+ >
34
+ <YourAppComponents />
35
+ </PearHyperliquidProvider>
36
+ );
37
+ }
38
+ ```
39
+
40
+ ### Using Migration Functions
41
+
42
+ The migration functions are provided directly by the PearHyperliquidProvider and accessed via hooks:
43
+
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
+ };
77
+
78
+ return (
79
+ <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}
87
+ </div>
88
+ )}
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
+ </div>
102
+ );
103
+ }
104
+ ```
105
+
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';
113
+
114
+ function MyComponent() {
115
+ const { client, setAuthToken, setHeaders, getBaseUrl } = usePearHyperliquid();
116
+
117
+ const handleAuth = () => {
118
+ setAuthToken('new-bearer-token');
119
+ };
120
+
121
+ return (
122
+ <div>
123
+ <p>Base URL: {getBaseUrl()}</p>
124
+ <button onClick={handleAuth}>Set Auth Token</button>
125
+ </div>
126
+ );
127
+ }
128
+ ```
129
+
130
+ ### Direct Client Usage (Legacy)
131
+
132
+ You can still use the client directly without the provider:
133
+
134
+ ```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);
163
+ }
164
+ ```
165
+
166
+ ## API Reference
167
+
168
+ ### PearHyperliquidProvider
169
+
170
+ React Provider component that manages both the SDK client and migration functions.
171
+
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
177
+
178
+ **Provides:**
179
+ - Client instance for API calls
180
+ - Migration functions with state management
181
+ - Context for all child hooks
182
+
183
+ ### Hooks
184
+
185
+ #### useMigrationHooks()
186
+ Returns migration-specific operations managed by the provider. Must be used within `PearHyperliquidProvider`.
187
+
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
194
+
195
+ **Future migration operations:**
196
+ - `openPositions.sync()` - Will be added for open positions migration
197
+ - `closedPositions.sync()` - Will be added for closed positions migration
198
+
199
+ #### usePearHyperliquid()
200
+ Returns generic SDK utilities. Must be used within `PearHyperliquidProvider`.
201
+
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
207
+
208
+ #### usePearHyperliquidClient()
209
+ Lower-level hook that returns the client instance directly.
210
+
211
+ ### PearHyperliquidClient
212
+
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`
229
+
230
+ ## Error Handling
231
+
232
+ The SDK provides structured error handling with the `ApiErrorResponse` type:
233
+
234
+ ```typescript
235
+ interface ApiErrorResponse {
236
+ statusCode: number;
237
+ message: string;
238
+ error?: string;
239
+ }
240
+ ```
241
+
242
+ Errors are automatically intercepted and transformed into this format.
243
+
244
+ ## Architecture
245
+
246
+ The SDK follows a provider-centric architecture where:
247
+
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
252
+
253
+ This ensures that migration functions are properly integrated with React's component lifecycle and state management.
254
+
255
+ ## Future Migration Operations
256
+
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
262
+
263
+ ## License
264
+
265
+ MIT
@@ -0,0 +1,43 @@
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
+ }
@@ -0,0 +1,2 @@
1
+ export { useAddress } from './useAddress';
2
+ export { useTradeHistories, useOpenPositions, useOpenOrders, useAccountSummary } from './useTrading';
@@ -0,0 +1,9 @@
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
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Hook to access trade histories
3
+ */
4
+ export declare const useTradeHistories: () => import("..").PaginatedTradeHistoryResponseDto | null;
5
+ /**
6
+ * Hook to access open positions
7
+ */
8
+ export declare const useOpenPositions: () => import("..").OpenPositionDto[] | null;
9
+ /**
10
+ * Hook to access open orders
11
+ */
12
+ export declare const useOpenOrders: () => import("..").OpenLimitOrderDto[] | null;
13
+ /**
14
+ * Hook to access account summary
15
+ */
16
+ export declare const useAccountSummary: () => import("..").AccountSummaryResponseDto | null;