@pear-protocol/hyperliquid-sdk 0.0.31 → 0.0.33

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.
@@ -6,4 +6,4 @@ export declare const fetchHistoricalCandles: (coin: string, startTime: number, e
6
6
  /**
7
7
  * Retrieve recent user fills from HyperLiquid and map to ExternalFillDto[]
8
8
  */
9
- export declare const fetchUserFillsFromHyperliquid: (user: string, aggregateByTime?: boolean) => Promise<ApiResponse<ExternalFillDto[]>>;
9
+ export declare const fetchUserFillsFromHyperliquid: (user: string, startTime: number, aggregateByTime?: boolean) => Promise<ApiResponse<ExternalFillDto[]>>;
@@ -12,3 +12,4 @@ export * from './useAutoSyncFills';
12
12
  export * from './usePosition';
13
13
  export * from './useOrders';
14
14
  export * from './useTwap';
15
+ export * from './useNotifications';
@@ -0,0 +1,10 @@
1
+ import type { NotificationDto } from '../types';
2
+ export interface UseNotificationsResult {
3
+ notifications: NotificationDto[] | null;
4
+ unreadCount: number;
5
+ }
6
+ /**
7
+ * Provides notifications and fills checkpoint data sourced from the SDK WebSocket.
8
+ * Data is persisted in the SDK's Zustand store.
9
+ */
10
+ export declare function useNotifications(): UseNotificationsResult;
package/dist/index.d.ts CHANGED
@@ -30,7 +30,7 @@ type WebSocketConnectionState = 'connecting' | 'connected' | 'disconnected' | 'e
30
30
  /**
31
31
  * WebSocket channels
32
32
  */
33
- type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'webData2' | 'allMids' | 'activeAssetData';
33
+ type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'webData2' | 'allMids' | 'activeAssetData';
34
34
  /**
35
35
  * WebSocket subscription message
36
36
  */
@@ -53,6 +53,16 @@ interface WebSocketDataMessage<T = unknown> {
53
53
  channel: WebSocketChannel;
54
54
  data: T;
55
55
  }
56
+ type NotificationCategory = 'TRADE_OPENED_OUTSIDE_PEAR' | 'POSITION_LIQUIDATED' | 'LIMIT_ORDER_FILLED' | 'LIMIT_ORDER_FAILED' | 'TP_ORDER_FILLED' | 'TP_ORDER_FAILED' | 'SL_ORDER_FILLED' | 'SL_ORDER_FAILED';
57
+ interface NotificationDto {
58
+ id: string;
59
+ address: string;
60
+ category: NotificationCategory;
61
+ parameters: Record<string, any>;
62
+ is_read: boolean;
63
+ created_at: string;
64
+ updated_at: string;
65
+ }
56
66
  interface ChunkFillDto {
57
67
  fillId: string;
58
68
  assetName: string;
@@ -120,7 +130,6 @@ interface TradeHistoryDataDto {
120
130
  totalValue: number;
121
131
  entryRatio: number;
122
132
  exitRatio: number;
123
- leverage: number;
124
133
  longAssets: TradeHistoryAssetDataDto[];
125
134
  shortAssets: TradeHistoryAssetDataDto[];
126
135
  createdAt: string;
@@ -433,7 +442,6 @@ interface RawAssetDto {
433
442
  interface RawPositionDto {
434
443
  positionId: string;
435
444
  address: string;
436
- leverage: number;
437
445
  stopLoss: number | null;
438
446
  takeProfit: number | null;
439
447
  status: string;
@@ -937,6 +945,16 @@ declare function useTwap(): {
937
945
  readonly cancelTwap: (orderId: string) => Promise<ApiResponse<CancelTwapResponseDto>>;
938
946
  };
939
947
 
948
+ interface UseNotificationsResult {
949
+ notifications: NotificationDto[] | null;
950
+ unreadCount: number;
951
+ }
952
+ /**
953
+ * Provides notifications and fills checkpoint data sourced from the SDK WebSocket.
954
+ * Data is persisted in the SDK's Zustand store.
955
+ */
956
+ declare function useNotifications(): UseNotificationsResult;
957
+
940
958
  interface UseHyperliquidWebSocketProps {
941
959
  wsUrl: string;
942
960
  address: string | null;
@@ -1060,5 +1078,5 @@ declare function mapTradingViewIntervalToCandleInterval(interval: string): Candl
1060
1078
  */
1061
1079
  declare function mapCandleIntervalToTradingViewInterval(interval: CandleInterval): string;
1062
1080
 
1063
- export { AccountSummaryCalculator, AuthStatus, ConflictDetector, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, updateRiskParameters, useAccountSummary, useAddress, useAgentWallet, useAuth, useAutoSyncFills, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePosition, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWebData };
1064
- export type { AccountSummaryResponseDto, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AutoSyncFillsOptions, AutoSyncFillsState, BalanceSummaryDto, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ClearinghouseState, CloseExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossMarginSummaryDto, CumFundingDto, ExecutionType, HLWebSocketResponse, HistoricalRange, LadderConfigInput, MarginSummaryDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderStatus, PairAssetInput, PerformanceOverlay, PositionAdjustmentType, PositionAssetDetailDto, PositionAssetSummaryDto, PositionResponseStatus, RealtimeBar, RealtimeBarsCallback, TokenConflict, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TpSlThresholdInput, TpSlThresholdType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TwapChunkStatusDto, TwapMonitoringDto, UniverseAsset, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAgentWalletOptions, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UsePerformanceOverlaysReturn, UseTokenSelectionMetadataReturn, UserProfile, UserSelectionState, WebData2Response, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
1081
+ export { AccountSummaryCalculator, AuthStatus, ConflictDetector, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, updateRiskParameters, useAccountSummary, useAddress, useAgentWallet, useAuth, useAutoSyncFills, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useNotifications, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePosition, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWebData };
1082
+ export type { AccountSummaryResponseDto, AdjustExecutionType, AdjustOrderRequestInput, AdjustOrderResponseDto, AdjustPositionRequestInput, AdjustPositionResponseDto, AgentWalletDto, AgentWalletState, ApiErrorResponse, ApiResponse, AssetCtx, AssetInformationDetail, AssetMarketData, AssetPosition, AutoSyncFillsOptions, AutoSyncFillsState, BalanceSummaryDto, CancelOrderResponseDto, CancelTwapResponseDto, CandleChartData, CandleData, CandleInterval, CandleSnapshotRequest, ClearinghouseState, CloseExecutionType, ClosePositionRequestInput, ClosePositionResponseDto, CreatePositionRequestInput, CreatePositionResponseDto, CrossMarginSummaryDto, CumFundingDto, ExecutionType, HLWebSocketResponse, HistoricalRange, LadderConfigInput, MarginSummaryDto, NotificationCategory, NotificationDto, OpenLimitOrderDto, OpenPositionDto, OrderAssetDto, OrderStatus, PairAssetInput, PerformanceOverlay, PositionAdjustmentType, PositionAssetDetailDto, PositionAssetSummaryDto, PositionResponseStatus, RealtimeBar, RealtimeBarsCallback, TokenConflict, TokenHistoricalPriceData, TokenMetadata, TokenSelection, TpSlThresholdInput, TpSlThresholdType, TradeHistoryAssetDataDto, TradeHistoryDataDto, TwapChunkStatusDto, TwapMonitoringDto, UniverseAsset, UpdateRiskParametersRequestInput, UpdateRiskParametersResponseDto, UseAgentWalletOptions, UseAuthOptions, UseBasketCandlesReturn, UseHistoricalPriceDataReturn, UseNotificationsResult, UsePerformanceOverlaysReturn, UseTokenSelectionMetadataReturn, UserProfile, UserSelectionState, WebData2Response, WebSocketAckResponse, WebSocketChannel, WebSocketConnectionState, WebSocketDataMessage, WebSocketMessage, WebSocketSubscribeMessage, WsAllMidsData };
package/dist/index.js CHANGED
@@ -2434,22 +2434,25 @@ const useUserData = create((set) => ({
2434
2434
  openOrders: null,
2435
2435
  accountSummary: null,
2436
2436
  twapDetails: null,
2437
+ notifications: null,
2437
2438
  setTradeHistories: (value) => set({ tradeHistories: value }),
2438
2439
  setRawOpenPositions: (value) => set({ rawOpenPositions: value }),
2439
2440
  setOpenOrders: (value) => set({ openOrders: value }),
2440
2441
  setAccountSummary: (value) => set({ accountSummary: value }),
2441
2442
  setTwapDetails: (value) => set({ twapDetails: value }),
2443
+ setNotifications: (value) => set({ notifications: value }),
2442
2444
  clean: () => set({
2443
2445
  tradeHistories: null,
2444
2446
  rawOpenPositions: null,
2445
2447
  openOrders: null,
2446
2448
  accountSummary: null,
2447
2449
  twapDetails: null,
2450
+ notifications: null,
2448
2451
  }),
2449
2452
  }));
2450
2453
 
2451
2454
  const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2452
- const { setTradeHistories, setRawOpenPositions, setOpenOrders, setAccountSummary, setTwapDetails, clean } = useUserData();
2455
+ const { setTradeHistories, setRawOpenPositions, setOpenOrders, setAccountSummary, setTwapDetails, setNotifications, clean, } = useUserData();
2453
2456
  const [lastError, setLastError] = useState(null);
2454
2457
  const [lastSubscribedAddress, setLastSubscribedAddress] = useState(null);
2455
2458
  // WebSocket connection
@@ -2493,6 +2496,10 @@ const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2493
2496
  case 'twap-details':
2494
2497
  setTwapDetails(dataMessage.data);
2495
2498
  break;
2499
+ case 'notifications':
2500
+ setNotifications(dataMessage.data);
2501
+ break;
2502
+ // 'fills-checkpoint' is intentionally ignored here
2496
2503
  }
2497
2504
  }
2498
2505
  }
@@ -7561,8 +7568,8 @@ const fetchHistoricalCandles = async (coin, startTime, endTime, interval) => {
7561
7568
  /**
7562
7569
  * Retrieve recent user fills from HyperLiquid and map to ExternalFillDto[]
7563
7570
  */
7564
- const fetchUserFillsFromHyperliquid = async (user, aggregateByTime = true) => {
7565
- const request = { type: 'userFills', user, aggregateByTime };
7571
+ const fetchUserFillsFromHyperliquid = async (user, startTime, aggregateByTime = true) => {
7572
+ const request = { type: 'userFillsByTime', user, startTime, aggregateByTime };
7566
7573
  try {
7567
7574
  const response = await axios$1.post('https://api.hyperliquid.xyz/info', request, {
7568
7575
  headers: { 'Content-Type': 'application/json' },
@@ -8181,8 +8188,29 @@ const syncFills = async (baseUrl, accessToken, payload) => {
8181
8188
  * Convenience: fetch user fills from HyperLiquid, then sync them to Pear backend
8182
8189
  */
8183
8190
  const syncUserFillsFromHyperliquid = async (baseUrl, accessToken, user, aggregateByTime = true) => {
8184
- const { data: fills } = await fetchUserFillsFromHyperliquid(user, aggregateByTime);
8185
- return syncFills(baseUrl, accessToken, { user, fills });
8191
+ const firstStartTime = 1735660800000; // 1 January 2025
8192
+ const allFills = [];
8193
+ const seenTids = new Set();
8194
+ let startTime = firstStartTime;
8195
+ let batchSize = 0;
8196
+ do {
8197
+ const { data: batch } = await fetchUserFillsFromHyperliquid(user, startTime, aggregateByTime);
8198
+ batchSize = batch.length;
8199
+ for (const fill of batch) {
8200
+ const tid = fill.tid;
8201
+ if (tid === undefined)
8202
+ continue;
8203
+ if (!seenTids.has(tid)) {
8204
+ seenTids.add(tid);
8205
+ allFills.push(fill);
8206
+ }
8207
+ }
8208
+ if (batchSize === 2000) {
8209
+ const last = batch[batch.length - 1];
8210
+ startTime = last.time;
8211
+ }
8212
+ } while (batchSize === 2000);
8213
+ return syncFills(baseUrl, accessToken, { user, fills: allFills });
8186
8214
  };
8187
8215
 
8188
8216
  /**
@@ -8335,10 +8363,11 @@ const calculatePositionAsset = (asset, currentPrice, totalInitialPositionSize, l
8335
8363
  };
8336
8364
  const buildPositionValue = (rawPositions, webData2, allMids) => {
8337
8365
  return rawPositions.map((position) => {
8366
+ const webData2Position = webData2.clearinghouseState.assetPositions.find(ap => ap.position.coin === position.longAssets[0].coin || ap.position.coin === position.shortAssets[0].coin);
8338
8367
  let mappedPosition = {
8339
8368
  positionId: position.positionId,
8340
8369
  address: position.address,
8341
- leverage: position.leverage,
8370
+ leverage: webData2Position === null || webData2Position === void 0 ? void 0 : webData2Position.position.leverage.value, // TODO: consider if user manually change leverage from the HL UI
8342
8371
  entryRatio: 1,
8343
8372
  marginUsed: 0,
8344
8373
  markRatio: 1,
@@ -8535,6 +8564,23 @@ function useTwap() {
8535
8564
  return { orders, cancelTwap: cancelTwap$1 };
8536
8565
  }
8537
8566
 
8567
+ /**
8568
+ * Provides notifications and fills checkpoint data sourced from the SDK WebSocket.
8569
+ * Data is persisted in the SDK's Zustand store.
8570
+ */
8571
+ function useNotifications() {
8572
+ const notifications = useUserData((state) => state.notifications);
8573
+ const unreadCount = useMemo(() => {
8574
+ if (!notifications)
8575
+ return 0;
8576
+ return notifications.reduce((acc, n) => acc + (n.is_read ? 0 : 1), 0);
8577
+ }, [notifications]);
8578
+ return {
8579
+ notifications,
8580
+ unreadCount,
8581
+ };
8582
+ }
8583
+
8538
8584
  const PearHyperliquidContext = createContext(undefined);
8539
8585
  /**
8540
8586
  * React Provider for PearHyperliquidClient
@@ -8653,7 +8699,7 @@ const PearHyperliquidProvider = ({ children, apiBaseUrl = 'https://hl-v2.pearpro
8653
8699
  address,
8654
8700
  intervalMs: 60000,
8655
8701
  aggregateByTime: true,
8656
- enabled: false, // Boolean(isAuthenticated && address && accessToken),
8702
+ enabled: Boolean(isAuthenticated && address && accessToken),
8657
8703
  });
8658
8704
  const contextValue = useMemo(() => ({
8659
8705
  // Config
@@ -8833,4 +8879,4 @@ function mapCandleIntervalToTradingViewInterval(interval) {
8833
8879
  }
8834
8880
  }
8835
8881
 
8836
- export { AccountSummaryCalculator, AuthStatus, ConflictDetector, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, updateRiskParameters, useAccountSummary, useAddress, useAgentWallet, useAuth, useAutoSyncFills, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePosition, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWebData };
8882
+ export { AccountSummaryCalculator, AuthStatus, ConflictDetector, PearHyperliquidProvider, TokenMetadataExtractor, adjustOrder, adjustPosition, calculateWeightedRatio, cancelOrder, cancelTwap, cancelTwapOrder, closePosition, computeBasketCandles, createCandleLookups, createPosition, getCompleteTimestamps, mapCandleIntervalToTradingViewInterval, mapTradingViewIntervalToCandleInterval, updateRiskParameters, useAccountSummary, useAddress, useAgentWallet, useAuth, useAutoSyncFills, useBasketCandles, useHistoricalPriceData, useHistoricalPriceDataStore, useHyperliquidNativeWebSocket, useHyperliquidWebSocket, useNotifications, useOpenOrders, useOrders, usePearAgentWallet, usePearAuth, usePearHyperliquid, usePerformanceOverlays, usePosition, useTokenSelectionMetadata, useTradeHistories, useTwap, useUserSelection, useWebData };
package/dist/types.d.ts CHANGED
@@ -51,7 +51,7 @@ export type WebSocketConnectionState = 'connecting' | 'connected' | 'disconnecte
51
51
  /**
52
52
  * WebSocket channels
53
53
  */
54
- export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'webData2' | 'allMids' | 'activeAssetData';
54
+ export type WebSocketChannel = 'trade-histories' | 'open-positions' | 'open-orders' | 'account-summary' | 'twap-details' | 'notifications' | 'webData2' | 'allMids' | 'activeAssetData';
55
55
  /**
56
56
  * WebSocket subscription message
57
57
  */
@@ -74,6 +74,16 @@ export interface WebSocketDataMessage<T = unknown> {
74
74
  channel: WebSocketChannel;
75
75
  data: T;
76
76
  }
77
+ export type NotificationCategory = 'TRADE_OPENED_OUTSIDE_PEAR' | 'POSITION_LIQUIDATED' | 'LIMIT_ORDER_FILLED' | 'LIMIT_ORDER_FAILED' | 'TP_ORDER_FILLED' | 'TP_ORDER_FAILED' | 'SL_ORDER_FILLED' | 'SL_ORDER_FAILED';
78
+ export interface NotificationDto {
79
+ id: string;
80
+ address: string;
81
+ category: NotificationCategory;
82
+ parameters: Record<string, any>;
83
+ is_read: boolean;
84
+ created_at: string;
85
+ updated_at: string;
86
+ }
77
87
  export interface ChunkFillDto {
78
88
  fillId: string;
79
89
  assetName: string;
@@ -141,7 +151,6 @@ export interface TradeHistoryDataDto {
141
151
  totalValue: number;
142
152
  entryRatio: number;
143
153
  exitRatio: number;
144
- leverage: number;
145
154
  longAssets: TradeHistoryAssetDataDto[];
146
155
  shortAssets: TradeHistoryAssetDataDto[];
147
156
  createdAt: string;
@@ -518,7 +527,6 @@ export interface RawAssetDto {
518
527
  export interface RawPositionDto {
519
528
  positionId: string;
520
529
  address: string;
521
- leverage: number;
522
530
  stopLoss: number | null;
523
531
  takeProfit: number | null;
524
532
  status: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pear-protocol/hyperliquid-sdk",
3
- "version": "0.0.31",
3
+ "version": "0.0.33",
4
4
  "description": "React SDK for Pear Protocol Hyperliquid API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",