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

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 +0 -30
  2. package/dist/PerpsController-method-action-types.d.ts +1 -14
  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 +1 -11
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +0 -24
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/perpsConfig.d.ts +0 -16
  10. package/dist/constants/perpsConfig.d.ts.map +1 -1
  11. package/dist/constants/perpsConfig.js +0 -24
  12. package/dist/constants/perpsConfig.js.map +1 -1
  13. package/dist/errors.d.ts +0 -7
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/errors.js +0 -9
  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 +0 -1
  22. package/dist/perpsErrorCodes.d.ts.map +1 -1
  23. package/dist/perpsErrorCodes.js +0 -1
  24. package/dist/perpsErrorCodes.js.map +1 -1
  25. package/dist/providers/AggregatedPerpsProvider.d.ts +1 -2
  26. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  27. package/dist/providers/AggregatedPerpsProvider.js +0 -9
  28. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  29. package/dist/providers/HyperLiquidProvider.d.ts +1 -19
  30. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  31. package/dist/providers/HyperLiquidProvider.js +26 -120
  32. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  33. package/dist/providers/LighterProvider.d.ts +1 -10
  34. package/dist/providers/LighterProvider.d.ts.map +1 -1
  35. package/dist/providers/LighterProvider.js +0 -12
  36. package/dist/providers/LighterProvider.js.map +1 -1
  37. package/dist/services/TradingService.d.ts +1 -17
  38. package/dist/services/TradingService.d.ts.map +1 -1
  39. package/dist/services/TradingService.js +4 -60
  40. package/dist/services/TradingService.js.map +1 -1
  41. package/dist/types/index.d.ts +0 -39
  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 +0 -2
  45. package/dist/utils/orderCalculations.d.ts.map +1 -1
  46. package/dist/utils/orderCalculations.js +1 -3
  47. package/dist/utils/orderCalculations.js.map +1 -1
  48. package/dist/utils/perpsFormatters.d.ts +53 -125
  49. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  50. package/dist/utils/perpsFormatters.js +202 -345
  51. package/dist/utils/perpsFormatters.js.map +1 -1
  52. package/dist/utils/positionProtection.d.ts +1 -10
  53. package/dist/utils/positionProtection.d.ts.map +1 -1
  54. package/dist/utils/positionProtection.js +0 -13
  55. package/dist/utils/positionProtection.js.map +1 -1
  56. package/package.json +1 -2
@@ -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, toPositionTpslLegPrices, } from '../utils/positionProtection.js';
34
+ import { assertExpectedPosition } 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,60 +8473,6 @@ 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';
8530
8476
  const expectedPosition = params.expectedPosition === undefined
8531
8477
  ? undefined
8532
8478
  : { ...params.expectedPosition };
@@ -8549,7 +8495,7 @@ export class HyperLiquidProvider {
8549
8495
  };
