@pear-protocol/exchanges-sdk 0.0.17 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +73 -137
  2. package/dist/client/base-ws.d.ts +30 -0
  3. package/dist/client/base-ws.js +113 -0
  4. package/dist/client/binance/exchange-ws.d.ts +19 -0
  5. package/dist/client/binance/exchange-ws.js +26 -0
  6. package/dist/{account/exchanges → client}/binance/rest.d.ts +2 -6
  7. package/dist/{account/exchanges → client}/binance/rest.js +4 -11
  8. package/dist/client/binance/types.d.ts +68 -0
  9. package/dist/client/binance/types.js +1 -0
  10. package/dist/client/binance/ws.d.ts +30 -0
  11. package/dist/client/binance/ws.js +54 -0
  12. package/dist/client/bybit/exchange-ws.d.ts +20 -0
  13. package/dist/client/bybit/exchange-ws.js +28 -0
  14. package/dist/{account/exchanges → client}/bybit/rest.js +3 -2
  15. package/dist/{account/exchanges → client}/bybit/types.d.ts +1 -9
  16. package/dist/client/bybit/types.js +1 -0
  17. package/dist/client/bybit/ws.d.ts +17 -0
  18. package/dist/client/bybit/ws.js +50 -0
  19. package/dist/client/exchange-ws.d.ts +12 -0
  20. package/dist/client/exchange-ws.js +10 -0
  21. package/dist/client/hyperliquid/exchange-ws.d.ts +15 -0
  22. package/dist/client/hyperliquid/exchange-ws.js +21 -0
  23. package/dist/client/hyperliquid/rest.d.ts +3 -0
  24. package/dist/client/hyperliquid/rest.js +12 -0
  25. package/dist/{account/exchanges → client}/hyperliquid/types.d.ts +18 -39
  26. package/dist/client/hyperliquid/types.js +1 -0
  27. package/dist/client/hyperliquid/ws.d.ts +10 -0
  28. package/dist/client/hyperliquid/ws.js +16 -0
  29. package/dist/client/index.d.ts +31 -0
  30. package/dist/client/index.js +47 -0
  31. package/dist/client/lighter/constants.d.ts +4 -0
  32. package/dist/client/lighter/constants.js +4 -0
  33. package/dist/client/lighter/exchange-ws.d.ts +15 -0
  34. package/dist/client/lighter/exchange-ws.js +21 -0
  35. package/dist/client/lighter/rest.d.ts +56 -0
  36. package/dist/client/lighter/rest.js +27 -0
  37. package/dist/client/lighter/types.d.ts +32 -0
  38. package/dist/client/lighter/types.js +1 -0
  39. package/dist/client/lighter/ws.d.ts +10 -0
  40. package/dist/client/lighter/ws.js +17 -0
  41. package/dist/client/okx/exchange-ws.d.ts +20 -0
  42. package/dist/client/okx/exchange-ws.js +28 -0
  43. package/dist/{account/exchanges → client}/okx/rest.js +2 -2
  44. package/dist/{account/exchanges → client}/okx/types.d.ts +1 -10
  45. package/dist/client/okx/types.js +1 -0
  46. package/dist/client/okx/ws.d.ts +17 -0
  47. package/dist/client/okx/ws.js +61 -0
  48. package/dist/helper/factory.d.ts +10 -0
  49. package/dist/helper/factory.js +12 -0
  50. package/dist/helper/index.d.ts +7 -0
  51. package/dist/helper/index.js +2 -0
  52. package/dist/helper/lighter/ethereum/abi.d.ts +66 -0
  53. package/dist/helper/lighter/ethereum/abi.js +40 -0
  54. package/dist/helper/lighter/ethereum/index.d.ts +8 -0
  55. package/dist/helper/lighter/ethereum/index.js +34 -0
  56. package/dist/helper/lighter/ethereum/types.d.ts +23 -0
  57. package/dist/helper/lighter/ethereum/types.js +1 -0
  58. package/dist/helper/lighter/helper.d.ts +9 -0
  59. package/dist/helper/lighter/helper.js +67 -0
  60. package/dist/helper/lighter/index.d.ts +6 -0
  61. package/dist/helper/lighter/index.js +2 -0
  62. package/dist/helper/lighter/types.d.ts +63 -0
  63. package/dist/helper/lighter/types.js +35 -0
  64. package/dist/helper/types.d.ts +11 -0
  65. package/dist/helper/types.js +1 -0
  66. package/dist/index.d.ts +37 -24
  67. package/dist/index.js +6 -21
  68. package/dist/sdk.d.ts +43 -0
  69. package/dist/sdk.js +52 -0
  70. package/dist/syncer/base.d.ts +33 -0
  71. package/dist/syncer/base.js +14 -0
  72. package/dist/syncer/index.d.ts +18 -0
  73. package/dist/syncer/index.js +1 -0
  74. package/dist/tracker/base.d.ts +79 -0
  75. package/dist/tracker/base.js +120 -0
  76. package/dist/tracker/binance/const.d.ts +4 -0
  77. package/dist/tracker/binance/const.js +4 -0
  78. package/dist/{account/exchanges → tracker}/binance/mapper.d.ts +4 -1
  79. package/dist/{account/exchanges → tracker}/binance/mapper.js +7 -6
  80. package/dist/tracker/binance/tracker.d.ts +60 -0
  81. package/dist/tracker/binance/tracker.js +181 -0
  82. package/dist/tracker/binance/types.d.ts +6 -0
  83. package/dist/{account/exchanges → tracker}/bybit/mapper.d.ts +5 -3
  84. package/dist/{account/exchanges → tracker}/bybit/mapper.js +11 -10
  85. package/dist/tracker/bybit/tracker.d.ts +51 -0
  86. package/dist/tracker/bybit/tracker.js +138 -0
  87. package/dist/tracker/bybit/types.d.ts +7 -0
  88. package/dist/{account/exchanges → tracker}/hyperliquid/mapper.d.ts +6 -4
  89. package/dist/{account/exchanges → tracker}/hyperliquid/mapper.js +18 -16
  90. package/dist/tracker/hyperliquid/tracker.d.ts +62 -0
  91. package/dist/tracker/hyperliquid/tracker.js +219 -0
  92. package/dist/tracker/hyperliquid/types.d.ts +23 -0
  93. package/dist/tracker/index.d.ts +38 -0
  94. package/dist/tracker/index.js +81 -0
  95. package/dist/tracker/lighter/const.d.ts +3 -0
  96. package/dist/tracker/lighter/const.js +3 -0
  97. package/dist/tracker/lighter/mapper.d.ts +16 -0
  98. package/dist/tracker/lighter/mapper.js +77 -0
  99. package/dist/tracker/lighter/tracker.d.ts +53 -0
  100. package/dist/tracker/lighter/tracker.js +150 -0
  101. package/dist/tracker/lighter/types.d.ts +16 -0
  102. package/dist/tracker/lighter/types.js +6 -0
  103. package/dist/{account/exchanges → tracker}/okx/mapper.d.ts +5 -3
  104. package/dist/{account/exchanges → tracker}/okx/mapper.js +11 -10
  105. package/dist/tracker/okx/tracker.d.ts +51 -0
  106. package/dist/tracker/okx/tracker.js +134 -0
  107. package/dist/tracker/okx/types.d.ts +8 -0
  108. package/dist/tracker/types.d.ts +63 -0
  109. package/dist/{account → tracker}/types.js +6 -4
  110. package/dist/tracker/utils.d.ts +11 -0
  111. package/dist/{account → tracker}/utils.js +0 -2
  112. package/dist/types.d.ts +50 -0
  113. package/dist/types.js +1 -0
  114. package/package.json +8 -4
  115. package/dist/account/account-manager.d.ts +0 -31
  116. package/dist/account/account-manager.js +0 -119
  117. package/dist/account/exchange-account.d.ts +0 -35
  118. package/dist/account/exchange-account.js +0 -158
  119. package/dist/account/exchanges/base.d.ts +0 -48
  120. package/dist/account/exchanges/base.js +0 -41
  121. package/dist/account/exchanges/binance/asset-tracker.d.ts +0 -26
  122. package/dist/account/exchanges/binance/asset-tracker.js +0 -38
  123. package/dist/account/exchanges/binance/const.d.ts +0 -10
  124. package/dist/account/exchanges/binance/const.js +0 -10
  125. package/dist/account/exchanges/binance/orchestrator.d.ts +0 -31
  126. package/dist/account/exchanges/binance/orchestrator.js +0 -91
  127. package/dist/account/exchanges/binance/state-handler.d.ts +0 -33
  128. package/dist/account/exchanges/binance/state-handler.js +0 -113
  129. package/dist/account/exchanges/binance/types.d.ts +0 -5
  130. package/dist/account/exchanges/binance/ws.d.ts +0 -23
  131. package/dist/account/exchanges/binance/ws.js +0 -69
  132. package/dist/account/exchanges/bybit/asset-tracker.d.ts +0 -26
  133. package/dist/account/exchanges/bybit/asset-tracker.js +0 -37
  134. package/dist/account/exchanges/bybit/const.d.ts +0 -7
  135. package/dist/account/exchanges/bybit/const.js +0 -7
  136. package/dist/account/exchanges/bybit/orchestrator.d.ts +0 -22
  137. package/dist/account/exchanges/bybit/orchestrator.js +0 -66
  138. package/dist/account/exchanges/bybit/state-handler.d.ts +0 -23
  139. package/dist/account/exchanges/bybit/state-handler.js +0 -70
  140. package/dist/account/exchanges/bybit/ws.d.ts +0 -19
  141. package/dist/account/exchanges/bybit/ws.js +0 -83
  142. package/dist/account/exchanges/hyperliquid/asset-tracker.d.ts +0 -35
  143. package/dist/account/exchanges/hyperliquid/asset-tracker.js +0 -83
  144. package/dist/account/exchanges/hyperliquid/orchestrator.d.ts +0 -26
  145. package/dist/account/exchanges/hyperliquid/orchestrator.js +0 -102
  146. package/dist/account/exchanges/hyperliquid/state-handler.d.ts +0 -25
  147. package/dist/account/exchanges/hyperliquid/state-handler.js +0 -104
  148. package/dist/account/exchanges/index.d.ts +0 -11
  149. package/dist/account/exchanges/index.js +0 -32
  150. package/dist/account/exchanges/okx/asset-tracker.d.ts +0 -26
  151. package/dist/account/exchanges/okx/asset-tracker.js +0 -34
  152. package/dist/account/exchanges/okx/const.d.ts +0 -7
  153. package/dist/account/exchanges/okx/const.js +0 -7
  154. package/dist/account/exchanges/okx/orchestrator.d.ts +0 -22
  155. package/dist/account/exchanges/okx/orchestrator.js +0 -57
  156. package/dist/account/exchanges/okx/state-handler.d.ts +0 -24
  157. package/dist/account/exchanges/okx/state-handler.js +0 -78
  158. package/dist/account/exchanges/okx/ws.d.ts +0 -20
  159. package/dist/account/exchanges/okx/ws.js +0 -103
  160. package/dist/account/index.d.ts +0 -11
  161. package/dist/account/index.js +0 -4
  162. package/dist/account/types.d.ts +0 -5
  163. package/dist/account/utils.d.ts +0 -10
  164. package/dist/credentials.d.ts +0 -28
  165. package/dist/credentials.js +0 -46
  166. package/dist/types-Caz2X4h0.d.ts +0 -151
  167. package/dist/utils/ws.d.ts +0 -10
  168. package/dist/utils/ws.js +0 -42
  169. /package/dist/{account/exchanges → client}/bybit/rest.d.ts +0 -0
  170. /package/dist/{utils → client}/hmac.d.ts +0 -0
  171. /package/dist/{utils → client}/hmac.js +0 -0
  172. /package/dist/{account/exchanges → client}/okx/rest.d.ts +0 -0
  173. /package/dist/{account/exchanges → tracker}/binance/types.js +0 -0
  174. /package/dist/{account/exchanges → tracker}/bybit/types.js +0 -0
  175. /package/dist/{account/exchanges → tracker}/hyperliquid/const.d.ts +0 -0
  176. /package/dist/{account/exchanges → tracker}/hyperliquid/const.js +0 -0
  177. /package/dist/{account/exchanges → tracker}/hyperliquid/types.js +0 -0
  178. /package/dist/{account/exchanges → tracker}/okx/types.js +0 -0
