@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.
@@ -1,2 +1,4 @@
1
1
  export { useAddress } from './useAddress';
2
2
  export { useTradeHistories, useOpenPositions, useOpenOrders, useAccountSummary } from './useTrading';
3
+ export { useCalculatedOpenPositions } from './useCalculatedPositions';
4
+ export { useCalculatedAccountSummary } from './useCalculatedAccountSummary';
@@ -0,0 +1,5 @@
1
+ import type { AccountSummaryResponseDto, WebData2Response, OpenLimitOrderDto } from '../types';
2
+ /**
3
+ * Hook that calculates account summary by syncing platform data with HyperLiquid real-time data
4
+ */
5
+ export declare const useCalculatedAccountSummary: (platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, webData2: WebData2Response | null, agentWalletAddress?: string, agentWalletStatus?: string) => AccountSummaryResponseDto | null;
@@ -0,0 +1,5 @@
1
+ import type { OpenPositionDto, WebData2Response, WsAllMidsData } from '../types';
2
+ /**
3
+ * Hook that calculates open positions by syncing platform positions with HyperLiquid real-time data
4
+ */
5
+ export declare const useCalculatedOpenPositions: (platformPositions: OpenPositionDto[] | null, webData2: WebData2Response | null, allMids: WsAllMidsData | null) => OpenPositionDto[] | null;
@@ -1,29 +1,16 @@
1
- import { OpenPositionDto, AccountSummaryResponseDto } from '../types';
2
1
  /**
3
2
  * Hook to access trade histories
4
3
  */
5
- export declare const useTradeHistories: () => import("../types").PaginatedTradeHistoryResponseDto | null;
4
+ export declare const useTradeHistories: () => import("..").PaginatedTradeHistoryResponseDto | null;
6
5
  /**
7
- * Hook to access open positions with enhanced real-time synchronization
6
+ * Hook to access open positions with real-time calculations
8
7
  */
9
- export declare const useOpenPositions: () => {
10
- positions: OpenPositionDto[];
11
- isLoading: boolean;
12
- lastSyncTime: Date | null;
13
- rawWsPositions: OpenPositionDto[] | null;
14
- resync: () => Promise<void>;
15
- };
8
+ export declare const useOpenPositions: () => import("..").OpenPositionDto[] | null;
16
9
  /**
17
10
  * Hook to access open orders
18
11
  */
19
- export declare const useOpenOrders: () => import("../types").OpenLimitOrderDto[] | null;
12
+ export declare const useOpenOrders: () => import("..").OpenLimitOrderDto[] | null;
20
13
  /**
21
- * Hook to access account summary with enhanced real-time data from Hyperliquid
14
+ * Hook to access account summary with real-time calculations
22
15
  */
23
- export declare const useAccountSummary: () => {
24
- summary: AccountSummaryResponseDto | null;
25
- isLoading: boolean;
26
- lastSyncTime: Date | null;
27
- rawWsSummary: AccountSummaryResponseDto | null;
28
- resync: () => Promise<void>;
29
- };
16
+ export declare const useAccountSummary: () => import("..").AccountSummaryResponseDto | null;
@@ -0,0 +1,13 @@
1
+ import { ReadyState } from 'react-use-websocket';
2
+ import type { WebData2Response, WsAllMidsData } from './types';
3
+ export interface UseHyperliquidNativeWebSocketProps {
4
+ address: string | null;
5
+ }
6
+ export interface UseHyperliquidNativeWebSocketReturn {
7
+ webData2: WebData2Response | null;
8
+ allMids: WsAllMidsData | null;
9
+ connectionStatus: ReadyState;
10
+ isConnected: boolean;
11
+ lastError: string | null;
12
+ }
13
+ export declare const useHyperliquidNativeWebSocket: ({ address }: UseHyperliquidNativeWebSocketProps) => UseHyperliquidNativeWebSocketReturn;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import * as hl from '@nktkas/hyperliquid';
2
1
  import React, { ReactNode } from 'react';