8550
8496
  const assertScope = async () => {
8551
8497
  const current = await this.#walletService.getUserAddressWithDefault();
8552
- this.#assertProviderLifecycleCurrent(lifecycle, operationName);
8498
+ this.#assertProviderLifecycleCurrent(lifecycle, 'updatePositionTPSL');
8553
8499
  if (current.toLowerCase() !== userAddress.toLowerCase() ||
8554
8500
  this.#clientService.isTestnetMode() !== isTestnet) {
8555
8501
  throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
@@ -8631,7 +8577,6 @@ export class HyperLiquidProvider {
8631
8577
  throw new Error(`Asset ${symbol} not found in ${dexName ?? 'main'} DEX universe`);
8632
8578
  }
8633
8579
  const precision = validateOrderPrecision({
8634
- price: legScope?.limitPrice,
8635
8580
  takeProfitPrice,
8636
8581
  stopLossPrice,
8637
8582
  takeProfitSize,
@@ -8669,13 +8614,6 @@ export class HyperLiquidProvider {
8669
8614
  // HyperLiquid accepts one builder context for the whole TP/SL action.
8670
8615
  // Position TP/SL has no parent policy to inherit, so resolve every
8671
8616
  // 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;
8679
8617
  const feePolicyContexts = [
8680
8618
  ...(takeProfitPrice
8681
8619
  ? [
@@ -8683,12 +8621,8 @@ export class HyperLiquidProvider {
8683
8621
  symbol,
8684
8622
  isBuy: !isLong,
8685
8623
  size: resolveTpslSize(takeProfitSize),
8686
- orderType: takeProfitFillPrice === undefined
8687
- ? 'take_profit_market'
8688
- : 'take_profit_limit',
8689
- ...(takeProfitFillPrice !== undefined && {
8690
- price: takeProfitFillPrice,
8691
- }),
8624
+ orderType: 'take_profit_limit',
8625
+ price: takeProfitPrice,
8692
8626
  triggerPrice: takeProfitPrice,
8693
8627
  reduceOnly: true,
8694
8628
  },
@@ -8700,12 +8634,7 @@ export class HyperLiquidProvider {
8700
8634
  symbol,
8701
8635
  isBuy: !isLong,
8702
8636
  size: resolveTpslSize(stopLossSize),
8703
- orderType: stopLossFillPrice === undefined
8704
- ? 'stop_market'
8705
- : 'stop_limit',
8706
- ...(stopLossFillPrice !== undefined && {
8707
- price: stopLossFillPrice,
8708
- }),
8637
+ orderType: 'stop_market',
8709
8638
  triggerPrice: stopLossPrice,
8710
8639
  reduceOnly: true,
8711
8640
  },
@@ -8774,14 +8703,6 @@ export class HyperLiquidProvider {
8774
8703
  }
8775
8704
  });
8776
8705
  };
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
- };
8785
8706
  // Use atomic getter to prevent race condition between check and get
8786
8707
  const cachedOrders = this.#subscriptionService.getOrdersCacheIfInitialized();
8787
8708
  // Replacing TP/SL has to consider standalone ('na' grouping) triggers —
@@ -8800,8 +8721,7 @@ export class HyperLiquidProvider {
8800
8721
  Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&
8801
8722
  order.detailedOrderType &&
8802
8723
  (order.detailedOrderType.includes('Take Profit') ||
8803
- order.detailedOrderType.includes('Stop')) &&
8804
- isInLegScope(order.detailedOrderType)));
8724
+ order.detailedOrderType.includes('Stop'))));
8805
8725
  if (cachedOrders === null ||
8806
8726
  isPartialTpsl ||
8807
8727
  cacheShowsStandaloneTriggers) {
@@ -8829,8 +8749,7 @@ export class HyperLiquidProvider {
8829
8749
  !childOrderIds.has(order.oid)) &&
8830
8750
  order.isTrigger &&
8831
8751
  (order.orderType.includes('Take Profit') ||
8832
- order.orderType.includes('Stop')) &&
8833
- isInLegScope(order.orderType));
8752
+ order.orderType.includes('Stop')));
8834
8753
  captureRestorableTpslOrders(tpslOrders.map((order) => adaptOrderFromSDK(order, position)));
