@metamask-previews/perps-controller 22.3.0-preview-13e241f7f → 22.3.0-preview-693aef2bf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/PerpsController-method-action-types.d.ts +14 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +11 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +24 -0
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/perpsConfig.d.ts +16 -0
  10. package/dist/constants/perpsConfig.d.ts.map +1 -1
  11. package/dist/constants/perpsConfig.js +24 -0
  12. package/dist/constants/perpsConfig.js.map +1 -1
  13. package/dist/errors.d.ts +7 -0
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/errors.js +9 -0
  16. package/dist/errors.js.map +1 -1
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/perpsErrorCodes.d.ts +1 -0
  22. package/dist/perpsErrorCodes.d.ts.map +1 -1
  23. package/dist/perpsErrorCodes.js +1 -0
  24. package/dist/perpsErrorCodes.js.map +1 -1
  25. package/dist/providers/AggregatedPerpsProvider.d.ts +2 -1
  26. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  27. package/dist/providers/AggregatedPerpsProvider.js +9 -0
  28. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  29. package/dist/providers/HyperLiquidProvider.d.ts +19 -1
  30. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  31. package/dist/providers/HyperLiquidProvider.js +120 -26
  32. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  33. package/dist/providers/LighterProvider.d.ts +10 -1
  34. package/dist/providers/LighterProvider.d.ts.map +1 -1
  35. package/dist/providers/LighterProvider.js +12 -0
  36. package/dist/providers/LighterProvider.js.map +1 -1
  37. package/dist/services/TradingService.d.ts +17 -1
  38. package/dist/services/TradingService.d.ts.map +1 -1
  39. package/dist/services/TradingService.js +60 -4
  40. package/dist/services/TradingService.js.map +1 -1
  41. package/dist/types/index.d.ts +39 -0
  42. package/dist/types/index.d.ts.map +1 -1
  43. package/dist/types/index.js.map +1 -1
  44. package/dist/utils/orderCalculations.d.ts +2 -0
  45. package/dist/utils/orderCalculations.d.ts.map +1 -1
  46. package/dist/utils/orderCalculations.js +3 -1
  47. package/dist/utils/orderCalculations.js.map +1 -1
  48. package/dist/utils/perpsFormatters.d.ts +125 -53
  49. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  50. package/dist/utils/perpsFormatters.js +345 -202
  51. package/dist/utils/perpsFormatters.js.map +1 -1
  52. package/dist/utils/positionProtection.d.ts +10 -1
  53. package/dist/utils/positionProtection.d.ts.map +1 -1
  54. package/dist/utils/positionProtection.js +13 -0
  55. package/dist/utils/positionProtection.js.map +1 -1
  56. package/package.json +1 -1
@@ -31,7 +31,7 @@ import { transformMarketData } from '../utils/marketDataTransform.js';
31
31
  import { compileMarketPattern, shouldIncludeMarket, } from '../utils/marketUtils.js';
32
32
  import { buildOrdersArray, calculateFinalPositionSize, calculateOrderPriceAndSize, computeChaseQuotePrice, computeScalePriceLadder, floorToSizeDecimals, formatPartialTpslSize, getPriceTick, splitScaleSizes, validateOrderPrecision, } from '../utils/orderCalculations.js';
33
33
  import { getTriggerDirection, getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, isTriggerOrderType, resolvePositionTriggerSummaryPrice, toSDKTimeInForce, } from '../utils/orderTypes.js';
34
- import { assertExpectedPosition } from '../utils/positionProtection.js';
34
+ import { assertExpectedPosition, toPositionTpslLegPrices, } from '../utils/positionProtection.js';
35
35
  import { createStandaloneInfoClient, queryStandaloneClearinghouseStates, queryStandaloneOpenOrders, } from '../utils/standaloneInfoClient.js';
36
36
  import { parseBoundedNonNegativeDecimal } from '../utils/stringParseUtils.js';
37
37
  import { markSubscriptionCloid, quantizeBuilderFeeTenthsBps, } from '../utils/subscriptionFeeWaiver.js';
