@lifi/perps-sdk-provider-hyperliquid 0.0.0-preview-be3da034 → 0.0.0-preview-52d27cc0

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 (91) hide show
  1. package/README.md +58 -19
  2. package/dist/cjs/services/getActivity.d.ts.map +1 -1
  3. package/dist/cjs/services/getActivity.js +33 -17
  4. package/dist/cjs/services/getActivity.js.map +1 -1
  5. package/dist/cjs/services/getLedgerHistory.d.ts +17 -0
  6. package/dist/cjs/services/getLedgerHistory.d.ts.map +1 -0
  7. package/dist/cjs/services/getLedgerHistory.js +19 -0
  8. package/dist/cjs/services/getLedgerHistory.js.map +1 -0
  9. package/dist/cjs/services/getPortfolioHistory.d.ts.map +1 -1
  10. package/dist/cjs/services/getPortfolioHistory.js +15 -1
  11. package/dist/cjs/services/getPortfolioHistory.js.map +1 -1
  12. package/dist/cjs/types/account.d.ts +1 -0
  13. package/dist/cjs/types/account.d.ts.map +1 -1
  14. package/dist/cjs/types/account.js.map +1 -1
  15. package/dist/cjs/types/ledger.d.ts +25 -1
  16. package/dist/cjs/types/ledger.d.ts.map +1 -1
  17. package/dist/cjs/types/ledger.js +16 -1
  18. package/dist/cjs/types/ledger.js.map +1 -1
  19. package/dist/cjs/utils/mapActivity.d.ts.map +1 -1
  20. package/dist/cjs/utils/mapActivity.js +65 -22
  21. package/dist/cjs/utils/mapActivity.js.map +1 -1
  22. package/dist/cjs/utils/mapPortfolioTransfers.d.ts +4 -0
  23. package/dist/cjs/utils/mapPortfolioTransfers.d.ts.map +1 -0
  24. package/dist/cjs/utils/mapPortfolioTransfers.js +157 -0
  25. package/dist/cjs/utils/mapPortfolioTransfers.js.map +1 -0
  26. package/dist/cjs/utils/mapPosition.d.ts.map +1 -1
  27. package/dist/cjs/utils/mapPosition.js +8 -0
  28. package/dist/cjs/utils/mapPosition.js.map +1 -1
  29. package/dist/cjs/websocket/HyperliquidWsProvider.d.ts +3 -3
  30. package/dist/cjs/websocket/HyperliquidWsProvider.d.ts.map +1 -1
  31. package/dist/cjs/websocket/HyperliquidWsProvider.js +10 -14
  32. package/dist/cjs/websocket/HyperliquidWsProvider.js.map +1 -1
  33. package/dist/esm/services/getActivity.d.ts.map +1 -1
  34. package/dist/esm/services/getActivity.js +35 -18
  35. package/dist/esm/services/getActivity.js.map +1 -1
  36. package/dist/esm/services/getLedgerHistory.d.ts +19 -0
  37. package/dist/esm/services/getLedgerHistory.d.ts.map +1 -0
  38. package/dist/esm/services/getLedgerHistory.js +16 -0
  39. package/dist/esm/services/getLedgerHistory.js.map +1 -0
  40. package/dist/esm/services/getPortfolioHistory.d.ts.map +1 -1
  41. package/dist/esm/services/getPortfolioHistory.js +15 -1
  42. package/dist/esm/services/getPortfolioHistory.js.map +1 -1
  43. package/dist/esm/types/account.d.ts +2 -0
  44. package/dist/esm/types/account.d.ts.map +1 -1
  45. package/dist/esm/types/account.js.map +1 -1
  46. package/dist/esm/types/ledger.d.ts +45 -1
  47. package/dist/esm/types/ledger.d.ts.map +1 -1
  48. package/dist/esm/types/ledger.js +27 -0
  49. package/dist/esm/types/ledger.js.map +1 -1
  50. package/dist/esm/utils/mapActivity.d.ts +1 -7
  51. package/dist/esm/utils/mapActivity.d.ts.map +1 -1
  52. package/dist/esm/utils/mapActivity.js +68 -36
  53. package/dist/esm/utils/mapActivity.js.map +1 -1
  54. package/dist/esm/utils/mapPortfolioTransfers.d.ts +5 -0
  55. package/dist/esm/utils/mapPortfolioTransfers.d.ts.map +1 -0
  56. package/dist/esm/utils/mapPortfolioTransfers.js +154 -0
  57. package/dist/esm/utils/mapPortfolioTransfers.js.map +1 -0
  58. package/dist/esm/utils/mapPosition.d.ts +3 -8
  59. package/dist/esm/utils/mapPosition.d.ts.map +1 -1
  60. package/dist/esm/utils/mapPosition.js +12 -9
  61. package/dist/esm/utils/mapPosition.js.map +1 -1
  62. package/dist/esm/websocket/HyperliquidWsProvider.d.ts +7 -7
  63. package/dist/esm/websocket/HyperliquidWsProvider.d.ts.map +1 -1
  64. package/dist/esm/websocket/HyperliquidWsProvider.js +14 -18
  65. package/dist/esm/websocket/HyperliquidWsProvider.js.map +1 -1
  66. package/dist/types/services/getActivity.d.ts.map +1 -1
  67. package/dist/types/services/getLedgerHistory.d.ts +19 -0
  68. package/dist/types/services/getLedgerHistory.d.ts.map +1 -0
  69. package/dist/types/services/getPortfolioHistory.d.ts.map +1 -1
  70. package/dist/types/types/account.d.ts +2 -0
  71. package/dist/types/types/account.d.ts.map +1 -1
  72. package/dist/types/types/ledger.d.ts +45 -1
  73. package/dist/types/types/ledger.d.ts.map +1 -1
  74. package/dist/types/utils/mapActivity.d.ts +1 -7
  75. package/dist/types/utils/mapActivity.d.ts.map +1 -1
  76. package/dist/types/utils/mapPortfolioTransfers.d.ts +5 -0
  77. package/dist/types/utils/mapPortfolioTransfers.d.ts.map +1 -0
  78. package/dist/types/utils/mapPosition.d.ts +3 -8
  79. package/dist/types/utils/mapPosition.d.ts.map +1 -1
  80. package/dist/types/websocket/HyperliquidWsProvider.d.ts +7 -7
  81. package/dist/types/websocket/HyperliquidWsProvider.d.ts.map +1 -1
  82. package/package.json +3 -3
  83. package/src/services/getActivity.ts +46 -37
  84. package/src/services/getLedgerHistory.ts +42 -0
  85. package/src/services/getPortfolioHistory.ts +28 -4
  86. package/src/types/account.ts +2 -0
  87. package/src/types/ledger.ts +77 -0
  88. package/src/utils/mapActivity.ts +90 -36
  89. package/src/utils/mapPortfolioTransfers.ts +203 -0
  90. package/src/utils/mapPosition.ts +17 -8
  91. package/src/websocket/HyperliquidWsProvider.ts +16 -18