2
+ import { ReadyState } from 'react-use-websocket';
3
3
 
4
4
  /**
5
5
  * Raw value data for trade history positions
@@ -215,7 +215,7 @@ type WebSocketConnectionState = 'connecting' | 'connected' | 'disconnected' | 'e
215
215
  /**
216
216
  * WebSocket channels
217
217
  */
218
- type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary';
218
+ type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'webData2' | 'allMids';
219
219
  /**
220
220
  * WebSocket subscription message
221
221
  */
@@ -223,14 +223,6 @@ interface WebSocketSubscribeMessage {
223
223
  action?: 'subscribe' | 'unsubscribe';
224
224
  address: string;
225
225
  }
226
- /**
227
- * WebSocket response message
228
- */
229
- interface WebSocketResponse {
230
- success?: boolean;
231
- message?: string;
232
- error?: string;
233
- }
234
226
  /**
235
227
  * WebSocket data message
236
228
  */
@@ -396,6 +388,132 @@ interface AccountSummaryResponseDto {
396
388
  balanceSummary: BalanceSummaryDto;
397
389
  agentWallet: AgentWalletDto;
398
390
  }
391
+ /**
392
+ * WebSocket message from HyperLiquid native API
393
+ */
394
+ interface WebSocketMessage {
395
+ method: "subscribe" | "unsubscribe";
396
+ subscription: {
397
+ type: string;
398
+ coin?: string;
399
+ interval?: string;
400
+ user?: string;
401
+ aggregateByTime?: boolean;
402
+ };
403
+ }
404
+ /**
405
+ * WebSocket response message
406
+ */
407
+ interface WebSocketResponse {
408
+ success?: boolean;
409
+ message?: string;
410
+ error?: string;
411
+ }
412
+ /**
413
+ * WebSocket response from HyperLiquid native API
414
+ */
415
+ interface WebSocketResponse {
416
+ channel: string;
417
+ data: any;
418
+ }
419
+ /**
420
+ * All mids data structure
421
+ */
422
+ interface WsAllMidsData {
423
+ mids: Record<string, string>;
424
+ }
425
+ /**
426
+ * Asset context data
427
+ */
428
+ interface AssetCtx {
429
+ funding: string;
430
+ openInterest: string;
431
+ prevDayPx: string;
432
+ dayNtlVlm: string;
433
+ markPx: string;
434
+ midPx?: string;
435
+ impactPxs?: string[];
436
+ oraclePx: string;
437
+ }
438
+ /**
439
+ * Universe asset metadata
440
+ */
441
+ interface UniverseAsset {
442
+ name: string;
443
+ szDecimals: number;
444
+ maxLeverage: number;
445
+ onlyIsolated: boolean;
446
+ }
447
+ /**
448
+ * WebData2 response structure
449
+ */
450
+ interface WebData2Response {
451
+ assetCtxs: AssetCtx[];
452
+ meta: {
453
+ universe: UniverseAsset[];
454
+ };
455
+ clearinghouseState: {
456
+ assetPositions: AssetPosition[];
457
+ crossMaintenanceMarginUsed: string;
458
+ crossMarginSummary: {
459
+ accountValue: string;
460
+ totalMarginUsed: string;
461
+ totalNtlPos: string;
462
+ totalRawUsd: string;
463
+ };
464
+ marginSummary: {
465
+ accountValue: string;
466
+ totalMarginUsed: string;
467
+ totalNtlPos: string;
468
+ totalRawUsd: string;
469
+ };
470
+ time: number;
471
+ withdrawable: string;
472
+ };
473
+ perpsAtOpenInterestCap?: string[];
474
+ }
475
+ /**
476
+ * Asset position data
477
+ */
478
+ interface AssetPosition {
479
+ position: {
480
+ coin: string;
481
+ entryPx?: string;
482
+ leverage: {
483
+ type: string;
484
+ value: number;
485
+ };
486
+ liquidationPx?: string;
487
+ marginUsed: string;
488
+ maxLeverage: number;
489
+ positionValue: string;
490
+ returnOnEquity: string;
491
+ szi: string;
492
+ unrealizedPnl: string;
493
+ };
494
+ type: string;
495
+ cumFunding: {
496
+ allTime: string;
497
+ sinceChange: string;
498
+ sinceOpen: string;
499
+ };
500
+ }
501
+ /**
502
+ * Asset information detail
503
+ */
504
+ interface AssetInformationDetail {
505
+ name: string;
506
+ funding: string;
507
+ openInterest: string;
508
+ prevDayPx: string;
509
+ dayNtlVlm: string;
510
+ oraclePx: string;
511
+ markPx: string;
512
+ midPx?: string;
513
+ dayBaseVlm: string;
514
+ priceChange: number;
515
+ assetIndex: number;
516
+ }
399
517
 