@@ -8473,6 +8473,60 @@ export class HyperLiquidProvider {
8473
8473
  * @returns A promise that resolves to the result.
8474
8474
  */
8475
8475
  async updatePositionTPSL(params) {
8476
+ return this.#replacePositionTpsl(params);
8477
+ }
8478
+ /**
8479
+ * Replace one TP/SL leg of a position and leave the other leg untouched.
8480
+ *
8481
+ * Only triggers on the requested side are cancelled (position-bound ones, and
8482
+ * standalone ones so two triggers on one side never rest together). The new
8483
+ * leg is placed with 'positionTpsl' grouping and size 0, so it keeps
8484
+ * protecting the whole position. The sibling leg keeps its order id. Triggers
8485
+ * that belong to a pending order are never touched.
8486
+ *
8487
+ * @param params - The operation parameters.
8488
+ * @param params.symbol - Asset symbol of the position
8489
+ * @param params.leg - 'tp' or 'sl'
8490
+ * @param params.triggerPrice - New trigger price for the leg
8491
+ * @param params.limitPrice - Fill price once triggered; omit for market
8492
+ * @param params.expectedPosition - Optional position precondition
8493
+ * @returns A promise that resolves to the result.
8494
+ */
8495
+ async replacePositionTPSLLeg(params) {
8496
+ const { symbol, leg, triggerPrice, limitPrice, maxSlippageBps, expectedPosition, } = params;
8497
+ if (leg !== 'tp' && leg !== 'sl') {
8498
+ return { success: false, error: `Unknown TP/SL leg: ${String(leg)}` };
8499
+ }
8500
+ // An empty or non-positive trigger would read as "remove this leg" below.
8501
+ // A replace never clears, so refuse it before anything is touched.
8502
+ if (!(parseFloat(triggerPrice) > 0)) {
8503
+ return {
8504
+ success: false,
8505
+ error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,
8506
+ };
8507
+ }
8508
+ if (limitPrice !== undefined && !(parseFloat(limitPrice) > 0)) {
8509
+ return { success: false, error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE };
8510
+ }
8511
+ return this.#replacePositionTpsl({
8512
+ symbol,
8513
+ ...(expectedPosition && { expectedPosition }),
8514
+ ...toPositionTpslLegPrices({ leg, triggerPrice }),
8515
+ }, { leg, limitPrice, maxSlippageBps });
8516
+ }
8517
+ /**
8518
+ * Shared write path for {@link updatePositionTPSL} and
8519
+ * {@link replacePositionTPSLLeg}. Without a leg scope it replaces every
8520
+ * TP/SL on the market; with one it only touches that leg.
8521
+ *
8522
+ * @param params - The TP/SL update parameters.
8523
+ * @param legScope - Restricts the replace to one leg and its execution.
8524
+ * @returns A promise that resolves to the result.
8525
+ */
8526
+ async #replacePositionTpsl(params, legScope) {
8527
+ const operationName = legScope
8528
+ ? 'replacePositionTPSLLeg'
8529
+ : 'updatePositionTPSL';
8476
8530
  const expectedPosition = params.expectedPosition === undefined
8477
8531
  ? undefined
8478
8532
  : { ...params.expectedPosition };
@@ -8495,7 +8549,7 @@ export class HyperLiquidProvider {
8495
8549
  };