8835
8754
  cancelRequests = tpslOrders.map((order) => ({
8836
8755
  a: assetId,
@@ -8854,8 +8773,7 @@ export class HyperLiquidProvider {
8854
8773
  Boolean(TP_SL_CONFIG.UsePositionBoundTpsl) &&
8855
8774
  order.detailedOrderType &&
8856
8775
  (order.detailedOrderType.includes('Take Profit') ||
8857
- order.detailedOrderType.includes('Stop')) &&
8858
- isInLegScope(order.detailedOrderType));
8776
+ order.detailedOrderType.includes('Stop')));
8859
8777
  captureRestorableTpslOrders(tpslOrders);
8860
8778
  cancelRequests = tpslOrders.map((order) => ({
8861
8779
  a: assetId,
@@ -8864,35 +8782,20 @@ export class HyperLiquidProvider {
8864
8782
  }
8865
8783
  // Build orders array for TP/SL
8866
8784
  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
- });
8885
8785
  // Take Profit order
8886
8786
  if (takeProfitPrice) {
8887
8787
  const tpOrder = {
8888
8788
  a: assetId,
8889
8789
  b: !isLong, // Opposite side to close position
8890
- p: legOrderPrice('take_profit_market', takeProfitPrice, takeProfitFillPrice),
8790
+ p: formatHyperLiquidPrice({
8791
+ price: parseFloat(takeProfitPrice),
8792
+ szDecimals: assetInfo.szDecimals,
8793
+ }),
8891
8794
  s: resolveTpslSize(takeProfitSize),
8892
8795
  r: true, // Always reduce-only for position TP
8893
8796
  t: {
8894
8797
  trigger: {
8895
- isMarket: takeProfitFillPrice === undefined,
8798
+ isMarket: false, // Limit order when triggered
8896
8799
  triggerPx: formatHyperLiquidPrice({
8897
8800
  price: parseFloat(takeProfitPrice),
8898
8801
  szDecimals: assetInfo.szDecimals,
@@ -8908,12 +8811,15 @@ export class HyperLiquidProvider {
8908
8811
  const slOrder = {
8909
8812
  a: assetId,
8910
8813
  b: !isLong, // Opposite side to close position
8911
- p: legOrderPrice('stop_market', stopLossPrice, stopLossFillPrice),
8814
+ p: formatHyperLiquidPrice({
8815
+ price: parseFloat(stopLossPrice),
8816
+ szDecimals: assetInfo.szDecimals,
8817
+ }),
8912
8818
  s: resolveTpslSize(stopLossSize),
8913
8819
  r: true, // Always reduce-only for position SL
8914
8820
  t: {
8915
8821
  trigger: {
8916
- isMarket: stopLossFillPrice === undefined,
8822
+ isMarket: true, // Market order when triggered for faster execution
8917
8823
  triggerPx: formatHyperLiquidPrice({
8918
8824
  price: parseFloat(stopLossPrice),
8919
8825
  szDecimals: assetInfo.szDecimals,
@@ -9070,7 +8976,7 @@ export class HyperLiquidProvider {
9070
8976
  await assertScope();
9071
8977
  if (!signerFailure) {
9072
8978
  this.#deps.logger.error(restorationFailure ??
9073
- new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), this.#getErrorContext(operationName, {
8979
+ new Error(PERPS_ERROR_CODES.TPSL_PROTECTION_LOST), this.#getErrorContext('updatePositionTPSL', {
9074
8980
  symbol,
9075
8981
  stage: 'restoration',
9076
8982
  protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,
@@ -9107,7 +9013,7 @@ export class HyperLiquidProvider {
9107
9013
  // of the old protection restores it below.
9108
9014
  if (oldCancellation.signerFailure &&
9109
9015
  (orders.length === 0 || oldCancellation.cancelledOrderIds.length === 0)) {
9110
- this.#logRetryableSignerFailure(operationName, { symbol });
9016
+ this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
9111
9017
  return createErrorResult(oldCancellation.signerFailure, {
9112
9018
  success: false,
9113
9019
  });
@@ -9139,7 +9045,7 @@ export class HyperLiquidProvider {
9139
9045
  catch (error) {
9140
9046
  this.#deps.debugLogger.log('Could not reconcile TP/SL protection after an incomplete cancel', {
9141
9047
  symbol,
9142
- error: ensureError(error, `HyperLiquidProvider.${operationName}.reconcileProtection`).message,
9048
+ error: ensureError(error, 'HyperLiquidProvider.updatePositionTPSL.reconcileProtection').message,
9143
9049
  });
9144
9050
  }
9145
9051
  await assertScope();
@@ -9161,14 +9067,14 @@ export class HyperLiquidProvider {
9161
9067
  ]),
9162
9068
  ];
9163
9069
  if (oldCancellation.signerFailure) {
9164
- this.#logRetryableSignerFailure(operationName, { symbol });
9070
+ this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
9165
9071
  return createErrorResult(oldCancellation.signerFailure, {
9166
9072
  success: false,
9167
9073
  childOrderIds: survivingOrderIds,
9168
9074
  });
9169
9075
  }
9170
9076
  const updateError = new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
9171
- this.#deps.logger.error(updateError, this.#getErrorContext(operationName, {
9077
+ this.#deps.logger.error(updateError, this.#getErrorContext('updatePositionTPSL', {
9172
9078
  symbol: params.symbol,
9173
9079
  hasTakeProfit: params.takeProfitPrice !== undefined,
9174
9080
  hasStopLoss: params.stopLossPrice !== undefined,
@@ -9327,7 +9233,7 @@ export class HyperLiquidProvider {
9327
9233
  ...remainingReplacementIds.map(String),
9328
9234
  ];
9329
9235
  if (cleanupFailure && recoverableOrderIds.length > 0) {
9330
- this.#deps.logger.error(cleanupFailure, this.#getErrorContext(operationName, {
9236
+ this.#deps.logger.error(cleanupFailure, this.#getErrorContext('updatePositionTPSL', {
9331
9237
  symbol,
9332
9238
  stage: 'cleanup',
9333
9239
  protectionStatus: PERPS_ERROR_CODES.TPSL_PROTECTION_LOST,
@@ -9366,11 +9272,11 @@ export class HyperLiquidProvider {
9366
9272
  });
9367
9273
  }
9368
9274
  catch (error) {
9369
- const signerFailure = await this.#handleSignerFailure(error, operationName, { symbol: params.symbol });
9275
+ const signerFailure = await this.#handleSignerFailure(error, 'updatePositionTPSL', { symbol: params.symbol });
9370
9276
  if (signerFailure) {
9371
9277
  return createErrorResult(signerFailure, { success: false });
9372
9278
  }
9373
- this.#deps.logger.error(ensureError(error, `HyperLiquidProvider.${operationName}`), this.#getErrorContext(operationName, {
9279
+ this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'), this.#getErrorContext('updatePositionTPSL', {
9374
9280
  symbol: params.symbol,
9375
9281
  hasTakeProfit: params.takeProfitPrice !== undefined,
9376
9282
  hasStopLoss: params.stopLossPrice !== undefined,