@rabby-wallet/hyperliquid-sdk 1.1.1-beta.1 → 1.1.1-beta.5

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,4 +1,5 @@
1
- import type { OrderResponse, CancelResponse, ExchangeClientConfig, PlaceOrderParams, MultiOrderParams, CancelOrderParams, ModifyOrderParams, WithdrawParams, ApproveBuilderFeeParams, PrepareApproveBuilderFeeResult, SendApproveParams, MarketOrderParams, UpdateLeverageParams, BindTpslByOrderIdParams, UpdateIsolatedMarginParams, TwapOrderParams, TwapCancelParams, TwapOrderResponse } from '../types';
1
+ import { ExchangeType } from '../types/constants';
2
+ import type { OrderResponse, CancelResponse, ExchangeClientConfig, PlaceOrderParams, MultiOrderParams, CancelOrderParams, ModifyOrderParams, WithdrawParams, ApproveBuilderFeeParams, PrepareApproveBuilderFeeResult, SendApproveParams, MarketOrderParams, UpdateLeverageParams, BindTpslByOrderIdParams, UpdateIsolatedMarginParams } from '../types';
2
3
  /**
3
4
  * Client for executing trades on Hyperliquid (perpetuals only)
4
5
  * Only includes essential trading APIs as specified
@@ -72,6 +73,15 @@ export declare class ExchangeClient {
72
73
  */
73
74
  modifyOrder(params: ModifyOrderParams): Promise<any>;
74
75
  updateIsolatedMargin(params: UpdateIsolatedMarginParams): Promise<any>;
76
+ prepareSetReferrer(code: string): {
77
+ typedData: import("@metamask/eth-sig-util").TypedMessage<import("@metamask/eth-sig-util").MessageTypes>;
78
+ action: {
79
+ type: ExchangeType;
80
+ code: string;
81
+ };
82
+ nonce: number;
83
+ };
84
+ sendSetReferrer(params: SendApproveParams): Promise<any>;
75
85
  /**
76
86
  * Set referrer for 10% fee
77
87
  */
@@ -115,13 +125,4 @@ export declare class ExchangeClient {
115
125
  */
116
126
  prepareWithdraw(params: WithdrawParams): PrepareApproveBuilderFeeResult;
117
127
  sendWithdraw(params: SendApproveParams): Promise<any>;
118
- /**
119
- * Place a TWAP order
120
- * TWAP orders split a large order into smaller slices over time
121
- */
122
- placeTwapOrder(params: TwapOrderParams): Promise<TwapOrderResponse>;
123
- /**
124
- * Cancel a TWAP order
125
- */
126
- cancelTwapOrder(params: TwapCancelParams): Promise<any>;
127
128
  }
@@ -469,6 +469,28 @@ class ExchangeClient {
469
469
  });
470
470
  });
471
471
  }
472
+ prepareSetReferrer(code) {
473
+ const nonce = Date.now();
474
+ try {
475
+ const action = {
476
+ type: constants_1.ExchangeType.SET_REFERRER,
477
+ code,
478
+ };
479
+ const typedData = (0, signer_1.prepareSetReferrerTypedData)({ action, isTestnet: this.isTestnet, nonce });
480
+ return { typedData, action, nonce };
481
+ }
482
+ catch (error) {
483
+ throw error;
484
+ }
485
+ }
486
+ sendSetReferrer(params) {
487
+ const splitSignature = (0, signer_1.splitSig)(params.signature);
488
+ return this.httpClient.exchange({
489
+ action: params.action,
490
+ nonce: params.nonce,
491
+ signature: splitSignature,
492
+ });
493
+ }
472
494
  /**
473
495
  * Set referrer for 10% fee
474
496
  */
@@ -631,54 +653,5 @@ class ExchangeClient {
631
653
  signature: splitSignature,
632
654
  });
633
655
  }
634
- /**
635
- * Place a TWAP order
636
- * TWAP orders split a large order into smaller slices over time
637
- */
638
- placeTwapOrder(params) {
639
- return __awaiter(this, void 0, void 0, function* () {
640
- const nonce = Date.now();
641
- const action = {
642
- type: constants_1.ExchangeType.TWAP_ORDER,
643
- a: yield this.symbolConversion.getAssetIndex(params.coin),
644
- b: params.isBuy,
645
- s: (0, number_1.removeTrailingZeros)(params.sz),
646
- r: params.reduceOnly || false,
647
- m: params.durationMillis,
648
- t: params.randomizeDelay || false,
649
- };
650
- if (params.builder) {
651
- action.builder = {
652
- b: params.builder.address,
653
- f: params.builder.fee,
654
- };
655
- }
656
- const signature = (0, signer_1.signL1AgentAction)(this.getAgentPrivateKey(), action, this.isTestnet, nonce);
657
- return this.httpClient.exchange({
658
- action,
659
- nonce,
660
- signature,
661
- });
662
- });
663
- }
664
- /**
665
- * Cancel a TWAP order
666
- */
667
- cancelTwapOrder(params) {
668
- return __awaiter(this, void 0, void 0, function* () {
669
- const nonce = Date.now();
670
- const action = {
671
- type: constants_1.ExchangeType.TWAP_CANCEL,
672
- a: yield this.symbolConversion.getAssetIndex(params.coin),
673
- t: params.twapId,
674
- };
675
- const signature = (0, signer_1.signL1AgentAction)(this.getAgentPrivateKey(), action, this.isTestnet, nonce);
676
- return this.httpClient.exchange({
677
- action,
678
- nonce,
679
- signature,
680
- });
681
- });
682
- }
683
656
  }
684
657
  exports.ExchangeClient = ExchangeClient;