8496
8550
  const assertScope = async () => {
8497
8551
  const current = await this.#walletService.getUserAddressWithDefault();
8498
- this.#assertProviderLifecycleCurrent(lifecycle, 'updatePositionTPSL');
8552
+ this.#assertProviderLifecycleCurrent(lifecycle, operationName);
8499
8553
  if (current.toLowerCase() !== userAddress.toLowerCase() ||
8500
8554
  this.#clientService.isTestnetMode() !== isTestnet) {
8501
8555
  throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
@@ -8577,6 +8631,7 @@ export class HyperLiquidProvider {
8577
8631
  throw new Error(`Asset ${symbol} not found in ${dexName ?? 'main'} DEX universe`);
8578
8632
  }
8579
8633
  const precision = validateOrderPrecision({
8634
+ price: legScope?.limitPrice,
8580
8635
  takeProfitPrice,
8581
8636
  stopLossPrice,
8582
8637
  takeProfitSize,
@@ -8614,6 +8669,13 @@ export class HyperLiquidProvider {
8614
8669
  // HyperLiquid accepts one builder context for the whole TP/SL action.
8615
8670
  // Position TP/SL has no parent policy to inherit, so resolve every
8616
8671
  // included trigger and charge the batch when any child policy charges.
8672
+ // The price each leg fills at once triggered; undefined executes at
8673
+ // market. A whole-position update fills TP as a limit at its trigger and
8674
+ // SL at market. A leg replace fills at its limit price, else at market.
8675
+ const takeProfitFillPrice = legScope
8676
+ ? legScope.limitPrice
8677
+ : takeProfitPrice;
8678
+ const stopLossFillPrice = legScope?.limitPrice;
8617
8679
  const feePolicyContexts = [
8618
8680
  ...(takeProfitPrice
8619
8681
  ? [
@@ -8621,8 +8683,12 @@ export class HyperLiquidProvider {
8621
8683
  symbol,
8622
8684
  isBuy: !isLong,
8623
8685
  size: resolveTpslSize(takeProfitSize),
8624
- orderType: 'take_profit_limit',
8625
- price: takeProfitPrice,
8686
+ orderType: takeProfitFillPrice === undefined
8687
+ ? 'take_profit_market'
8688
+ : 'take_profit_limit',
8689
+ ...(takeProfitFillPrice !== undefined && {
8690
+ price: takeProfitFillPrice,
8691
+ }),
8626
8692
  triggerPrice: takeProfitPrice,
8627
8693
  reduceOnly: true,
8628
8694
  },
@@ -8634,7 +8700,12 @@ export class HyperLiquidProvider {
8634
8700
  symbol,
8635
8701
  isBuy: !isLong,
8636
8702
  size: resolveTpslSize(stopLossSize),
8637
- orderType: 'stop_market',
8703
+ orderType: stopLossFillPrice === undefined
8704
+ ? 'stop_market'
8705
+ : 'stop_limit',
8706
+ ...(stopLossFillPrice !== undefined && {
8707
+ price: stopLossFillPrice,
8708
+ }),
8638
8709
  triggerPrice: stopLossPrice,
8639
8710
  reduceOnly: true,
8640
8711
  },
@@ -8703,6 +8774,14 @@ export class HyperLiquidProvider {
8703
8774
  }
8704
8775
  });
8705
8776
  };
8777
+ // A leg replace cancels only triggers on its own side, so the sibling
8778
+ // leg keeps its order. A whole-position update considers both sides.
8779
+ const isInLegScope = (orderType) => {
8780
+ if (!legScope) {
8781
+ return true;
8782
+ }
8783
+ return Boolean(orderType?.includes(legScope.leg === 'tp' ? 'Take Profit' : 'Stop'));
8784
+ };
8706
8785
  // Use atomic getter to prevent race condition between check and get
8707
8786
  const cachedOrders = this.#subscriptionService.getOrdersCacheIfInitialized();
8708
8787
  // Replacing TP/SL has to consider standalone ('na' grouping) triggers —
@@ -8721,7 +8800,8 @@ export class HyperLiquidProvider {
8721
8800
  Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&
8722
8801
  order.detailedOrderType &&
8723
8802
  (order.detailedOrderType.includes('Take Profit') ||
8724
- order.detailedOrderType.includes('Stop'))));
8803
+ order.detailedOrderType.includes('Stop')) &&
8804
+ isInLegScope(order.detailedOrderType)));
8725
8805
  if (cachedOrders === null ||
8726
8806
  isPartialTpsl ||
8727
8807
  cacheShowsStandaloneTriggers) {
@@ -8749,7 +8829,8 @@ export class HyperLiquidProvider {
8749
8829
  !childOrderIds.has(order.oid)) &&
8750
8830
  order.isTrigger &&
8751
8831
  (order.orderType.includes('Take Profit') ||
8752
- order.orderType.includes('Stop')));
8832
+ order.orderType.includes('Stop')) &&
8833
+ isInLegScope(order.orderType));
8753
8834
  captureRestorableTpslOrders(tpslOrders.map((order) => adaptOrderFromSDK(order, position)));