400
518
  /**
401
519
  * Main SDK client for Pear Protocol Hyperliquid API integration
@@ -498,81 +616,6 @@ declare class PearMigrationSDK {
498
616
  getBaseUrl(): string;
499
617
  }
500
618
 
501
- interface AllAssetInformation {
502
- universe: hl.PerpsUniverse;
503
- assetsCtx: hl.PerpsAssetCtx;
504
- }
505
- /**
506
- * Hyperliquid service client for direct API communication
507
- */
508
- declare class HyperliquidService {
509
- private infoClient;
510
- private subsClient?;
511
- private wsTransport?;
512
- private allMidsData;
513
- private webData2;
514
- private assetBySymbol;
515
- private allAssetsCache;
516
- constructor(wsUrl?: string, isTestnet?: boolean);
517
- private initializeWebSocket;
518
- /**
519
- * Refresh asset cache when webData2 updates
520
- */
521
- private refreshAssetCache;
522
- /**
523
- * Get asset information by symbol - O(1) lookup
524
- */
525
- getAssetInfo(symbol: string): hl.PerpsUniverse | null;
526
- /**
527
- * Get asset context by symbol - O(1) lookup
528
- */
529
- getAssetCtx(symbol: string): hl.PerpsAssetCtx | null;
530
- /**
531
- * Get asset index by symbol - O(1) lookup
532
- */
533
- getAssetIndex(symbol: string): number | null;
534
- /**
535
- * Get all assets with caching
536
- */
537
- getAllAssets(): AllAssetInformation[];
538
- /**
539
- * Get current market price for an asset
540
- */
541
- getMarketPrice(symbol: string): number;
542
- /**
543
- * Get optimal decimal places for an asset
544
- */
545
- getOptimalDecimal(symbol: string): number;
546
- /**
547
- * Get user's open positions from Hyperliquid
548
- */
549
- getUserPositions(address: string): Promise<hl.AssetPosition[]>;
550
- /**
551
- * Get user's account summary from Hyperliquid
552
- */
553
- getAccountSummary(address: string): Promise<hl.PerpsClearinghouseState | null>;
554
- /**
555
- * Get user's open orders from Hyperliquid
556
- */
557
- getUserOrders(address: string): Promise<any[]>;
558
- /**
559
- * Update the user address for webData2 subscription
560
- */
561
- updateUserAddress(address: string | null): void;
562
- /**
563
- * Get the info client instance
564
- */
565
- getInfoClient(): hl.InfoClient;
566
- /**
567
- * Check if WebSocket is connected
568
- */
569
- isWebSocketConnected(): boolean;
570
- /**
571
- * Clean up resources
572
- */
573
- cleanup(): Promise<void>;
574
- }
575
-
576
619
  interface PearHyperliquidProviderProps {
577
620
  config: PearHyperliquidConfig;
578
621
  /**
@@ -580,11 +623,6 @@ interface PearHyperliquidProviderProps {
580
623
  * @default 'wss://hl-v2.pearprotocol.io/ws'
581
624
  */
582
625
  wsUrl?: string;
583
- /**
584
- * Hyperliquid WebSocket URL
585
- * @default 'wss://api.hyperliquid.xyz/ws'
586
- */
587
- hyperliquidWsUrl?: string;
588
626
  children: ReactNode;
589
627
  }