@@ -1,4 +1,4 @@
1
- import type { Meta, AssetCtx, ClearinghouseState, UserFills, CandleSnapshot, AllMids, ExtraAgent, OpenOrder, FeeResponse, UserNonFundingLedgerUpdates, UserHistoricalOrders, ReferralResponse, L2BookSnapshot, UserTwapSliceFill, FundingHistoryItem, UserFunding } from '../types';
1
+ import type { Meta, AssetCtx, ClearinghouseState, UserFills, CandleSnapshot, AllMids, ExtraAgent, OpenOrder, FeeResponse, UserNonFundingLedgerUpdates, UserHistoricalOrders, ReferralResponse } from '../types';
2
2
  export interface InfoClientConfig {
3
3
  isTestnet?: boolean;
4
4
  timeout?: number;
@@ -61,29 +61,4 @@ export declare class InfoClient {
61
61
  * Get user's approved persistent agents
62
62
  */
63
63
  extraAgents(address?: string): Promise<ExtraAgent[]>;
64
- /**
65
- * get L2 order book for a specific coin
66
- * nSigFigs: Optional field to aggregate levels to nSigFigs significant figures. Valid values are 2, 3, 4, 5, and null, which means full precision
67
- * mantissa: Optional field to aggregate levels. This field is only allowed if nSigFigs is 5. Accepts values of 1(null), 2 or 5.
68
- * total six level
69
- * nSigFig: 5 default
70
- * nSigFig: 5 mantissa: 2
71
- * nSigFig: 5 mantissa: 5
72
- * nSigFig: 4
73
- * nSigFig: 3
74
- * nSigFig: 2
75
- */
76
- getL2Book(coin: string, nSigFigs?: number, mantissa?: number): Promise<L2BookSnapshot>;
77
- /**
78
- * Get user's TWAP slice fills
79
- */
80
- getUserTwapSliceFills(address?: string, startTime?: number, endTime?: number): Promise<UserTwapSliceFill[]>;
81
- /**
82
- * Get funding history for a specific coin
83
- */
84
- getFundingHistory(coin: string, startTime: number, endTime?: number): Promise<FundingHistoryItem[]>;
85
- /**
86
- * Get user funding
87
- */
88
- getUserFunding(address?: string): Promise<UserFunding[]>;
89
64
  }
@@ -244,74 +244,5 @@ class InfoClient {
244
244
  });
245
245
  });
246
246
  }
247
- /**
248
- * get L2 order book for a specific coin
249
- * nSigFigs: Optional field to aggregate levels to nSigFigs significant figures. Valid values are 2, 3, 4, 5, and null, which means full precision
250
- * mantissa: Optional field to aggregate levels. This field is only allowed if nSigFigs is 5. Accepts values of 1(null), 2 or 5.
251
- * total six level
252
- * nSigFig: 5 default
253
- * nSigFig: 5 mantissa: 2
254
- * nSigFig: 5 mantissa: 5
255
- * nSigFig: 4
256
- * nSigFig: 3
257
- * nSigFig: 2
258
- */
259
- getL2Book(coin, nSigFigs, mantissa) {
260
- return __awaiter(this, void 0, void 0, function* () {
261
- return this.httpClient.info({
262
- type: constants_1.InfoType.L2_BOOK,
263
- coin,
264
- nSigFigs,
265
- // Optional field to aggregate levels to nSigFigs significant figures. Valid values are 2, 3, 4, 5, and null, which means full precision
266
- mantissa,
267
- // Optional field to aggregate levels. This field is only allowed if nSigFigs is 5. Accepts values of 1, 2 or 5.
268
- });
269
- });
270
- }
271
- /**
272
- * Get user's TWAP slice fills
273
- */
274
- getUserTwapSliceFills(address, startTime, endTime) {
275
- return __awaiter(this, void 0, void 0, function* () {
276
- const user = address || this.masterAddress;
277
- if (!user) {
278
- throw new Error('user address is empty');
279
- }
280
- return this.httpClient.info({
281
- type: constants_1.InfoType.USER_TWAP_SLICE_FILLS,
282
- user,
283
- startTime: startTime || 0,
284
- endTime,
285
- });
286
- });
287
- }
288
- /**
289
- * Get funding history for a specific coin
290
- */
291
- getFundingHistory(coin, startTime, endTime) {
292
- return __awaiter(this, void 0, void 0, function* () {
293
- return this.httpClient.info({
294
- type: constants_1.InfoType.FUNDING_HISTORY,
295
- coin,
296
- startTime,
297
- endTime,
298
- });
299
- });
300
- }
301
- /**
302
- * Get user funding
303
- */
304
- getUserFunding(address) {
305
- return __awaiter(this, void 0, void 0, function* () {
306
- const user = address || this.masterAddress;
307
- if (!user) {
308
- throw new Error('user address is empty');
309
- }
310
- return this.httpClient.info({
311
- type: constants_1.InfoType.USER_FUNDING,
312
- user,
313
- });
314
- });
315
- }
316
247
  }
317
248
  exports.InfoClient = InfoClient;