8754
8835
  cancelRequests = tpslOrders.map((order) => ({
8755
8836
  a: assetId,
@@ -8773,7 +8854,8 @@ export class HyperLiquidProvider {
8773
8854
  Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&
8774
8855
  order.detailedOrderType &&
8775
8856
  (order.detailedOrderType.includes('Take Profit') ||
8776
- order.detailedOrderType.includes('Stop')));
8857
+ order.detailedOrderType.includes('Stop')) &&
8858
+ isInLegScope(order.detailedOrderType));
8777
8859
  captureRestorableTpslOrders(tpslOrders);
8778
8860
  cancelRequests = tpslOrders.map((order) => ({
8779
8861
  a: assetId,
@@ -8782,20 +8864,35 @@ export class HyperLiquidProvider {
8782
8864
  }
8783
8865
  // Build orders array for TP/SL
8784
8866
  const orders = [];
8867
+ // The limit HyperLiquid fills a leg at once triggered. A replaced market
8868
+ // leg is capped like any market trigger: its trigger moved against the
8869
+ // closing side by the slippage tolerance. A whole-position update keeps
8870
+ // its existing prices.
8871
+ const legOrderPrice = (orderType, triggerPrice, fillPrice) => legScope && fillPrice === undefined
8872
+ ? calculateOrderPriceAndSize({
8873
+ orderType,
8874
+ isBuy: !isLong,
8875
+ finalPositionSize: 0,
8876
+ currentPrice: 0,
8877
+ triggerPrice,
8878
+ maxSlippageBps: legScope.maxSlippageBps,
8879
+ szDecimals: assetInfo.szDecimals,
8880
+ }).formattedPrice
8881
+ : formatHyperLiquidPrice({
8882
+ price: parseFloat(fillPrice ?? triggerPrice),
8883
+ szDecimals: assetInfo.szDecimals,
8884
+ });
8785
8885
  // Take Profit order
8786
8886
  if (takeProfitPrice) {
8787
8887
  const tpOrder = {
8788
8888
  a: assetId,
8789
8889
  b: !isLong, // Opposite side to close position
8790
- p: formatHyperLiquidPrice({
8791
- price: parseFloat(takeProfitPrice),
8792
- szDecimals: assetInfo.szDecimals,
8793
- }),
8890
+ p: legOrderPrice('take_profit_market', takeProfitPrice, takeProfitFillPrice),
8794
8891
  s: resolveTpslSize(takeProfitSize),
8795
8892
  r: true, // Always reduce-only for position TP
8796
8893
  t: {
8797
8894
  trigger: {
8798
- isMarket: false, // Limit order when triggered
8895
+ isMarket: takeProfitFillPrice === undefined,
8799
8896
  triggerPx: formatHyperLiquidPrice({
8800
8897
  price: parseFloat(takeProfitPrice),
8801
8898
  szDecimals: assetInfo.szDecimals,
@@ -8811,15 +8908,12 @@ export class HyperLiquidProvider {
8811
8908
  const slOrder = {
8812
8909
  a: assetId,
8813
8910
  b: !isLong, // Opposite side to close position
8814
- p: formatHyperLiquidPrice({
8815
- price: parseFloat(stopLossPrice),
8816
- szDecimals: assetInfo.szDecimals,
8817
- }),
8911
+ p: legOrderPrice('stop_market', stopLossPrice, stopLossFillPrice),
8818
8912
  s: resolveTpslSize(stopLossSize),
8819
8913
  r: true, // Always reduce-only for position SL
8820
8914
  t: {
8821
8915
  trigger: {
8822
- isMarket: true, // Market order when triggered for faster execution
8916
+ isMarket: stopLossFillPrice === undefined,
8823
8917
  triggerPx: formatHyperLiquidPrice({
8824
8918
  price: parseFloat(stopLossPrice),
8825
8919
  szDecimals: assetInfo.szDecimals,
@@ -8976,7 +9070,7 @@ export class HyperLiquidProvider {
8976
9070
  await assertScope();
8977
9071
  if (!signerFailure) {
8978
9072
  this.#deps.logger.error(restorationFailure ??
8979
- new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), this.#getErrorContext('updatePositionTPSL', {
9073
+ new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), this.#getErrorContext(operationName, {
8980
9074
  symbol,
8981
9075
  stage: 'restoration',
8982
9076
  protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,
@@ -9013,7 +9107,7 @@ export class HyperLiquidProvider {
9013
9107
  // of the old protection restores it below.
9014
9108
  if (oldCancellation.signerFailure &&
9015
9109
  (orders.length === 0 || oldCancellation.cancelledOrderIds.length === 0)) {
9016
- this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
9110
+ this.#logRetryableSignerFailure(operationName, { symbol });
9017
9111
  return createErrorResult(oldCancellation.signerFailure, {
9018
9112
  success: false,
9019
9113
  });
@@ -9045,7 +9139,7 @@ export class HyperLiquidProvider {
9045
9139
  catch (error) {
9046
9140
  this.#deps.debugLogger.log('Could not reconcile TP/SL protection after an incomplete cancel', {
9047
9141
  symbol,
9048
- error: ensureError(error, 'HyperLiquidProvider.updatePositionTPSL.reconcileProtection').message,
9142
+ error: ensureError(error, `HyperLiquidProvider.${operationName}.reconcileProtection`).message,
9049
9143
  });
9050
9144
  }
9051
9145
  await assertScope();
@@ -9067,14 +9161,14 @@ export class HyperLiquidProvider {
9067
9161
  ]),
9068
9162
  ];
9069
9163
  if (oldCancellation.signerFailure) {
9070
- this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
9164
+ this.#logRetryableSignerFailure(operationName, { symbol });
9071
9165
  return createErrorResult(oldCancellation.signerFailure, {
9072
9166
  success: false,
9073
9167
  childOrderIds: survivingOrderIds,
9074
9168
  });
9075
9169
  }
9076
9170
  const updateError = new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
9077
- this.#deps.logger.error(updateError, this.#getErrorContext('updatePositionTPSL', {
9171
+ this.#deps.logger.error(updateError, this.#getErrorContext(operationName, {
9078
9172
  symbol: params.symbol,
9079
9173
  hasTakeProfit: params.takeProfitPrice !== undefined,
9080
9174
  hasStopLoss: params.stopLossPrice !== undefined,
@@ -9233,7 +9327,7 @@ export class HyperLiquidProvider {
9233
9327
  ...remainingReplacementIds.map(String),
9234
9328
  ];
9235
9329
  if (cleanupFailure && recoverableOrderIds.length > 0) {
9236
- this.#deps.logger.error(cleanupFailure, this.#getErrorContext('updatePositionTPSL', {
9330
+ this.#deps.logger.error(cleanupFailure, this.#getErrorContext(operationName, {
9237
9331
  symbol,
9238
9332
  stage: 'cleanup',
9239
9333
  protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,
@@ -9272,11 +9366,11 @@ export class HyperLiquidProvider {
9272
9366
  });
9273
9367
  }
9274
9368
  catch (error) {
9275
- const signerFailure = await this.#handleSignerFailure(error, 'updatePositionTPSL', { symbol: params.symbol });
9369
+ const signerFailure = await this.#handleSignerFailure(error, operationName, { symbol: params.symbol });
9276
9370
  if (signerFailure) {
9277
9371
  return createErrorResult(signerFailure, { success: false });
9278
9372
  }
9279
- this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'), this.#getErrorContext('updatePositionTPSL', {
9373
+ this.#deps.logger.error(ensureError(error, `HyperLiquidProvider.${operationName}`), this.#getErrorContext(operationName, {
9280
9374
  symbol: params.symbol,
9281
9375
  hasTakeProfit: params.takeProfitPrice !== undefined,
9282
9376
  hasStopLoss: params.stopLossPrice !== undefined,