590
628
  /**
@@ -599,10 +637,6 @@ declare const usePearHyperliquidClient: () => PearHyperliquidClient;
599
637
  * Hook to use migration SDK from context
600
638
  */
601
639
  declare const useMigrationSDK: () => PearMigrationSDK;
602
- /**
603
- * Hook to use Hyperliquid service from context
604
- */
605
- declare const useHyperliquidService: () => HyperliquidService;
606
640
 
607
641
  /**
608
642
  * Hook to manage address (login/logout functionality)
@@ -619,29 +653,179 @@ declare const useAddress: () => {
619
653
  */
620
654
  declare const useTradeHistories: () => PaginatedTradeHistoryResponseDto | null;
621
655
  /**
622
- * Hook to access open positions with enhanced real-time synchronization
656
+ * Hook to access open positions with real-time calculations
623
657
  */
624
- declare const useOpenPositions: () => {
625
- positions: OpenPositionDto[];
626
- isLoading: boolean;
627
- lastSyncTime: Date | null;
628
- rawWsPositions: OpenPositionDto[] | null;
629
- resync: () => Promise<void>;
630
- };
658
+ declare const useOpenPositions: () => OpenPositionDto[] | null;
631
659
  /**
632
660
  * Hook to access open orders
633
661
  */
634
662
  declare const useOpenOrders: () => OpenLimitOrderDto[] | null;
635
663
  /**
636
- * Hook to access account summary with enhanced real-time data from Hyperliquid
664
+ * Hook to access account summary with real-time calculations
637
665
  */