@@ -1,4 +1,4 @@
1
- import type { L2Book, Candle, WsOrder, WebData2, WsActiveAssetCtx, WsUserFills, WsClearinghouseState, Notification, WsTwapStates, WsOpenOrders, WsUserTwapSliceFills, WsUserTwapHistory, wsUserNonFundingLedgerUpdates, WsAllMids } from '../types';
1
+ import type { AllMids, L2Book, Candle, WsOrder, WebData2, WsActiveAssetCtx, WsUserFills, WsClearinghouseState } from '../types';
2
2
  export interface WebSocketClientConfig {
3
3
  masterAddress?: string;
4
4
  isTestnet?: boolean;
@@ -17,8 +17,7 @@ export declare class WebSocketClient {
17
17
  private ws;
18
18
  private readonly url;
19
19
  private readonly config;
20
- private typeSubscriptions;
21
- private userSubscriptions;
20
+ private subscriptions;
22
21
  private activeSubscriptions;
23
22
  private reconnectAttempts;
24
23
  private isConnecting;
@@ -45,11 +44,6 @@ export declare class WebSocketClient {
45
44
  */
46
45
  disconnect(): void;
47
46
  private getSubscriptionKey;
48
- /**
49
- * Dispatch message to matching subscriptions
50
- * Uses direct lookup instead of iteration for better performance
51
- */
52
- private dispatchMessage;
53
47
  /**
54
48
  * Subscribe to a channel
55
49
  */
@@ -57,24 +51,11 @@ export declare class WebSocketClient {
57
51
  /**
58
52
  * Subscribe to all mid prices
59
53
  */
60
- subscribeToAllMids(callback: SubscriptionCallback<WsAllMids>): Subscription;
54
+ subscribeToAllMids(callback: SubscriptionCallback<AllMids>): Subscription;
61
55
  /**
62
56
  * Subscribe to L2 order book for a specific coin
63
- * nSigFigs: Optional field to aggregate levels to nSigFigs significant figures. Valid values are 2, 3, 4, 5, and null, which means full precision
64
- * mantissa: Optional field to aggregate levels. This field is only allowed if nSigFigs is 5. Accepts values of 1, 2 or 5.
65
- * total six level
66
- * nSigFig: 5 default
67
- * nSigFig: 5 mantissa: 2
68
- * nSigFig: 5 mantissa: 5
69
- * nSigFig: 4
70
- * nSigFig: 3
71
- * nSigFig: 2
72
- */
73
- subscribeToL2Book({ coin, nSigFigs, mantissa, }: {
74
- coin: string;
75
- nSigFigs?: number;
76
- mantissa?: number;
77
- }, callback: SubscriptionCallback<L2Book>): Subscription;
57
+ */
58
+ subscribeToL2Book(coin: string, callback: SubscriptionCallback<L2Book>): Subscription;
78
59
  /**
79
60
  * Subscribe to active asset ctx
80
61
  */
@@ -127,28 +108,4 @@ export declare class WebSocketClient {
127
108
  * @param state 'active' | 'background' | 'inactive'
128
109
  */
129
110
  handleAppStateChange(state: string): void;
130
- /**
131
- * Subscribe to notification messages
132
- */
133
- subscribeToNotification(callback: SubscriptionCallback<Notification>): Subscription;
134
- /**
135
- * Subscribe to TWAP order states
136
- */
137
- subscribeToTwapStates(callback: SubscriptionCallback<WsTwapStates>): Subscription;
138
- /**
139
- * Subscribe to open orders
140
- */
141
- subscribeToOpenOrders(callback: SubscriptionCallback<WsOpenOrders>): Subscription;
142
- /**
143
- * Subscribe to user non-funding ledger updates (deposits/withdrawals)
144
- */
145
- subscribeToUserNonFundingLedgerUpdates(callback: SubscriptionCallback<wsUserNonFundingLedgerUpdates>): Subscription;
146
- /**
147
- * Subscribe to user TWAP slice fills
148
- */
149
- subscribeToUserTwapSliceFills(callback: SubscriptionCallback<WsUserTwapSliceFills>): Subscription;
150
- /**
151
- * Subscribe to user TWAP history
152
- */
153
- subscribeToUserTwapHistory(callback: SubscriptionCallback<WsUserTwapHistory>): Subscription;
154
111
  }
@@ -17,10 +17,7 @@ const constants_1 = require("../types/constants");
17
17
  class WebSocketClient {
18
18
  constructor(config) {
19
19
  this.ws = null;
20
- // Map<type, callback[]> for most subscription types
21
- this.typeSubscriptions = new Map();
22
- // Map<type:user, callback[]> for clearinghouseState (multi-account support)
23
- this.userSubscriptions = new Map();
20
+ this.subscriptions = new Map();
24
21
  this.activeSubscriptions = new Map();
25
22
  this.reconnectAttempts = 0;
26
23
  this.isConnecting = false;
@@ -81,24 +78,7 @@ class WebSocketClient {
81
78
  var _a;
82
79
  if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
83
80
  const subKey = this.getSubscriptionKey(message.subscription);
84
- const type = message.subscription.type;
85
- const user = message.subscription.user;
86
- // Register callback in appropriate map
87
- if (type === constants_1.WsSubscriptionType.CLEARINGHOUSE_STATE && user) {
88
- const userKey = `${type}:${user.toLowerCase()}`;
89
- const callbacks = this.userSubscriptions.get(userKey) || [];
90
- if (!callbacks.includes(callback)) {
91
- callbacks.push(callback);
92
- this.userSubscriptions.set(userKey, callbacks);
93
- }
94
- }
95
- else {
96
- const callbacks = this.typeSubscriptions.get(type) || [];
97
- if (!callbacks.includes(callback)) {
98
- callbacks.push(callback);
99
- this.typeSubscriptions.set(type, callbacks);
100
- }
101
- }
81
+ this.subscriptions.set(message.subscription.type, callback);
102
82
  this.activeSubscriptions.set(subKey, { message, callback });
103
83
  this.ws.send(JSON.stringify(Object.assign(Object.assign({}, message), { method: 'subscribe' })));
104
84
  }
@@ -108,15 +88,50 @@ class WebSocketClient {
108
88
  resolve();
109
89
  };
110
90
  this.ws.onmessage = (event) => {
91
+ var _a;
111
92
  try {
112
93
  const data = JSON.parse(event.data);
113
94
  // Handle pong response
114
95
  if (data.channel === 'pong') {
96
+ // console.log('Received pong from server'); // 可以注释掉以减少日志输出
115
97
  return;
116
98
  }
117
99
  const type = data.channel;
118
- // Dispatch message to matching subscriptions
119
- this.dispatchMessage(type, data.data);
100
+ // Iterate through active subscriptions to find matching ones
101
+ let hasDispatched = false;
102
+ for (const { message, callback } of this.activeSubscriptions.values()) {
103
+ const subParams = message.subscription;
104
+ if (subParams.type === type) {
105
+ let isMatch = true;
106
+ // Filter based on subscription parameters
107
+ if (type === 'l2Book' && data.data.coin !== subParams.coin)
108
+ isMatch = false;
109
+ if (type === 'trades' && ((_a = data.data[0]) === null || _a === void 0 ? void 0 : _a.coin) !== subParams.coin)
110
+ isMatch = false;
111
+ if (type === 'candle' && (data.data.s !== subParams.coin || data.data.i !== subParams.interval))
112
+ isMatch = false;
113
+ if (type === 'activeAssetCtx' && data.data.coin !== subParams.coin)
114
+ isMatch = false;
115
+ // For user-specific data
116
+ if (subParams.user) {
117
+ // If response data contains user, verify it matches
118
+ if (data.data && data.data.user && data.data.user.toLowerCase() !== subParams.user.toLowerCase()) {
119
+ isMatch = false;
120
+ }
121
+ }
122
+ if (isMatch) {
123
+ callback(data.data);
124
+ hasDispatched = true;
125
+ }
126
+ }
127
+ }
128
+ // Fallback to simple type map if no active subscription matched (backward compatibility or if activeSubscriptions missing)
129
+ if (!hasDispatched) {
130
+ const callback = this.subscriptions.get(type);
131
+ if (callback) {
132
+ callback(data.data);
133
+ }
134
+ }
120
135
  }
121
136
  catch (error) {
122
137
  console.error('Error parsing WebSocket message:', error);
@@ -192,8 +207,7 @@ class WebSocketClient {
192
207
  this.ws.close();
193
208
  this.ws = null;
194
209
  }
195
- this.typeSubscriptions.clear();
196
- this.userSubscriptions.clear();
210
+ this.subscriptions.clear();
197
211
  this.activeSubscriptions.clear();
198
212
  this.pendingSubscriptions = [];
199
213
  this.reconnectAttempts = 0; // 重置重连计数
@@ -201,26 +215,6 @@ class WebSocketClient {
201
215
  getSubscriptionKey(subscription) {
202
216
  return JSON.stringify(subscription);
203
217
  }
204
- /**
205
- * Dispatch message to matching subscriptions
206
- * Uses direct lookup instead of iteration for better performance
207
- */
208
- dispatchMessage(type, data) {
209
- // Special handling for clearinghouseState: dispatch by type:user
210
- if (type === constants_1.WsSubscriptionType.CLEARINGHOUSE_STATE && data.user) {
211
- const userKey = `${type}:${data.user.toLowerCase()}`;
212
- const callbacks = this.userSubscriptions.get(userKey);
213
- if (callbacks && callbacks.length > 0) {
214
- callbacks.forEach(callback => callback(data));
215
- return;
216
- }
217
- }
218
- // For all other types: direct lookup by type
219
- const callbacks = this.typeSubscriptions.get(type);
220
- if (callbacks && callbacks.length > 0) {
221
- callbacks.forEach(callback => callback(data));
222
- }
223
- }
224
218
  /**
225
219
  * Subscribe to a channel
226
220
  */
@@ -229,22 +223,8 @@ class WebSocketClient {
229
223
  const subscriptionData = { message, callback };
230
224
  const subKey = this.getSubscriptionKey(message.subscription);
231
225
  const type = message.subscription.type;
232
- const user = message.subscription.user;
233
- // Register callback in appropriate map
234
- if (type === constants_1.WsSubscriptionType.CLEARINGHOUSE_STATE && user) {
235
- // Multi-account support: store by type:user
236
- const userKey = `${type}:${user.toLowerCase()}`;
237
- const callbacks = this.userSubscriptions.get(userKey) || [];
238
- callbacks.push(callback);
239
- this.userSubscriptions.set(userKey, callbacks);
240
- }
241
- else {
242
- // Normal subscriptions: store by type
243
- const callbacks = this.typeSubscriptions.get(type) || [];
244
- callbacks.push(callback);
245
- this.typeSubscriptions.set(type, callbacks);
246
- }
247
226
  if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
227
+ this.subscriptions.set(type, callback);
248
228
  this.activeSubscriptions.set(subKey, subscriptionData);
249
229
  this.ws.send(JSON.stringify(Object.assign(Object.assign({}, message), { method: 'subscribe' })));
250
230
  }
@@ -260,31 +240,16 @@ class WebSocketClient {
260
240
  unsubscribe: () => {
261
241
  var _a;
262
242
  this.activeSubscriptions.delete(subKey);
263
- // Remove callback from appropriate map
264
- if (type === constants_1.WsSubscriptionType.CLEARINGHOUSE_STATE && user) {
265
- const userKey = `${type}:${user.toLowerCase()}`;
266
- const callbacks = this.userSubscriptions.get(userKey);
267
- if (callbacks) {
268
- const filtered = callbacks.filter(cb => cb !== callback);
269
- if (filtered.length > 0) {
270
- this.userSubscriptions.set(userKey, filtered);
271
- }
272
- else {
273
- this.userSubscriptions.delete(userKey);
274
- }
243
+ // Only remove the global callback if no other active subscriptions use this channel type
244
+ let hasOtherSubs = false;
245
+ for (const sub of this.activeSubscriptions.values()) {
246
+ if (sub.message.subscription.type === type) {
247
+ hasOtherSubs = true;
248
+ break;
275
249
  }
276
250
  }
277
- else {
278
- const callbacks = this.typeSubscriptions.get(type);
279
- if (callbacks) {
280
- const filtered = callbacks.filter(cb => cb !== callback);
281
- if (filtered.length > 0) {
282
- this.typeSubscriptions.set(type, filtered);
283
- }
284
- else {
285
- this.typeSubscriptions.delete(type);
286
- }
287
- }
251
+ if (!hasOtherSubs) {
252
+ this.subscriptions.delete(type);
288
253
  }
289
254
  if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
290
255
  this.ws.send(JSON.stringify(Object.assign(Object.assign({}, message), { method: 'unsubscribe' })));
@@ -299,24 +264,15 @@ class WebSocketClient {
299
264
  */
300
265
  subscribeToAllMids(callback) {
301
266
  return this.subscribe({
302
- subscription: { type: constants_1.WsSubscriptionType.ALL_MIDS },
267
+ subscription: { type: 'allMids' },
303
268
  }, callback);
304
269
  }
305
270
  /**
306
271
  * Subscribe to L2 order book for a specific coin
307
- * nSigFigs: Optional field to aggregate levels to nSigFigs significant figures. Valid values are 2, 3, 4, 5, and null, which means full precision
308
- * mantissa: Optional field to aggregate levels. This field is only allowed if nSigFigs is 5. Accepts values of 1, 2 or 5.
309
- * total six level
310
- * nSigFig: 5 default
311
- * nSigFig: 5 mantissa: 2
312
- * nSigFig: 5 mantissa: 5
313
- * nSigFig: 4
314
- * nSigFig: 3
315
- * nSigFig: 2
316
272
  */
317
- subscribeToL2Book({ coin, nSigFigs, mantissa, }, callback) {
273
+ subscribeToL2Book(coin, callback) {
318
274
  return this.subscribe({
319
- subscription: { type: constants_1.WsSubscriptionType.L2_BOOK, coin, nSigFigs: nSigFigs !== null && nSigFigs !== void 0 ? nSigFigs : null, mantissa: mantissa !== null && mantissa !== void 0 ? mantissa : null },
275
+ subscription: { type: 'l2Book', coin },
320
276
  }, callback);
321
277
  }
322
278
  /**
@@ -324,7 +280,7 @@ class WebSocketClient {
324
280
  */
325
281
  subscribeToActiveAssetCtx(coin, callback) {
326
282
  return this.subscribe({
327
- subscription: { type: constants_1.WsSubscriptionType.ACTIVE_ASSET_CTX, coin },
283
+ subscription: { type: 'activeAssetCtx', coin },
328
284
  }, callback);
329
285
  }
330
286
  /**
@@ -332,7 +288,7 @@ class WebSocketClient {
332
288
  */
333
289
  subscribeToTrades(coin, callback) {
334
290
  return this.subscribe({
335
- subscription: { type: constants_1.WsSubscriptionType.TRADES, coin },
291
+ subscription: { type: 'trades', coin },
336
292
  }, callback);
337
293
  }
338
294
  /**
@@ -340,7 +296,7 @@ class WebSocketClient {
340
296
  */
341
297
  subscribeToCandles(coin, interval, callback) {
342
298
  return this.subscribe({
343
- subscription: { type: constants_1.WsSubscriptionType.CANDLE, coin, interval },
299
+ subscription: { type: 'candle', coin, interval },
344
300
  }, callback);
345
301
  }
346
302
  /**
@@ -351,7 +307,7 @@ class WebSocketClient {
351
307
  throw new Error('masterAddress is empty');
352
308
  }
353
309
  return this.subscribe({
354
- subscription: { type: constants_1.WsSubscriptionType.USER_FILLS, user: this.config.masterAddress, aggregateByTime: true },
310
+ subscription: { type: 'userFills', user: this.config.masterAddress, aggregateByTime: true },
355
311
  }, callback);
356
312
  }
357
313
  /**
@@ -362,7 +318,7 @@ class WebSocketClient {
362
318
  throw new Error('masterAddress is empty');
363
319
  }
364
320
  return this.subscribe({
365
- subscription: { type: constants_1.WsSubscriptionType.ORDER_UPDATES, user: this.config.masterAddress },
321
+ subscription: { type: 'orderUpdates', user: this.config.masterAddress },
366
322
  }, callback);
367
323
  }
368
324
  /**
@@ -373,7 +329,7 @@ class WebSocketClient {
373
329
  throw new Error('masterAddress is empty');
374
330
  }
375
331
  return this.subscribe({
376
- subscription: { type: constants_1.WsSubscriptionType.USER_FUNDINGS, user: this.config.masterAddress },
332
+ subscription: { type: 'userFundings', user: this.config.masterAddress },
377
333
  }, callback);
378
334
  }
379
335
  /**
@@ -385,7 +341,7 @@ class WebSocketClient {
385
341
  throw new Error('masterAddress is empty');
386
342
  }
387
343
  return this.subscribe({
388
- subscription: { type: constants_1.WsSubscriptionType.WEB_DATA2, user: this.config.masterAddress },
344
+ subscription: { type: 'webData2', user: this.config.masterAddress },
389
345
  }, callback);
390
346
  }
391
347
  subscribeToClearinghouseState(user, callback) {
@@ -394,7 +350,7 @@ class WebSocketClient {
394
350
  throw new Error('user address is empty');
395
351
  }
396
352
  const subscriptions = users.map(u => this.subscribe({
397
- subscription: { type: constants_1.WsSubscriptionType.CLEARINGHOUSE_STATE, user: u || this.config.masterAddress },
353
+ subscription: { type: 'clearinghouseState', user: u || this.config.masterAddress },
398
354
  }, callback));
399
355
  return {
400
356
  unsubscribe: () => {
@@ -456,71 +412,5 @@ class WebSocketClient {
456
412
  }
457
413
  }
458
414
  }
459
- /**
460
- * Subscribe to notification messages
461
- */
462
- subscribeToNotification(callback) {
463
- if (!this.config.masterAddress) {
464
- throw new Error('masterAddress is empty');
465
- }
466
- return this.subscribe({
467
- subscription: { type: constants_1.WsSubscriptionType.NOTIFICATION, user: this.config.masterAddress },
468
- }, callback);
469
- }
470
- /**
471
- * Subscribe to TWAP order states
472
- */
473
- subscribeToTwapStates(callback) {
474
- if (!this.config.masterAddress) {
475
- throw new Error('masterAddress is empty');
476
- }
477
- return this.subscribe({
478
- subscription: { type: constants_1.WsSubscriptionType.TWAP_STATES, user: this.config.masterAddress },
479
- }, callback);
480
- }
481
- /**
482
- * Subscribe to open orders
483
- */
484
- subscribeToOpenOrders(callback) {
485
- if (!this.config.masterAddress) {
486
- throw new Error('masterAddress is empty');
487
- }
488
- return this.subscribe({
489
- subscription: { type: constants_1.WsSubscriptionType.OPEN_ORDERS, user: this.config.masterAddress },
490
- }, callback);
491
- }
492
- /**
493
- * Subscribe to user non-funding ledger updates (deposits/withdrawals)
494
- */
495
- subscribeToUserNonFundingLedgerUpdates(callback) {
496
- if (!this.config.masterAddress) {
497
- throw new Error('masterAddress is empty');
498
- }
499
- return this.subscribe({
500
- subscription: { type: constants_1.WsSubscriptionType.USER_NON_FUNDING_LEDGER_UPDATES, user: this.config.masterAddress },
501
- }, callback);
502
- }
503
- /**
504
- * Subscribe to user TWAP slice fills
505
- */
506
- subscribeToUserTwapSliceFills(callback) {
507
- if (!this.config.masterAddress) {
508
- throw new Error('masterAddress is empty');
509
- }
510
- return this.subscribe({
511
- subscription: { type: constants_1.WsSubscriptionType.USER_TWAP_SLICE_FILLS, user: this.config.masterAddress },
512
- }, callback);
513
- }
514
- /**
515
- * Subscribe to user TWAP history
516
- */
517
- subscribeToUserTwapHistory(callback) {
518
- if (!this.config.masterAddress) {
519
- throw new Error('masterAddress is empty');
520
- }
521
- return this.subscribe({
522
- subscription: { type: constants_1.WsSubscriptionType.USER_TWAP_HISTORY, user: this.config.masterAddress },
523
- }, callback);
524
- }
525
415
  }
526
416
  exports.WebSocketClient = WebSocketClient;
package/dist/index.d.ts CHANGED
@@ -6,4 +6,4 @@ export { HttpClient, HttpClientConfig } from './client/http-client';
6
6
  export * from './types';
7
7
  export * from './types/constants';
8
8
  export { BASE_URLS, WSS_URLS, ENDPOINTS } from './types/constants';
9
- export { InfoType, ExchangeType, OrderType, TimeInForce, WsSubscriptionType } from './types/constants';
9
+ export { InfoType, ExchangeType, OrderType, TimeInForce } from './types/constants';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.WsSubscriptionType = exports.TimeInForce = exports.OrderType = exports.ExchangeType = exports.InfoType = exports.ENDPOINTS = exports.WSS_URLS = exports.BASE_URLS = exports.HttpClient = exports.WebSocketClient = exports.ExchangeClient = exports.InfoClient = exports.HyperliquidSDK = void 0;
17
+ exports.TimeInForce = exports.OrderType = exports.ExchangeType = exports.InfoType = exports.ENDPOINTS = exports.WSS_URLS = exports.BASE_URLS = exports.HttpClient = exports.WebSocketClient = exports.ExchangeClient = exports.InfoClient = exports.HyperliquidSDK = void 0;
18
18
  // Main SDK
19
19
  var hyperliquid_sdk_1 = require("./hyperliquid-sdk");
20
20
  Object.defineProperty(exports, "HyperliquidSDK", { enumerable: true, get: function () { return hyperliquid_sdk_1.HyperliquidSDK; } });
@@ -40,4 +40,3 @@ Object.defineProperty(exports, "InfoType", { enumerable: true, get: function ()
40
40
  Object.defineProperty(exports, "ExchangeType", { enumerable: true, get: function () { return constants_2.ExchangeType; } });
41
41
  Object.defineProperty(exports, "OrderType", { enumerable: true, get: function () { return constants_2.OrderType; } });
42
42
  Object.defineProperty(exports, "TimeInForce", { enumerable: true, get: function () { return constants_2.TimeInForce; } });
43
- Object.defineProperty(exports, "WsSubscriptionType", { enumerable: true, get: function () { return constants_2.WsSubscriptionType; } });
@@ -23,22 +23,17 @@ export declare enum ExchangeType {
23
23
  APPROVE_AGENT = "approveAgent",
24
24
  APPROVE_BUILDER_FEE = "approveBuilderFee",
25
25
  SUB_ACCOUNT_TRANSFER = "subAccountTransfer",
26
- SET_REFERRER = "setReferrer",
27
- TWAP_ORDER = "twapOrder",
28
- TWAP_CANCEL = "twapCancel"
26
+ SET_REFERRER = "setReferrer"
29
27
  }
30
28
  export declare enum InfoType {
31
29
  ALL_MIDS = "allMids",
32
- NOTIFICATION = "notification",
33
30
  USER_NON_FUNDING_LEDGER_UPDATES = "userNonFundingLedgerUpdates",
34
31
  USER_HISTORICAL_ORDERS = "historicalOrders",
35
32
  USER_OPEN_ORDERS = "openOrders",
36
33
  USER_FILLS = "userFills",
37
34
  USER_FILLS_BY_TIME = "userFillsByTime",
38
- USER_TWAP_SLICE_FILLS = "userTwapSliceFills",
39
35
  ORDER_STATUS = "orderStatus",
40
36
  L2_BOOK = "l2Book",
41
- TRADES = "trades",
42
37
  CANDLES_SNAPSHOT = "candleSnapshot",
43
38
  META_AND_ASSET_CTXS = "metaAndAssetCtxs",
44
39
  USER_FUNDING = "userFunding",
@@ -73,21 +68,3 @@ export declare const CHAIN_IDS: {
73
68
  readonly HYPERLIQUID_MAINNET: 1337;
74
69
  };
75
70
  export declare const SLIPPAGE = 0.08;
76
- export declare enum WsSubscriptionType {
77
- ALL_MIDS = "allMids",
78
- L2_BOOK = "l2Book",
79
- TRADES = "trades",
80
- CANDLE = "candle",
81
- ACTIVE_ASSET_CTX = "activeAssetCtx",
82
- USER_FILLS = "userFills",
83
- ORDER_UPDATES = "orderUpdates",
84
- USER_FUNDINGS = "userFundings",
85
- WEB_DATA2 = "webData2",
86
- CLEARINGHOUSE_STATE = "clearinghouseState",
87
- NOTIFICATION = "notification",
88
- TWAP_STATES = "twapStates",
89
- OPEN_ORDERS = "openOrders",
90
- USER_NON_FUNDING_LEDGER_UPDATES = "userNonFundingLedgerUpdates",
91
- USER_TWAP_SLICE_FILLS = "userTwapSliceFills",
92
- USER_TWAP_HISTORY = "userTwapHistory"
93
- }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WsSubscriptionType = exports.SLIPPAGE = exports.CHAIN_IDS = exports.TimeInForce = exports.OrderType = exports.InfoType = exports.ExchangeType = exports.ENDPOINTS = exports.WSS_URLS = exports.BASE_URLS = void 0;
3
+ exports.SLIPPAGE = exports.CHAIN_IDS = exports.TimeInForce = exports.OrderType = exports.InfoType = exports.ExchangeType = exports.ENDPOINTS = exports.WSS_URLS = exports.BASE_URLS = void 0;
4
4
  // API endpoints
5
5
  exports.BASE_URLS = {
6
6
  PRODUCTION: 'https://api.hyperliquid.xyz',
@@ -30,23 +30,18 @@ var ExchangeType;
30
30
  ExchangeType["APPROVE_BUILDER_FEE"] = "approveBuilderFee";
31
31
  ExchangeType["SUB_ACCOUNT_TRANSFER"] = "subAccountTransfer";
32
32
  ExchangeType["SET_REFERRER"] = "setReferrer";
33
- ExchangeType["TWAP_ORDER"] = "twapOrder";
34
- ExchangeType["TWAP_CANCEL"] = "twapCancel";
35
33
  })(ExchangeType || (exports.ExchangeType = ExchangeType = {}));
36
34
  // Info types for API requests (perpetuals only)
37
35
  var InfoType;
38
36
  (function (InfoType) {
39
37
  InfoType["ALL_MIDS"] = "allMids";
40
- InfoType["NOTIFICATION"] = "notification";
41
38
  InfoType["USER_NON_FUNDING_LEDGER_UPDATES"] = "userNonFundingLedgerUpdates";
42
39
  InfoType["USER_HISTORICAL_ORDERS"] = "historicalOrders";
43
40
  InfoType["USER_OPEN_ORDERS"] = "openOrders";
44
41
  InfoType["USER_FILLS"] = "userFills";
45
42
  InfoType["USER_FILLS_BY_TIME"] = "userFillsByTime";
46
- InfoType["USER_TWAP_SLICE_FILLS"] = "userTwapSliceFills";
47
43
  InfoType["ORDER_STATUS"] = "orderStatus";
48
44
  InfoType["L2_BOOK"] = "l2Book";
49
- InfoType["TRADES"] = "trades";
50
45
  InfoType["CANDLES_SNAPSHOT"] = "candleSnapshot";
51
46
  InfoType["META_AND_ASSET_CTXS"] = "metaAndAssetCtxs";
52
47
  InfoType["USER_FUNDING"] = "userFunding";
@@ -86,23 +81,3 @@ exports.CHAIN_IDS = {
86
81
  HYPERLIQUID_MAINNET: 1337,
87
82
  };
88
83
  exports.SLIPPAGE = 0.08;
89
- // WebSocket subscription types
90
- var WsSubscriptionType;
91
- (function (WsSubscriptionType) {
92
- WsSubscriptionType["ALL_MIDS"] = "allMids";
93
- WsSubscriptionType["L2_BOOK"] = "l2Book";
94
- WsSubscriptionType["TRADES"] = "trades";
95
- WsSubscriptionType["CANDLE"] = "candle";
96
- WsSubscriptionType["ACTIVE_ASSET_CTX"] = "activeAssetCtx";
97
- WsSubscriptionType["USER_FILLS"] = "userFills";
98
- WsSubscriptionType["ORDER_UPDATES"] = "orderUpdates";
99
- WsSubscriptionType["USER_FUNDINGS"] = "userFundings";
100
- WsSubscriptionType["WEB_DATA2"] = "webData2";
101
- WsSubscriptionType["CLEARINGHOUSE_STATE"] = "clearinghouseState";
102
- WsSubscriptionType["NOTIFICATION"] = "notification";
103
- WsSubscriptionType["TWAP_STATES"] = "twapStates";
104
- WsSubscriptionType["OPEN_ORDERS"] = "openOrders";
105
- WsSubscriptionType["USER_NON_FUNDING_LEDGER_UPDATES"] = "userNonFundingLedgerUpdates";
106
- WsSubscriptionType["USER_TWAP_SLICE_FILLS"] = "userTwapSliceFills";
107
- WsSubscriptionType["USER_TWAP_HISTORY"] = "userTwapHistory";
108
- })(WsSubscriptionType || (exports.WsSubscriptionType = WsSubscriptionType = {}));
@@ -154,11 +154,6 @@ export interface UserFill {
154
154
  export type UserFills = {
155
155
  [asset: string]: UserFill[];
156
156
  };
157
- export type wsUserNonFundingLedgerUpdates = {
158
- user: string;
159
- isSnapshot: boolean;
160
- nonFundingLedgerUpdates: UserNonFundingLedgerUpdates[];
161
- };
162
157
  export type UserNonFundingLedgerUpdates = {
163
158
  time: number;
164
159
  hash: string;
@@ -286,9 +281,6 @@ export interface AssetCtx {
286
281
  export interface AllMids {
287
282
  [coin: string]: string;
288
283
  }
289
- export interface WsAllMids {
290
- mids: AllMids;
291
- }
292
284
  export interface L2Book {
293
285
  coin: string;
294
286
  levels: [WsLevel[], WsLevel[]];
@@ -475,104 +467,3 @@ export interface ReferralResponse {
475
467
  };
476
468
  rewardHistory: any[];
477
469
  }
478
- export interface TwapOrderParams {
479
- coin: string;
480
- isBuy: boolean;
481
- sz: string;
482
- reduceOnly?: boolean;
483
- durationMillis: number;
484
- randomizeDelay?: boolean;
485
- builder?: {
486
- address: string;
487
- fee: number;
488
- };
489
- }
490
- export interface TwapCancelParams {
491
- coin: string;
492
- twapId: number;
493
- }
494
- export interface TwapOrderResponse {
495
- status: 'ok';
496
- response: {
497
- type: 'twapOrder';
498
- data: {
499
- twapId: number;
500
- };
501
- };
502
- }
503
- export interface TwapState {
504
- twapId: number;
505
- coin: string;
506
- isBuy: boolean;
507
- sz: string;
508
- reduceOnly: boolean;
509
- totalSz: string;
510
- executedSz: string;
511
- remainingSz: string;
512
- startTime: number;
513
- endTime: number;
514
- status: 'active' | 'completed' | 'cancelled';
515
- }
516
- export interface WsTwapStates {
517
- dex: string;
518
- user: string;
519
- states?: TwapState[];
520
- }
521
- export interface WsOpenOrders {
522
- user: string;
523
- orders?: OpenOrder[];
524
- }
525
- export interface WsUserTwapSliceFills {
526
- user: string;
527
- fills?: UserTwapSliceFill[];
528
- }
529
- export interface WsUserTwapHistory {
530
- user: string;
531
- history?: UserTwapHistory[];
532
- }
533
- export interface UserTwapSliceFill {
534
- coin: string;
535
- px: string;
536
- sz: string;
537
- side: Side;
538
- time: number;
539
- hash: string;
540
- oid: number;
541
- crossed: boolean;
542
- fee: string;
543
- tid: number;
544
- twapId: number;
545
- }
546
- export interface UserTwapHistory {
547
- twapId: number;
548
- user: string;
549
- coin: string;
550
- side: Side;
551
- sz: string;
552
- totalFilled: string;
553
- avgFillPx: string;
554
- startTime: number;
555
- endTime: number;
556
- status: string;
557
- }
558
- export interface L2BookSnapshot {
559
- coin: string;
560
- levels: [WsLevel[], WsLevel[]];
561
- time: number;
562
- }
563
- export interface FundingHistoryItem {
564
- coin: string;
565
- fundingRate: string;
566
- premium: string;
567
- time: number;
568
- }
569
- export interface UserFunding {
570
- time: number;
571
- coin: string;
572
- usdc: string;
573
- szi: string;
574
- fundingRate: string;
575
- }
576
- export interface Notification {
577
- notification: string;
578
- }
@@ -23,6 +23,11 @@ export declare const signTypedDataV4: ({ privateKey, domain, primaryType, payloa
23
23
  message: Record<string, unknown>;
24
24
  }) => Signature;
25
25
  export declare const signL1AgentAction: (privateKey: string, action: unknown, isTestnet: boolean, nonce: number) => Signature;
26
+ export declare const prepareSetReferrerTypedData: ({ action, isTestnet, nonce, }: {
27
+ action: Record<string, unknown>;
28
+ isTestnet: boolean;
29
+ nonce: number;
30
+ }) => TypedMessage<MessageTypes>;
26
31
  /**
27
32
  * Prepare some action sign must by master wallet so we need to prepare the typed data
28
33
  * Returns typed data that needs to be signed by the main wallet
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.prepareMasterSignData = exports.signL1AgentAction = exports.signTypedDataV4 = exports.splitSig = exports.EIP712_DOMAIN_TYPES = void 0;
36
+ exports.prepareMasterSignData = exports.prepareSetReferrerTypedData = exports.signL1AgentAction = exports.signTypedDataV4 = exports.splitSig = exports.EIP712_DOMAIN_TYPES = void 0;
37
37
  const ethUtil = __importStar(require("@ethereumjs/util"));
38
38
  const sigUtil = __importStar(require("@metamask/eth-sig-util"));
39
39
  const keccak_1 = require("ethereum-cryptography/keccak");
@@ -109,6 +109,34 @@ const signL1AgentAction = (privateKey, action, isTestnet, nonce) => {
109
109
  return (0, exports.signTypedDataV4)({ privateKey, domain, primaryType: 'Agent', payloadTypes, message });
110
110
  };
111
111
  exports.signL1AgentAction = signL1AgentAction;
112
+ const prepareSetReferrerTypedData = ({ action, isTestnet, nonce, }) => {
113
+ const domain = {
114
+ name: 'Exchange',
115
+ version: '1',
116
+ chainId: constants_1.CHAIN_IDS.HYPERLIQUID_MAINNET,
117
+ verifyingContract: '0x0000000000000000000000000000000000000000',
118
+ };
119
+ const payloadTypes = [
120
+ { name: 'source', type: 'string' },
121
+ { name: 'connectionId', type: 'bytes32' },
122
+ ];
123
+ const primaryType = 'Agent';
124
+ const types = {
125
+ EIP712Domain: exports.EIP712_DOMAIN_TYPES,
126
+ [primaryType]: payloadTypes,
127
+ };
128
+ const typedData = {
129
+ domain,
130
+ types,
131
+ primaryType,
132
+ message: {
133
+ source: !isTestnet ? 'a' : 'b',
134
+ connectionId: generateActionHash(action, nonce),
135
+ }
136
+ };
137
+ return typedData;
138
+ };
139
+ exports.prepareSetReferrerTypedData = prepareSetReferrerTypedData;
112
140
  /**
113
141
  * Prepare some action sign must by master wallet so we need to prepare the typed data
114
142
  * Returns typed data that needs to be signed by the main wallet
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rabby-wallet/hyperliquid-sdk",
3
- "version": "1.1.1-beta.1",
3
+ "version": "1.1.1-beta.5",
4
4
  "description": "Simplified Hyperliquid Perpetuals Trading SDK for Frontend Applications",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",