@@ -1,66 +0,0 @@
1
- import { BaseOrchestrator } from '../base';
2
- import { BybitAssetTracker } from './asset-tracker';
3
- import { fetchWalletBalance, fetchPositions, fetchAccountInfo } from './rest';
4
- import { BybitStateHandler } from './state-handler';
5
- import './types';
6
- import { BybitWs } from './ws';
7
-
8
- class BybitOrchestrator extends BaseOrchestrator {
9
- ws = null;
10
- creds;
11
- stateHandler;
12
- assetTracker;
13
- constructor(config, credentials) {
14
- super(config);
15
- this.credentials = credentials;
16
- this.creds = credentials;
17
- this.assetTracker = new BybitAssetTracker({
18
- onStateUpdate: (update) => this.onStateUpdate(update),
19
- onError: (err) => this.onError(err),
20
- getCreds: () => this.creds,
21
- getDemo: () => this.demo
22
- });
23
- this.stateHandler = new BybitStateHandler({
24
- onStateUpdate: (update) => this.onStateUpdate(update),
25
- getTrackedAssetInfos: () => this.assetTracker.getInfos()
26
- });
27
- }
28
- async initAsync() {
29
- const [wallet, positionsUsd, positionsUsdc, accountInfo] = await Promise.all([
30
- fetchWalletBalance(this.creds, this.demo),
31
- fetchPositions(this.creds, "USDT", this.demo),
32
- fetchPositions(this.creds, "USDC", this.demo),
33
- fetchAccountInfo(this.creds, this.demo)
34
- ]);
35
- this.stateHandler.handleInitialData(
36
- wallet ?? null,
37
- [positionsUsd, positionsUsdc].flat(),
38
- accountInfo?.marginMode ?? null
39
- );
40
- this.ws = new BybitWs(
41
- {
42
- onMessage: (msg) => this.stateHandler.handleMessage(msg)
43
- },
44
- this.demo
45
- );
46
- await this.ws.connect(this.creds);
47
- }
48
- cleanupConnections() {
49
- this.ws?.close();
50
- }
51
- async stop() {
52
- this.stopped = true;
53
- this.cleanupConnections();
54
- }
55
- get isConnected() {
56
- return this.ws?.isConnected ?? false;
57
- }
58
- onAssetTracked(coin) {
59
- this.assetTracker.onAssetTracked(coin);
60
- }
61
- onAssetUntracked(coin) {
62
- this.assetTracker.onAssetUntracked(coin);
63
- }
64
- }
65
-
66
- export { BybitOrchestrator };
@@ -1,23 +0,0 @@
1
- import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
2
- import { BybitRawWallet, BybitRawPosition, BybitAccountType, BybitWsMessage } from './types.js';
3
- import '@pear-protocol/types';
4
- import '../hyperliquid/types.js';
5
- import '../okx/types.js';
6
-
7
- type OnStateUpdate = (update: StateUpdate) => void;
8
- declare class BybitStateHandler {
9
- private onStateUpdate;
10
- private getTrackedAssetInfos;
11
- private rawCoins;
12
- private lastWallet;
13
- private accountType;
14
- constructor(deps: {
15
- onStateUpdate: OnStateUpdate;
16
- getTrackedAssetInfos: () => Map<string, TrackedAssetInfo>;
17
- });
18
- handleInitialData(wallet: BybitRawWallet | null, positions: BybitRawPosition[], accountType: BybitAccountType | null): void;
19
- handleMessage(msg: BybitWsMessage): void;
20
- private handleWalletUpdate;
21
- }
22
-
23
- export { BybitStateHandler };
@@ -1,70 +0,0 @@
1
- import { mergeRawCoins, buildBalance, mapPositions, mapPositionUpdates } from './mapper';
2
- import './types';
3
-
4
- class BybitStateHandler {
5
- onStateUpdate;
6
- getTrackedAssetInfos;
7
- rawCoins = /* @__PURE__ */ new Map();
8
- lastWallet = null;
9
- accountType = null;
10
- constructor(deps) {
11
- this.onStateUpdate = deps.onStateUpdate;
12
- this.getTrackedAssetInfos = deps.getTrackedAssetInfos;
13
- }
14
- handleInitialData(wallet, positions, accountType) {
15
- this.accountType = accountType;
16
- if (wallet) {
17
- this.lastWallet = wallet;
18
- this.rawCoins = mergeRawCoins(/* @__PURE__ */ new Map(), wallet.coin ?? []);
19
- const balance = buildBalance(wallet, this.rawCoins, this.accountType);
20
- if (balance) this.onStateUpdate({ balance });
21
- }
22
- this.onStateUpdate({ positions: mapPositions(positions) });
23
- }
24
- handleMessage(msg) {
25
- if (msg.topic === "wallet") {
26
- const wallet = msg.data[0];
27
- if (wallet) this.handleWalletUpdate(wallet);
28
- } else if (msg.topic === "position") {
29
- const rawPositions = msg.data;
30
- const positions = mapPositionUpdates(rawPositions);
31
- if (positions.size > 0) {
32
- const trackedAssetInfos = this.getTrackedAssetInfos();
33
- const trackedAssets = /* @__PURE__ */ new Map();
34
- for (const pos of rawPositions) {
35
- const existing = trackedAssetInfos.get(pos.symbol);
36
- if (existing) {
37
- const leverage = pos.leverage || existing.leverage;
38
- const marginType = pos.tradeMode === "1" ? "isolated" : "cross";
39
- const updated = { ...existing, leverage, marginType };
40
- trackedAssetInfos.set(pos.symbol, updated);
41
- trackedAssets.set(pos.symbol, updated);
42
- }
43
- }
44
- this.onStateUpdate({
45
- positions,
46
- ...trackedAssets.size > 0 ? { trackedAssets } : {}
47
- });
48
- }
49
- }
50
- }
51
- handleWalletUpdate(raw) {
52
- this.rawCoins = mergeRawCoins(this.rawCoins, raw.coin ?? []);
53
- const merged = this.lastWallet ? {
54
- totalEquity: raw.totalEquity || this.lastWallet.totalEquity,
55
- totalWalletBalance: raw.totalWalletBalance || this.lastWallet.totalWalletBalance,
56
- totalMarginBalance: raw.totalMarginBalance || this.lastWallet.totalMarginBalance,
57
- totalAvailableBalance: raw.totalAvailableBalance || this.lastWallet.totalAvailableBalance,
58
- totalPerpUPL: raw.totalPerpUPL || this.lastWallet.totalPerpUPL,
59
- totalInitialMargin: raw.totalInitialMargin || this.lastWallet.totalInitialMargin,
60
- totalMaintenanceMargin: raw.totalMaintenanceMargin || this.lastWallet.totalMaintenanceMargin,
61
- accountMMRate: raw.accountMMRate || this.lastWallet.accountMMRate,
62
- coin: raw.coin ?? this.lastWallet.coin
63
- } : raw;
64
- this.lastWallet = merged;
65
- const balance = buildBalance(merged, this.rawCoins, this.accountType);
66
- if (balance) this.onStateUpdate({ balance });
67
- }
68
- }
69
-
70
- export { BybitStateHandler };
@@ -1,19 +0,0 @@
1
- import { BybitCredentialsDTO } from '@pear-protocol/types';
2
- import { BybitWsHandlers } from './types.js';
3
-
4
- declare class BybitWs {
5
- private ws;
6
- private pingTimer;
7
- private handlers;
8
- private demo;
9
- private creds;
10
- private readonly pingIntervalMs;
11
- constructor(handlers: BybitWsHandlers, demo: boolean, pingIntervalMs?: number);
12
- connect(creds: BybitCredentialsDTO): Promise<void>;
13
- close(): void;
14
- get isConnected(): boolean;
15
- private clearPing;
16
- private authenticate;
17
- }
18
-
19
- export { BybitWs };
@@ -1,83 +0,0 @@
1
- import { hmacSha256Hex } from '../../../utils/hmac';
2
- import { createWs, sendWs, waitForOpen, ReconnectingWebSocket, clearIntervalTimer } from '../../../utils/ws';
3
- import { DEFAULT_PING_INTERVAL_MS, WS_URL_DEMO, WS_URL } from './const';
4
-
5
- class BybitWs {
6
- ws = null;
7
- pingTimer = null;
8
- handlers;
9
- demo;
10
- creds = null;
11
- pingIntervalMs;
12
- constructor(handlers, demo, pingIntervalMs = DEFAULT_PING_INTERVAL_MS) {
13
- this.handlers = handlers;
14
- this.demo = demo;
15
- this.pingIntervalMs = pingIntervalMs;
16
- }
17
- async connect(creds) {
18
- this.creds = creds;
19
- this.ws = createWs(this.demo ? WS_URL_DEMO : WS_URL);
20
- this.ws.addEventListener("message", (event) => {
21
- try {
22
- const msg = JSON.parse(event.data);
23
- if (msg.topic && msg.data) {
24
- this.handlers.onMessage({ topic: msg.topic, data: msg.data });
25
- }
26
- } catch {
27
- }
28
- });
29
- let initialOpen = true;
30
- this.ws.addEventListener("open", () => {
31
- if (initialOpen) {
32
- initialOpen = false;
33
- return;
34
- }
35
- if (!this.creds) return;
36
- this.authenticate(this.creds).then(() => {
37
- sendWs(this.ws, { op: "subscribe", args: ["wallet", "position"] });
38
- }).catch(() => {
39
- });
40
- });
41
- await waitForOpen(this.ws);
42
- await this.authenticate(creds);
43
- sendWs(this.ws, { op: "subscribe", args: ["wallet", "position"] });
44
- this.pingTimer = setInterval(() => sendWs(this.ws, { op: "ping" }), this.pingIntervalMs);
45
- }
46
- close() {
47
- this.clearPing();
48
- this.creds = null;
49
- if (this.ws) {
50
- this.ws.close();
51
- this.ws = null;
52
- }
53
- }
54
- get isConnected() {
55
- return this.ws?.readyState === ReconnectingWebSocket.OPEN;
56
- }
57
- clearPing() {
58
- this.pingTimer = clearIntervalTimer(this.pingTimer);
59
- }
60
- async authenticate(creds) {
61
- const expires = Date.now() + 1e4;
62
- const signature = await hmacSha256Hex(creds.api_secret, `GET/realtime${expires}`);
63
- return new Promise((resolve, reject) => {
64
- const timeout = setTimeout(() => reject(new Error("Bybit auth timeout")), 1e4);
65
- const handler = (event) => {
66
- try {
67
- const msg = JSON.parse(event.data);
68
- if (msg.op === "auth") {
69
- clearTimeout(timeout);
70
- this.ws?.removeEventListener("message", handler);
71
- if (msg.success) resolve();
72
- else reject(new Error(`Bybit auth failed: ${msg.ret_msg}`));
73
- }
74
- } catch {
75
- }
76
- };
77
- this.ws?.addEventListener("message", handler);
78
- sendWs(this.ws, { op: "auth", args: [creds.api_key, expires, signature] });
79
- });
80
- }
81
- }
82
-
83
- export { BybitWs };
@@ -1,35 +0,0 @@
1
- import { WebSocket } from 'partysocket';
2
- import { S as StateUpdate } from '../../../types-Caz2X4h0.js';
3
- import { ActiveAssetDataEvent } from './types.js';
4
- import '@pear-protocol/types';
5
- import '../bybit/types.js';
6
- import '../okx/types.js';
7
-
8
- type OnStateUpdate = (update: StateUpdate) => void;
9
- type OnActiveAssetData = (data: ActiveAssetDataEvent) => void;
10
- declare class HyperliquidAssetTracker {
11
- private onStateUpdate;
12
- private onActiveAssetData;
13
- private getWs;
14
- private getAddress;
15
- private isStopped;
16
- private subscribedCoins;
17
- private trackedAssetData;
18
- constructor(deps: {
19
- onStateUpdate: OnStateUpdate;
20
- onActiveAssetData: OnActiveAssetData;
21
- getWs: () => WebSocket | null;
22
- getAddress: () => `0x${string}` | null;
23
- isStopped: () => boolean;
24
- });
25
- onAssetTracked(coin: string): void;
26
- onAssetUntracked(coin: string): void;
27
- canUntrack(coin: string): boolean;
28
- handleActiveAssetDataMessage(data: ActiveAssetDataEvent): void;
29
- subscribeAll(coins: ReadonlySet<string>): void;
30
- private subscribeActiveAssetData;
31
- private unsubscribeActiveAssetData;
32
- private buildTrackedAssetsMap;
33
- }
34
-
35
- export { HyperliquidAssetTracker };
@@ -1,83 +0,0 @@
1
- import { sendWs } from '../../../utils/ws';
2
- import { LOCKED_TRACKED_COINS } from './const';
3
- import { buildTrackedAssetInfo } from './state-handler';
4
-
5
- class HyperliquidAssetTracker {
6
- onStateUpdate;
7
- onActiveAssetData;
8
- getWs;
9
- getAddress;
10
- isStopped;
11
- subscribedCoins = /* @__PURE__ */ new Set();
12
- trackedAssetData = /* @__PURE__ */ new Map();
13
- constructor(deps) {
14
- this.onStateUpdate = deps.onStateUpdate;
15
- this.onActiveAssetData = deps.onActiveAssetData;
16
- this.getWs = deps.getWs;
17
- this.getAddress = deps.getAddress;
18
- this.isStopped = deps.isStopped;
19
- }
20
- onAssetTracked(coin) {
21
- this.subscribeActiveAssetData(coin);
22
- }
23
- onAssetUntracked(coin) {
24
- this.unsubscribeActiveAssetData(coin);
25
- this.trackedAssetData.delete(coin);
26
- this.onStateUpdate({ trackedAssets: this.buildTrackedAssetsMap() });
27
- }
28
- canUntrack(coin) {
29
- return !LOCKED_TRACKED_COINS.includes(coin);
30
- }
31
- handleActiveAssetDataMessage(data) {
32
- if (!data.coin) return;
33
- if (!this.subscribedCoins.has(data.coin)) return;
34
- this.trackedAssetData.set(data.coin, data);
35
- this.onActiveAssetData(data);
36
- }
37
- subscribeAll(coins) {
38
- for (const coin of coins) {
39
- if (!LOCKED_TRACKED_COINS.includes(coin)) {
40
- this.subscribeActiveAssetData(coin);
41
- }
42
- }
43
- }
44
- subscribeActiveAssetData(coin) {
45
- const ws = this.getWs();
46
- const address = this.getAddress();
47
- if (!ws || !address || this.isStopped()) return;
48
- if (this.subscribedCoins.has(coin)) return;
49
- this.subscribedCoins.add(coin);
50
- sendWs(ws, {
51
- method: "subscribe",
52
- subscription: {
53
- type: "activeAssetData",
54
- coin,
55
- user: address.toLowerCase()
56
- }
57
- });
58
- }
59
- unsubscribeActiveAssetData(coin) {
60
- if (!this.subscribedCoins.has(coin)) return;
61
- this.subscribedCoins.delete(coin);
62
- const ws = this.getWs();
63
- const address = this.getAddress();
64
- if (!ws || !address) return;
65
- sendWs(ws, {
66
- method: "unsubscribe",
67
- subscription: {
68
- type: "activeAssetData",
69
- coin,
70
- user: address.toLowerCase()
71
- }
72
- });
73
- }
74
- buildTrackedAssetsMap() {
75
- const result = /* @__PURE__ */ new Map();
76
- for (const [coin, data] of this.trackedAssetData) {
77
- result.set(coin, buildTrackedAssetInfo(data));
78
- }
79
- return result;
80
- }
81
- }
82
-
83
- export { HyperliquidAssetTracker };
@@ -1,26 +0,0 @@
1
- import { g as SupportedCredentials } from '../../../types-Caz2X4h0.js';
2
- import { BaseOrchestrator, OrchestratorConfig } from '../base.js';
3
- import '@pear-protocol/types';
4
- import '../bybit/types.js';
5
- import './types.js';
6
- import '../okx/types.js';
7
-
8
- declare class HyperliquidOrchestrator extends BaseOrchestrator {
9
- private ws;
10
- private address;
11
- private stateHandler;
12
- private assetTracker;
13
- constructor(config: OrchestratorConfig, credentials: SupportedCredentials);
14
- protected initAsync(): Promise<void>;
15
- private subscribe;
16
- private handleMessage;
17
- private fetchInfo;
18
- protected cleanupConnections(): void;
19
- stop(): Promise<void>;
20
- get isConnected(): boolean;
21
- onAssetTracked(coin: string): void;
22
- onAssetUntracked(coin: string): void;
23
- protected canUntrackAsset(coin: string): boolean;
24
- }
25
-
26
- export { HyperliquidOrchestrator };
@@ -1,102 +0,0 @@
1
- import { createWs, waitForOpen, sendWs } from '../../../utils/ws';
2
- import { BaseOrchestrator } from '../base';
3
- import { HyperliquidAssetTracker } from './asset-tracker';
4
- import { LOCKED_TRACKED_COINS } from './const';
5
- import { HyperliquidStateHandler } from './state-handler';
6
-
7
- const HL_WS_URL = "wss://api.hyperliquid.xyz/ws";
8
- const HL_INFO_URL = "https://api.hyperliquid.xyz/info";
9
- class HyperliquidOrchestrator extends BaseOrchestrator {
10
- ws = null;
11
- address;
12
- stateHandler;
13
- assetTracker;
14
- constructor(config, credentials) {
15
- super(config);
16
- const creds = credentials;
17
- this.credentials = credentials;
18
- this.address = creds.address;
19
- this.stateHandler = new HyperliquidStateHandler((update) => this.onStateUpdate(update));
20
- this.assetTracker = new HyperliquidAssetTracker({
21
- onStateUpdate: (update) => this.onStateUpdate(update),
22
- onActiveAssetData: (data) => this.stateHandler.handleActiveAssetData(data),
23
- getWs: () => this.ws,
24
- getAddress: () => this.address,
25
- isStopped: () => this.stopped
26
- });
27
- }
28
- async initAsync() {
29
- const allMetas = await this.fetchInfo({ type: "allPerpMetas" });
30
- this.stateHandler.loadPerpMetas(allMetas);
31
- this.ws = createWs(HL_WS_URL);
32
- await waitForOpen(this.ws);
33
- this.ws.addEventListener("message", (event) => {
34
- this.handleMessage(event.data);
35
- });
36
- const userAddr = this.address.toLowerCase();
37
- this.subscribe({ type: "allDexsClearinghouseState", user: userAddr });
38
- this.subscribe({ type: "spotState", user: userAddr });
39
- this.subscribe({ type: "webData3", user: userAddr });
40
- for (const coin of LOCKED_TRACKED_COINS) {
41
- this.trackAsset(coin);
42
- }
43
- this.assetTracker.subscribeAll(this.trackedCoins);
44
- }
45
- subscribe(subscription) {
46
- sendWs(this.ws, { method: "subscribe", subscription });
47
- }
48
- handleMessage(raw) {
49
- try {
50
- const text = typeof raw === "string" ? raw : void 0;
51
- if (!text) return;
52
- const msg = JSON.parse(text);
53
- if (!msg.channel || !msg.data) return;
54
- switch (msg.channel) {
55
- case "allDexsClearinghouseState":
56
- this.stateHandler.handleClearinghouseState(msg.data);
57
- break;
58
- case "spotState":
59
- this.stateHandler.handleSpotState(msg.data);
60
- break;
61
- case "webData3":
62
- this.stateHandler.handleWebData3(msg.data);
63
- break;
64
- case "activeAssetData":
65
- this.assetTracker.handleActiveAssetDataMessage(msg.data);
66
- break;
67
- }
68
- } catch {
69
- }
70
- }
71
- async fetchInfo(body) {
72
- const res = await fetch(HL_INFO_URL, {
73
- method: "POST",
74
- headers: { "Content-Type": "application/json" },
75
- body: JSON.stringify(body)
76
- });
77
- if (!res.ok) throw new Error(`Hyperliquid info request failed: ${res.status}`);
78
- return res.json();
79
- }
80
- cleanupConnections() {
81
- this.ws?.close();
82
- this.ws = null;
83
- }
84
- async stop() {
85
- this.stopped = true;
86
- this.cleanupConnections();
87
- }
88
- get isConnected() {
89
- return this.ws !== null && !this.stopped;
90
- }
91
- onAssetTracked(coin) {
92
- this.assetTracker.onAssetTracked(coin);
93
- }
94
- onAssetUntracked(coin) {
95
- this.assetTracker.onAssetUntracked(coin);
96
- }
97
- canUntrackAsset(coin) {
98
- return this.assetTracker.canUntrack(coin);
99
- }
100
- }
101
-
102
- export { HyperliquidOrchestrator };
@@ -1,25 +0,0 @@
1
- import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
2
- import { AllPerpMetasResponse, AllDexsClearinghouseStateEvent, ActiveAssetDataEvent, WebData3Event, SpotStateEvent } from './types.js';
3
- import '@pear-protocol/types';
4
- import '../bybit/types.js';
5
- import '../okx/types.js';
6
-
7
- type OnStateUpdate = (update: StateUpdate) => void;
8
- declare class HyperliquidStateHandler {
9
- private onStateUpdate;
10
- private lastSummary;
11
- private spotCoinBalances;
12
- private accountType;
13
- private symbolToCollateralToken;
14
- private availableToTradeByCollateral;
15
- constructor(onStateUpdate: OnStateUpdate);
16
- loadPerpMetas(allMetas: AllPerpMetasResponse): void;
17
- handleClearinghouseState(data: AllDexsClearinghouseStateEvent): void;
18
- handleActiveAssetData(data: ActiveAssetDataEvent): void;
19
- handleWebData3(data: WebData3Event): void;
20
- handleSpotState(data: SpotStateEvent): void;
21
- private buildBalance;
22
- }
23
- declare function buildTrackedAssetInfo(data: ActiveAssetDataEvent): TrackedAssetInfo;
24
-
25
- export { HyperliquidStateHandler, buildTrackedAssetInfo };
@@ -1,104 +0,0 @@
1
- import { mapPositions, mapBalance } from './mapper';
2
- import { COLLATERAL_TOKEN_MAP } from './types';
3
-
4
- class HyperliquidStateHandler {
5
- onStateUpdate;
6
- lastSummary = {
7
- accountValue: 0,
8
- totalMarginUsed: 0,
9
- totalRawUsd: 0,
10
- crossMaintenanceMarginUsed: 0,
11
- withdrawable: 0,
12
- totalUnrealizedPnl: 0
13
- };
14
- spotCoinBalances = /* @__PURE__ */ new Map();
15
- accountType = null;
16
- symbolToCollateralToken = /* @__PURE__ */ new Map();
17
- availableToTradeByCollateral = /* @__PURE__ */ new Map();
18
- constructor(onStateUpdate) {
19
- this.onStateUpdate = onStateUpdate;
20
- }
21
- loadPerpMetas(allMetas) {
22
- allMetas.forEach((dexMeta) => {
23
- const collateralToken = COLLATERAL_TOKEN_MAP[dexMeta.collateralToken];
24
- dexMeta.universe.forEach((asset) => {
25
- if (!asset.name) return;
26
- if (collateralToken && !this.symbolToCollateralToken.has(asset.name)) {
27
- this.symbolToCollateralToken.set(asset.name, collateralToken);
28
- }
29
- });
30
- });
31
- }
32
- handleClearinghouseState(data) {
33
- const states = (data.clearinghouseStates || []).map(([, s]) => s).filter(Boolean);
34
- const sumStr = (values) => values.reduce((acc, v) => acc + (Number.parseFloat(v || "0") || 0), 0);
35
- const allAssetPositions = states.flatMap((s) => s.assetPositions || []);
36
- const totalUnrealizedPnl = allAssetPositions.reduce(
37
- (acc, ap) => acc + (Number.parseFloat(ap.position.unrealizedPnl || "0") || 0),
38
- 0
39
- );
40
- this.lastSummary = {
41
- accountValue: sumStr(states.map((s) => s.crossMarginSummary.accountValue)),
42
- totalMarginUsed: sumStr(states.map((s) => s.crossMarginSummary.totalMarginUsed)),
43
- totalRawUsd: sumStr(states.map((s) => s.crossMarginSummary.totalRawUsd)),
44
- crossMaintenanceMarginUsed: sumStr(states.map((s) => s.crossMaintenanceMarginUsed)),
45
- withdrawable: sumStr(states.map((s) => s.withdrawable)),
46
- totalUnrealizedPnl
47
- };
48
- const balance = this.buildBalance();
49
- const positions = mapPositions(allAssetPositions);
50
- const leverageSettings = /* @__PURE__ */ new Map();
51
- for (const ap of allAssetPositions) {
52
- const coin = ap.position.coin;
53
- if (coin && ap.position.leverage?.value) {
54
- leverageSettings.set(coin, ap.position.leverage.value.toString());
55
- }
56
- }
57
- this.onStateUpdate({ balance: balance ?? void 0, positions, leverageSettings });
58
- }
59
- handleActiveAssetData(data) {
60
- if (!data.coin) return;
61
- const collateral = this.symbolToCollateralToken.get(data.coin);
62
- if (collateral && data.availableToTrade) {
63
- const long = Number.parseFloat(data.availableToTrade[0] || "0");
64
- const short = Number.parseFloat(data.availableToTrade[1] || "0");
65
- const minAvailable = Math.min(long, short);
66
- this.availableToTradeByCollateral.set(collateral, minAvailable);
67
- const balance = this.buildBalance();
68
- if (balance) this.onStateUpdate({ balance });
69
- }
70
- const trackedAssets = /* @__PURE__ */ new Map();
71
- trackedAssets.set(data.coin, buildTrackedAssetInfo(data));
72
- this.onStateUpdate({ trackedAssets });
73
- }
74
- handleWebData3(data) {
75
- this.accountType = data.userState.abstraction ?? null;
76
- }
77
- handleSpotState(data) {
78
- const balances = data?.spotState?.balances;
79
- if (!balances) return;
80
- for (const b of balances) {
81
- const total = Number.parseFloat(b.total || "0");
82
- const hold = Number.parseFloat(b.hold || "0");
83
- if (total !== 0 || hold !== 0) {
84
- this.spotCoinBalances.set(b.coin, { coin: b.coin, total, hold });
85
- } else {
86
- this.spotCoinBalances.delete(b.coin);
87
- }
88
- }
89
- const balance = this.buildBalance();
90
- if (balance) this.onStateUpdate({ balance });
91
- }
92
- buildBalance() {
93
- return mapBalance(this.lastSummary, this.spotCoinBalances, this.accountType, this.availableToTradeByCollateral);
94
- }
95
- }
96
- function buildTrackedAssetInfo(data) {
97
- return {
98
- coin: data.coin,
99
- leverage: (data.leverage?.value ?? 1).toString(),
100
- marginType: data.leverage?.type
101
- };
102
- }
103
-
104
- export { HyperliquidStateHandler, buildTrackedAssetInfo };
@@ -1,11 +0,0 @@
1
- import { Connector } from '@pear-protocol/types';
2
- import { g as SupportedCredentials } from '../../types-Caz2X4h0.js';
3
- export { f as BinanceAccountType } from '../../types-Caz2X4h0.js';
4
- import { OrchestratorConfig, Orchestrator } from './base.js';
5
- export { BybitAccountType } from './bybit/types.js';
6
- export { HyperliquidAccountType } from './hyperliquid/types.js';
7
- export { OkxAccountType } from './okx/types.js';
8
-
9
- declare function createOrchestrator(exchange: Connector, config: OrchestratorConfig, credentials: SupportedCredentials): Orchestrator;
10
-
11
- export { Orchestrator, OrchestratorConfig, createOrchestrator };
@@ -1,32 +0,0 @@
1
- import './base';
2
- import { BinanceOrchestrator } from './binance/orchestrator';
3
- import { BybitOrchestrator } from './bybit/orchestrator';
4
- import { HyperliquidOrchestrator } from './hyperliquid/orchestrator';
5
- import { OkxOrchestrator } from './okx/orchestrator';
6
- export { BinanceAccountType } from './binance/types';
7
- export { BybitAccountType } from './bybit/types';
8
- export { HyperliquidAccountType } from './hyperliquid/types';
9
- export { OkxAccountType } from './okx/types';
10
-
11
- function createOrchestrator(exchange, config, credentials) {
12
- let orchestrator;
13
- switch (exchange) {
14
- case "binance":
15
- orchestrator = new BinanceOrchestrator(config, credentials);
16
- break;
17
- case "bybit":
18
- orchestrator = new BybitOrchestrator(config, credentials);
19
- break;
20
- case "hyperliquid":
21
- orchestrator = new HyperliquidOrchestrator(config, credentials);
22
- break;
23
- case "okx":
24
- orchestrator = new OkxOrchestrator(config, credentials);
25
- break;
26
- default:
27
- throw new Error(`Unsupported exchange: ${exchange}`);
28
- }
29
- return orchestrator;
30
- }
31
-
32
- export { createOrchestrator };