638
- declare const useAccountSummary: () => {
639
- summary: AccountSummaryResponseDto | null;
640
- isLoading: boolean;
641
- lastSyncTime: Date | null;
642
- rawWsSummary: AccountSummaryResponseDto | null;
643
- resync: () => Promise<void>;
644
- };
666
+ declare const useAccountSummary: () => AccountSummaryResponseDto | null;
667
+
668
+ /**
669
+ * Hook that calculates open positions by syncing platform positions with HyperLiquid real-time data
670
+ */
671
+ declare const useCalculatedOpenPositions: (platformPositions: OpenPositionDto[] | null, webData2: WebData2Response | null, allMids: WsAllMidsData | null) => OpenPositionDto[] | null;
672
+
673
+ /**
674
+ * Hook that calculates account summary by syncing platform data with HyperLiquid real-time data
675
+ */
676
+ declare const useCalculatedAccountSummary: (platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, webData2: WebData2Response | null, agentWalletAddress?: string, agentWalletStatus?: string) => AccountSummaryResponseDto | null;
677
+
678
+ interface WebSocketData {
679
+ tradeHistories: PaginatedTradeHistoryResponseDto | null;
680
+ openPositions: OpenPositionDto[] | null;
681
+ openOrders: OpenLimitOrderDto[] | null;
682
+ accountSummary: AccountSummaryResponseDto | null;
683
+ }
684
+ interface UseHyperliquidWebSocketProps {
685
+ wsUrl: string;
686
+ address: string | null;
687
+ }
688
+ interface UseHyperliquidWebSocketReturn {
689
+ data: WebSocketData;
690
+ connectionStatus: ReadyState;
691
+ isConnected: boolean;
692
+ lastError: string | null;
693
+ }
694
+ declare const useHyperliquidWebSocket: ({ wsUrl, address }: UseHyperliquidWebSocketProps) => UseHyperliquidWebSocketReturn;
695
+
696
+ interface UseHyperliquidNativeWebSocketProps {
697
+ address: string | null;
698
+ }
699
+ interface UseHyperliquidNativeWebSocketReturn {
700
+ webData2: WebData2Response | null;
701
+ allMids: WsAllMidsData | null;
702
+ connectionStatus: ReadyState;
703
+ isConnected: boolean;
704
+ lastError: string | null;
705
+ }
706
+ declare const useHyperliquidNativeWebSocket: ({ address }: UseHyperliquidNativeWebSocketProps) => UseHyperliquidNativeWebSocketReturn;
707
+
708
+ /**
709
+ * Position side enum for calculations
710
+ */
711
+ declare enum PositionSide {
712
+ LONG = "LONG",
713
+ SHORT = "SHORT"
714
+ }
715
+ /**
716
+ * Aggregate position calculation utility class that handles cross-position asset syncing
717
+ */
718
+ declare class AggregatePositionCalculator {
719
+ private webData2;
720
+ private allMids;
721
+ constructor(webData2: WebData2Response | null, allMids: WsAllMidsData | null);
722
+ /**
723
+ * Get market price for a coin from allMids data
724
+ */
725
+ getMarketPrice(coin: string): number;
726
+ /**
727
+ * Get user positions from webData2
728
+ */
729
+ getUserPositions(): AssetPosition[];
730
+ /**
731
+ * Calculate updated open positions by syncing platform positions with HyperLiquid data
732
+ * Uses aggregate totals across all positions for accurate cross-position sync
733
+ */
734
+ calculateOpenPositions(platformPositions: OpenPositionDto[]): OpenPositionDto[];
735
+ /**
736
+ * Calculate total platform sizes per asset across all positions
737
+ */
738
+ private calculatePlatformTotalsByAsset;
739
+ /**
740
+ * Extract base currency from asset name (handles "LINK/USD" -> "LINK")
741
+ */
742
+ private extractBaseCurrency;
743
+ /**
744
+ * Sync a single position with HyperLiquid data using aggregate totals
745
+ */
746
+ private syncPositionWithAggregateData;
747
+ /**
748
+ * Sync individual asset with aggregate data awareness
749
+ */
750
+ private syncAssetWithAggregateData;
751
+ /**
752
+ * Determine sync status with sophisticated side-aware logic
753
+ */
754
+ private determineSyncStatus;
755
+ /**
756
+ * Build updated position with synced data
757
+ */
758
+ private buildUpdatedPosition;
759
+ /**
760
+ * Map sync result to PositionAssetDetailDto
761
+ */
762
+ private mapSyncResultToAssetDto;
763
+ /**
764
+ * Calculate entry ratio using actual sizes from sync results
765
+ */
766
+ private calculateEntryRatio;
767
+ /**
768
+ * Calculate mark ratio using actual sizes and current prices
769
+ */
770
+ private calculateMarkRatio;
771
+ /**
772
+ * Calculate net funding from sync results
773
+ */
774
+ private calculateNetFundingFromSyncResults;
775
+ /**
776
+ * Calculate total unrealized PnL from sync results
777
+ */
778
+ private calculateTotalUnrealizedPnlFromSyncResults;
779
+ /**
780
+ * Calculate current total position value using market prices
781
+ */
782
+ private calculateCurrentTotalPositionValue;
783
+ /**
784
+ * Calculate entry total position value using entry prices
785
+ */
786
+ private calculateEntryTotalPositionValue;
787
+ }
788
+
789
+ /**
790
+ * Account summary calculation utility class
791
+ */
792
+ declare class AccountSummaryCalculator {
793
+ private webData2;
794
+ constructor(webData2: WebData2Response | null);
795
+ /**
796
+ * Calculate account summary from webData2 and platform orders
797
+ */
798
+ calculateAccountSummary(platformAccountSummary: AccountSummaryResponseDto | null, platformOpenOrders: OpenLimitOrderDto[] | null, agentWalletAddress?: string, agentWalletStatus?: string): AccountSummaryResponseDto | null;
799
+ /**
800
+ * Calculate total USD value of open limit orders
801
+ */
802
+ private calculateTotalLimitOrderValue;
803
+ /**
804
+ * Get real-time clearinghouse state from webData2
805
+ */
806
+ getClearinghouseState(): {
807
+ assetPositions: AssetPosition[];
808
+ crossMaintenanceMarginUsed: string;
809
+ crossMarginSummary: {
810
+ accountValue: string;
811
+ totalMarginUsed: string;
812
+ totalNtlPos: string;
813
+ totalRawUsd: string;
814
+ };
815
+ marginSummary: {
816
+ accountValue: string;
817
+ totalMarginUsed: string;
818
+ totalNtlPos: string;
819
+ totalRawUsd: string;
820
+ };
821
+ time: number;
822
+ withdrawable: string;
823
+ } | null;
824
+ /**
825
+ * Check if real-time data is available
826
+ */
827
+ hasRealTimeData(): boolean;
828
+ }
645
829
 
