@lifi/perps-sdk-provider-hyperliquid 35.0.0 → 36.0.0

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 +2 -2
  30. package/dist/cjs/websocket/HyperliquidWsProvider.d.ts.map +1 -1
  31. package/dist/cjs/websocket/HyperliquidWsProvider.js +2 -2
  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 +2 -2
  63. package/dist/esm/websocket/HyperliquidWsProvider.d.ts.map +1 -1
  64. package/dist/esm/websocket/HyperliquidWsProvider.js +2 -2
  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 +2 -2
  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 +4 -2
@@ -15,17 +15,17 @@ import { ActivityType, PerpsErrorCode } from '@lifi/perps-types'
15
15
  import type { Address } from 'viem'
16
16
  import { PROVIDER_KEY } from '../constants.js'
17
17
  import type { HyperliquidContext } from '../context.js'
18
- import type {
19
- HlUserFills,
20
- HlUserFunding,
21
- HlUserNonFundingLedgerUpdates,
22
- } from '../types/index.js'
18
+ import type { HlUserFills, HlUserFunding } from '../types/index.js'
23
19
  import {
20
+ isAccountActivationGasDelta,
21
+ isAccountClassTransferDelta,
24
22
  isBorrowLendDelta,
25
23
  isCollateralTransferDelta,
26
24
  isCStakingTransferDelta,
27
25
  isDepositDelta,
26
+ isGossipPriorityGasAuctionDelta,
28
27
  isLiquidationDelta,
28
+ isRewardsClaimDelta,
29
29
  isSendAssetDelta,
30
30
  isSpotTransferDelta,
31
31
  isVaultTransferDelta,
@@ -43,6 +43,7 @@ import {
43
43
  } from '../utils/infoClient.js'
44
44
  import { isFillLiquidatingAccount } from '../utils/isFillLiquidatingAccount.js'
45
45
  import { requireAccountExists } from './getAccountExists.js'
46
+ import { getLedgerHistory, getLedgerWindow } from './getLedgerHistory.js'
46
47
  import { getHistoryLimit, historyPage } from './historyPagination.js'
47
48
 
48
49
  /**
@@ -73,6 +74,9 @@ const ASSET_BEARING_TYPES: ReadonlySet<ActivityType> = new Set([
73
74
  ActivityType.DEPOSIT,
74
75
  ActivityType.WITHDRAWAL,
75
76
  ActivityType.TRANSFER,
77
+ ActivityType.FEE,
78
+ ActivityType.REWARD,
79
+ ActivityType.INTERNAL_TRANSFER,
76
80
  ])
77
81
 
78
82
  const needsMarkets = (typeFilter: ActivityType[] | undefined): boolean =>
@@ -129,31 +133,23 @@ const fetchLiquidationHistory = async (
129
133
  lastTime = Math.max(lastTime, fill.time)
130
134
  }
131
135
  // Exclusions must cover the entire order, not the current SDK page's ledger window.
132
- const ledger = await historyPage(
133
- { startTime: firstTime, endTime: lastTime },
134
- Number.MAX_SAFE_INTEGER,
135
- async (startTime, endTime) => {
136
- const updates = await infoRequest<HlUserNonFundingLedgerUpdates>(
137
- apiUrl,
138
- { type: 'userNonFundingLedgerUpdates', user, startTime, endTime },
139
- options
140
- )
141
- return {
142
- items: updates.filter(
143
- (entry) => isLiquidationDelta(entry.delta) && hashes.has(entry.hash)
144
- ),
145
- saturated: updates.length >= 500,
146
- }
147
- },
148
- (entry) => ({ time: entry.time, key: entry.hash }),
149
- options?.signal
136
+ const ledger = await getLedgerHistory(
137
+ apiUrl,
138
+ { user, startTime: firstTime, endTime: lastTime },
139
+ options
150
140
  )
151
141
  return mapLiquidationFills(
152
142
  fills,
153
143
  PROVIDER_KEY,
154
144
  user,
155
145
  resolveMarket,
156
- new Set(ledger.items.map((entry) => entry.hash))
146
+ new Set(
147
+ ledger
148
+ .filter(
149
+ (entry) => isLiquidationDelta(entry.delta) && hashes.has(entry.hash)
150
+ )
151
+ .map((entry) => entry.hash)
152
+ )
157
153
  )
158
154
  }
159
155
 
@@ -170,14 +166,10 @@ const fetchActivityData = async (
170
166
  !typeFilter || typeFilter.some((t) => t !== ActivityType.FUNDING)
171
167
  const needFunding = !typeFilter || typeFilter.includes(ActivityType.FUNDING)
172
168
 
173
- const [ledgerUpdates, fundingUpdates, liquidations] = await Promise.all([
169
+ const [ledgerWindow, fundingUpdates, liquidations] = await Promise.all([
174
170
  needLedger
175
- ? infoRequest<HlUserNonFundingLedgerUpdates>(
176
- apiUrl,
177
- { type: 'userNonFundingLedgerUpdates', ...timeParams },
178
- options
179
- )
180
- : Promise.resolve([] as HlUserNonFundingLedgerUpdates),
171
+ ? getLedgerWindow(apiUrl, timeParams, options)
172
+ : Promise.resolve({ items: [], saturated: false }),
181
173
  needFunding
182
174
  ? infoRequest<HlUserFunding>(
183
175
  apiUrl,
@@ -187,11 +179,12 @@ const fetchActivityData = async (
187
179
  : Promise.resolve([] as HlUserFunding),
188
180
  liquidationHistory,
189
181
  ])
190
- if (ledgerUpdates.length >= 500 || fundingUpdates.length >= 500) {
182
+ if (ledgerWindow.saturated || fundingUpdates.length >= 500) {
191
183
  return { items: [], saturated: true }
192
184
  }
193
185
 
194
- const ledgerItems: ActivityItem[] = ledgerUpdates.flatMap(
186
+ const ledgerKeyCounts = new Map<string, number>()
187
+ const ledgerItems: ActivityItem[] = ledgerWindow.items.flatMap(
195
188
  (entry): ActivityItem[] => {
196
189
  if (
197
190
  typeFilter !== undefined &&
@@ -199,13 +192,20 @@ const fetchActivityData = async (
199
192
  !typeFilter.includes(ActivityType.DEPOSIT)) ||
200
193
  (isWithdrawDelta(entry.delta) &&
201
194
  !typeFilter.includes(ActivityType.WITHDRAWAL)) ||
195
+ (!typeFilter.includes(ActivityType.FEE) &&
196
+ (isGossipPriorityGasAuctionDelta(entry.delta) ||
197
+ isAccountActivationGasDelta(entry.delta))) ||
198
+ (isRewardsClaimDelta(entry.delta) &&
199
+ !typeFilter.includes(ActivityType.REWARD)) ||
202
200
  (!typeFilter.includes(ActivityType.TRANSFER) &&
203
201
  (isSpotTransferDelta(entry.delta) ||
204
202
  isSendAssetDelta(entry.delta) ||
205
203
  isCollateralTransferDelta(entry.delta) ||
206
- isVaultTransferDelta(entry.delta) ||
207
- isCStakingTransferDelta(entry.delta) ||
208
- isBorrowLendDelta(entry.delta))))
204
+ isVaultTransferDelta(entry.delta))) ||
205
+ (!typeFilter.includes(ActivityType.INTERNAL_TRANSFER) &&
206
+ (isCStakingTransferDelta(entry.delta) ||
207
+ isBorrowLendDelta(entry.delta) ||
208
+ isAccountClassTransferDelta(entry.delta))))
209
209
  ) {
210
210
  return []
211
211
  }
@@ -216,7 +216,16 @@ const fetchActivityData = async (
216
216
  assetRegistry,
217
217
  resolveMarket
218
218
  )
219
- return item === null ? [] : [item]
219
+ if (item === null) {
220
+ return []
221
+ }
222
+ // Identical zero-hash rows synthesize one id; a suffix keeps page keys unique.
223
+ const key = `${item.type}:${item.id}`
224
+ const occurrence = ledgerKeyCounts.get(key) ?? 0
225
+ ledgerKeyCounts.set(key, occurrence + 1)
226
+ return [
227
+ occurrence === 0 ? item : { ...item, id: `${item.id}:${occurrence}` },
228
+ ]
220
229
  }
221
230
  )
222
231
 
@@ -0,0 +1,42 @@
1
+ import type { Address } from 'viem'
2
+ import type { HlUserNonFundingLedgerUpdates } from '../types/index.js'
3
+ import { type InfoRequestOptions, infoRequest } from '../utils/infoClient.js'
4
+ import { historyPage } from './historyPagination.js'
5
+
6
+ /** Read one raw ledger window and report venue truncation before any filtering. */
7
+ export const getLedgerWindow = async (
8
+ apiUrl: string,
9
+ params: { user: Address; startTime: number; endTime: number },
10
+ options?: InfoRequestOptions
11
+ ): Promise<{ items: HlUserNonFundingLedgerUpdates; saturated: boolean }> => {
12
+ const items = await infoRequest<HlUserNonFundingLedgerUpdates>(
13
+ apiUrl,
14
+ { type: 'userNonFundingLedgerUpdates', ...params },
15
+ options
16
+ )
17
+ return { items, saturated: items.length >= 500 }
18
+ }
19
+
20
+ /** Read the complete inclusive ledger interval through the shared capped-window paginator. */
21
+ export const getLedgerHistory = async (
22
+ apiUrl: string,
23
+ params: { user: Address; startTime: number; endTime: number },
24
+ options?: InfoRequestOptions
25
+ ): Promise<HlUserNonFundingLedgerUpdates> => {
26
+ const page = await historyPage(
27
+ params,
28
+ Number.MAX_SAFE_INTEGER,
29
+ (startTime, endTime) =>
30
+ getLedgerWindow(
31
+ apiUrl,
32
+ { user: params.user, startTime, endTime },
33
+ options
34
+ ),
35
+ (entry) => ({
36
+ time: entry.time,
37
+ key: `${entry.hash}:${JSON.stringify(entry.delta)}`,
38
+ }),
39
+ options?.signal
40
+ )
41
+ return page.items
42
+ }
@@ -21,7 +21,9 @@ import type {
21
21
  } from '../types/index.js'
22
22
  import { isUnifiedAbstraction } from '../utils/abstractionMode.js'
23
23
  import { hlInfoOptions, infoRequest } from '../utils/infoClient.js'
24
+ import { mapPortfolioTransfers } from '../utils/mapPortfolioTransfers.js'
24
25
  import { requireAccountExists } from './getAccountExists.js'
26
+ import { getLedgerHistory } from './getLedgerHistory.js'
25
27
 
26
28
  /** Parameters for {@link getPortfolioHistory}. @public */
27
29
  export interface GetPortfolioHistoryParams {
@@ -134,12 +136,34 @@ export async function getPortfolioHistory(
134
136
  }
135
137
 
136
138
  const pnlHistory = validSamples(window.pnlHistory, 'portfolio PnL sample')
139
+ const points = joinWindow(
140
+ validSamples(window.accountValueHistory, 'portfolio value sample'),
141
+ pnlHistory,
142
+ period
143
+ )
144
+ const first = points[0]
145
+ const last = points.at(-1)
146
+ const ledger =
147
+ first !== undefined &&
148
+ last !== undefined &&
149
+ last.timestamp > first.timestamp
150
+ ? await getLedgerHistory(
151
+ apiUrl,
152
+ {
153
+ user: params.address,
154
+ startTime: first.timestamp,
155
+ endTime: last.timestamp,
156
+ },
157
+ infoOpts
158
+ )
159
+ : []
137
160
  return {
138
161
  range: params.range,
139
- points: joinWindow(
140
- validSamples(window.accountValueHistory, 'portfolio value sample'),
141
- pnlHistory,
142
- period
162
+ points: mapPortfolioTransfers(
163
+ points,
164
+ ledger,
165
+ params.address,
166
+ isUnifiedAbstraction(abstraction)
143
167
  ),
144
168
  volume: window.vlm,
145
169
  totalPnl: pnlHistory.at(-1)?.[1],
@@ -25,6 +25,8 @@ export type HlPosition = {
25
25
  liquidationPx: string | null
26
26
  /** Unrealized PnL in quote-asset units. */
27
27
  unrealizedPnl: string
28
+ /** Return on the entry notional ÷ the current leverage, as a fraction (`'0.1'` is 10%). */
29
+ returnOnEquity?: string
28
30
  /** Margin currently assigned to this position. */
29
31
  marginUsed: string
30
32
  /** Leverage mode and numeric leverage multiplier. */
@@ -162,6 +162,43 @@ export type HlBorrowLendDelta = {
162
162
  interestAmount: string
163
163
  }
164
164
 
165
+ /** A priority gas charge in the specified token's units. @public */
166
+ export type HlGossipPriorityGasAuctionDelta = {
167
+ type: 'gossipPriorityGasAuction'
168
+ token: string
169
+ amount: string
170
+ }
171
+
172
+ /** An account activation charge in the specified token's units. @public */
173
+ export type HlAccountActivationGasDelta = {
174
+ type: 'accountActivationGas'
175
+ token: string
176
+ amount: string
177
+ }
178
+
179
+ /** Claimed reward income in the specified token's units. @public */
180
+ export type HlRewardsClaimDelta = {
181
+ type: 'rewardsClaim'
182
+ token: string
183
+ amount: string
184
+ }
185
+
186
+ /** USDC movement between one account's spot and perps balances. @public */
187
+ export type HlAccountClassTransferDelta = {
188
+ type: 'accountClassTransfer'
189
+ usdc: string
190
+ toPerp: boolean
191
+ }
192
+
193
+ /** Narrow account-class transfers only when the venue gives a direction and an amount. @public */
194
+ export const isAccountClassTransferDelta = (
195
+ delta: HlLedgerDelta
196
+ ): delta is HlAccountClassTransferDelta =>
197
+ delta.type === 'accountClassTransfer' &&
198
+ 'toPerp' in delta &&
199
+ typeof delta.toPerp === 'boolean' &&
200
+ hasUsdcAmount(delta)
201
+
165
202
  /**
166
203
  * Union of known Hyperliquid non-funding ledger deltas plus an open fallback
167
204
  * for endpoint variants the provider does not map.
@@ -177,6 +214,10 @@ export type HlLedgerDelta =
177
214
  | HlLiquidationDelta
178
215
  | HlCStakingTransferDelta
179
216
  | HlBorrowLendDelta
217
+ | HlGossipPriorityGasAuctionDelta
218
+ | HlAccountActivationGasDelta
219
+ | HlRewardsClaimDelta
220
+ | HlAccountClassTransferDelta
180
221
  | {
181
222
  type: string
182
223
  usdc?: string
@@ -263,6 +304,42 @@ export const isBorrowLendDelta = (
263
304
  'operation' in delta &&
264
305
  HL_BORROW_LEND_OPERATIONS.has(delta.operation)
265
306
 
307
+ const hasTokenAmount = (delta: HlLedgerDelta): boolean =>
308
+ 'token' in delta &&
309
+ typeof delta.token === 'string' &&
310
+ 'amount' in delta &&
311
+ typeof delta.amount === 'string'
312
+
313
+ /**
314
+ * Type guard for `HlGossipPriorityGasAuctionDelta`. The token and amount are
315
+ * part of the guard: a row without them names no charge.
316
+ * @public
317
+ */
318
+ export const isGossipPriorityGasAuctionDelta = (
319
+ delta: HlLedgerDelta
320
+ ): delta is HlGossipPriorityGasAuctionDelta =>
321
+ delta.type === 'gossipPriorityGasAuction' && hasTokenAmount(delta)
322
+
323
+ /**
324
+ * Type guard for `HlAccountActivationGasDelta`. Same token-and-amount
325
+ * requirement as `isGossipPriorityGasAuctionDelta`.
326
+ * @public
327
+ */
328
+ export const isAccountActivationGasDelta = (
329
+ delta: HlLedgerDelta
330
+ ): delta is HlAccountActivationGasDelta =>
331
+ delta.type === 'accountActivationGas' && hasTokenAmount(delta)
332
+
333
+ /**
334
+ * Type guard for `HlRewardsClaimDelta`. Same token-and-amount requirement as
335
+ * `isGossipPriorityGasAuctionDelta`.
336
+ * @public
337
+ */
338
+ export const isRewardsClaimDelta = (
339
+ delta: HlLedgerDelta
340
+ ): delta is HlRewardsClaimDelta =>
341
+ delta.type === 'rewardsClaim' && hasTokenAmount(delta)
342
+
266
343
  /**
267
344
  * One timestamped non-funding ledger update. `time` is milliseconds since
268
345
  * epoch and `hash` is the upstream transaction identifier.
@@ -13,9 +13,13 @@ import type {
13
13
  Asset,
14
14
  DepositActivity,
15
15
  Fee,
16
+ FeeActivity,
16
17
  FundingActivity,
18
+ InternalTransferActivity,
19
+ InternalTransferBalance,
17
20
  LiquidationActivity,
18
21
  MarketDisplay,
22
+ RewardActivity,
19
23
  TransferActivity,
20
24
  WithdrawalActivity,
21
25
  } from '@lifi/perps-types'
@@ -28,11 +32,15 @@ import type {
28
32
  HlUserFill,
29
33
  } from '../types/index.js'
30
34
  import {
35
+ isAccountActivationGasDelta,
36
+ isAccountClassTransferDelta,
31
37
  isBorrowLendDelta,
32
38
  isCollateralTransferDelta,
33
39
  isCStakingTransferDelta,
34
40
  isDepositDelta,
41
+ isGossipPriorityGasAuctionDelta,
35
42
  isLiquidationDelta,
43
+ isRewardsClaimDelta,
36
44
  isSendAssetDelta,
37
45
  isSpotTransferDelta,
38
46
  isVaultTransferDelta,
@@ -56,15 +64,17 @@ const HL_NATIVE_TOKEN_SYMBOL = 'HYPE'
56
64
  // Hyperliquid reserves spot token index 0 for USDC.
57
65
  const HL_COLLATERAL_ASSET_ID = '0'
58
66
 
59
- /**
60
- * Direction relative to the account's spot balance, the same frame as an
61
- * outbound `vaultDeposit`.
62
- */
63
- const BORROW_LEND_DIRECTION: Record<HlBorrowLendOperation, 'IN' | 'OUT'> = {
64
- supply: 'OUT',
65
- withdraw: 'IN',
66
- borrow: 'IN',
67
- repay: 'OUT',
67
+ const BORROW_LEND_BALANCES: Record<
68
+ HlBorrowLendOperation,
69
+ {
70
+ sourceBalance: InternalTransferBalance
71
+ destinationBalance: InternalTransferBalance
72
+ }
73
+ > = {
74
+ supply: { sourceBalance: 'spot', destinationBalance: 'borrowLend' },
75
+ withdraw: { sourceBalance: 'borrowLend', destinationBalance: 'spot' },
76
+ borrow: { sourceBalance: 'borrowLend', destinationBalance: 'spot' },
77
+ repay: { sourceBalance: 'spot', destinationBalance: 'borrowLend' },
68
78
  }
69
79
 
70
80
  /**
@@ -91,13 +101,7 @@ const resolveLedgerAsset = (
91
101
  return asset
92
102
  }
93
103
 
94
- /**
95
- * Map supported ledger entries; exclude same-account moves and unsupported types.
96
- * Staking and borrow-lend moves map with the queried account as counterparty.
97
- * Missing collateral throws; an unregistered spot token skips the row, and
98
- * unresolved liquidation markets omit only those positions.
99
- * @public
100
- */
104
+ /** Map supported ledger entries, preserving venue amounts and operation metadata. */
101
105
  export const mapLedgerEntry = (
102
106
  entry: HlLedgerUpdate,
103
107
  providerKey: string,
@@ -176,39 +180,59 @@ export const mapLedgerEntry = (
176
180
  } satisfies TransferActivity
177
181
  }
178
182
 
179
- if (isCStakingTransferDelta(delta) || isBorrowLendDelta(delta)) {
180
- const asset = resolveLedgerAsset(delta.token, assetRegistry, providerKey)
183
+ if (
184
+ isCStakingTransferDelta(delta) ||
185
+ isBorrowLendDelta(delta) ||
186
+ isAccountClassTransferDelta(delta)
187
+ ) {
188
+ const accountClass = isAccountClassTransferDelta(delta)
189
+ const staking = isCStakingTransferDelta(delta)
190
+ const asset = accountClass
191
+ ? assetRegistry.require(HL_COLLATERAL_ASSET_ID)
192
+ : resolveLedgerAsset(delta.token, assetRegistry, providerKey)
181
193
  if (asset === null) {
182
194
  return null
183
195
  }
184
- // A completed unstake is a system event with the zero hash and no venue
185
- // transaction, so the id is synthesized and no explorer link applies.
196
+ const balances = accountClass
197
+ ? ({
198
+ sourceBalance: delta.toPerp ? 'spot' : 'perps',
199
+ destinationBalance: delta.toPerp ? 'perps' : 'spot',
200
+ } as const)
201
+ : staking
202
+ ? ({
203
+ sourceBalance: delta.isDeposit ? 'spot' : 'staking',
204
+ destinationBalance: delta.isDeposit ? 'staking' : 'spot',
205
+ } as const)
206
+ : BORROW_LEND_BALANCES[delta.operation]
207
+ const amount = accountClass ? delta.usdc : delta.amount
208
+ const token = accountClass ? HL_COLLATERAL_SYMBOL : delta.token
209
+ // Preserve the staking zero-hash identity's IN/OUT segment.
210
+ const action = accountClass
211
+ ? `${balances.sourceBalance}:${balances.destinationBalance}`
212
+ : staking
213
+ ? delta.isDeposit
214
+ ? 'OUT'
215
+ : 'IN'
216
+ : delta.operation
186
217
  const hasTransaction = entry.hash !== zeroHash
187
- const direction = isCStakingTransferDelta(delta)
188
- ? delta.isDeposit
189
- ? 'OUT'
190
- : 'IN'
191
- : BORROW_LEND_DIRECTION[delta.operation]
192
- const action = isCStakingTransferDelta(delta) ? direction : delta.operation
193
218
  return {
194
219
  ...base,
195
220
  ...(hasTransaction
196
221
  ? {}
197
222
  : {
198
- id: `${delta.type}:${delta.token}:${action}:${delta.amount}:${base.timestamp}`,
223
+ id: `${delta.type}:${token}:${action}:${amount}:${base.timestamp}`,
199
224
  }),
200
- type: ActivityType.TRANSFER,
201
- direction,
202
- counterpartyAddress: queriedAddress.toLowerCase(),
225
+ type: ActivityType.INTERNAL_TRANSFER,
226
+ ...balances,
203
227
  asset,
204
- amount: delta.amount,
205
- meta: isCStakingTransferDelta(delta)
206
- ? { transferType: delta.type }
207
- : {
228
+ amount,
229
+ meta: isBorrowLendDelta(delta)
230
+ ? {
208
231
  transferType: delta.type,
209
232
  operation: delta.operation,
210
233
  interestAmount: delta.interestAmount,
211
- },
234
+ }
235
+ : { transferType: delta.type },
212
236
  ...(hasTransaction
213
237
  ? {
214
238
  explorerLink: explorerTxUrl(
@@ -217,7 +241,37 @@ export const mapLedgerEntry = (
217
241
  ),
218
242
  }
219
243
  : {}),
220
- } satisfies TransferActivity
244
+ } satisfies InternalTransferActivity
245
+ }
246
+
247
+ if (
248
+ isGossipPriorityGasAuctionDelta(delta) ||
249
+ isAccountActivationGasDelta(delta) ||
250
+ isRewardsClaimDelta(delta)
251
+ ) {
252
+ const asset = resolveLedgerAsset(delta.token, assetRegistry, providerKey)
253
+ if (asset === null) {
254
+ return null
255
+ }
256
+ const hasTransaction = entry.hash !== zeroHash
257
+ return {
258
+ ...base,
259
+ id: hasTransaction
260
+ ? entry.hash
261
+ : `${delta.type}:${delta.token}:${delta.amount}:${timestamp}`,
262
+ type: isRewardsClaimDelta(delta) ? ActivityType.REWARD : ActivityType.FEE,
263
+ asset,
264
+ amount: delta.amount,
265
+ meta: { ledgerType: delta.type },
266
+ ...(hasTransaction
267
+ ? {
268
+ explorerLink: explorerTxUrl(
269
+ ExplorerChainId.HYPERLIQUID,
270
+ entry.hash
271
+ ),
272
+ }
273
+ : {}),
274
+ } satisfies FeeActivity | RewardActivity
221
275
  }
222
276
 
223
277
  if (isVaultTransferDelta(delta)) {