@pear-protocol/hyperliquid-sdk 0.0.5 → 0.0.8

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.
@@ -3,8 +3,7 @@ import { ReadyState } from 'react-use-websocket';
3
3
  import { PearHyperliquidClient } from './client';
4
4
  import { PearHyperliquidConfig } from './types';
5
5
  import { PearMigrationSDK } from './migration-sdk';
6
- import { HyperliquidService } from './hyperliquid-service';
7
- import type { PaginatedTradeHistoryResponseDto, OpenPositionDto, OpenLimitOrderDto, AccountSummaryResponseDto } from './types';
6
+ import type { PaginatedTradeHistoryResponseDto, OpenPositionDto, OpenLimitOrderDto, AccountSummaryResponseDto, WebData2Response, WsAllMidsData } from './types';
8
7
  interface WebSocketData {
9
8
  tradeHistories: PaginatedTradeHistoryResponseDto | null;
10
9
  openPositions: OpenPositionDto[] | null;
@@ -14,13 +13,17 @@ interface WebSocketData {
14
13
  export interface PearHyperliquidContextType {
15
14
  client: PearHyperliquidClient;
16
15
  migrationSDK: PearMigrationSDK;
17
- hyperliquidService: HyperliquidService;
18
16
  address: string | null;
19
17
  setAddress: (address: string | null) => void;
20
18
  connectionStatus: ReadyState;
21
19
  isConnected: boolean;
22
20
  data: WebSocketData;
23
21
  lastError: string | null;
22
+ nativeConnectionStatus: ReadyState;
23
+ nativeIsConnected: boolean;
24
+ nativeLastError: string | null;
25
+ webData2: WebData2Response | null;
26
+ allMids: WsAllMidsData | null;
24
27
  }
25
28
  export declare const PearHyperliquidContext: React.Context<PearHyperliquidContextType | undefined>;
26
29
  interface PearHyperliquidProviderProps {
@@ -30,11 +33,6 @@ interface PearHyperliquidProviderProps {
30
33
  * @default 'wss://hl-v2.pearprotocol.io/ws'
31
34
  */
32
35
  wsUrl?: string;
33
- /**
34
- * Hyperliquid WebSocket URL
35
- * @default 'wss://api.hyperliquid.xyz/ws'
36
- */
37
- hyperliquidWsUrl?: string;
38
36
  children: ReactNode;
39
37
  }
40
38
  /**
@@ -49,8 +47,4 @@ export declare const usePearHyperliquidClient: () => PearHyperliquidClient;
49
47
  * Hook to use migration SDK from context
50
48
  */
51
49
  export declare const useMigrationSDK: () => PearMigrationSDK;
52
- /**
53
- * Hook to use Hyperliquid service from context
54
- */
55
- export declare const useHyperliquidService: () => HyperliquidService;
56
50
  export {};
package/dist/types.d.ts CHANGED
@@ -212,7 +212,7 @@ export type WebSocketConnectionState = 'connecting' | 'connected' | 'disconnecte
212
212
  /**
213
213
  * WebSocket channels
214
214
  */
215
- export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary';
215
+ export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'webData2' | 'allMids';
216
216
  /**
217
217
  * WebSocket subscription message
218
218
  */
@@ -402,3 +402,121 @@ export interface AddressState {
402
402
  autoConnect: boolean;
403
403
  previousAddresses: string[];
404
404
  }
405
+ /**
406
+ * WebSocket message from HyperLiquid native API
407
+ */
408
+ export interface WebSocketMessage {
409
+ method: "subscribe" | "unsubscribe";
410
+ subscription: {
411
+ type: string;
412
+ coin?: string;
413
+ interval?: string;
414
+ user?: string;
415
+ aggregateByTime?: boolean;
416
+ };
417
+ }
418
+ /**
419
+ * WebSocket response from HyperLiquid native API
420
+ */
421
+ export interface WebSocketResponse {
422
+ channel: string;
423
+ data: any;
424
+ }
425
+ /**
426
+ * All mids data structure
427
+ */
428
+ export interface WsAllMidsData {
429
+ mids: Record<string, string>;
430
+ }
431
+ /**
432
+ * Asset context data
433
+ */
434
+ export interface AssetCtx {
435
+ funding: string;
436
+ openInterest: string;
437
+ prevDayPx: string;
438
+ dayNtlVlm: string;
439
+ markPx: string;
440
+ midPx?: string;
441
+ impactPxs?: string[];
442
+ oraclePx: string;
443
+ }
444
+ /**
445
+ * Universe asset metadata
446
+ */
447
+ export interface UniverseAsset {
448
+ name: string;
449
+ szDecimals: number;
450
+ maxLeverage: number;
451
+ onlyIsolated: boolean;
452
+ }
453
+ /**
454
+ * WebData2 response structure
455
+ */
456
+ export interface WebData2Response {
457
+ assetCtxs: AssetCtx[];
458
+ meta: {
459
+ universe: UniverseAsset[];
460
+ };
461
+ clearinghouseState: {
462
+ assetPositions: AssetPosition[];
463
+ crossMaintenanceMarginUsed: string;
464
+ crossMarginSummary: {
465
+ accountValue: string;
466
+ totalMarginUsed: string;
467
+ totalNtlPos: string;
468
+ totalRawUsd: string;
469
+ };
470
+ marginSummary: {
471
+ accountValue: string;
472
+ totalMarginUsed: string;
473
+ totalNtlPos: string;
474
+ totalRawUsd: string;
475
+ };
476
+ time: number;
477
+ withdrawable: string;
478
+ };
479
+ perpsAtOpenInterestCap?: string[];
480
+ }
481
+ /**
482
+ * Asset position data
483
+ */
484
+ export interface AssetPosition {
485
+ position: {
486
+ coin: string;
487
+ entryPx?: string;
488
+ leverage: {
489
+ type: string;
490
+ value: number;
491
+ };
492
+ liquidationPx?: string;
493
+ marginUsed: string;
494
+ maxLeverage: number;
495
+ positionValue: string;
496
+ returnOnEquity: string;
497
+ szi: string;
498
+ unrealizedPnl: string;
499
+ };
500
+ type: string;
501
+ cumFunding: {
502
+ allTime: string;
503
+ sinceChange: string;
504
+ sinceOpen: string;
505
+ };
506
+ }
507
+ /**
508
+ * Asset information detail
509
+ */
510
+ export interface AssetInformationDetail {
511
+ name: string;
512
+ funding: string;
513
+ openInterest: string;
514
+ prevDayPx: string;
515
+ dayNtlVlm: string;
516
+ oraclePx: string;
517
+ markPx: string;
518
+ midPx?: string;
519
+ dayBaseVlm: string;
520
+ priceChange: number;
521
+ assetIndex: number;
522
+ }
@@ -0,0 +1,41 @@
1
+ import type { AccountSummaryResponseDto, WebData2Response, OpenLimitOrderDto } from '../types';
2
+ /**
3
+ * Account summary calculation utility class
4
+ */
5
+ export declare class AccountSummaryCalculator {
6
+ private webData2;
7
+ constructor(webData2: WebData2Response | null);
8
+ /**
9
+ * Calculate account summary from webData2 and platform orders
10
+ */
11
+ calculateAccountSummary(platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, agentWalletAddress?: string, agentWalletStatus?: string): AccountSummaryResponseDto | null;
12
+ /**
13
+ * Calculate total USD value of open limit orders
14
+ */
15
+ private calculateTotalLimitOrderValue;
16
+ /**
17
+ * Get real-time clearinghouse state from webData2
18
+ */
19
+ getClearinghouseState(): {
20
+ assetPositions: import("../types").AssetPosition[];
21
+ crossMaintenanceMarginUsed: string;
22
+ crossMarginSummary: {
23
+ accountValue: string;
24
+ totalMarginUsed: string;
25
+ totalNtlPos: string;
26
+ totalRawUsd: string;
27
+ };
28
+ marginSummary: {
29
+ accountValue: string;
30
+ totalMarginUsed: string;
31
+ totalNtlPos: string;
32
+ totalRawUsd: string;
33
+ };
34
+ time: number;
35
+ withdrawable: string;
36
+ } | null;
37
+ /**
38
+ * Check if real-time data is available
39
+ */
40
+ hasRealTimeData(): boolean;
41
+ }
@@ -0,0 +1,81 @@
1
+ import type { OpenPositionDto, AssetPosition, WebData2Response, WsAllMidsData } from '../types';
2
+ /**
3
+ * Position side enum for calculations
4
+ */
5
+ export declare enum PositionSide {
6
+ LONG = "LONG",
7
+ SHORT = "SHORT"
8
+ }
9
+ /**
10
+ * Aggregate position calculation utility class that handles cross-position asset syncing
11
+ */
12
+ export declare class AggregatePositionCalculator {
13
+ private webData2;
14
+ private allMids;
15
+ constructor(webData2: WebData2Response | null, allMids: WsAllMidsData | null);
16
+ /**
17
+ * Get market price for a coin from allMids data
18
+ */
19
+ getMarketPrice(coin: string): number;
20
+ /**
21
+ * Get user positions from webData2
22
+ */
23
+ getUserPositions(): AssetPosition[];
24
+ /**
25
+ * Calculate updated open positions by syncing platform positions with HyperLiquid data
26
+ * Uses aggregate totals across all positions for accurate cross-position sync
27
+ */
28
+ calculateOpenPositions(platformPositions: OpenPositionDto[]): OpenPositionDto[];
29
+ /**
30
+ * Calculate total platform sizes per asset across all positions
31
+ */
32
+ private calculatePlatformTotalsByAsset;
33
+ /**
34
+ * Extract base currency from asset name (handles "LINK/USD" -> "LINK")
35
+ */
36
+ private extractBaseCurrency;
37
+ /**
38
+ * Sync a single position with HyperLiquid data using aggregate totals
39
+ */
40
+ private syncPositionWithAggregateData;
41
+ /**
42
+ * Sync individual asset with aggregate data awareness
43
+ */
44
+ private syncAssetWithAggregateData;
45
+ /**
46
+ * Determine sync status with sophisticated side-aware logic
47
+ */
48
+ private determineSyncStatus;
49
+ /**
50
+ * Build updated position with synced data
51
+ */
52
+ private buildUpdatedPosition;
53
+ /**
54
+ * Map sync result to PositionAssetDetailDto
55
+ */
56
+ private mapSyncResultToAssetDto;
57
+ /**
58
+ * Calculate entry ratio using actual sizes from sync results
59
+ */
60
+ private calculateEntryRatio;
61
+ /**
62
+ * Calculate mark ratio using actual sizes and current prices
63
+ */
64
+ private calculateMarkRatio;
65
+ /**
66
+ * Calculate net funding from sync results
67
+ */
68
+ private calculateNetFundingFromSyncResults;
69
+ /**
70
+ * Calculate total unrealized PnL from sync results
71
+ */
72
+ private calculateTotalUnrealizedPnlFromSyncResults;
73
+ /**
74
+ * Calculate current total position value using market prices
75
+ */
76
+ private calculateCurrentTotalPositionValue;
77
+ /**
78
+ * Calculate entry total position value using entry prices
79
+ */
80
+ private calculateEntryTotalPositionValue;
81
+ }
@@ -0,0 +1,20 @@
1
+ import { ReadyState } from 'react-use-websocket';
2
+ import type { PaginatedTradeHistoryResponseDto, OpenPositionDto, OpenLimitOrderDto, AccountSummaryResponseDto } from './types';
3
+ interface WebSocketData {
4
+ tradeHistories: PaginatedTradeHistoryResponseDto | null;
5
+ openPositions: OpenPositionDto[] | null;
6
+ openOrders: OpenLimitOrderDto[] | null;
7
+ accountSummary: AccountSummaryResponseDto | null;
8
+ }
9
+ export interface UseHyperliquidWebSocketProps {
10
+ wsUrl: string;
11
+ address: string | null;
12
+ }
13
+ export interface UseHyperliquidWebSocketReturn {
14
+ data: WebSocketData;
15
+ connectionStatus: ReadyState;
16
+ isConnected: boolean;
17
+ lastError: string | null;
18
+ }
19
+ export declare const useHyperliquidWebSocket: ({ wsUrl, address }: UseHyperliquidWebSocketProps) => UseHyperliquidWebSocketReturn;
20
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.5",
3
+ "version": "0.0.8",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
@@ -15,7 +15,6 @@
15
15
  "clean": "rimraf dist"
16
16
  },
17
17
  "dependencies": {
18
- "@nktkas/hyperliquid": "^0.22.1",
19
18
  "axios": "^1.6.0",
20
19
  "react-use-websocket": "^4.8.1"
21
20
  },
@@ -34,14 +33,7 @@
34
33
  "tslib": "^2.6.0",
35
34
  "typescript": "^5.0.0"
36
35
  },
37
- "keywords": [
38
- "pear",
39
- "hyperliquid",
40
- "sdk",
41
- "react",
42
- "trading",
43
- "api"
44
- ],
36
+ "keywords": ["pear", "hyperliquid", "sdk", "react", "trading", "api"],
45
37
  "author": "Pear Protocol",
46
38
  "license": "MIT",
47
39
  "repository": {
@@ -54,4 +46,4 @@
54
46
  "access": "public"
55
47
  },
56
48
  "private": false
57
- }
49
+ }
@@ -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
- }