646
- export { HyperliquidService, PearHyperliquidClient, PearHyperliquidProvider, PearMigrationSDK, PearHyperliquidClient as default, useAccountSummary, useAddress, useHyperliquidService, useMigrationSDK, useOpenOrders, useOpenPositions, usePearHyperliquidClient, useTradeHistories };
647
- export type { AccountSummaryResponseDto, AgentWalletDto, ApiErrorResponse, ApiResponse, BalanceSummaryDto, CrossMarginSummaryDto, CumFundingDto, MarginSummaryDto, MigrationHookState, MigrationHooks, OpenLimitOrderDto, OpenOrderV1Dto, OpenPositionDto, OpenPositionV1Dto, OrderAssetDto, OrderStatus, PaginatedTradeHistoryResponseDto, PearHyperliquidConfig, PnlDto, PositionAssetDetailDto, PositionSideDto, PositionSyncStatus, RawValueDto, SyncOpenOrderDto, SyncOpenOrderResponseDto, SyncOpenPositionDto, SyncOpenPositionResponseDto, SyncTradeHistoryDto, SyncTradeHistoryResponseDto, TpSlDto, TradeHistoryAssetDataDto, TradeHistoryDataDto, TradeHistoryV1Dto, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketResponse, WebSocketSubscribeMessage };
830
+ export { AccountSummaryCalculator, AggregatePositionCalculator, PearHyperliquidClient, PearHyperliquidProvider, PearMigrationSDK, PositionSide, PearHyperliquidClient as default, useAccountSummary, useAddress, useCalculatedAccountSummary, useCalculatedOpenPositions, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useMigrationSDK, useOpenOrders, useOpenPositions, usePearHyperliquidClient, useTradeHistories };
831
+ export type { AccountSummaryResponseDto, AgentWalletDto, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetPosition, BalanceSummaryDto, CrossMarginSummaryDto, CumFundingDto, MarginSummaryDto, MigrationHookState, MigrationHooks, OpenLimitOrderDto, OpenOrderV1Dto, OpenPositionDto, OpenPositionV1Dto, OrderAssetDto, OrderStatus, PaginatedTradeHistoryResponseDto, PearHyperliquidConfig, PnlDto, PositionAssetDetailDto, PositionSideDto, PositionSyncStatus, RawValueDto, SyncOpenOrderDto, SyncOpenOrderResponseDto, SyncOpenPositionDto, SyncOpenPositionResponseDto, SyncTradeHistoryDto, SyncTradeHistoryResponseDto, TpSlDto, TradeHistoryAssetDataDto, TradeHistoryDataDto, TradeHistoryV1Dto, UniverseAsset, WebData2Response, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketResponse, WebSocketSubscribeMessage, WsAllMidsData };