@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488
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.
- package/CHANGELOG.md +105 -9
- package/dist/PerpsController-method-action-types.d.ts +149 -3
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +125 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +787 -31
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +69 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +82 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +15 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +14 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +10 -2
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +11 -3
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +10 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/internal/accountReturnOnEquity.d.ts +12 -0
- package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
- package/dist/internal/accountReturnOnEquity.js +18 -0
- package/dist/internal/accountReturnOnEquity.js.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
- package/dist/internal/marketNumericValues.d.ts +10 -0
- package/dist/internal/marketNumericValues.d.ts.map +1 -0
- package/dist/internal/marketNumericValues.js +9 -0
- package/dist/internal/marketNumericValues.js.map +1 -0
- package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
- package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
- package/dist/internal/perpsDisplaySymbol.js +21 -0
- package/dist/internal/perpsDisplaySymbol.js.map +1 -0
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +140 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +72 -4
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +751 -159
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +2 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +11 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/selectors.d.ts +15 -5
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +23 -5
- package/dist/selectors.js.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.js +8 -10
- package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +8 -0
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +65 -0
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +117 -30
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +20 -3
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +55 -3
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +139 -0
- package/dist/services/StreamChannelManager.d.ts.map +1 -0
- package/dist/services/StreamChannelManager.js +475 -0
- package/dist/services/StreamChannelManager.js.map +1 -0
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +7 -0
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/agentSigner.d.ts +8 -0
- package/dist/services/agentSigner.d.ts.map +1 -1
- package/dist/services/agentSigner.js +13 -0
- package/dist/services/agentSigner.js.map +1 -1
- package/dist/types/hyperliquid-types.d.ts +9 -1
- package/dist/types/hyperliquid-types.d.ts.map +1 -1
- package/dist/types/hyperliquid-types.js +10 -0
- package/dist/types/hyperliquid-types.js.map +1 -1
- package/dist/types/index.d.ts +434 -17
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +17 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -1
- package/dist/utils/accountAggregation.js +21 -5
- package/dist/utils/accountAggregation.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +31 -10
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +68 -28
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +17 -4
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +23 -7
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +17 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +264 -29
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +4 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +46 -9
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +13 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +1 -2
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +7 -17
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +35 -5
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +62 -6
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
- package/dist/utils/perpsDiskPersistence.js +10 -0
- package/dist/utils/perpsDiskPersistence.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +31 -0
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +26 -0
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/dist/utils/priceDeviation.d.ts +9 -6
- package/dist/utils/priceDeviation.d.ts.map +1 -1
- package/dist/utils/priceDeviation.js +17 -26
- package/dist/utils/priceDeviation.js.map +1 -1
- package/dist/utils/sortMarkets.d.ts +13 -5
- package/dist/utils/sortMarkets.d.ts.map +1 -1
- package/dist/utils/sortMarkets.js +60 -38
- package/dist/utils/sortMarkets.js.map +1 -1
- package/docs/architecture.md +54 -24
- package/docs/client-contract.md +52 -27
- package/docs/contracts/events.md +38 -32
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/formatting.md +2 -0
- package/docs/venues/lighter/capabilities.md +18 -15
- package/package.json +1 -1
|
@@ -104,6 +104,14 @@ export type CloseSizeParams = {
|
|
|
104
104
|
price: number | string;
|
|
105
105
|
/** Decimals the venue accepts for a size (`PerpsOrderLimits.sizeDecimals`). */
|
|
106
106
|
sizeDecimals: number;
|
|
107
|
+
/**
|
|
108
|
+
* How a partial size meets the size grid. `up` (default) rounds half up
|
|
109
|
+
* and adds one step when that leaves the size below the request, so the
|
|
110
|
+
* close covers the requested value. `down` rounds down, so several partial
|
|
111
|
+
* closes of one position, such as split take-profit levels, never add up to
|
|
112
|
+
* more than the position.
|
|
113
|
+
*/
|
|
114
|
+
rounding?: CloseSizeRounding;
|
|
107
115
|
} & ({
|
|
108
116
|
/** Percent of the position to close, 0 to 100. */
|
|
109
117
|
percent: number;
|
|
@@ -113,6 +121,8 @@ export type CloseSizeParams = {
|
|
|
113
121
|
usdAmount: number | string;
|
|
114
122
|
percent?: never;
|
|
115
123
|
});
|
|
124
|
+
/** How {@link calculateCloseSize} puts a partial size on the size grid. */
|
|
125
|
+
export type CloseSizeRounding = 'up' | 'down';
|
|
116
126
|
/** Result of {@link calculateCloseSize}. */
|
|
117
127
|
export type CloseSize = {
|
|
118
128
|
/**
|
|
@@ -125,13 +135,16 @@ export type CloseSize = {
|
|
|
125
135
|
};
|
|
126
136
|
/**
|
|
127
137
|
* Size to close for a percent or USD amount of a position, in exact decimal
|
|
128
|
-
* arithmetic.
|
|
129
|
-
*
|
|
130
|
-
* requested
|
|
138
|
+
* arithmetic. A request for the whole position returns the exact position
|
|
139
|
+
* size. Otherwise, by default, the size rounds half up to `sizeDecimals`;
|
|
140
|
+
* when that leaves it below the requested size, one size step is added so the
|
|
141
|
+
* close covers the requested value. With `rounding: 'down'` it rounds down to
|
|
142
|
+
* `sizeDecimals` instead. The result never exceeds the position.
|
|
131
143
|
*
|
|
132
144
|
* @param params - See {@link CloseSizeParams}.
|
|
133
145
|
* @returns The close size and value, or undefined when an input is missing,
|
|
134
|
-
* out of range or not a number,
|
|
146
|
+
* out of range or not a number, the position is empty, or `rounding: 'down'`
|
|
147
|
+
* leaves a requested size below one size step.
|
|
135
148
|
*/
|
|
136
149
|
export declare function calculateCloseSize(params: CloseSizeParams): CloseSize | undefined;
|
|
137
150
|
//# sourceMappingURL=closeCalculations.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"closeCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAerE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC,mEAAmE;IACnE,QAAQ,EAAE,IAAI,CACZ,QAAQ,EACR,MAAM,GAAG,YAAY,GAAG,YAAY,GAAG,eAAe,CACvD,GAAG;QACF,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,CAAC;KAC9C,CAAC;IACF;;;;;OAKG;IACH,UAAU,EAAE,iBAAiB,CAAC;IAC9B;;;OAGG;IACH,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B;;;OAGG;IACH,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACnC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,oFAAoF;IACpF,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,0DAA0D;IAC1D,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,2DAA2D;IAC3D,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACxB;;;;;OAKG;IACH,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,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uEAAuE;IACvE,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B,OAAO,CAAC,EAAE,KAAK,CAAC;CACjB,CACJ,CAAC;AAEF,2EAA2E;AAC3E,MAAM,MAAM,iBAAiB,GAAG,IAAI,GAAG,MAAM,CAAC;AAE9C,4CAA4C;AAC5C,MAAM,MAAM,SAAS,GAAG;IACtB;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,6EAA6E;IAC7E,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,GACtB,SAAS,GAAG,SAAS,CAgDvB"}
|
|
@@ -129,13 +129,16 @@ export function calculateNetClosedPnl({ pnl, fee, }) {
|
|
|
129
129
|
}
|
|
130
130
|
/**
|
|
131
131
|
* Size to close for a percent or USD amount of a position, in exact decimal
|
|
132
|
-
* arithmetic.
|
|
133
|
-
*
|
|
134
|
-
* requested
|
|
132
|
+
* arithmetic. A request for the whole position returns the exact position
|
|
133
|
+
* size. Otherwise, by default, the size rounds half up to `sizeDecimals`;
|
|
134
|
+
* when that leaves it below the requested size, one size step is added so the
|
|
135
|
+
* close covers the requested value. With `rounding: 'down'` it rounds down to
|
|
136
|
+
* `sizeDecimals` instead. The result never exceeds the position.
|
|
135
137
|
*
|
|
136
138
|
* @param params - See {@link CloseSizeParams}.
|
|
137
139
|
* @returns The close size and value, or undefined when an input is missing,
|
|
138
|
-
* out of range or not a number,
|
|
140
|
+
* out of range or not a number, the position is empty, or `rounding: 'down'`
|
|
141
|
+
* leaves a requested size below one size step.
|
|
139
142
|
*/
|
|
140
143
|
export function calculateCloseSize(params) {
|
|
141
144
|
const { sizeDecimals } = params;
|
|
@@ -162,9 +165,22 @@ export function calculateCloseSize(params) {
|
|
|
162
165
|
}
|
|
163
166
|
requestedSize = BigNumber.min(usdAmount.dividedBy(price), positionSize);
|
|
164
167
|
}
|
|
165
|
-
let size
|
|
166
|
-
if (
|
|
167
|
-
size =
|
|
168
|
+
let size;
|
|
169
|
+
if (requestedSize.gte(positionSize)) {
|
|
170
|
+
size = positionSize;
|
|
171
|
+
}
|
|
172
|
+
else if (params.rounding === 'down') {
|
|
173
|
+
size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_DOWN);
|
|
174
|
+
if (size.isZero() && requestedSize.isGreaterThan(0)) {
|
|
175
|
+
// Below one size step: no order can close it.
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_HALF_UP);
|
|
181
|
+
if (size.lt(requestedSize)) {
|
|
182
|
+
size = size.plus(new BigNumber(1).shiftedBy(-sizeDecimals));
|
|
183
|
+
}
|
|
168
184
|
}
|
|
169
185
|
return {
|
|
170
186
|
size: BigNumber.min(size, positionSize).toNumber(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"closeCalculations.js","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;GAOG;AACH,MAAM,kCAAkC,GAAuC;IAC7E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAAK;CACf,CAAC;AAqEF,SAAS,SAAS,CAAC,KAAkC;IACnD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IACrC,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CACxB,KAAkC;IAElC,MAAM,OAAO,GA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cash a\n * close returns (\"You'll receive\") and a fill's closed PnL net of its fee.\n */\nimport { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { PerpsProviderType, Position } from '../types/index.js';\n\n/**\n * Whether a provider's isolated `Position.marginUsed` is the collateral\n * backing the position. Hyperliquid's is, with the unrealized PnL at mark\n * included. Lighter's is the initial margin the position requires at its\n * current value; its allocated collateral is not on `Position`, so the margin\n * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as\n * reported and never holds the unrealized PnL.\n */\nconst ISOLATED_MARGIN_USED_IS_COLLATERAL: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Inputs to {@link estimateCloseReceive}.\n */\nexport type CloseReceiveEstimateParams = {\n /** The position being closed; a `Position` can be passed as-is. */\n position: Pick<\n Position,\n 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'\n > & {\n leverage: Pick<Position['leverage'], 'type'>;\n };\n /**\n * Provider holding the position. It decides whether isolated `marginUsed`\n * is the position's collateral; for Lighter or an unknown provider,\n * isolated margin returned is undefined. `Position.providerId` is only set\n * under aggregation, so pass the provider explicitly.\n */\n providerId: PerpsProviderType;\n /**\n * Size to close in base units, unsigned: the whole position or part of it.\n * A size above the position size closes the whole position.\n */\n closeSize: number | string;\n /**\n * Price the close executes at: the limit price of a limit close, else the\n * live price. Undefined until known.\n */\n price: number | string | undefined;\n /**\n * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as\n * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which\n * already applies the maker or taker rate and any fee discount. Undefined\n * until quoted.\n */\n feeRate: number | undefined;\n};\n\n/**\n * The cash a close returns, in USD. Each figure is undefined while an input it\n * needs is missing or unusable; none falls back to 0.\n */\nexport type CloseReceiveEstimate = {\n /** The closed share of the margin backing the position, unrealized PnL excluded. */\n marginReturned: number | undefined;\n /** PnL realized on the closed size at the close price. */\n realizedPnl: number | undefined;\n /** Fee on the closed notional at the supplied fee rate. */\n fee: number | undefined;\n /**\n * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first\n * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.\n * A margin row that includes the PnL and a fee row, shown at that rounding,\n * add up to it. Undefined unless all three are known.\n */\n receive: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.\n */\nexport type NetClosedPnlParams = {\n /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */\n pnl?: number | string;\n /** Fee paid on the fill (`OrderFill.fee`). */\n fee?: number | string;\n};\n\nfunction toDecimal(value: number | string | undefined): BigNumber | undefined {\n if (value === undefined) {\n return undefined;\n }\n const decimal = new BigNumber(value);\n return decimal.isFinite() ? decimal : undefined;\n}\n\nfunction toPositiveDecimal(\n value: number | string | undefined,\n): BigNumber | undefined {\n const decimal = toDecimal(value);\n return decimal?.isGreaterThan(0) ? decimal : undefined;\n}\n\n/**\n * The unrealized PnL the position's margin holds: all of it for isolated\n * margin that is the position's collateral, none for cross margin.\n *\n * @param position - The position being closed.\n * @param providerId - Provider holding the position.\n * @returns The held PnL, or undefined when it or the collateral is unknown.\n */\nfunction heldUnrealizedPnl(\n position: CloseReceiveEstimateParams['position'],\n providerId: PerpsProviderType,\n): BigNumber | undefined {\n if (position.leverage.type !== 'isolated') {\n return new BigNumber(0);\n }\n if (\n !Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||\n !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]\n ) {\n return undefined;\n }\n return toDecimal(position.unrealizedPnl);\n}\n\nfunction roundUsd(value: BigNumber): BigNumber {\n return value.decimalPlaces(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n BigNumber.ROUND_HALF_UP,\n );\n}\n\n/**\n * Estimate the cash a close returns: the closed share of the position's\n * backing margin, plus the PnL realized at the close price, minus the fee.\n *\n * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid\n * isolated margin, which holds it. Cross margin is taken as reported. Lighter\n * isolated `marginUsed` is required margin, not the allocated collateral, so\n * its margin returned and receive are undefined. The realized PnL replaces the\n * mark-price PnL, so a limit close is quoted at its limit price. A close is\n * reduce-only, so a `closeSize` above the position size closes the whole\n * position.\n *\n * @param params - The close inputs.\n * @param params.position - The position being closed.\n * @param params.providerId - Provider holding the position.\n * @param params.closeSize - Unsigned size to close, in base units.\n * @param params.price - Price the close executes at.\n * @param params.feeRate - Total fee rate for the close, as a decimal.\n * @returns The estimate; a figure is undefined while an input it needs is\n * missing or unusable.\n */\nexport function estimateCloseReceive({\n position,\n providerId,\n closeSize,\n price,\n feeRate,\n}: CloseReceiveEstimateParams): CloseReceiveEstimate {\n const size = toDecimal(position.size);\n const positionSize = size?.isZero() ? undefined : size;\n const requested = toPositiveDecimal(closeSize);\n const closing =\n requested !== undefined && positionSize !== undefined\n ? BigNumber.min(requested, positionSize.abs())\n : requested;\n const closePrice = toPositiveDecimal(price);\n const entryPrice = toPositiveDecimal(position.entryPrice);\n const rate = toDecimal(feeRate);\n\n const marginUsed = toDecimal(position.marginUsed);\n const heldPnl = heldUnrealizedPnl(position, providerId);\n\n const marginReturned =\n marginUsed !== undefined &&\n heldPnl !== undefined &&\n positionSize !== undefined &&\n closing !== undefined\n ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())\n : undefined;\n const realizedPnl =\n positionSize !== undefined &&\n closing !== undefined &&\n closePrice !== undefined &&\n entryPrice !== undefined\n ? (positionSize.isNegative()\n ? entryPrice.minus(closePrice)\n : closePrice.minus(entryPrice)\n ).times(closing)\n : undefined;\n const fee =\n closing !== undefined && closePrice !== undefined && rate !== undefined\n ? closing.times(closePrice).times(rate)\n : undefined;\n const receive =\n marginReturned !== undefined &&\n realizedPnl !== undefined &&\n fee !== undefined\n ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))\n : undefined;\n\n return {\n marginReturned: marginReturned?.toNumber(),\n realizedPnl: realizedPnl?.toNumber(),\n fee: fee?.toNumber(),\n receive: receive?.toNumber(),\n };\n}\n\n/**\n * A fill's closed PnL net of its fee: the venue's realized PnL less the fee\n * paid on the fill.\n *\n * @param params - The fill figures.\n * @param params.pnl - Realized PnL the venue reported.\n * @param params.fee - Fee paid on the fill.\n * @returns The net PnL in USD, or undefined when either figure is missing,\n * empty or not a finite number.\n */\nexport function calculateNetClosedPnl({\n pnl,\n fee,\n}: NetClosedPnlParams): number | undefined {\n const gross = toDecimal(pnl);\n const cost = toDecimal(fee);\n return gross === undefined || cost === undefined\n ? undefined\n : gross.minus(cost).toNumber();\n}\n\n/**\n * Inputs to {@link calculateCloseSize}: the share of the position to close as\n * a percent, or as a USD amount at `price`.\n */\nexport type CloseSizeParams = {\n /** Position size in base units; the sign is ignored. */\n positionSize: number | string;\n /** Price the close is valued at. */\n price: number | string;\n /** Decimals the venue accepts for a size (`PerpsOrderLimits.sizeDecimals`). */\n sizeDecimals: number;\n} & (\n | {\n /** Percent of the position to close, 0 to 100. */\n percent: number;\n usdAmount?: never;\n }\n | {\n /** USD value to close; above the position's value closes all of it. */\n usdAmount: number | string;\n percent?: never;\n }\n);\n\n/** Result of {@link calculateCloseSize}. */\nexport type CloseSize = {\n /**\n * Size to close, on the venue's size grid, or the exact position size when\n * the close covers the whole position.\n */\n size: number;\n /** Value of the requested share before size rounding, in USD to the cent. */\n usdValue: number;\n};\n\n/**\n * Size to close for a percent or USD amount of a position, in exact decimal\n * arithmetic. The size rounds half up to `sizeDecimals`; when that leaves it\n * below the requested size, one size step is added so the close covers the\n * requested value. The result never exceeds the position.\n *\n * @param params - See {@link CloseSizeParams}.\n * @returns The close size and value, or undefined when an input is missing,\n * out of range or not a number, or the position is empty.\n */\nexport function calculateCloseSize(\n params: CloseSizeParams,\n): CloseSize | undefined {\n const { sizeDecimals } = params;\n const positionSize = toDecimal(params.positionSize)?.abs();\n const price = toPositiveDecimal(params.price);\n if (\n !Number.isInteger(sizeDecimals) ||\n sizeDecimals < 0 ||\n !positionSize?.isGreaterThan(0) ||\n price === undefined\n ) {\n return undefined;\n }\n\n let requestedSize: BigNumber;\n if (params.usdAmount === undefined) {\n const percent = toDecimal(params.percent);\n if (percent === undefined || percent.lt(0) || percent.gt(100)) {\n return undefined;\n }\n requestedSize = percent.dividedBy(100).multipliedBy(positionSize);\n } else {\n const usdAmount = toDecimal(params.usdAmount);\n if (usdAmount === undefined || usdAmount.lt(0)) {\n return undefined;\n }\n requestedSize = BigNumber.min(usdAmount.dividedBy(price), positionSize);\n }\n\n let size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_HALF_UP);\n if (size.lt(requestedSize)) {\n size = size.plus(new BigNumber(1).shiftedBy(-sizeDecimals));\n }\n\n return {\n size: BigNumber.min(size, positionSize).toNumber(),\n usdValue: roundUsd(requestedSize.multipliedBy(price)).toNumber(),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"closeCalculations.js","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;GAOG;AACH,MAAM,kCAAkC,GAAuC;IAC7E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAAK;CACf,CAAC;AAqEF,SAAS,SAAS,CAAC,KAAkC;IACnD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IACrC,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CACxB,KAAkC;IAElC,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IACjC,OA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,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,QAAQ,EAAE;QAClD,QAAQ,EAAE,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,EAAE;KACjE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Close-position figures shared by Mobile, Extension and Terminal: the cash a\n * close returns (\"You'll receive\") and a fill's closed PnL net of its fee.\n */\nimport { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { PerpsProviderType, Position } from '../types/index.js';\n\n/**\n * Whether a provider's isolated `Position.marginUsed` is the collateral\n * backing the position. Hyperliquid's is, with the unrealized PnL at mark\n * included. Lighter's is the initial margin the position requires at its\n * current value; its allocated collateral is not on `Position`, so the margin\n * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as\n * reported and never holds the unrealized PnL.\n */\nconst ISOLATED_MARGIN_USED_IS_COLLATERAL: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Inputs to {@link estimateCloseReceive}.\n */\nexport type CloseReceiveEstimateParams = {\n /** The position being closed; a `Position` can be passed as-is. */\n position: Pick<\n Position,\n 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'\n > & {\n leverage: Pick<Position['leverage'], 'type'>;\n };\n /**\n * Provider holding the position. It decides whether isolated `marginUsed`\n * is the position's collateral; for Lighter or an unknown provider,\n * isolated margin returned is undefined. `Position.providerId` is only set\n * under aggregation, so pass the provider explicitly.\n */\n providerId: PerpsProviderType;\n /**\n * Size to close in base units, unsigned: the whole position or part of it.\n * A size above the position size closes the whole position.\n */\n closeSize: number | string;\n /**\n * Price the close executes at: the limit price of a limit close, else the\n * live price. Undefined until known.\n */\n price: number | string | undefined;\n /**\n * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as\n * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which\n * already applies the maker or taker rate and any fee discount. Undefined\n * until quoted.\n */\n feeRate: number | undefined;\n};\n\n/**\n * The cash a close returns, in USD. Each figure is undefined while an input it\n * needs is missing or unusable; none falls back to 0.\n */\nexport type CloseReceiveEstimate = {\n /** The closed share of the margin backing the position, unrealized PnL excluded. */\n marginReturned: number | undefined;\n /** PnL realized on the closed size at the close price. */\n realizedPnl: number | undefined;\n /** Fee on the closed notional at the supplied fee rate. */\n fee: number | undefined;\n /**\n * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first\n * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.\n * A margin row that includes the PnL and a fee row, shown at that rounding,\n * add up to it. Undefined unless all three are known.\n */\n receive: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.\n */\nexport type NetClosedPnlParams = {\n /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */\n pnl?: number | string;\n /** Fee paid on the fill (`OrderFill.fee`). */\n fee?: number | string;\n};\n\nfunction toDecimal(value: number | string | undefined): BigNumber | undefined {\n if (value === undefined) {\n return undefined;\n }\n const decimal = new BigNumber(value);\n return decimal.isFinite() ? decimal : undefined;\n}\n\nfunction toPositiveDecimal(\n value: number | string | undefined,\n): BigNumber | undefined {\n const decimal = toDecimal(value);\n return decimal?.isGreaterThan(0) ? decimal : undefined;\n}\n\n/**\n * The unrealized PnL the position's margin holds: all of it for isolated\n * margin that is the position's collateral, none for cross margin.\n *\n * @param position - The position being closed.\n * @param providerId - Provider holding the position.\n * @returns The held PnL, or undefined when it or the collateral is unknown.\n */\nfunction heldUnrealizedPnl(\n position: CloseReceiveEstimateParams['position'],\n providerId: PerpsProviderType,\n): BigNumber | undefined {\n if (position.leverage.type !== 'isolated') {\n return new BigNumber(0);\n }\n if (\n !Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||\n !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]\n ) {\n return undefined;\n }\n return toDecimal(position.unrealizedPnl);\n}\n\nfunction roundUsd(value: BigNumber): BigNumber {\n return value.decimalPlaces(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n BigNumber.ROUND_HALF_UP,\n );\n}\n\n/**\n * Estimate the cash a close returns: the closed share of the position's\n * backing margin, plus the PnL realized at the close price, minus the fee.\n *\n * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid\n * isolated margin, which holds it. Cross margin is taken as reported. Lighter\n * isolated `marginUsed` is required margin, not the allocated collateral, so\n * its margin returned and receive are undefined. The realized PnL replaces the\n * mark-price PnL, so a limit close is quoted at its limit price. A close is\n * reduce-only, so a `closeSize` above the position size closes the whole\n * position.\n *\n * @param params - The close inputs.\n * @param params.position - The position being closed.\n * @param params.providerId - Provider holding the position.\n * @param params.closeSize - Unsigned size to close, in base units.\n * @param params.price - Price the close executes at.\n * @param params.feeRate - Total fee rate for the close, as a decimal.\n * @returns The estimate; a figure is undefined while an input it needs is\n * missing or unusable.\n */\nexport function estimateCloseReceive({\n position,\n providerId,\n closeSize,\n price,\n feeRate,\n}: CloseReceiveEstimateParams): CloseReceiveEstimate {\n const size = toDecimal(position.size);\n const positionSize = size?.isZero() ? undefined : size;\n const requested = toPositiveDecimal(closeSize);\n const closing =\n requested !== undefined && positionSize !== undefined\n ? BigNumber.min(requested, positionSize.abs())\n : requested;\n const closePrice = toPositiveDecimal(price);\n const entryPrice = toPositiveDecimal(position.entryPrice);\n const rate = toDecimal(feeRate);\n\n const marginUsed = toDecimal(position.marginUsed);\n const heldPnl = heldUnrealizedPnl(position, providerId);\n\n const marginReturned =\n marginUsed !== undefined &&\n heldPnl !== undefined &&\n positionSize !== undefined &&\n closing !== undefined\n ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())\n : undefined;\n const realizedPnl =\n positionSize !== undefined &&\n closing !== undefined &&\n closePrice !== undefined &&\n entryPrice !== undefined\n ? (positionSize.isNegative()\n ? entryPrice.minus(closePrice)\n : closePrice.minus(entryPrice)\n ).times(closing)\n : undefined;\n const fee =\n closing !== undefined && closePrice !== undefined && rate !== undefined\n ? closing.times(closePrice).times(rate)\n : undefined;\n const receive =\n marginReturned !== undefined &&\n realizedPnl !== undefined &&\n fee !== undefined\n ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))\n : undefined;\n\n return {\n marginReturned: marginReturned?.toNumber(),\n realizedPnl: realizedPnl?.toNumber(),\n fee: fee?.toNumber(),\n receive: receive?.toNumber(),\n };\n}\n\n/**\n * A fill's closed PnL net of its fee: the venue's realized PnL less the fee\n * paid on the fill.\n *\n * @param params - The fill figures.\n * @param params.pnl - Realized PnL the venue reported.\n * @param params.fee - Fee paid on the fill.\n * @returns The net PnL in USD, or undefined when either figure is missing,\n * empty or not a finite number.\n */\nexport function calculateNetClosedPnl({\n pnl,\n fee,\n}: NetClosedPnlParams): number | undefined {\n const gross = toDecimal(pnl);\n const cost = toDecimal(fee);\n return gross === undefined || cost === undefined\n ? undefined\n : gross.minus(cost).toNumber();\n}\n\n/**\n * Inputs to {@link calculateCloseSize}: the share of the position to close as\n * a percent, or as a USD amount at `price`.\n */\nexport type CloseSizeParams = {\n /** Position size in base units; the sign is ignored. */\n positionSize: number | string;\n /** Price the close is valued at. */\n price: number | string;\n /** Decimals the venue accepts for a size (`PerpsOrderLimits.sizeDecimals`). */\n sizeDecimals: number;\n /**\n * How a partial size meets the size grid. `up` (default) rounds half up\n * and adds one step when that leaves the size below the request, so the\n * close covers the requested value. `down` rounds down, so several partial\n * closes of one position, such as split take-profit levels, never add up to\n * more than the position.\n */\n rounding?: CloseSizeRounding;\n} & (\n | {\n /** Percent of the position to close, 0 to 100. */\n percent: number;\n usdAmount?: never;\n }\n | {\n /** USD value to close; above the position's value closes all of it. */\n usdAmount: number | string;\n percent?: never;\n }\n);\n\n/** How {@link calculateCloseSize} puts a partial size on the size grid. */\nexport type CloseSizeRounding = 'up' | 'down';\n\n/** Result of {@link calculateCloseSize}. */\nexport type CloseSize = {\n /**\n * Size to close, on the venue's size grid, or the exact position size when\n * the close covers the whole position.\n */\n size: number;\n /** Value of the requested share before size rounding, in USD to the cent. */\n usdValue: number;\n};\n\n/**\n * Size to close for a percent or USD amount of a position, in exact decimal\n * arithmetic. A request for the whole position returns the exact position\n * size. Otherwise, by default, the size rounds half up to `sizeDecimals`;\n * when that leaves it below the requested size, one size step is added so the\n * close covers the requested value. With `rounding: 'down'` it rounds down to\n * `sizeDecimals` instead. The result never exceeds the position.\n *\n * @param params - See {@link CloseSizeParams}.\n * @returns The close size and value, or undefined when an input is missing,\n * out of range or not a number, the position is empty, or `rounding: 'down'`\n * leaves a requested size below one size step.\n */\nexport function calculateCloseSize(\n params: CloseSizeParams,\n): CloseSize | undefined {\n const { sizeDecimals } = params;\n const positionSize = toDecimal(params.positionSize)?.abs();\n const price = toPositiveDecimal(params.price);\n if (\n !Number.isInteger(sizeDecimals) ||\n sizeDecimals < 0 ||\n !positionSize?.isGreaterThan(0) ||\n price === undefined\n ) {\n return undefined;\n }\n\n let requestedSize: BigNumber;\n if (params.usdAmount === undefined) {\n const percent = toDecimal(params.percent);\n if (percent === undefined || percent.lt(0) || percent.gt(100)) {\n return undefined;\n }\n requestedSize = percent.dividedBy(100).multipliedBy(positionSize);\n } else {\n const usdAmount = toDecimal(params.usdAmount);\n if (usdAmount === undefined || usdAmount.lt(0)) {\n return undefined;\n }\n requestedSize = BigNumber.min(usdAmount.dividedBy(price), positionSize);\n }\n\n let size: BigNumber;\n if (requestedSize.gte(positionSize)) {\n size = positionSize;\n } else if (params.rounding === 'down') {\n size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_DOWN);\n if (size.isZero() && requestedSize.isGreaterThan(0)) {\n // Below one size step: no order can close it.\n return undefined;\n }\n } else {\n size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_HALF_UP);\n if (size.lt(requestedSize)) {\n size = size.plus(new BigNumber(1).shiftedBy(-sizeDecimals));\n }\n }\n\n return {\n size: BigNumber.min(size, positionSize).toNumber(),\n usdValue: roundUsd(requestedSize.multipliedBy(price)).toNumber(),\n };\n}\n"]}
|
|
@@ -60,7 +60,16 @@ export declare function adaptPositionTriggerOrderFromSDK(params: {
|
|
|
60
60
|
positionSize: string;
|
|
61
61
|
entryPrice?: string;
|
|
62
62
|
}): PositionTriggerOrder | undefined;
|
|
63
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Map one `meta.universe` entry to {@link MarketInfo}.
|
|
65
|
+
*
|
|
66
|
+
* @param sdkMarket - The venue market.
|
|
67
|
+
* @param marginTables - `meta.marginTables` from the same response. Needed to
|
|
68
|
+
* resolve tiered tables (ids of 50 and above); single-tier ids resolve
|
|
69
|
+
* without it.
|
|
70
|
+
* @returns The market, with `marginTiers` when the table resolves.
|
|
71
|
+
*/
|
|
72
|
+
export declare function adaptMarketFromSDK(sdkMarket: MetaResponse['universe'][number], marginTables?: MetaResponse['marginTables']): MarketInfo;
|
|
64
73
|
export declare function adaptAccountStateFromSDK(perpsState: ClearinghouseStateResponse): AccountState;
|
|
65
74
|
export declare function buildAssetMapping(params: {
|
|
66
75
|
metaUniverse: MetaResponse['universe'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidAdapter.d.ts","sourceRoot":"","sources":["../../src/utils/hyperLiquidAdapter.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,0BAA0B,EAC1B,sBAAsB,EACtB,YAAY,EACZ,cAAc,EACf,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,YAAY,EAEZ,UAAU,EACV,KAAK,EACL,WAAW,IAAI,gBAAgB,EAC/B,QAAQ,EACR,oBAAoB,EACpB,WAAW,EACX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B,CAAC,MAAM,EAAE;IAC5C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,MAAM,CAGT;AAED,wBAAgB,oBAAoB,CAClC,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,GAClB,MAAM,CASR;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,GAAG,MAAM,GAAG,SAAS,CAKrB;AAED,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG;IACjD,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB,CASA;AAED,wBAAgB,6CAA6C,CAC3D,gBAAgB,EAAE,eAAe,EAAE,GAClC,eAAe,EAAE,CAkDnB;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,SAAS,sBAAsB,EAAE,EACzC,MAAM,EAAE,MAAM,GACb,WAAW,EAAE,CA4Bf"}
|
|
@@ -3,6 +3,7 @@ import { BigNumber } from 'bignumber.js';
|
|
|
3
3
|
import { BASIS_POINTS_DIVISOR, HIP3_ASSET_ID_CONFIG, isUnrestrictedMarginMode, } from '../constants/hyperLiquidConfig.js';
|
|
4
4
|
import { DECIMAL_PRECISION_CONFIG, ORDER_SLIPPAGE_CONFIG, } from '../constants/perpsConfig.js';
|
|
5
5
|
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
6
|
+
import { resolveHyperLiquidMarginTiers } from './hyperLiquidPositionPreview.js';
|
|
6
7
|
import { buildTriggerOrderType, classifyTriggerDirection, getTriggerDirection, getTriggerExecution, isLimitExecutionOrderType, isTriggerOrderType, toSDKTimeInForce, } from './orderTypes.js';
|
|
7
8
|
import { roundToSignificantFiguresGrid } from './pricePrecision.js';
|
|
8
9
|
import { buildPublicTrade, sortPublicTradesNewestFirst, } from './publicTrades.js';
|
|
@@ -380,10 +381,24 @@ export function adaptPositionTriggerOrderFromSDK(params) {
|
|
|
380
381
|
reduceOnly: Boolean(rawOrder.reduceOnly),
|
|
381
382
|
};
|
|
382
383
|
}
|
|
383
|
-
|
|
384
|
+
/**
|
|
385
|
+
* Map one `meta.universe` entry to {@link MarketInfo}.
|
|
386
|
+
*
|
|
387
|
+
* @param sdkMarket - The venue market.
|
|
388
|
+
* @param marginTables - `meta.marginTables` from the same response. Needed to
|
|
389
|
+
* resolve tiered tables (ids of 50 and above); single-tier ids resolve
|
|
390
|
+
* without it.
|
|
391
|
+
* @returns The market, with `marginTiers` when the table resolves.
|
|
392
|
+
*/
|
|
393
|
+
export function adaptMarketFromSDK(sdkMarket, marginTables) {
|
|
384
394
|
// The venue also sends `normal` (no restriction), which the SDK type omits.
|
|
385
395
|
// `MarketInfo.marginMode` carries restrictions only, so drop it.
|
|
386
396
|
const venueMarginMode = sdkMarket.marginMode;
|
|
397
|
+
const marginTiers = resolveHyperLiquidMarginTiers({
|
|
398
|
+
marginTableId: sdkMarket.marginTableId,
|
|
399
|
+
maxLeverage: sdkMarket.maxLeverage,
|
|
400
|
+
marginTables,
|
|
401
|
+
});
|
|
387
402
|
return {
|
|
388
403
|
name: sdkMarket.name,
|
|
389
404
|
szDecimals: sdkMarket.szDecimals,
|
|
@@ -394,6 +409,7 @@ export function adaptMarketFromSDK(sdkMarket) {
|
|
|
394
409
|
marginMode: sdkMarket.marginMode,
|
|
395
410
|
}),
|
|
396
411
|
isDelisted: sdkMarket.isDelisted,
|
|
412
|
+
...(marginTiers && { marginTiers }),
|
|
397
413
|
};
|
|
398
414
|
}
|
|
399
415
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidAdapter.js","sourceRoot":"","sources":["../../src/utils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AC,CAAC;QAC5B,CAAC;IACH,CAAC;IACD,OAAO,2BAA2B,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { hasProperty, Hex, isHexString } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\n isUnrestrictedMarginMode,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n DECIMAL_PRECISION_CONFIG,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n AssetPosition,\n FrontendOrder,\n ClearinghouseStateResponse,\n HyperLiquidPublicTrade,\n MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\n PublicTrade,\n RawLedgerUpdate,\n UserHistoryItem,\n} from '../types/index.js';\nimport type { TpslLinkage, TriggerOrderType } from '../types/perps-types.js';\nimport {\n buildTriggerOrderType,\n classifyTriggerDirection,\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n toSDKTimeInForce,\n} from './orderTypes.js';\nimport { roundToSignificantFiguresGrid } from './pricePrecision.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\ntype FrontendOrderWithParentTpsl = FrontendOrder & {\n takeProfitPrice?: unknown;\n stopLossPrice?: unknown;\n takeProfitOrderId?: unknown;\n stopLossOrderId?: unknown;\n};\n\nexport const HYPERLIQUID_SCALE_CLOID_MARKER = '4d4d5343';\n\n/**\n * Recover the Scale group shared by MetaMask-generated rung CLOIDs.\n *\n * @param clientOrderId - HyperLiquid client order ID.\n * @returns The Scale handle, or undefined for an unrelated order.\n */\nexport const readScaleGroupId = (\n clientOrderId: string | null | undefined,\n): string | undefined => {\n const normalized = clientOrderId?.toLowerCase();\n if (\n normalized?.length !== 34 ||\n !normalized.startsWith(`0x${HYPERLIQUID_SCALE_CLOID_MARKER}`)\n ) {\n return undefined;\n }\n return `scale:${normalized.slice(2, -2)}`;\n};\n\nconst readOptionalString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst readOptionalOrderId = (value: unknown): string | undefined => {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value.toString();\n }\n\n return undefined;\n};\n\nconst getParentTpslMetadata = (\n rawOrder: FrontendOrderWithParentTpsl,\n): {\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitOrderId?: string;\n stopLossOrderId?: string;\n} => ({\n takeProfitPrice: readOptionalString(rawOrder.takeProfitPrice),\n stopLossPrice: readOptionalString(rawOrder.stopLossPrice),\n takeProfitOrderId: readOptionalOrderId(rawOrder.takeProfitOrderId),\n stopLossOrderId: readOptionalOrderId(rawOrder.stopLossOrderId),\n});\n\n/**\n * HyperLiquid SDK Adapter Utilities\n *\n * These functions transform between MetaMask Perps API types and HyperLiquid SDK types.\n * The SDK uses cryptic property names for efficiency, but our API uses descriptive names\n * to provide a consistent interface across different perps protocols.\n */\n\nexport function adaptOrderToSDK(\n order: PerpsOrderParams,\n symbolToAssetId: Map<string, number>,\n): SDKOrderParams {\n const assetId = symbolToAssetId.get(order.symbol);\n if (assetId === undefined) {\n const availableDexs = new Set<string>();\n symbolToAssetId.forEach((_, symbol) => {\n if (symbol.includes(':')) {\n const dex = symbol.split(':')[0];\n availableDexs.add(dex);\n }\n });\n\n const dexHint =\n availableDexs.size > 0\n ? ` Available HIP-3 DEXs: ${Array.from(availableDexs).join(', ')}`\n : ' No HIP-3 DEXs currently available.';\n\n throw new Error(\n `Asset ${order.symbol} not found in asset mapping.${dexHint} Check console logs for \"HyperLiquidProvider: Asset mapping built\" to see available assets.`,\n );\n }\n\n return {\n a: assetId,\n b: order.isBuy,\n p: order.price ?? resolveTriggerCapPrice(order) ?? '0',\n s: order.size,\n r: order.reduceOnly ?? false,\n t: adaptOrderTypeToSDK(order),\n c:\n order.clientOrderId && isHexString(order.clientOrderId)\n ? order.clientOrderId\n : undefined,\n };\n}\n\n/**\n * Derive the slippage cap a market-on-trigger order submits as its price.\n *\n * A `stop_market` / `take_profit_market` order legitimately carries no limit\n * price, but the SDK still requires a positive `p` — it is the cap the order\n * fills against once the trigger fires, not a resting price. Sending `'0'`\n * fails SDK validation before the request is ever made.\n *\n * The cap follows the order's own tolerance, matching `calculateOrderPriceAndSize`\n * on the `placeOrder` path, so the same order priced through either route gets\n * the same execution bound.\n *\n * @param order - Order params carrying the placement type, trigger price, and\n * slippage tolerance.\n * @returns The formatted cap price, or undefined when the order needs no cap.\n */\nfunction resolveTriggerCapPrice(order: PerpsOrderParams): string | undefined {\n if (\n !isTriggerOrderType(order.orderType) ||\n isLimitExecutionOrderType(order.orderType) ||\n !order.triggerPrice\n ) {\n return undefined;\n }\n\n const triggerPrice = parseFloat(order.triggerPrice);\n if (!Number.isFinite(triggerPrice)) {\n return undefined;\n }\n\n // Accept the deprecated decimal `slippage` too, normalizing it to bps the way\n // `placeOrder` does, so neither spelling silently falls back to the default.\n const effectiveBps =\n order.maxSlippageBps ??\n (typeof order.slippage === 'number'\n ? Math.round(order.slippage * BASIS_POINTS_DIVISOR)\n : undefined) ??\n ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n\n // Buying pays up to the cap, selling accepts down to it.\n const slippage = effectiveBps / BASIS_POINTS_DIVISOR;\n const capPrice = order.isBuy\n ? triggerPrice * (1 + slippage)\n : triggerPrice * (1 - slippage);\n\n return capPrice.toString();\n}\n\n/**\n * Map a placement type onto the SDK's order-type field.\n *\n * @param order - Order params carrying the placement type and trigger price\n * @returns The SDK order-type field\n */\nfunction adaptOrderTypeToSDK(order: PerpsOrderParams): SDKOrderParams['t'] {\n if (isTriggerOrderType(order.orderType)) {\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n if (!order.triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(order.orderType),\n triggerPx: order.triggerPrice,\n tpsl: getTriggerDirection(order.orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n }\n\n if (order.orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(order.timeInForce) } };\n }\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n}\n\n/**\n * Map the provider-agnostic TP/SL linkage onto HyperLiquid's grouping vocabulary.\n *\n * @param linkage - How the attached TP/SL is linked.\n * @returns The HyperLiquid grouping value.\n */\nexport function adaptTpslLinkageToGrouping(\n linkage: TpslLinkage,\n): 'na' | 'normalTpsl' | 'positionTpsl' {\n switch (linkage) {\n case 'position':\n return 'positionTpsl';\n case 'order':\n return 'normalTpsl';\n default:\n return 'na';\n }\n}\n\n/**\n * Margin Hyperliquid shows for a cross position. When cross equity is below\n * the cross initial margin, the venue scales each cross position's margin by\n * `accountValue / totalMarginUsed`.\n *\n * @param marginUsed - The position's raw margin used.\n * @param crossMarginSummary - The clearinghouse's cross margin summary.\n * @returns The displayed margin, or undefined when an input is not a number.\n */\nfunction deriveCrossDisplayMarginUsed(\n marginUsed: string,\n crossMarginSummary: ClearinghouseStateResponse['crossMarginSummary'],\n): string | undefined {\n const margin = new BigNumber(marginUsed);\n const accountValue = new BigNumber(crossMarginSummary.accountValue);\n const totalMarginUsed = new BigNumber(crossMarginSummary.totalMarginUsed);\n if (\n !margin.isFinite() ||\n !accountValue.isFinite() ||\n !totalMarginUsed.isFinite()\n ) {\n return undefined;\n }\n if (totalMarginUsed.lte(0) || accountValue.gte(totalMarginUsed)) {\n return margin.toFixed();\n }\n return BigNumber.max(\n margin.times(accountValue).div(totalMarginUsed),\n 0,\n ).toFixed();\n}\n\n/**\n * Adapt a Hyperliquid asset position.\n *\n * @param assetPosition - Position from a clearinghouse state.\n * @param crossMarginSummary - That clearinghouse's `crossMarginSummary`. When\n * given, a cross position also carries `displayMarginUsed`.\n * @returns The position.\n */\nexport function adaptPositionFromSDK(\n assetPosition: AssetPosition,\n crossMarginSummary?: ClearinghouseStateResponse['crossMarginSummary'],\n): Position {\n const pos = assetPosition.position;\n const displayMarginUsed =\n pos.leverage.type === 'cross' && crossMarginSummary\n ? deriveCrossDisplayMarginUsed(pos.marginUsed, crossMarginSummary)\n : undefined;\n return {\n symbol: pos.coin,\n size: pos.szi,\n entryPrice: pos.entryPx,\n positionValue: pos.positionValue,\n unrealizedPnl: pos.unrealizedPnl,\n marginUsed: pos.marginUsed,\n ...(displayMarginUsed !== undefined && { displayMarginUsed }),\n leverage: {\n type: pos.leverage.type,\n value: pos.leverage.value,\n rawUsd:\n pos.leverage.type === 'isolated' ? pos.leverage.rawUsd : undefined,\n },\n liquidationPrice: pos.liquidationPx,\n maxLeverage: pos.maxLeverage,\n returnOnEquity: pos.returnOnEquity,\n cumulativeFunding: pos.cumFunding,\n takeProfitCount: 0,\n stopLossCount: 0,\n };\n}\n\nexport function adaptOrderFromSDK(\n rawOrder: FrontendOrder,\n position?: Position,\n): Order {\n // TODO: Remove this widened boundary type when FrontendOrder includes\n // takeProfitPrice/stopLossPrice and takeProfitOrderId/stopLossOrderId.\n const parentTpslMetadata = getParentTpslMetadata(rawOrder);\n\n // Extract basic fields with appropriate conversions\n const orderId = rawOrder.oid?.toString() || '';\n const symbol = rawOrder.coin;\n const side: 'buy' | 'sell' = rawOrder.side === 'B' ? 'buy' : 'sell';\n const detailedOrderType = rawOrder.orderType;\n const { isTrigger } = rawOrder;\n const { reduceOnly } = rawOrder;\n\n const triggerOrderType = adaptTriggerOrderTypeFromSDK(detailedOrderType);\n\n let orderType: 'limit' | 'market' = 'market';\n if (triggerOrderType) {\n // Trigger orders always carry a limitPx (the slippage cap for\n // market-on-trigger execution), so the placement type is the only reliable\n // source for how the order actually executes.\n orderType = getTriggerExecution(triggerOrderType);\n } else if (\n detailedOrderType?.toLowerCase().includes('limit') ||\n rawOrder.limitPx\n ) {\n orderType = 'limit';\n }\n\n const price = rawOrder.limitPx || rawOrder.triggerPx || '0';\n\n let size = rawOrder.sz;\n let originalSize = rawOrder.origSz || size;\n\n let currentSize = parseFloat(size);\n let origSize = parseFloat(originalSize);\n\n if (rawOrder.isPositionTpsl && origSize === 0 && position) {\n const absPositionSize = Math.abs(parseFloat(position.size));\n currentSize = absPositionSize;\n origSize = absPositionSize;\n size = absPositionSize.toString();\n originalSize = absPositionSize.toString();\n }\n\n const filledSize = origSize - currentSize;\n\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n let takeProfitOrderId: string | undefined;\n let stopLossOrderId: string | undefined;\n\n // TODO: We assume that there can only be 1 TP and 1 SL as children but there can be several TPSLs as children\n if (rawOrder.children && rawOrder.children.length > 0) {\n rawOrder.children.forEach((child) => {\n if (child.isTrigger && child.orderType) {\n if (child.orderType.includes('Take Profit')) {\n // HyperLiquid represents \"no trigger price\" as an empty string, not\n // null/undefined, so `||` (not `??`) is required to fall back to\n // limitPx when triggerPx is ''.\n takeProfitPrice = child.triggerPx || child.limitPx;\n takeProfitOrderId = child.oid.toString();\n } else if (child.orderType.includes('Stop')) {\n stopLossPrice = child.triggerPx || child.limitPx;\n stopLossOrderId = child.oid.toString();\n }\n }\n });\n }\n\n // Fallback: preserve parent-level TP/SL metadata when children are absent.\n takeProfitPrice ??= parentTpslMetadata.takeProfitPrice;\n stopLossPrice ??= parentTpslMetadata.stopLossPrice;\n takeProfitOrderId ??= parentTpslMetadata.takeProfitOrderId;\n stopLossOrderId ??= parentTpslMetadata.stopLossOrderId;\n\n // Build the order object\n const order: Order = {\n orderId,\n symbol,\n side,\n orderType,\n size,\n originalSize,\n price,\n filledSize: filledSize.toString(),\n remainingSize: size,\n status: 'open' as const,\n timestamp: rawOrder.timestamp,\n detailedOrderType,\n isTrigger,\n reduceOnly,\n };\n\n const strategyGroupId = readScaleGroupId(rawOrder.cloid);\n if (strategyGroupId) {\n order.strategyGroupId = strategyGroupId;\n }\n\n if (typeof rawOrder.isPositionTpsl === 'boolean') {\n order.isPositionTpsl = rawOrder.isPositionTpsl;\n }\n\n if (takeProfitPrice) {\n order.takeProfitPrice = takeProfitPrice;\n order.takeProfitOrderId = takeProfitOrderId;\n }\n if (stopLossPrice) {\n order.stopLossPrice = stopLossPrice;\n order.stopLossOrderId = stopLossOrderId;\n }\n if (rawOrder.triggerPx) {\n order.triggerPrice = rawOrder.triggerPx;\n }\n\n if (triggerOrderType) {\n order.triggerOrderType = triggerOrderType;\n }\n\n return order;\n}\n\n/**\n * Map HyperLiquid's human-readable order type string onto the provider-agnostic\n * trigger placement type.\n *\n * @param detailedOrderType - HyperLiquid `orderType` string (e.g. `'Stop Limit'`)\n * @returns The normalized trigger placement type, or undefined for non-trigger orders\n */\nexport function adaptTriggerOrderTypeFromSDK(\n detailedOrderType: string | undefined,\n): TriggerOrderType | undefined {\n if (!detailedOrderType) {\n return undefined;\n }\n\n const isTakeProfit = detailedOrderType.includes('Take Profit');\n const isStop = detailedOrderType.includes('Stop');\n\n if (!isTakeProfit && !isStop) {\n return undefined;\n }\n\n return buildTriggerOrderType({\n direction: isTakeProfit ? 'take_profit' : 'stop',\n execution: detailedOrderType.includes('Limit') ? 'limit' : 'market',\n });\n}\n\n/**\n * Build the position-state view of a trigger order attached to a position.\n *\n * HyperLiquid encodes \"the whole position\" as size `0` for position-bound TP/SL,\n * which is resolved here against the position size so consumers always see a\n * concrete quantity and can tell partial triggers apart.\n *\n * @param params - Mapping parameters\n * @param params.rawOrder - Raw HyperLiquid frontend order\n * @param params.positionSize - Signed or unsigned position size\n * @param params.entryPrice - Entry price, used to classify a trigger the exchange left unnamed\n * @returns The normalized trigger order, or undefined when the order is not a trigger\n */\nexport function adaptPositionTriggerOrderFromSDK(params: {\n rawOrder: Pick<\n FrontendOrder,\n 'oid' | 'orderType' | 'triggerPx' | 'limitPx' | 'sz' | 'reduceOnly'\n >;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { rawOrder, positionSize, entryPrice } = params;\n\n const orderType = adaptTriggerOrderTypeFromSDK(rawOrder.orderType);\n\n // HyperLiquid uses '' for \"no trigger price\", so `||` (not `??`) is required.\n const triggerPrice = rawOrder.triggerPx || rawOrder.limitPx || '0';\n\n // Same rule as the WebSocket path: an unnamed trigger keeps its recoverable\n // direction and leaves its execution mode unstated, so both transports\n // report the same set of orders.\n const direction = orderType\n ? getTriggerDirection(orderType)\n : classifyTriggerDirection({ triggerPrice, entryPrice, positionSize });\n\n if (!direction) {\n return undefined;\n }\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(rawOrder.sz || '0'));\n\n // Position-bound TP/SL carries size 0, meaning the whole position.\n const size = rawSize > 0 ? rawSize : absolutePositionSize;\n\n return {\n orderId: rawOrder.oid.toString(),\n direction,\n orderType,\n triggerPrice,\n size: size.toString(),\n isPartial:\n rawSize > 0 && absolutePositionSize > 0 && rawSize < absolutePositionSize,\n reduceOnly: Boolean(rawOrder.reduceOnly),\n };\n}\n\nexport function adaptMarketFromSDK(\n sdkMarket: MetaResponse['universe'][number],\n): MarketInfo {\n // The venue also sends `normal` (no restriction), which the SDK type omits.\n // `MarketInfo.marginMode` carries restrictions only, so drop it.\n const venueMarginMode: string | undefined = sdkMarket.marginMode;\n return {\n name: sdkMarket.name,\n szDecimals: sdkMarket.szDecimals,\n maxLeverage: sdkMarket.maxLeverage,\n marginTableId: sdkMarket.marginTableId,\n onlyIsolated: sdkMarket.onlyIsolated,\n ...(!isUnrestrictedMarginMode(venueMarginMode) && {\n marginMode: sdkMarket.marginMode,\n }),\n isDelisted: sdkMarket.isDelisted,\n };\n}\n\n/**\n * Read one clearinghouse's cross-margin summary. A payload without the cross\n * fields reports none; present values must be finite decimals.\n *\n * @param perpsState - Clearinghouse state for one DEX.\n * @returns The summary, or undefined when the payload carries none.\n */\nfunction adaptCrossMarginSummaryFromSDK(\n perpsState: ClearinghouseStateResponse,\n): CrossMarginSummary | undefined {\n const { crossMarginSummary, crossMaintenanceMarginUsed } = perpsState;\n if (!crossMarginSummary || crossMaintenanceMarginUsed === undefined) {\n return undefined;\n }\n const summary: CrossMarginSummary = {\n accountValue: crossMarginSummary.accountValue,\n maintenanceMargin: crossMaintenanceMarginUsed,\n marginUsed: crossMarginSummary.totalMarginUsed,\n notional: crossMarginSummary.totalNtlPos,\n };\n for (const [field, value] of Object.entries(summary)) {\n if (parseFiniteDecimal(value) === null) {\n throw new Error(\n `Invalid HyperLiquid cross margin ${field} '${String(value)}'`,\n );\n }\n }\n return summary;\n}\n\n// Perps-only account adapter. Spot balances are layered on afterwards by\n// addSpotBalanceToAccountState, which enforces the USDC-only policy via\n// SPOT_COLLATERAL_COINS. Keeping spot logic out of here preserves a single\n// source of truth for spot balance math.\nexport function adaptAccountStateFromSDK(\n perpsState: ClearinghouseStateResponse,\n): AccountState {\n const { totalUnrealizedPnl, weightedReturnOnEquity } =\n perpsState.assetPositions.reduce(\n (acc, assetPos: AssetPosition) => {\n const unrealizedPnl = parseFloat(\n assetPos.position.unrealizedPnl || '0',\n );\n const marginUsed = parseFloat(assetPos.position.marginUsed || '0');\n const returnOnEquity = parseFloat(\n assetPos.position.returnOnEquity || '0',\n );\n acc.totalUnrealizedPnl += unrealizedPnl;\n acc.weightedReturnOnEquity += returnOnEquity * marginUsed;\n return acc;\n },\n {\n totalUnrealizedPnl: 0,\n weightedReturnOnEquity: 0,\n },\n );\n const totalMarginUsed = parseFloat(\n perpsState.marginSummary.totalMarginUsed || '0',\n );\n const totalReturnOnEquityPercentage =\n totalMarginUsed > 0\n ? ((weightedReturnOnEquity / totalMarginUsed) * 100).toString()\n : '0';\n\n const perpsBalance = parseFloat(perpsState.marginSummary.accountValue);\n\n const withdrawable = perpsState.withdrawable || '0';\n const crossMarginSummary = adaptCrossMarginSummaryFromSDK(perpsState);\n const accountState: AccountState = {\n spendableBalance: withdrawable,\n withdrawableBalance: withdrawable,\n totalBalance: perpsBalance.toString() || '0',\n marginUsed: perpsState.marginSummary.totalMarginUsed || '0',\n unrealizedPnl: totalUnrealizedPnl.toString() || '0',\n returnOnEquity: totalReturnOnEquityPercentage || '0',\n ...(crossMarginSummary ? { crossMarginSummary } : {}),\n };\n\n return accountState;\n}\n\nexport function buildAssetMapping(params: {\n metaUniverse: MetaResponse['universe'];\n dex?: string | null;\n perpDexIndex: number;\n}): {\n symbolToAssetId: Map<string, number>;\n assetIdToSymbol: Map<number, string>;\n} {\n const { metaUniverse, perpDexIndex } = params;\n const symbolToAssetId = new Map<string, number>();\n const assetIdToSymbol = new Map<number, string>();\n\n metaUniverse.forEach((asset, index) => {\n const assetId = calculateHip3AssetId(perpDexIndex, index);\n symbolToAssetId.set(asset.name, assetId);\n assetIdToSymbol.set(assetId, asset.name);\n });\n\n return { symbolToAssetId, assetIdToSymbol };\n}\n\nexport function formatHyperLiquidPrice(params: {\n price: string | number;\n szDecimals: number;\n}): string {\n const { price, szDecimals } = params;\n return roundToSignificantFiguresGrid(\n price,\n DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals,\n DECIMAL_PRECISION_CONFIG.MaxSignificantFigures,\n );\n}\n\nexport function formatHyperLiquidSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const { size, szDecimals } = params;\n const number = typeof size === 'string' ? parseFloat(size) : size;\n\n if (isNaN(number)) {\n return '0';\n }\n\n const formatted = number.toFixed(szDecimals);\n\n if (!formatted.includes('.')) {\n return formatted;\n }\n\n return formatted.replace(/\\.?0+$/u, '');\n}\n\nexport function calculatePositionSize(params: {\n usdValue: number;\n leverage: number;\n assetPrice: number;\n}): number {\n const { usdValue, leverage, assetPrice } = params;\n return (usdValue * leverage) / assetPrice;\n}\n\nexport function calculateHip3AssetId(\n perpDexIndex: number,\n indexInMeta: number,\n): number {\n if (perpDexIndex === 0) {\n return indexInMeta;\n }\n return (\n HIP3_ASSET_ID_CONFIG.BaseAssetId +\n perpDexIndex * HIP3_ASSET_ID_CONFIG.DexMultiplier +\n indexInMeta\n );\n}\n\n/**\n * Build the provider-neutral execution id for a HyperLiquid fill.\n *\n * HyperLiquid's `tid` is a 50-bit hash, and the venue documents\n * `(block_time, coin, tid)` as a trade's global identity, so all three go into\n * the id. REST and websocket fills report the same `time`, `coin` and `tid` for\n * one execution, so both transports yield the same id.\n *\n * @param fill - The raw HyperLiquid fill.\n * @param fill.coin - Venue asset name, including any HIP-3 dex prefix.\n * @param fill.time - Fill block time in milliseconds.\n * @param fill.tid - Venue trade id.\n * @returns The id, or `undefined` when the payload carries no `tid`. Omitting\n * it, rather than stringifying a missing value, keeps malformed fills from\n * sharing one id.\n */\nexport function buildHyperLiquidFillId(fill: {\n coin: string;\n time: number;\n tid?: number | null;\n}): string | undefined {\n if (fill.tid === undefined || fill.tid === null) {\n return undefined;\n }\n return `${fill.coin}:${fill.time}:${fill.tid}`;\n}\n\nexport function parseAssetName(assetName: string): {\n dex: string | null;\n symbol: string;\n} {\n const colonIndex = assetName.indexOf(':');\n if (colonIndex === -1) {\n return { dex: null, symbol: assetName };\n }\n return {\n dex: assetName.substring(0, colonIndex),\n symbol: assetName.substring(colonIndex + 1),\n };\n}\n\nexport function adaptHyperLiquidLedgerUpdateToUserHistoryItem(\n rawLedgerUpdates: RawLedgerUpdate[],\n): UserHistoryItem[] {\n return (rawLedgerUpdates || [])\n .filter((update) => {\n if (update.delta.type === 'deposit') {\n return true;\n }\n if (update.delta.type === 'withdraw') {\n return true;\n }\n if (update.delta.type === 'internalTransfer') {\n const usdc = Number.parseFloat(update.delta.usdc ?? '0');\n if (Number.isNaN(usdc)) {\n return false;\n }\n return usdc > 0;\n }\n return false;\n })\n .map((update) => {\n let amount = '0';\n let asset = 'USDC';\n\n if (hasProperty(update.delta, 'usdc') && update.delta.usdc) {\n amount = Math.abs(parseFloat(update.delta.usdc)).toString();\n }\n if (\n hasProperty(update.delta, 'coin') &&\n typeof update.delta.coin === 'string'\n ) {\n asset = update.delta.coin;\n }\n\n return {\n id: `history-${update.hash}`,\n timestamp: update.time,\n amount,\n asset,\n txHash: update.hash,\n status: 'completed' as const,\n type: update.delta.type === 'withdraw' ? 'withdrawal' : 'deposit',\n details: {\n source: '',\n bridgeContract: undefined,\n recipient: undefined,\n blockNumber: undefined,\n chainId: undefined,\n synthetic: undefined,\n },\n };\n });\n}\n\nconst HYPERLIQUID_ZERO_HASH = /^0x0+$/u;\nconst HYPERLIQUID_TRADE_SIDE = { B: 'buy', A: 'sell' } as const;\n\n/**\n * Adapt Hyperliquid public trades (REST `recentTrades` or WS `trades`) to\n * {@link PublicTrade}, newest first. Trades for another coin and malformed\n * trades are dropped. `side` is the aggressor's: `B` bought, `A` sold. The id\n * comes from {@link buildHyperLiquidFillId}, so both transports give one\n * execution the same id.\n *\n * @param trades - SDK trades.\n * @param symbol - Requested coin; other coins are dropped.\n * @returns The trades for `symbol`, newest first.\n */\nexport function adaptPublicTradesFromHyperLiquid(\n trades: readonly HyperLiquidPublicTrade[],\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const trade of trades) {\n if (trade.coin !== symbol) {\n continue;\n }\n const publicTrade = buildPublicTrade({\n id:\n typeof trade.tid === 'number'\n ? buildHyperLiquidFillId(trade)\n : undefined,\n symbol,\n price: trade.px,\n size: trade.sz,\n side: HYPERLIQUID_TRADE_SIDE[trade.side] ?? null,\n timestamp: trade.time,\n txHash:\n typeof trade.hash === 'string' &&\n !HYPERLIQUID_ZERO_HASH.test(trade.hash)\n ? trade.hash\n : undefined,\n providerId: 'hyperliquid',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(ad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AAC,IAAI,CAAC,IAAI,IAAI;YAChD,SAAS,EAAE,KAAK,CAAC,IAAI;YACrB,MAAM,EACJ,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;gBAC9B,CAAC,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;gBACrC,CAAC,CAAC,KAAK,CAAC,IAAI;gBACZ,CAAC,CAAC,SAAS;YACf,UAAU,EAAE,aAAa;SAC1B,CAAC,CAAC;QACH,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;IACD,OAAO,2BAA2B,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { hasProperty, Hex, isHexString } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BASIS_POINTS_DIVISOR,\n HIP3_ASSET_ID_CONFIG,\n isUnrestrictedMarginMode,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n DECIMAL_PRECISION_CONFIG,\n ORDER_SLIPPAGE_CONFIG,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n AssetPosition,\n FrontendOrder,\n ClearinghouseStateResponse,\n HyperLiquidPublicTrade,\n MetaResponse,\n SDKOrderParams,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n MarketInfo,\n Order,\n OrderParams as PerpsOrderParams,\n Position,\n PositionTriggerOrder,\n PublicTrade,\n RawLedgerUpdate,\n UserHistoryItem,\n} from '../types/index.js';\nimport type { TpslLinkage, TriggerOrderType } from '../types/perps-types.js';\nimport { resolveHyperLiquidMarginTiers } from './hyperLiquidPositionPreview.js';\nimport {\n buildTriggerOrderType,\n classifyTriggerDirection,\n getTriggerDirection,\n getTriggerExecution,\n isLimitExecutionOrderType,\n isTriggerOrderType,\n toSDKTimeInForce,\n} from './orderTypes.js';\nimport { roundToSignificantFiguresGrid } from './pricePrecision.js';\nimport {\n buildPublicTrade,\n sortPublicTradesNewestFirst,\n} from './publicTrades.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\ntype FrontendOrderWithParentTpsl = FrontendOrder & {\n takeProfitPrice?: unknown;\n stopLossPrice?: unknown;\n takeProfitOrderId?: unknown;\n stopLossOrderId?: unknown;\n};\n\nexport const HYPERLIQUID_SCALE_CLOID_MARKER = '4d4d5343';\n\n/**\n * Recover the Scale group shared by MetaMask-generated rung CLOIDs.\n *\n * @param clientOrderId - HyperLiquid client order ID.\n * @returns The Scale handle, or undefined for an unrelated order.\n */\nexport const readScaleGroupId = (\n clientOrderId: string | null | undefined,\n): string | undefined => {\n const normalized = clientOrderId?.toLowerCase();\n if (\n normalized?.length !== 34 ||\n !normalized.startsWith(`0x${HYPERLIQUID_SCALE_CLOID_MARKER}`)\n ) {\n return undefined;\n }\n return `scale:${normalized.slice(2, -2)}`;\n};\n\nconst readOptionalString = (value: unknown): string | undefined =>\n typeof value === 'string' && value.length > 0 ? value : undefined;\n\nconst readOptionalOrderId = (value: unknown): string | undefined => {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value.toString();\n }\n\n return undefined;\n};\n\nconst getParentTpslMetadata = (\n rawOrder: FrontendOrderWithParentTpsl,\n): {\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitOrderId?: string;\n stopLossOrderId?: string;\n} => ({\n takeProfitPrice: readOptionalString(rawOrder.takeProfitPrice),\n stopLossPrice: readOptionalString(rawOrder.stopLossPrice),\n takeProfitOrderId: readOptionalOrderId(rawOrder.takeProfitOrderId),\n stopLossOrderId: readOptionalOrderId(rawOrder.stopLossOrderId),\n});\n\n/**\n * HyperLiquid SDK Adapter Utilities\n *\n * These functions transform between MetaMask Perps API types and HyperLiquid SDK types.\n * The SDK uses cryptic property names for efficiency, but our API uses descriptive names\n * to provide a consistent interface across different perps protocols.\n */\n\nexport function adaptOrderToSDK(\n order: PerpsOrderParams,\n symbolToAssetId: Map<string, number>,\n): SDKOrderParams {\n const assetId = symbolToAssetId.get(order.symbol);\n if (assetId === undefined) {\n const availableDexs = new Set<string>();\n symbolToAssetId.forEach((_, symbol) => {\n if (symbol.includes(':')) {\n const dex = symbol.split(':')[0];\n availableDexs.add(dex);\n }\n });\n\n const dexHint =\n availableDexs.size > 0\n ? ` Available HIP-3 DEXs: ${Array.from(availableDexs).join(', ')}`\n : ' No HIP-3 DEXs currently available.';\n\n throw new Error(\n `Asset ${order.symbol} not found in asset mapping.${dexHint} Check console logs for \"HyperLiquidProvider: Asset mapping built\" to see available assets.`,\n );\n }\n\n return {\n a: assetId,\n b: order.isBuy,\n p: order.price ?? resolveTriggerCapPrice(order) ?? '0',\n s: order.size,\n r: order.reduceOnly ?? false,\n t: adaptOrderTypeToSDK(order),\n c:\n order.clientOrderId && isHexString(order.clientOrderId)\n ? order.clientOrderId\n : undefined,\n };\n}\n\n/**\n * Derive the slippage cap a market-on-trigger order submits as its price.\n *\n * A `stop_market` / `take_profit_market` order legitimately carries no limit\n * price, but the SDK still requires a positive `p` — it is the cap the order\n * fills against once the trigger fires, not a resting price. Sending `'0'`\n * fails SDK validation before the request is ever made.\n *\n * The cap follows the order's own tolerance, matching `calculateOrderPriceAndSize`\n * on the `placeOrder` path, so the same order priced through either route gets\n * the same execution bound.\n *\n * @param order - Order params carrying the placement type, trigger price, and\n * slippage tolerance.\n * @returns The formatted cap price, or undefined when the order needs no cap.\n */\nfunction resolveTriggerCapPrice(order: PerpsOrderParams): string | undefined {\n if (\n !isTriggerOrderType(order.orderType) ||\n isLimitExecutionOrderType(order.orderType) ||\n !order.triggerPrice\n ) {\n return undefined;\n }\n\n const triggerPrice = parseFloat(order.triggerPrice);\n if (!Number.isFinite(triggerPrice)) {\n return undefined;\n }\n\n // Accept the deprecated decimal `slippage` too, normalizing it to bps the way\n // `placeOrder` does, so neither spelling silently falls back to the default.\n const effectiveBps =\n order.maxSlippageBps ??\n (typeof order.slippage === 'number'\n ? Math.round(order.slippage * BASIS_POINTS_DIVISOR)\n : undefined) ??\n ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps;\n\n // Buying pays up to the cap, selling accepts down to it.\n const slippage = effectiveBps / BASIS_POINTS_DIVISOR;\n const capPrice = order.isBuy\n ? triggerPrice * (1 + slippage)\n : triggerPrice * (1 - slippage);\n\n return capPrice.toString();\n}\n\n/**\n * Map a placement type onto the SDK's order-type field.\n *\n * @param order - Order params carrying the placement type and trigger price\n * @returns The SDK order-type field\n */\nfunction adaptOrderTypeToSDK(order: PerpsOrderParams): SDKOrderParams['t'] {\n if (isTriggerOrderType(order.orderType)) {\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n if (!order.triggerPrice) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED);\n }\n\n return {\n trigger: {\n isMarket: !isLimitExecutionOrderType(order.orderType),\n triggerPx: order.triggerPrice,\n tpsl: getTriggerDirection(order.orderType) === 'stop' ? 'sl' : 'tp',\n },\n };\n }\n\n if (order.orderType === 'limit') {\n return { limit: { tif: toSDKTimeInForce(order.timeInForce) } };\n }\n if (order.timeInForce !== undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED);\n }\n return { limit: { tif: 'FrontendMarket' } };\n}\n\n/**\n * Map the provider-agnostic TP/SL linkage onto HyperLiquid's grouping vocabulary.\n *\n * @param linkage - How the attached TP/SL is linked.\n * @returns The HyperLiquid grouping value.\n */\nexport function adaptTpslLinkageToGrouping(\n linkage: TpslLinkage,\n): 'na' | 'normalTpsl' | 'positionTpsl' {\n switch (linkage) {\n case 'position':\n return 'positionTpsl';\n case 'order':\n return 'normalTpsl';\n default:\n return 'na';\n }\n}\n\n/**\n * Margin Hyperliquid shows for a cross position. When cross equity is below\n * the cross initial margin, the venue scales each cross position's margin by\n * `accountValue / totalMarginUsed`.\n *\n * @param marginUsed - The position's raw margin used.\n * @param crossMarginSummary - The clearinghouse's cross margin summary.\n * @returns The displayed margin, or undefined when an input is not a number.\n */\nfunction deriveCrossDisplayMarginUsed(\n marginUsed: string,\n crossMarginSummary: ClearinghouseStateResponse['crossMarginSummary'],\n): string | undefined {\n const margin = new BigNumber(marginUsed);\n const accountValue = new BigNumber(crossMarginSummary.accountValue);\n const totalMarginUsed = new BigNumber(crossMarginSummary.totalMarginUsed);\n if (\n !margin.isFinite() ||\n !accountValue.isFinite() ||\n !totalMarginUsed.isFinite()\n ) {\n return undefined;\n }\n if (totalMarginUsed.lte(0) || accountValue.gte(totalMarginUsed)) {\n return margin.toFixed();\n }\n return BigNumber.max(\n margin.times(accountValue).div(totalMarginUsed),\n 0,\n ).toFixed();\n}\n\n/**\n * Adapt a Hyperliquid asset position.\n *\n * @param assetPosition - Position from a clearinghouse state.\n * @param crossMarginSummary - That clearinghouse's `crossMarginSummary`. When\n * given, a cross position also carries `displayMarginUsed`.\n * @returns The position.\n */\nexport function adaptPositionFromSDK(\n assetPosition: AssetPosition,\n crossMarginSummary?: ClearinghouseStateResponse['crossMarginSummary'],\n): Position {\n const pos = assetPosition.position;\n const displayMarginUsed =\n pos.leverage.type === 'cross' && crossMarginSummary\n ? deriveCrossDisplayMarginUsed(pos.marginUsed, crossMarginSummary)\n : undefined;\n return {\n symbol: pos.coin,\n size: pos.szi,\n entryPrice: pos.entryPx,\n positionValue: pos.positionValue,\n unrealizedPnl: pos.unrealizedPnl,\n marginUsed: pos.marginUsed,\n ...(displayMarginUsed !== undefined && { displayMarginUsed }),\n leverage: {\n type: pos.leverage.type,\n value: pos.leverage.value,\n rawUsd:\n pos.leverage.type === 'isolated' ? pos.leverage.rawUsd : undefined,\n },\n liquidationPrice: pos.liquidationPx,\n maxLeverage: pos.maxLeverage,\n returnOnEquity: pos.returnOnEquity,\n cumulativeFunding: pos.cumFunding,\n takeProfitCount: 0,\n stopLossCount: 0,\n };\n}\n\nexport function adaptOrderFromSDK(\n rawOrder: FrontendOrder,\n position?: Position,\n): Order {\n // TODO: Remove this widened boundary type when FrontendOrder includes\n // takeProfitPrice/stopLossPrice and takeProfitOrderId/stopLossOrderId.\n const parentTpslMetadata = getParentTpslMetadata(rawOrder);\n\n // Extract basic fields with appropriate conversions\n const orderId = rawOrder.oid?.toString() || '';\n const symbol = rawOrder.coin;\n const side: 'buy' | 'sell' = rawOrder.side === 'B' ? 'buy' : 'sell';\n const detailedOrderType = rawOrder.orderType;\n const { isTrigger } = rawOrder;\n const { reduceOnly } = rawOrder;\n\n const triggerOrderType = adaptTriggerOrderTypeFromSDK(detailedOrderType);\n\n let orderType: 'limit' | 'market' = 'market';\n if (triggerOrderType) {\n // Trigger orders always carry a limitPx (the slippage cap for\n // market-on-trigger execution), so the placement type is the only reliable\n // source for how the order actually executes.\n orderType = getTriggerExecution(triggerOrderType);\n } else if (\n detailedOrderType?.toLowerCase().includes('limit') ||\n rawOrder.limitPx\n ) {\n orderType = 'limit';\n }\n\n const price = rawOrder.limitPx || rawOrder.triggerPx || '0';\n\n let size = rawOrder.sz;\n let originalSize = rawOrder.origSz || size;\n\n let currentSize = parseFloat(size);\n let origSize = parseFloat(originalSize);\n\n if (rawOrder.isPositionTpsl && origSize === 0 && position) {\n const absPositionSize = Math.abs(parseFloat(position.size));\n currentSize = absPositionSize;\n origSize = absPositionSize;\n size = absPositionSize.toString();\n originalSize = absPositionSize.toString();\n }\n\n const filledSize = origSize - currentSize;\n\n let takeProfitPrice: string | undefined;\n let stopLossPrice: string | undefined;\n let takeProfitOrderId: string | undefined;\n let stopLossOrderId: string | undefined;\n\n // TODO: We assume that there can only be 1 TP and 1 SL as children but there can be several TPSLs as children\n if (rawOrder.children && rawOrder.children.length > 0) {\n rawOrder.children.forEach((child) => {\n if (child.isTrigger && child.orderType) {\n if (child.orderType.includes('Take Profit')) {\n // HyperLiquid represents \"no trigger price\" as an empty string, not\n // null/undefined, so `||` (not `??`) is required to fall back to\n // limitPx when triggerPx is ''.\n takeProfitPrice = child.triggerPx || child.limitPx;\n takeProfitOrderId = child.oid.toString();\n } else if (child.orderType.includes('Stop')) {\n stopLossPrice = child.triggerPx || child.limitPx;\n stopLossOrderId = child.oid.toString();\n }\n }\n });\n }\n\n // Fallback: preserve parent-level TP/SL metadata when children are absent.\n takeProfitPrice ??= parentTpslMetadata.takeProfitPrice;\n stopLossPrice ??= parentTpslMetadata.stopLossPrice;\n takeProfitOrderId ??= parentTpslMetadata.takeProfitOrderId;\n stopLossOrderId ??= parentTpslMetadata.stopLossOrderId;\n\n // Build the order object\n const order: Order = {\n orderId,\n symbol,\n side,\n orderType,\n size,\n originalSize,\n price,\n filledSize: filledSize.toString(),\n remainingSize: size,\n status: 'open' as const,\n timestamp: rawOrder.timestamp,\n detailedOrderType,\n isTrigger,\n reduceOnly,\n };\n\n const strategyGroupId = readScaleGroupId(rawOrder.cloid);\n if (strategyGroupId) {\n order.strategyGroupId = strategyGroupId;\n }\n\n if (typeof rawOrder.isPositionTpsl === 'boolean') {\n order.isPositionTpsl = rawOrder.isPositionTpsl;\n }\n\n if (takeProfitPrice) {\n order.takeProfitPrice = takeProfitPrice;\n order.takeProfitOrderId = takeProfitOrderId;\n }\n if (stopLossPrice) {\n order.stopLossPrice = stopLossPrice;\n order.stopLossOrderId = stopLossOrderId;\n }\n if (rawOrder.triggerPx) {\n order.triggerPrice = rawOrder.triggerPx;\n }\n\n if (triggerOrderType) {\n order.triggerOrderType = triggerOrderType;\n }\n\n return order;\n}\n\n/**\n * Map HyperLiquid's human-readable order type string onto the provider-agnostic\n * trigger placement type.\n *\n * @param detailedOrderType - HyperLiquid `orderType` string (e.g. `'Stop Limit'`)\n * @returns The normalized trigger placement type, or undefined for non-trigger orders\n */\nexport function adaptTriggerOrderTypeFromSDK(\n detailedOrderType: string | undefined,\n): TriggerOrderType | undefined {\n if (!detailedOrderType) {\n return undefined;\n }\n\n const isTakeProfit = detailedOrderType.includes('Take Profit');\n const isStop = detailedOrderType.includes('Stop');\n\n if (!isTakeProfit && !isStop) {\n return undefined;\n }\n\n return buildTriggerOrderType({\n direction: isTakeProfit ? 'take_profit' : 'stop',\n execution: detailedOrderType.includes('Limit') ? 'limit' : 'market',\n });\n}\n\n/**\n * Build the position-state view of a trigger order attached to a position.\n *\n * HyperLiquid encodes \"the whole position\" as size `0` for position-bound TP/SL,\n * which is resolved here against the position size so consumers always see a\n * concrete quantity and can tell partial triggers apart.\n *\n * @param params - Mapping parameters\n * @param params.rawOrder - Raw HyperLiquid frontend order\n * @param params.positionSize - Signed or unsigned position size\n * @param params.entryPrice - Entry price, used to classify a trigger the exchange left unnamed\n * @returns The normalized trigger order, or undefined when the order is not a trigger\n */\nexport function adaptPositionTriggerOrderFromSDK(params: {\n rawOrder: Pick<\n FrontendOrder,\n 'oid' | 'orderType' | 'triggerPx' | 'limitPx' | 'sz' | 'reduceOnly'\n >;\n positionSize: string;\n entryPrice?: string;\n}): PositionTriggerOrder | undefined {\n const { rawOrder, positionSize, entryPrice } = params;\n\n const orderType = adaptTriggerOrderTypeFromSDK(rawOrder.orderType);\n\n // HyperLiquid uses '' for \"no trigger price\", so `||` (not `??`) is required.\n const triggerPrice = rawOrder.triggerPx || rawOrder.limitPx || '0';\n\n // Same rule as the WebSocket path: an unnamed trigger keeps its recoverable\n // direction and leaves its execution mode unstated, so both transports\n // report the same set of orders.\n const direction = orderType\n ? getTriggerDirection(orderType)\n : classifyTriggerDirection({ triggerPrice, entryPrice, positionSize });\n\n if (!direction) {\n return undefined;\n }\n const absolutePositionSize = Math.abs(parseFloat(positionSize || '0'));\n const rawSize = Math.abs(parseFloat(rawOrder.sz || '0'));\n\n // Position-bound TP/SL carries size 0, meaning the whole position.\n const size = rawSize > 0 ? rawSize : absolutePositionSize;\n\n return {\n orderId: rawOrder.oid.toString(),\n direction,\n orderType,\n triggerPrice,\n size: size.toString(),\n isPartial:\n rawSize > 0 && absolutePositionSize > 0 && rawSize < absolutePositionSize,\n reduceOnly: Boolean(rawOrder.reduceOnly),\n };\n}\n\n/**\n * Map one `meta.universe` entry to {@link MarketInfo}.\n *\n * @param sdkMarket - The venue market.\n * @param marginTables - `meta.marginTables` from the same response. Needed to\n * resolve tiered tables (ids of 50 and above); single-tier ids resolve\n * without it.\n * @returns The market, with `marginTiers` when the table resolves.\n */\nexport function adaptMarketFromSDK(\n sdkMarket: MetaResponse['universe'][number],\n marginTables?: MetaResponse['marginTables'],\n): MarketInfo {\n // The venue also sends `normal` (no restriction), which the SDK type omits.\n // `MarketInfo.marginMode` carries restrictions only, so drop it.\n const venueMarginMode: string | undefined = sdkMarket.marginMode;\n const marginTiers = resolveHyperLiquidMarginTiers({\n marginTableId: sdkMarket.marginTableId,\n maxLeverage: sdkMarket.maxLeverage,\n marginTables,\n });\n return {\n name: sdkMarket.name,\n szDecimals: sdkMarket.szDecimals,\n maxLeverage: sdkMarket.maxLeverage,\n marginTableId: sdkMarket.marginTableId,\n onlyIsolated: sdkMarket.onlyIsolated,\n ...(!isUnrestrictedMarginMode(venueMarginMode) && {\n marginMode: sdkMarket.marginMode,\n }),\n isDelisted: sdkMarket.isDelisted,\n ...(marginTiers && { marginTiers }),\n };\n}\n\n/**\n * Read one clearinghouse's cross-margin summary. A payload without the cross\n * fields reports none; present values must be finite decimals.\n *\n * @param perpsState - Clearinghouse state for one DEX.\n * @returns The summary, or undefined when the payload carries none.\n */\nfunction adaptCrossMarginSummaryFromSDK(\n perpsState: ClearinghouseStateResponse,\n): CrossMarginSummary | undefined {\n const { crossMarginSummary, crossMaintenanceMarginUsed } = perpsState;\n if (!crossMarginSummary || crossMaintenanceMarginUsed === undefined) {\n return undefined;\n }\n const summary: CrossMarginSummary = {\n accountValue: crossMarginSummary.accountValue,\n maintenanceMargin: crossMaintenanceMarginUsed,\n marginUsed: crossMarginSummary.totalMarginUsed,\n notional: crossMarginSummary.totalNtlPos,\n };\n for (const [field, value] of Object.entries(summary)) {\n if (parseFiniteDecimal(value) === null) {\n throw new Error(\n `Invalid HyperLiquid cross margin ${field} '${String(value)}'`,\n );\n }\n }\n return summary;\n}\n\n// Perps-only account adapter. Spot balances are layered on afterwards by\n// addSpotBalanceToAccountState, which enforces the USDC-only policy via\n// SPOT_COLLATERAL_COINS. Keeping spot logic out of here preserves a single\n// source of truth for spot balance math.\nexport function adaptAccountStateFromSDK(\n perpsState: ClearinghouseStateResponse,\n): AccountState {\n const { totalUnrealizedPnl, weightedReturnOnEquity } =\n perpsState.assetPositions.reduce(\n (acc, assetPos: AssetPosition) => {\n const unrealizedPnl = parseFloat(\n assetPos.position.unrealizedPnl || '0',\n );\n const marginUsed = parseFloat(assetPos.position.marginUsed || '0');\n const returnOnEquity = parseFloat(\n assetPos.position.returnOnEquity || '0',\n );\n acc.totalUnrealizedPnl += unrealizedPnl;\n acc.weightedReturnOnEquity += returnOnEquity * marginUsed;\n return acc;\n },\n {\n totalUnrealizedPnl: 0,\n weightedReturnOnEquity: 0,\n },\n );\n const totalMarginUsed = parseFloat(\n perpsState.marginSummary.totalMarginUsed || '0',\n );\n const totalReturnOnEquityPercentage =\n totalMarginUsed > 0\n ? ((weightedReturnOnEquity / totalMarginUsed) * 100).toString()\n : '0';\n\n const perpsBalance = parseFloat(perpsState.marginSummary.accountValue);\n\n const withdrawable = perpsState.withdrawable || '0';\n const crossMarginSummary = adaptCrossMarginSummaryFromSDK(perpsState);\n const accountState: AccountState = {\n spendableBalance: withdrawable,\n withdrawableBalance: withdrawable,\n totalBalance: perpsBalance.toString() || '0',\n marginUsed: perpsState.marginSummary.totalMarginUsed || '0',\n unrealizedPnl: totalUnrealizedPnl.toString() || '0',\n returnOnEquity: totalReturnOnEquityPercentage || '0',\n ...(crossMarginSummary ? { crossMarginSummary } : {}),\n };\n\n return accountState;\n}\n\nexport function buildAssetMapping(params: {\n metaUniverse: MetaResponse['universe'];\n dex?: string | null;\n perpDexIndex: number;\n}): {\n symbolToAssetId: Map<string, number>;\n assetIdToSymbol: Map<number, string>;\n} {\n const { metaUniverse, perpDexIndex } = params;\n const symbolToAssetId = new Map<string, number>();\n const assetIdToSymbol = new Map<number, string>();\n\n metaUniverse.forEach((asset, index) => {\n const assetId = calculateHip3AssetId(perpDexIndex, index);\n symbolToAssetId.set(asset.name, assetId);\n assetIdToSymbol.set(assetId, asset.name);\n });\n\n return { symbolToAssetId, assetIdToSymbol };\n}\n\nexport function formatHyperLiquidPrice(params: {\n price: string | number;\n szDecimals: number;\n}): string {\n const { price, szDecimals } = params;\n return roundToSignificantFiguresGrid(\n price,\n DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals,\n DECIMAL_PRECISION_CONFIG.MaxSignificantFigures,\n );\n}\n\nexport function formatHyperLiquidSize(params: {\n size: string | number;\n szDecimals: number;\n}): string {\n const { size, szDecimals } = params;\n const number = typeof size === 'string' ? parseFloat(size) : size;\n\n if (isNaN(number)) {\n return '0';\n }\n\n const formatted = number.toFixed(szDecimals);\n\n if (!formatted.includes('.')) {\n return formatted;\n }\n\n return formatted.replace(/\\.?0+$/u, '');\n}\n\nexport function calculatePositionSize(params: {\n usdValue: number;\n leverage: number;\n assetPrice: number;\n}): number {\n const { usdValue, leverage, assetPrice } = params;\n return (usdValue * leverage) / assetPrice;\n}\n\nexport function calculateHip3AssetId(\n perpDexIndex: number,\n indexInMeta: number,\n): number {\n if (perpDexIndex === 0) {\n return indexInMeta;\n }\n return (\n HIP3_ASSET_ID_CONFIG.BaseAssetId +\n perpDexIndex * HIP3_ASSET_ID_CONFIG.DexMultiplier +\n indexInMeta\n );\n}\n\n/**\n * Build the provider-neutral execution id for a HyperLiquid fill.\n *\n * HyperLiquid's `tid` is a 50-bit hash, and the venue documents\n * `(block_time, coin, tid)` as a trade's global identity, so all three go into\n * the id. REST and websocket fills report the same `time`, `coin` and `tid` for\n * one execution, so both transports yield the same id.\n *\n * @param fill - The raw HyperLiquid fill.\n * @param fill.coin - Venue asset name, including any HIP-3 dex prefix.\n * @param fill.time - Fill block time in milliseconds.\n * @param fill.tid - Venue trade id.\n * @returns The id, or `undefined` when the payload carries no `tid`. Omitting\n * it, rather than stringifying a missing value, keeps malformed fills from\n * sharing one id.\n */\nexport function buildHyperLiquidFillId(fill: {\n coin: string;\n time: number;\n tid?: number | null;\n}): string | undefined {\n if (fill.tid === undefined || fill.tid === null) {\n return undefined;\n }\n return `${fill.coin}:${fill.time}:${fill.tid}`;\n}\n\nexport function parseAssetName(assetName: string): {\n dex: string | null;\n symbol: string;\n} {\n const colonIndex = assetName.indexOf(':');\n if (colonIndex === -1) {\n return { dex: null, symbol: assetName };\n }\n return {\n dex: assetName.substring(0, colonIndex),\n symbol: assetName.substring(colonIndex + 1),\n };\n}\n\nexport function adaptHyperLiquidLedgerUpdateToUserHistoryItem(\n rawLedgerUpdates: RawLedgerUpdate[],\n): UserHistoryItem[] {\n return (rawLedgerUpdates || [])\n .filter((update) => {\n if (update.delta.type === 'deposit') {\n return true;\n }\n if (update.delta.type === 'withdraw') {\n return true;\n }\n if (update.delta.type === 'internalTransfer') {\n const usdc = Number.parseFloat(update.delta.usdc ?? '0');\n if (Number.isNaN(usdc)) {\n return false;\n }\n return usdc > 0;\n }\n return false;\n })\n .map((update) => {\n let amount = '0';\n let asset = 'USDC';\n\n if (hasProperty(update.delta, 'usdc') && update.delta.usdc) {\n amount = Math.abs(parseFloat(update.delta.usdc)).toString();\n }\n if (\n hasProperty(update.delta, 'coin') &&\n typeof update.delta.coin === 'string'\n ) {\n asset = update.delta.coin;\n }\n\n return {\n id: `history-${update.hash}`,\n timestamp: update.time,\n amount,\n asset,\n txHash: update.hash,\n status: 'completed' as const,\n type: update.delta.type === 'withdraw' ? 'withdrawal' : 'deposit',\n details: {\n source: '',\n bridgeContract: undefined,\n recipient: undefined,\n blockNumber: undefined,\n chainId: undefined,\n synthetic: undefined,\n },\n };\n });\n}\n\nconst HYPERLIQUID_ZERO_HASH = /^0x0+$/u;\nconst HYPERLIQUID_TRADE_SIDE = { B: 'buy', A: 'sell' } as const;\n\n/**\n * Adapt Hyperliquid public trades (REST `recentTrades` or WS `trades`) to\n * {@link PublicTrade}, newest first. Trades for another coin and malformed\n * trades are dropped. `side` is the aggressor's: `B` bought, `A` sold. The id\n * comes from {@link buildHyperLiquidFillId}, so both transports give one\n * execution the same id.\n *\n * @param trades - SDK trades.\n * @param symbol - Requested coin; other coins are dropped.\n * @returns The trades for `symbol`, newest first.\n */\nexport function adaptPublicTradesFromHyperLiquid(\n trades: readonly HyperLiquidPublicTrade[],\n symbol: string,\n): PublicTrade[] {\n const adapted: PublicTrade[] = [];\n for (const trade of trades) {\n if (trade.coin !== symbol) {\n continue;\n }\n const publicTrade = buildPublicTrade({\n id:\n typeof trade.tid === 'number'\n ? buildHyperLiquidFillId(trade)\n : undefined,\n symbol,\n price: trade.px,\n size: trade.sz,\n side: HYPERLIQUID_TRADE_SIDE[trade.side] ?? null,\n timestamp: trade.time,\n txHash:\n typeof trade.hash === 'string' &&\n !HYPERLIQUID_ZERO_HASH.test(trade.hash)\n ? trade.hash\n : undefined,\n providerId: 'hyperliquid',\n });\n if (publicTrade) {\n adapted.push(publicTrade);\n }\n }\n return sortPublicTradesNewestFirst(adapted);\n}\n"]}
|