@@ -0,0 +1,203 @@
1
+ import {
2
+ isDecimalString,
3
+ safeAddDecimalString,
4
+ safeIsDecimalStringZero,
5
+ safeSubtractDecimalString,
6
+ } from '@lifi/perps-sdk'
7
+ import type { PortfolioHistoryPoint } from '@lifi/perps-types'
8
+ import { isAddress } from 'viem'
9
+ import {
10
+ type HlLedgerDelta,
11
+ type HlLedgerUpdate,
12
+ isBorrowLendDelta,
13
+ isCollateralTransferDelta,
14
+ isCStakingTransferDelta,
15
+ isDepositDelta,
16
+ isSendAssetDelta,
17
+ isSpotTransferDelta,
18
+ isVaultTransferDelta,
19
+ isWithdrawDelta,
20
+ } from '../types/index.js'
21
+
22
+ const NON_CAPITAL_DELTAS: Readonly<Record<string, true>> = {
23
+ funding: true,
24
+ liquidation: true,
25
+ rewardsClaim: true,
26
+ vaultLeaderCommission: true,
27
+ deployGasAuction: true,
28
+ gossipPriorityGasAuction: true,
29
+ accountActivationGas: true,
30
+ spotGenesis: true,
31
+ }
32
+
33
+ const parseUnsignedAmount = (value: unknown): string | undefined =>
34
+ isDecimalString(value) && !value.startsWith('-') ? value : undefined
35
+
36
+ const parseSignedAmount = (
37
+ value: unknown,
38
+ incoming: boolean
39
+ ): string | undefined => {
40
+ const amount = parseUnsignedAmount(value)
41
+ return amount === undefined
42
+ ? undefined
43
+ : incoming
44
+ ? amount
45
+ : safeSubtractDecimalString('0', amount)
46
+ }
47
+
48
+ const parseTokenUsd = (delta: {
49
+ token: string
50
+ amount: string
51
+ usdcValue?: string
52
+ }): string | undefined => {
53
+ const amount = parseUnsignedAmount(delta.amount)
54
+ if (amount === undefined) {
55
+ return undefined
56
+ }
57
+ return delta.token.split(':')[0] === 'USDC'
58
+ ? amount
59
+ : parseUnsignedAmount(delta.usdcValue)
60
+ }
61
+
62
+ const classifyCapitalMovement = (
63
+ delta: HlLedgerDelta,
64
+ queried: string,
65
+ combined: boolean
66
+ ): string | undefined => {
67
+ if (isDepositDelta(delta)) {
68
+ return parseSignedAmount(delta.usdc, true)
69
+ }
70
+ if (isWithdrawDelta(delta)) {
71
+ return parseSignedAmount(delta.usdc, false)
72
+ }
73
+ if (
74
+ isCollateralTransferDelta(delta) ||
75
+ isSpotTransferDelta(delta) ||
76
+ isSendAssetDelta(delta)
77
+ ) {
78
+ if (
79
+ !isAddress(delta.user, { strict: false }) ||
80
+ !isAddress(delta.destination, { strict: false })
81
+ ) {
82
+ return undefined
83
+ }
84
+ const sender = delta.user.toLowerCase()
85
+ const recipient = delta.destination.toLowerCase()
86
+ let sourceIncluded = combined || !isSpotTransferDelta(delta)
87
+ let destinationIncluded = sourceIncluded
88
+ if (isSendAssetDelta(delta)) {
89
+ sourceIncluded = combined || delta.sourceDex !== 'spot'
90
+ destinationIncluded = combined || delta.destinationDex !== 'spot'
91
+ }
92
+ const outgoing = sender === queried && sourceIncluded
93
+ const incoming = recipient === queried && destinationIncluded
94
+ if (incoming === outgoing) {
95
+ return '0'
96
+ }
97
+ return parseSignedAmount(
98
+ isCollateralTransferDelta(delta) ? delta.usdc : parseTokenUsd(delta),
99
+ incoming
100
+ )
101
+ }
102
+ if (isVaultTransferDelta(delta)) {
103
+ if (!isAddress(delta.vault, { strict: false })) {
104
+ return undefined
105
+ }
106
+ const vault = delta.vault.toLowerCase()
107
+ if (delta.type === 'vaultDeposit') {
108
+ return vault === queried
109
+ ? undefined
110
+ : parseSignedAmount(delta.usdc, false)
111
+ }
112
+ if (!isAddress(delta.user, { strict: false })) {
113
+ return undefined
114
+ }
115
+ const user = delta.user.toLowerCase()
116
+ if (vault === queried && user === queried) {
117
+ return '0'
118
+ }
119
+ if (vault === queried) {
120
+ return parseSignedAmount(delta.requestedUsd, false)
121
+ }
122
+ return user === queried
123
+ ? parseSignedAmount(delta.netWithdrawnUsd, true)
124
+ : undefined
125
+ }
126
+ if (delta.type === 'cStakingTransfer' || delta.type === 'borrowLend') {
127
+ if (!combined) {
128
+ return '0'
129
+ }
130
+ if (isCStakingTransferDelta(delta)) {
131
+ return parseSignedAmount(parseTokenUsd(delta), !delta.isDeposit)
132
+ }
133
+ if (!isBorrowLendDelta(delta)) {
134
+ return undefined
135
+ }
136
+ const interest = parseUnsignedAmount(delta.interestAmount)
137
+ if (interest === undefined) {
138
+ return undefined
139
+ }
140
+ const releases =
141
+ delta.operation === 'withdraw' || delta.operation === 'borrow'
142
+ let amount = parseTokenUsd(delta)
143
+ if (
144
+ amount !== undefined &&
145
+ (delta.operation === 'withdraw' || delta.operation === 'repay') &&
146
+ !safeIsDecimalStringZero(interest)
147
+ ) {
148
+ amount = safeSubtractDecimalString(amount, interest)
149
+ }
150
+ return parseSignedAmount(amount, releases)
151
+ }
152
+ if (delta.type === 'accountClassTransfer') {
153
+ if (combined) {
154
+ return '0'
155
+ }
156
+ return typeof delta.toPerp === 'boolean'
157
+ ? parseSignedAmount(delta.usdc, delta.toPerp)
158
+ : undefined
159
+ }
160
+ if (delta.type === 'vaultCreate') {
161
+ return typeof delta.vault === 'string' &&
162
+ isAddress(delta.vault, { strict: false }) &&
163
+ delta.vault.toLowerCase() !== queried
164
+ ? parseSignedAmount(delta.usdc, false)
165
+ : undefined
166
+ }
167
+ return Object.hasOwn(NON_CAPITAL_DELTAS, delta.type) ? '0' : undefined
168
+ }
169
+
170
+ /** Add cumulative USD flows for the selected spot-and-perps or perps-only balances. */
171
+ export const mapPortfolioTransfers = (
172
+ points: PortfolioHistoryPoint[],
173
+ ledger: HlLedgerUpdate[],
174
+ address: string,
175
+ combined: boolean
176
+ ): PortfolioHistoryPoint[] => {
177
+ const first = points[0]
178
+ if (first === undefined) {
179
+ return []
180
+ }
181
+ const ordered = ledger
182
+ .filter((entry) => entry.time > first.timestamp)
183
+ .sort((a, b) => a.time - b.time)
184
+ const queried = address.toLowerCase()
185
+ let index = 0
186
+ let cumulative: string | undefined = '0'
187
+ return points.map((point) => {
188
+ while (index < ordered.length && ordered[index].time <= point.timestamp) {
189
+ const entry = ordered[index++]
190
+ if (cumulative !== undefined) {
191
+ const movement = classifyCapitalMovement(entry.delta, queried, combined)
192
+ cumulative =
193
+ movement === undefined
194
+ ? undefined
195
+ : safeAddDecimalString(cumulative, movement)
196
+ }
197
+ }
198
+ return {
199
+ ...point,
200
+ ...(cumulative === undefined ? {} : { netTransfers: cumulative }),
201
+ }
202
+ })
203
+ }
@@ -5,6 +5,7 @@ import {
5
5
  isDecimalString,
6
6
  isDecimalStringGreaterThan,
7
7
  isDecimalStringZero,
8
+ multiplyDecimalString,
8
9
  safeAbsDecimalString,
9
10
  safeDivideDecimalString,
10
11
  safeIsDecimalStringZero,
@@ -18,6 +19,7 @@ import { PROVIDER_KEY } from '../constants.js'
18
19
  import type { HlAssetPosition } from '../types/index.js'
19
20
 
20
21
  const warnNonPositiveLeverageOnce = createWarnOnce()
22
+ const warnInvalidReturnOnEquityOnce = createWarnOnce()
21
23
 
22
24
  const skipPosition = (
23
25
  marketId: string,
@@ -37,14 +39,9 @@ const skipPosition = (
37
39
  export const isOpenAssetPosition = (ap: HlAssetPosition): boolean =>
38
40
  safeIsDecimalStringZero(ap.position.szi) !== true
39
41
 
40
- /**
41
- * Map a non-zero Hyperliquid position payload to the SDK's normalized
42
- * position. Signed wire size determines side; decimal strings remain strings
43
- * in the normalized response. `cumFunding.sinceOpen` is negated because
44
- * Hyperliquid signs funding paid as positive and `accruedFunding` signs it as
45
- * negative. A row with an invalid size gives `undefined`; an invalid position
46
- * value, a non-positive leverage or an invalid funding leaves the derived field
47
- * absent, and a `null` or empty `liquidationPx` leaves `liquidationPrice` absent.
42
+ /** Map a Hyperliquid position; invalid size omits the row.
43
+ * Funding uses the opposite venue sign. Venue ROE fractions become percents.
44
+ * Invalid venue ROE warns once per market and uses the calculated fallback.
48
45
  * @public
49
46
  */
50
47
  export const mapPosition = (
@@ -83,6 +80,15 @@ export const mapPosition = (
83
80
  positionValue === undefined || leverage === undefined
84
81
  ? undefined
85
82
  : safeDivideDecimalString(positionValue, leverage)
83
+ if (
84
+ pos.returnOnEquity !== undefined &&
85
+ !isDecimalString(pos.returnOnEquity)
86
+ ) {
87
+ warnInvalidReturnOnEquityOnce(
88
+ `${PROVIDER_KEY}|position.returnOnEquity|${market.id}`,
89
+ `[${PROVIDER_KEY}] position \`returnOnEquity\` on market '${market.id}' is not a valid decimal, so the SDK calculates it when the other ROE inputs are valid: '${String(pos.returnOnEquity).slice(0, 64)}'`
90
+ )
91
+ }
86
92
  const marginMode =
87
93
  pos.leverage.type === 'cross' ? MarginMode.CROSS : MarginMode.ISOLATED
88
94
 
@@ -97,6 +103,9 @@ export const mapPosition = (
97
103
  ...(positionValue === undefined ? {} : { positionValue }),
98
104
  ...(pos.liquidationPx ? { liquidationPrice: pos.liquidationPx } : {}),
99
105
  unrealizedPnl: pos.unrealizedPnl,
106
+ ...(isDecimalString(pos.returnOnEquity)
107
+ ? { returnOnEquity: multiplyDecimalString(pos.returnOnEquity, '100') }
108
+ : {}),
100
109
  ...(accruedFunding === undefined ? {} : { accruedFunding }),
101
110
  ...(leverage === undefined ? {} : { leverage }),
102
111
  marginUsed: pos.marginUsed,
@@ -18,6 +18,7 @@ import {
18
18
  type QuoteListener,
19
19
  ReconnectingWebSocket,
20
20
  resolveSubscribeQuote,
21
+ type SubscriptionErrorListener,
21
22
  type SubscriptionListener,
22
23
  safeAddDecimalString,
23
24
  safeDecimalStringToNumber,
@@ -276,9 +277,10 @@ export class HyperliquidWsProvider extends WsProviderBase<object> {
276
277
  override async subscribe(
277
278
  sub: Subscription,
278
279
  listener: SubscriptionListener,
279
- onStatus?: WsStatusListener
280
+ onStatus?: WsStatusListener,
281
+ onError?: SubscriptionErrorListener
280
282
  ): Promise<() => void> {
281
- const unsubscribe = await super.subscribe(sub, listener, onStatus)
283
+ const unsubscribe = await super.subscribe(sub, listener, onStatus, onError)
282
284
  // The summary source is decided by the abstraction mode, so every
283
285
  // summary subscribe (re-)reads it — consumers resubscribe when they
284
286
  // observe an account-config change, and the wire channel is usually
@@ -822,14 +824,14 @@ export class HyperliquidWsProvider extends WsProviderBase<object> {
822
824
  }
823
825
 
824
826
  private handleAllDexsAssetCtxs(data: HlWsAllDexsAssetCtxsData) {
825
- this.emitMarketsContext(
827
+ this.updateMarketsContext(
826
828
  this.mergePerpAssetCtxEntries(allDexsAssetCtxEntries(data))
827
829
  )
828
830
  }
829
831
 
830
832
  private handlePac(base64: string) {
831
833
  this.pacDecodeChain.push(async () => {
832
- this.emitMarketsContext(
834
+ this.updateMarketsContext(
833
835
  this.mergePerpAssetCtxEntries(
834
836
  await decodeCompressedJson<HlWsPacData>(base64)
835
837
  )
@@ -882,7 +884,7 @@ export class HyperliquidWsProvider extends WsProviderBase<object> {
882
884
  }
883
885
  touched.add(marketId)
884
886
  }
885
- this.emitMarketsContext(touched)
887
+ this.updateMarketsContext(touched)
886
888
  })
887
889
  }
888
890
 
@@ -923,30 +925,26 @@ export class HyperliquidWsProvider extends WsProviderBase<object> {
923
925
  }
924
926
  touched.push(marketId)
925
927
  }
926
- this.emitMarketsContext(touched)
928
+ this.updateMarketsContext(touched)
927
929
  })
928
930
  }
929
931
 
930
932
  /**
931
- * Emit the all-markets context map, re-mapping only the markets the incoming
932
- * frame touched. Each emission is a fresh snapshot object that carries
933
- * untouched entries over by reference, so a listener holding an earlier
934
- * snapshot never observes later-frame mutation.
933
+ * Re-map only the markets the incoming frame touched, then hand the map to
934
+ * the base's throttled emit. The delivered event is a fresh snapshot built
935
+ * at delivery time, so a listener holding an earlier snapshot never observes
936
+ * later-frame mutation.
935
937
  */
936
- private emitMarketsContext(touchedMarketIds: Iterable<string>) {
937
- const data: Record<string, MarketContext> = {
938
- ...this.marketsContextByMarketId,
939
- }
938
+ private updateMarketsContext(touchedMarketIds: Iterable<string>) {
940
939
  for (const marketId of touchedMarketIds) {
941
940
  const context = this.computeMarketContext(marketId)
942
941
  if (context === undefined) {
943
- delete data[marketId]
942
+ delete this.marketsContextByMarketId[marketId]
944
943
  } else {
945
- data[marketId] = context
944
+ this.marketsContextByMarketId[marketId] = context
946
945
  }
947
946
  }
948
- this.marketsContextByMarketId = data
949
- this.emit('marketsContext', { channel: 'marketsContext', data })
947
+ this.emitMarketsContext(() => ({ ...this.marketsContextByMarketId }))
950
948
  }
951
949
 
952
950
  /**