@metamask-previews/perps-controller 19.0.0-preview-8cc0f94 → 19.0.0-preview-cbae429b5

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 (114) hide show
  1. package/CHANGELOG.md +3 -114
  2. package/README.md +1 -586
  3. package/dist/PerpsController-method-action-types.d.ts +14 -133
  4. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -1
  6. package/dist/PerpsController.d.ts +14 -111
  7. package/dist/PerpsController.d.ts.map +1 -1
  8. package/dist/PerpsController.js +42 -507
  9. package/dist/PerpsController.js.map +1 -1
  10. package/dist/aggregation/SubscriptionMultiplexer.d.ts +3 -7
  11. package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
  12. package/dist/aggregation/SubscriptionMultiplexer.js +2 -4
  13. package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
  14. package/dist/constants/hyperLiquidConfig.d.ts +1 -15
  15. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  16. package/dist/constants/hyperLiquidConfig.js +2 -16
  17. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  18. package/dist/constants/lighterConfig.d.ts +1 -61
  19. package/dist/constants/lighterConfig.d.ts.map +1 -1
  20. package/dist/constants/lighterConfig.js +1 -62
  21. package/dist/constants/lighterConfig.js.map +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/perpsErrorCodes.d.ts +0 -1
  26. package/dist/perpsErrorCodes.d.ts.map +1 -1
  27. package/dist/perpsErrorCodes.js +0 -1
  28. package/dist/perpsErrorCodes.js.map +1 -1
  29. package/dist/providers/AggregatedPerpsProvider.d.ts +4 -69
  30. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  31. package/dist/providers/AggregatedPerpsProvider.js +7 -176
  32. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  33. package/dist/providers/HyperLiquidProvider.d.ts +5 -5
  34. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  35. package/dist/providers/HyperLiquidProvider.js +145 -416
  36. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  37. package/dist/providers/LighterProvider.d.ts +57 -149
  38. package/dist/providers/LighterProvider.d.ts.map +1 -1
  39. package/dist/providers/LighterProvider.js +1119 -8262
  40. package/dist/providers/LighterProvider.js.map +1 -1
  41. package/dist/services/HyperLiquidClientService.d.ts +2 -3
  42. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  43. package/dist/services/HyperLiquidClientService.js +3 -14
  44. package/dist/services/HyperLiquidClientService.js.map +1 -1
  45. package/dist/services/LighterClientService.d.ts +2 -30
  46. package/dist/services/LighterClientService.d.ts.map +1 -1
  47. package/dist/services/LighterClientService.js +10 -151
  48. package/dist/services/LighterClientService.js.map +1 -1
  49. package/dist/services/TradingService.d.ts.map +1 -1
  50. package/dist/services/TradingService.js +2 -23
  51. package/dist/services/TradingService.js.map +1 -1
  52. package/dist/types/index.d.ts +21 -402
  53. package/dist/types/index.d.ts.map +1 -1
  54. package/dist/types/index.js.map +1 -1
  55. package/dist/types/lighter-types.d.ts +1 -94
  56. package/dist/types/lighter-types.d.ts.map +1 -1
  57. package/dist/types/lighter-types.js.map +1 -1
  58. package/dist/utils/lighterAdapter.d.ts +0 -7
  59. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  60. package/dist/utils/lighterAdapter.js +4 -4
  61. package/dist/utils/lighterAdapter.js.map +1 -1
  62. package/dist/utils/subscriptionFeeWaiver.d.ts +6 -7
  63. package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
  64. package/dist/utils/subscriptionFeeWaiver.js +6 -12
  65. package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
  66. package/package.json +1 -1
  67. package/dist/services/LighterChaseService.d.ts +0 -578
  68. package/dist/services/LighterChaseService.d.ts.map +0 -1
  69. package/dist/services/LighterChaseService.js +0 -1117
  70. package/dist/services/LighterChaseService.js.map +0 -1
  71. package/dist/services/LighterTwapService.d.ts +0 -288
  72. package/dist/services/LighterTwapService.d.ts.map +0 -1
  73. package/dist/services/LighterTwapService.js +0 -511
  74. package/dist/services/LighterTwapService.js.map +0 -1
  75. package/dist/services/lighterDispatchIdentity.d.ts +0 -28
  76. package/dist/services/lighterDispatchIdentity.d.ts.map +0 -1
  77. package/dist/services/lighterDispatchIdentity.js +0 -43
  78. package/dist/services/lighterDispatchIdentity.js.map +0 -1
  79. package/dist/utils/guardedHyperLiquidClient.d.ts +0 -13
  80. package/dist/utils/guardedHyperLiquidClient.d.ts.map +0 -1
  81. package/dist/utils/guardedHyperLiquidClient.js +0 -38
  82. package/dist/utils/guardedHyperLiquidClient.js.map +0 -1
  83. package/dist/utils/lighterAttachedOrders.d.ts +0 -53
  84. package/dist/utils/lighterAttachedOrders.d.ts.map +0 -1
  85. package/dist/utils/lighterAttachedOrders.js +0 -212
  86. package/dist/utils/lighterAttachedOrders.js.map +0 -1
  87. package/dist/utils/lighterChase.d.ts +0 -75
  88. package/dist/utils/lighterChase.d.ts.map +0 -1
  89. package/dist/utils/lighterChase.js +0 -207
  90. package/dist/utils/lighterChase.js.map +0 -1
  91. package/dist/utils/lighterLosslessJson.d.ts +0 -11
  92. package/dist/utils/lighterLosslessJson.d.ts.map +0 -1
  93. package/dist/utils/lighterLosslessJson.js +0 -136
  94. package/dist/utils/lighterLosslessJson.js.map +0 -1
  95. package/dist/utils/lighterNativeEdit.d.ts +0 -238
  96. package/dist/utils/lighterNativeEdit.d.ts.map +0 -1
  97. package/dist/utils/lighterNativeEdit.js +0 -573
  98. package/dist/utils/lighterNativeEdit.js.map +0 -1
  99. package/dist/utils/lighterScaleOrders.d.ts +0 -106
  100. package/dist/utils/lighterScaleOrders.d.ts.map +0 -1
  101. package/dist/utils/lighterScaleOrders.js +0 -496
  102. package/dist/utils/lighterScaleOrders.js.map +0 -1
  103. package/dist/utils/lighterTwap.d.ts +0 -42
  104. package/dist/utils/lighterTwap.d.ts.map +0 -1
  105. package/dist/utils/lighterTwap.js +0 -79
  106. package/dist/utils/lighterTwap.js.map +0 -1
  107. package/dist/utils/lighterTwapReconciliation.d.ts +0 -35
  108. package/dist/utils/lighterTwapReconciliation.d.ts.map +0 -1
  109. package/dist/utils/lighterTwapReconciliation.js +0 -237
  110. package/dist/utils/lighterTwapReconciliation.js.map +0 -1
  111. package/dist/utils/positionProtection.d.ts +0 -12
  112. package/dist/utils/positionProtection.d.ts.map +0 -1
  113. package/dist/utils/positionProtection.js +0 -29
  114. package/dist/utils/positionProtection.js.map +0 -1
@@ -1,79 +0,0 @@
1
- import { BigNumber } from 'bignumber.js';
2
- import { LIGHTER_MAX_ORDER_PRICE, LIGHTER_MAX_BASE_AMOUNT, LIGHTER_MINUTE_MS, LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME, } from '../constants/lighterConfig.js';
3
- const MAX_ORDER_PRICE = new BigNumber(LIGHTER_MAX_ORDER_PRICE);
4
- const MAX_BASE_AMOUNT = new BigNumber(LIGHTER_MAX_BASE_AMOUNT);
5
- const MINUTE_MILLISECONDS = LIGHTER_MINUTE_MS;
6
- /**
7
- * Prepare the verified type6 CreateOrder fields without signing or dispatching.
8
- *
9
- * This primitive deliberately supplies no lifecycle or acceptance claim. Lighter
10
- * TWAP remains unavailable until authoritative parent fills and termination are
11
- * established. The uint32 price and 48-bit amount bounds come from the pinned Lighter
12
- * Go constants. Schedule expiry is a safe JavaScript integer within int64;
13
- * transaction ExpiredAt has a separate bound. Numeric narrowing is not validation.
14
- * No unverified venue duration minimum or maximum is imposed here.
15
- *
16
- * @param intent - Exact amount, market precision, price protection, and clock.
17
- * @returns Immutable native order fields suitable for later lifecycle wiring.
18
- */
19
- export function prepareLighterTwapOrder(intent) {
20
- if (typeof intent.randomize !== 'boolean' || intent.randomize) {
21
- throw new Error('Lighter native TWAP randomization is unsupported');
22
- }
23
- if (typeof intent.isBuy !== 'boolean' ||
24
- typeof intent.reduceOnly !== 'boolean') {
25
- throw new Error('Lighter native TWAP requires explicit boolean flags');
26
- }
27
- for (const precision of [intent.sizeDecimals, intent.priceDecimals]) {
28
- if (!Number.isInteger(precision) || precision < 0 || precision > 255) {
29
- throw new Error('Invalid Lighter native TWAP market precision');
30
- }
31
- }
32
- if (!Number.isSafeInteger(intent.durationMinutes) ||
33
- intent.durationMinutes <= 0 ||
34
- !Number.isSafeInteger(intent.nowMilliseconds) ||
35
- intent.nowMilliseconds <= 0) {
36
- throw new Error('Invalid Lighter native TWAP duration or clock');
37
- }
38
- const orderExpiry = intent.nowMilliseconds + intent.durationMinutes * MINUTE_MILLISECONDS;
39
- if (!Number.isSafeInteger(orderExpiry) ||
40
- orderExpiry <= intent.nowMilliseconds) {
41
- throw new Error('Invalid Lighter native TWAP future millisecond expiry');
42
- }
43
- const values = [intent.size, intent.referencePrice, intent.slippage];
44
- if (values.some((value) => typeof value !== 'string' || !/^\d+(?:\.\d+)?$/u.test(value))) {
45
- throw new Error('Invalid Lighter native TWAP decimal');
46
- }
47
- const size = new BigNumber(intent.size).shiftedBy(intent.sizeDecimals);
48
- const reference = new BigNumber(intent.referencePrice);
49
- const slippage = new BigNumber(intent.slippage);
50
- if (!size.isInteger() ||
51
- !size.isPositive() ||
52
- size.isZero() ||
53
- size.gt(MAX_BASE_AMOUNT) ||
54
- !reference.isPositive() ||
55
- reference.isZero() ||
56
- !slippage.isFinite() ||
57
- slippage.lt(0) ||
58
- slippage.gte(1)) {
59
- throw new Error('Invalid Lighter native TWAP amount or price protection');
60
- }
61
- const price = reference
62
- .times(new BigNumber(1).plus(intent.isBuy ? slippage : slippage.negated()))
63
- .shiftedBy(intent.priceDecimals)
64
- .integerValue(intent.isBuy ? BigNumber.ROUND_FLOOR : BigNumber.ROUND_CEIL);
65
- if (!price.isFinite() || price.lt(1) || price.gt(MAX_ORDER_PRICE)) {
66
- throw new Error('Invalid Lighter native TWAP uint32 price bound');
67
- }
68
- return Object.freeze({
69
- baseAmount: size.toFixed(0),
70
- price: price.toFixed(0),
71
- isAsk: intent.isBuy ? 0 : 1,
72
- orderType: 6,
73
- timeInForce: LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME,
74
- reduceOnly: intent.reduceOnly ? 1 : 0,
75
- triggerPrice: '0',
76
- orderExpiry,
77
- });
78
- }
79
- //# sourceMappingURL=lighterTwap.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lighterTwap.js","sourceRoot":"","sources":["../../src/utils/lighterTwap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,oCAAoC,GACrC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC;AAC/D,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC;AAC/D,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AA6B9C;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAA6B;IAE7B,IAAI,OAAO,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QAC9D,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,IACE,OAAO,MAAM,CAAC,KAAK,KAAK,SAAS;QACjC,OAAO,MAAM,CAAC,UAAU,KAAK,SAAS,EACtC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,CAAC;IACD,KAAK,MAAM,SAAS,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;QACpE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC,IAAI,SAAS,GAAG,GAAG,EAAE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M,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACrC,YAAY,EAAE,GAAG;QACjB,WAAW;KACZ,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport {\n LIGHTER_MAX_ORDER_PRICE,\n LIGHTER_MAX_BASE_AMOUNT,\n LIGHTER_MINUTE_MS,\n LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME,\n} from '../constants/lighterConfig.js';\n\nconst MAX_ORDER_PRICE = new BigNumber(LIGHTER_MAX_ORDER_PRICE);\nconst MAX_BASE_AMOUNT = new BigNumber(LIGHTER_MAX_BASE_AMOUNT);\nconst MINUTE_MILLISECONDS = LIGHTER_MINUTE_MS;\n\n/** Inputs for native TWAP wire preparation; this does not authorize dispatch. */\ntype LighterTwapWireIntent = {\n size: string;\n referencePrice: string;\n sizeDecimals: number;\n priceDecimals: number;\n isBuy: boolean;\n /** Fractional slippage, represented as an exact decimal. */\n slippage: string;\n durationMinutes: number;\n /** Millisecond clock reading captured by the caller, never venue seconds. */\n nowMilliseconds: number;\n randomize: boolean;\n reduceOnly: boolean;\n};\n\ntype LighterTwapWireOrder = Readonly<{\n baseAmount: string;\n price: string;\n isAsk: 0 | 1;\n orderType: 6;\n timeInForce: typeof LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME;\n reduceOnly: 0 | 1;\n triggerPrice: '0';\n orderExpiry: number;\n}>;\n\n/**\n * Prepare the verified type6 CreateOrder fields without signing or dispatching.\n *\n * This primitive deliberately supplies no lifecycle or acceptance claim. Lighter\n * TWAP remains unavailable until authoritative parent fills and termination are\n * established. The uint32 price and 48-bit amount bounds come from the pinned Lighter\n * Go constants. Schedule expiry is a safe JavaScript integer within int64;\n * transaction ExpiredAt has a separate bound. Numeric narrowing is not validation.\n * No unverified venue duration minimum or maximum is imposed here.\n *\n * @param intent - Exact amount, market precision, price protection, and clock.\n * @returns Immutable native order fields suitable for later lifecycle wiring.\n */\nexport function prepareLighterTwapOrder(\n intent: LighterTwapWireIntent,\n): LighterTwapWireOrder {\n if (typeof intent.randomize !== 'boolean' || intent.randomize) {\n throw new Error('Lighter native TWAP randomization is unsupported');\n }\n if (\n typeof intent.isBuy !== 'boolean' ||\n typeof intent.reduceOnly !== 'boolean'\n ) {\n throw new Error('Lighter native TWAP requires explicit boolean flags');\n }\n for (const precision of [intent.sizeDecimals, intent.priceDecimals]) {\n if (!Number.isInteger(precision) || precision < 0 || precision > 255) {\n throw new Error('Invalid Lighter native TWAP market precision');\n }\n }\n if (\n !Number.isSafeInteger(intent.durationMinutes) ||\n intent.durationMinutes <= 0 ||\n !Number.isSafeInteger(intent.nowMilliseconds) ||\n intent.nowMilliseconds <= 0\n ) {\n throw new Error('Invalid Lighter native TWAP duration or clock');\n }\n const orderExpiry =\n intent.nowMilliseconds + intent.durationMinutes * MINUTE_MILLISECONDS;\n if (\n !Number.isSafeInteger(orderExpiry) ||\n orderExpiry <= intent.nowMilliseconds\n ) {\n throw new Error('Invalid Lighter native TWAP future millisecond expiry');\n }\n const values = [intent.size, intent.referencePrice, intent.slippage];\n if (\n values.some(\n (value) => typeof value !== 'string' || !/^\\d+(?:\\.\\d+)?$/u.test(value),\n )\n ) {\n throw new Error('Invalid Lighter native TWAP decimal');\n }\n const size = new BigNumber(intent.size).shiftedBy(intent.sizeDecimals);\n const reference = new BigNumber(intent.referencePrice);\n const slippage = new BigNumber(intent.slippage);\n if (\n !size.isInteger() ||\n !size.isPositive() ||\n size.isZero() ||\n size.gt(MAX_BASE_AMOUNT) ||\n !reference.isPositive() ||\n reference.isZero() ||\n !slippage.isFinite() ||\n slippage.lt(0) ||\n slippage.gte(1)\n ) {\n throw new Error('Invalid Lighter native TWAP amount or price protection');\n }\n const price = reference\n .times(new BigNumber(1).plus(intent.isBuy ? slippage : slippage.negated()))\n .shiftedBy(intent.priceDecimals)\n .integerValue(intent.isBuy ? BigNumber.ROUND_FLOOR : BigNumber.ROUND_CEIL);\n if (!price.isFinite() || price.lt(1) || price.gt(MAX_ORDER_PRICE)) {\n throw new Error('Invalid Lighter native TWAP uint32 price bound');\n }\n return Object.freeze({\n baseAmount: size.toFixed(0),\n price: price.toFixed(0),\n isAsk: intent.isBuy ? 0 : 1,\n orderType: 6,\n timeInForce: LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME,\n reduceOnly: intent.reduceOnly ? 1 : 0,\n triggerPrice: '0',\n orderExpiry,\n });\n}\n"]}
@@ -1,35 +0,0 @@
1
- import type { LighterTwapRecord } from '../services/LighterTwapService.js';
2
- import type { TwapOrder } from '../types/index.js';
3
- import type { LighterApiOrder, LighterRestTrade } from '../types/lighter-types.js';
4
- export type LighterTwapObservation = {
5
- clientOrderId: string;
6
- parentOrderId: string;
7
- parent: LighterApiOrder;
8
- children: LighterApiOrder[];
9
- trades: LighterRestTrade[];
10
- order: TwapOrder;
11
- /** Observation only until venue mapping and cancellation-race proof pass. */
12
- terminalObserved: boolean;
13
- };
14
- /**
15
- * Validate an exact parent independently of mutable fill reconciliation.
16
- *
17
- * @param record - Persisted signed schedule ownership.
18
- * @param parent - Exact client-ID lookup row.
19
- * @returns The immutable venue parent ID eligible for cancellation.
20
- */
21
- export declare function identifyLighterTwapParent(record: LighterTwapRecord, parent: LighterApiOrder): string;
22
- /**
23
- * Build an observational snapshot from complete parent/child and trade reads.
24
- * Callers must exhaust pagination and fence concurrent parent changes first.
25
- * Terminal observations are not authorization to clear durable obligations;
26
- * rollout must establish venue status and cancel-race semantics separately.
27
- *
28
- * @param record - Immutable owned schedule and signed placement identity.
29
- * @param rows - Complete relevant active/inactive order rows.
30
- * @param trades - Complete unaggregated trades for exact child IDs.
31
- * @param observedAt - Millisecond collection time.
32
- * @returns Reconciled totals, exact fills and observed native parent state.
33
- */
34
- export declare function reconcileLighterTwapObservation(record: LighterTwapRecord, rows: LighterApiOrder[], trades: LighterRestTrade[], observedAt: number): LighterTwapObservation;
35
- //# sourceMappingURL=lighterTwapReconciliation.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lighterTwapReconciliation.d.ts","sourceRoot":"","sources":["../../src/utils/lighterTwapReconciliation.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAC3E,OAAO,KAAK,EACV,SAAS,EAGV,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EACjB,MAAM,2BAA2B,CAAC;AAGnC,MAAM,MAAM,sBAAsB,GAAG;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,eAAe,CAAC;IACxB,QAAQ,EAAE,eAAe,EAAE,CAAC;IAC5B,MAAM,EAAE,gBAAgB,EAAE,CAAC;IAC3B,KAAK,EAAE,SAAS,CAAC;IACjB,6EAA6E;IAC7E,gBAAgB,EAAE,OAAO,CAAC;CAC3B,CAAC;AA6BF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,iBAAiB,EACzB,MAAM,EAAE,eAAe,GACtB,MAAM,CAmCR;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,iBAAiB,EACzB,IAAI,EAAE,eAAe,EAAE,EACvB,MAAM,EAAE,gBAAgB,EAAE,EAC1B,UAAU,EAAE,MAAM,GACjB,sBAAsB,CA0MxB"}
@@ -1,237 +0,0 @@
1
- import { BigNumber } from 'bignumber.js';
2
- import { LIGHTER_MINUTE_MS, LIGHTER_TX_EXPIRY_SLACK_MS, } from '../constants/lighterConfig.js';
3
- import { adaptFillFromLighterTrade } from './lighterAdapter.js';
4
- /**
5
- * @param numeric - JSON numeric ID, accepted only when lossless.
6
- * @param exact - Optional exact string ID.
7
- * @returns A canonical exact ID.
8
- */
9
- function exactId(numeric, exact) {
10
- if (!Number.isSafeInteger(numeric) ||
11
- numeric < 0 ||
12
- (exact !== undefined && exact !== String(numeric))) {
13
- throw new Error('Lighter TWAP order identity is unsafe or inconsistent');
14
- }
15
- return String(numeric);
16
- }
17
- /**
18
- * @param value - Required venue decimal amount.
19
- * @returns A validated nonnegative exact decimal.
20
- */
21
- function amount(value) {
22
- if (typeof value !== 'string' || !/^\d+(?:\.\d+)?$/u.test(value)) {
23
- throw new Error('Lighter TWAP execution amount is missing or malformed');
24
- }
25
- return new BigNumber(value);
26
- }
27
- /**
28
- * Validate an exact parent independently of mutable fill reconciliation.
29
- *
30
- * @param record - Persisted signed schedule ownership.
31
- * @param parent - Exact client-ID lookup row.
32
- * @returns The immutable venue parent ID eligible for cancellation.
33
- */
34
- export function identifyLighterTwapParent(record, parent) {
35
- const { intent } = record;
36
- if (exactId(parent.clientOrderIndex, parent.clientOrderId) !==
37
- intent.clientOrderId) {
38
- throw new Error('Lighter TWAP parent does not match immutable signed intent');
39
- }
40
- const parentOrderId = exactId(parent.orderIndex, parent.orderId);
41
- if (!Number.isSafeInteger(record.placement.nonce) ||
42
- parent.type !== 'twap' ||
43
- parent.ownerAccountIndex !== intent.owner.accountIndex ||
44
- parent.marketIndex !== intent.marketId ||
45
- parent.isAsk === intent.isBuy ||
46
- Boolean(parent.reduceOnly) !== intent.reduceOnly ||
47
- (parent.reduceOnly !== true &&
48
- parent.reduceOnly !== false &&
49
- parent.reduceOnly !== 0 &&
50
- parent.reduceOnly !== 1) ||
51
- parent.timeInForce !== 'good-till-time' ||
52
- parent.orderExpiry !== intent.orderExpiry ||
53
- parent.nonce !== record.placement.nonce ||
54
- !amount(parent.initialBaseAmount).eq(intent.size) ||
55
- !amount(parent.price).eq(intent.price) ||
56
- (record.parentOrderId !== undefined &&
57
- record.parentOrderId !== parentOrderId)) {
58
- throw new Error('Lighter TWAP parent does not match immutable signed intent');
59
- }
60
- return parentOrderId;
61
- }
62
- /**
63
- * Build an observational snapshot from complete parent/child and trade reads.
64
- * Callers must exhaust pagination and fence concurrent parent changes first.
65
- * Terminal observations are not authorization to clear durable obligations;
66
- * rollout must establish venue status and cancel-race semantics separately.
67
- *
68
- * @param record - Immutable owned schedule and signed placement identity.
69
- * @param rows - Complete relevant active/inactive order rows.
70
- * @param trades - Complete unaggregated trades for exact child IDs.
71
- * @param observedAt - Millisecond collection time.
72
- * @returns Reconciled totals, exact fills and observed native parent state.
73
- */
74
- export function reconcileLighterTwapObservation(record, rows, trades, observedAt) {
75
- const { intent } = record;
76
- const parents = rows.filter((row) => exactId(row.clientOrderIndex, row.clientOrderId) === intent.clientOrderId);
77
- if (parents.length !== 1) {
78
- throw new Error('Lighter TWAP exact parent is missing or ambiguous');
79
- }
80
- const parent = parents[0];
81
- const parentOrderId = identifyLighterTwapParent(record, parent);
82
- const children = [];
83
- const childIds = new Set();
84
- for (const row of rows) {
85
- if (row === parent) {
86
- continue;
87
- }
88
- const stringLink = row.parentOrderId;
89
- const numericLink = row.parentOrderIndex;
90
- const linked = stringLink === parentOrderId || numericLink === parent.orderIndex;
91
- if (!linked) {
92
- continue;
93
- }
94
- if (stringLink !== parentOrderId ||
95
- numericLink !== parent.orderIndex ||
96
- row.type !== 'twap-sub' ||
97
- row.ownerAccountIndex !== intent.owner.accountIndex ||
98
- row.marketIndex !== intent.marketId ||
99
- row.isAsk === intent.isBuy) {
100
- throw new Error('Lighter TWAP child parent linkage or ownership mismatch');
101
- }
102
- const id = exactId(row.orderIndex, row.orderId);
103
- if (childIds.has(id)) {
104
- throw new Error('Lighter TWAP child identity is ambiguous');
105
- }
106
- childIds.add(id);
107
- children.push(row);
108
- }
109
- const uniqueTrades = new Map();
110
- const fills = [];
111
- const totals = new Map();
112
- for (const trade of trades) {
113
- exactId(trade.bidId, trade.bidIdStr);
114
- exactId(trade.askId, trade.askIdStr);
115
- const sideId = intent.isBuy ? trade.bidId : trade.askId;
116
- const sideOwner = intent.isBuy ? trade.bidAccountId : trade.askAccountId;
117
- if (!childIds.has(exactId(sideId)) ||
118
- sideOwner !== intent.owner.accountIndex ||
119
- trade.marketId !== intent.marketId) {
120
- throw new Error('Lighter TWAP trade is not owned by an exact child');
121
- }
122
- const id = exactId(trade.tradeId, trade.tradeIdStr);
123
- const previous = uniqueTrades.get(id);
124
- if (previous) {
125
- if (JSON.stringify(previous) !== JSON.stringify(trade)) {
126
- throw new Error('Lighter TWAP conflicting duplicate trade');
127
- }
128
- continue;
129
- }
130
- if (!trade.txHash ||
131
- !Number.isSafeInteger(trade.timestamp) ||
132
- trade.timestamp < intent.startedAt - LIGHTER_TX_EXPIRY_SLACK_MS) {
133
- throw new Error('Lighter TWAP trade provenance is missing or predates intent');
134
- }
135
- uniqueTrades.set(id, trade);
136
- const adapted = adaptFillFromLighterTrade(trade, intent.symbol, intent.owner.accountIndex);
137
- const fill = {
138
- fillId: id,
139
- orderId: String(sideId),
140
- side: intent.isBuy ? 'buy' : 'sell',
141
- price: trade.price,
142
- size: trade.size,
143
- fee: adapted.fee,
144
- feeToken: adapted.feeToken,
145
- timestamp: trade.timestamp,
146
- transactionHash: trade.txHash,
147
- };
148
- fills.push(fill);
149
- const sum = totals.get(String(sideId)) ?? {
150
- base: new BigNumber(0),
151
- quote: new BigNumber(0),
152
- };
153
- sum.base = sum.base.plus(amount(trade.size));
154
- sum.quote = sum.quote.plus(amount(trade.usdAmount));
155
- totals.set(String(sideId), sum);
156
- }
157
- let executed = new BigNumber(0);
158
- let notional = new BigNumber(0);
159
- for (const child of children) {
160
- const sum = totals.get(String(child.orderIndex)) ?? {
161
- base: new BigNumber(0),
162
- quote: new BigNumber(0),
163
- };
164
- if (!amount(child.filledBaseAmount).eq(sum.base) ||
165
- !amount(child.filledQuoteAmount).eq(sum.quote)) {
166
- throw new Error('Lighter TWAP child fill totals do not match complete trade history');
167
- }
168
- executed = executed.plus(sum.base);
169
- notional = notional.plus(sum.quote);
170
- }
171
- if (!amount(parent.filledBaseAmount).eq(executed) ||
172
- !amount(parent.filledQuoteAmount).eq(notional) ||
173
- executed.gt(intent.size)) {
174
- throw new Error('Lighter TWAP parent fill totals do not match complete child history');
175
- }
176
- let status;
177
- if (['in-progress', 'pending', 'open'].includes(parent.status)) {
178
- status = 'active';
179
- }
180
- else if (parent.status === 'filled') {
181
- if (!executed.eq(intent.size)) {
182
- throw new Error('Lighter TWAP filled parent is underfilled');
183
- }
184
- status = 'completed';
185
- }
186
- else if (parent.status === 'canceled-expired') {
187
- status = executed.eq(intent.size) ? 'completed' : 'completed_underfilled';
188
- }
189
- else if (parent.status === 'canceled') {
190
- status = 'canceled';
191
- }
192
- else {
193
- throw new Error(`Lighter TWAP parent status mapping is unverified: ${parent.status}`);
194
- }
195
- if (status !== 'active' &&
196
- children.some((child) => ['in-progress', 'pending', 'open'].includes(child.status))) {
197
- throw new Error('Lighter TWAP terminal parent still has active child orders');
198
- }
199
- const elapsed = Math.max(0, Math.min(observedAt, intent.orderExpiry) - intent.startedAt);
200
- const order = {
201
- orderId: parentOrderId,
202
- symbol: intent.symbol,
203
- side: intent.isBuy ? 'buy' : 'sell',
204
- size: intent.size,
205
- executedSize: executed.toFixed(),
206
- remainingSize: new BigNumber(intent.size).minus(executed).toFixed(),
207
- executedNotional: notional.toFixed(),
208
- ...(executed.gt(0)
209
- ? { averagePrice: notional.div(executed).toFixed() }
210
- : {}),
211
- fillProgressBps: executed
212
- .div(intent.size)
213
- .times(10_000)
214
- .integerValue(BigNumber.ROUND_FLOOR)
215
- .toNumber(),
216
- timeProgressBps: Math.min(10_000, Math.floor((elapsed / (intent.durationMinutes * LIGHTER_MINUTE_MS)) * 10_000)),
217
- elapsedTimeMilliseconds: elapsed,
218
- durationMinutes: intent.durationMinutes,
219
- randomize: false,
220
- reduceOnly: intent.reduceOnly,
221
- status,
222
- startedAt: intent.startedAt,
223
- lastUpdated: observedAt,
224
- fills: fills.sort((a, b) => a.timestamp - b.timestamp || a.fillId.localeCompare(b.fillId)),
225
- providerId: 'lighter',
226
- };
227
- return {
228
- clientOrderId: intent.clientOrderId,
229
- parentOrderId,
230
- parent,
231
- children,
232
- trades: [...uniqueTrades.values()],
233
- order,
234
- terminalObserved: status !== 'active',
235
- };
236
- }
237
- //# sourceMappingURL=lighterTwapReconciliation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lighterTwapReconciliation.js","sourceRoot":"","sources":["../../src/utils/lighterTwapReconciliation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,iBAAiB,EACjB,0BAA0B,GAC3B,MAAM,+BAA+B,CAAC;AAWvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAahE;;;;GAIG;AACH,SAAS,OAAO,CAAC,OAAe,EAAE,KAAc;IAC9C,IACE,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC;QAC9B,OAAO,GAAG,CAAC;QACX,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC,EAClD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACzB,CAAC;AAED;;;GAGG;AACH,SAAS,MAAM,CAAC,KAAyB;IACvC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACjE,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAAyB,EACzB,MAAuB;IAEvB,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAC1B,IACE,OAAO,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,aAAa,CAAC;QACtD,MAAM,CAAC,aAAa,EACpB,CAAC;QACD,MAAM,IAAI,KAAK,CACb,4DAA4D,CAC7D,CAAC;IACJ,CAA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,eAAe;QACvC,SAAS,EAAE,KAAK;QAChB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,MAAM;QACN,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,WAAW,EAAE,UAAU;QACvB,KAAK,EAAE,KAAK,CAAC,IAAI,CACf,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,CAAC,CACxE;QACD,UAAU,EAAE,SAAS;KACtB,CAAC;IACF,OAAO;QACL,aAAa,EAAE,MAAM,CAAC,aAAa;QACnC,aAAa;QACb,MAAM;QACN,QAAQ;QACR,MAAM,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC;QAClC,KAAK;QACL,gBAAgB,EAAE,MAAM,KAAK,QAAQ;KACtC,CAAC;AACJ,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport {\n LIGHTER_MINUTE_MS,\n LIGHTER_TX_EXPIRY_SLACK_MS,\n} from '../constants/lighterConfig.js';\nimport type { LighterTwapRecord } from '../services/LighterTwapService.js';\nimport type {\n TwapOrder,\n TwapOrderFill,\n TwapOrderStatus,\n} from '../types/index.js';\nimport type {\n LighterApiOrder,\n LighterRestTrade,\n} from '../types/lighter-types.js';\nimport { adaptFillFromLighterTrade } from './lighterAdapter.js';\n\nexport type LighterTwapObservation = {\n clientOrderId: string;\n parentOrderId: string;\n parent: LighterApiOrder;\n children: LighterApiOrder[];\n trades: LighterRestTrade[];\n order: TwapOrder;\n /** Observation only until venue mapping and cancellation-race proof pass. */\n terminalObserved: boolean;\n};\n\n/**\n * @param numeric - JSON numeric ID, accepted only when lossless.\n * @param exact - Optional exact string ID.\n * @returns A canonical exact ID.\n */\nfunction exactId(numeric: number, exact?: string): string {\n if (\n !Number.isSafeInteger(numeric) ||\n numeric < 0 ||\n (exact !== undefined && exact !== String(numeric))\n ) {\n throw new Error('Lighter TWAP order identity is unsafe or inconsistent');\n }\n return String(numeric);\n}\n\n/**\n * @param value - Required venue decimal amount.\n * @returns A validated nonnegative exact decimal.\n */\nfunction amount(value: string | undefined): BigNumber {\n if (typeof value !== 'string' || !/^\\d+(?:\\.\\d+)?$/u.test(value)) {\n throw new Error('Lighter TWAP execution amount is missing or malformed');\n }\n return new BigNumber(value);\n}\n\n/**\n * Validate an exact parent independently of mutable fill reconciliation.\n *\n * @param record - Persisted signed schedule ownership.\n * @param parent - Exact client-ID lookup row.\n * @returns The immutable venue parent ID eligible for cancellation.\n */\nexport function identifyLighterTwapParent(\n record: LighterTwapRecord,\n parent: LighterApiOrder,\n): string {\n const { intent } = record;\n if (\n exactId(parent.clientOrderIndex, parent.clientOrderId) !==\n intent.clientOrderId\n ) {\n throw new Error(\n 'Lighter TWAP parent does not match immutable signed intent',\n );\n }\n const parentOrderId = exactId(parent.orderIndex, parent.orderId);\n if (\n !Number.isSafeInteger(record.placement.nonce) ||\n parent.type !== 'twap' ||\n parent.ownerAccountIndex !== intent.owner.accountIndex ||\n parent.marketIndex !== intent.marketId ||\n parent.isAsk === intent.isBuy ||\n Boolean(parent.reduceOnly) !== intent.reduceOnly ||\n (parent.reduceOnly !== true &&\n parent.reduceOnly !== false &&\n parent.reduceOnly !== 0 &&\n parent.reduceOnly !== 1) ||\n parent.timeInForce !== 'good-till-time' ||\n parent.orderExpiry !== intent.orderExpiry ||\n parent.nonce !== record.placement.nonce ||\n !amount(parent.initialBaseAmount).eq(intent.size) ||\n !amount(parent.price).eq(intent.price) ||\n (record.parentOrderId !== undefined &&\n record.parentOrderId !== parentOrderId)\n ) {\n throw new Error(\n 'Lighter TWAP parent does not match immutable signed intent',\n );\n }\n return parentOrderId;\n}\n\n/**\n * Build an observational snapshot from complete parent/child and trade reads.\n * Callers must exhaust pagination and fence concurrent parent changes first.\n * Terminal observations are not authorization to clear durable obligations;\n * rollout must establish venue status and cancel-race semantics separately.\n *\n * @param record - Immutable owned schedule and signed placement identity.\n * @param rows - Complete relevant active/inactive order rows.\n * @param trades - Complete unaggregated trades for exact child IDs.\n * @param observedAt - Millisecond collection time.\n * @returns Reconciled totals, exact fills and observed native parent state.\n */\nexport function reconcileLighterTwapObservation(\n record: LighterTwapRecord,\n rows: LighterApiOrder[],\n trades: LighterRestTrade[],\n observedAt: number,\n): LighterTwapObservation {\n const { intent } = record;\n const parents = rows.filter(\n (row) =>\n exactId(row.clientOrderIndex, row.clientOrderId) === intent.clientOrderId,\n );\n if (parents.length !== 1) {\n throw new Error('Lighter TWAP exact parent is missing or ambiguous');\n }\n const parent = parents[0];\n const parentOrderId = identifyLighterTwapParent(record, parent);\n const children: LighterApiOrder[] = [];\n const childIds = new Set<string>();\n for (const row of rows) {\n if (row === parent) {\n continue;\n }\n const stringLink = row.parentOrderId;\n const numericLink = row.parentOrderIndex;\n const linked =\n stringLink === parentOrderId || numericLink === parent.orderIndex;\n if (!linked) {\n continue;\n }\n if (\n stringLink !== parentOrderId ||\n numericLink !== parent.orderIndex ||\n row.type !== 'twap-sub' ||\n row.ownerAccountIndex !== intent.owner.accountIndex ||\n row.marketIndex !== intent.marketId ||\n row.isAsk === intent.isBuy\n ) {\n throw new Error(\n 'Lighter TWAP child parent linkage or ownership mismatch',\n );\n }\n const id = exactId(row.orderIndex, row.orderId);\n if (childIds.has(id)) {\n throw new Error('Lighter TWAP child identity is ambiguous');\n }\n childIds.add(id);\n children.push(row);\n }\n const uniqueTrades = new Map<string, LighterRestTrade>();\n const fills: TwapOrderFill[] = [];\n const totals = new Map<string, { base: BigNumber; quote: BigNumber }>();\n for (const trade of trades) {\n exactId(trade.bidId, trade.bidIdStr);\n exactId(trade.askId, trade.askIdStr);\n const sideId = intent.isBuy ? trade.bidId : trade.askId;\n const sideOwner = intent.isBuy ? trade.bidAccountId : trade.askAccountId;\n if (\n !childIds.has(exactId(sideId)) ||\n sideOwner !== intent.owner.accountIndex ||\n trade.marketId !== intent.marketId\n ) {\n throw new Error('Lighter TWAP trade is not owned by an exact child');\n }\n const id = exactId(trade.tradeId, trade.tradeIdStr);\n const previous = uniqueTrades.get(id);\n if (previous) {\n if (JSON.stringify(previous) !== JSON.stringify(trade)) {\n throw new Error('Lighter TWAP conflicting duplicate trade');\n }\n continue;\n }\n if (\n !trade.txHash ||\n !Number.isSafeInteger(trade.timestamp) ||\n trade.timestamp < intent.startedAt - LIGHTER_TX_EXPIRY_SLACK_MS\n ) {\n throw new Error(\n 'Lighter TWAP trade provenance is missing or predates intent',\n );\n }\n uniqueTrades.set(id, trade);\n const adapted = adaptFillFromLighterTrade(\n trade,\n intent.symbol,\n intent.owner.accountIndex,\n );\n const fill: TwapOrderFill = {\n fillId: id,\n orderId: String(sideId),\n side: intent.isBuy ? 'buy' : 'sell',\n price: trade.price,\n size: trade.size,\n fee: adapted.fee,\n feeToken: adapted.feeToken,\n timestamp: trade.timestamp,\n transactionHash: trade.txHash,\n };\n fills.push(fill);\n const sum = totals.get(String(sideId)) ?? {\n base: new BigNumber(0),\n quote: new BigNumber(0),\n };\n sum.base = sum.base.plus(amount(trade.size));\n sum.quote = sum.quote.plus(amount(trade.usdAmount));\n totals.set(String(sideId), sum);\n }\n let executed = new BigNumber(0);\n let notional = new BigNumber(0);\n for (const child of children) {\n const sum = totals.get(String(child.orderIndex)) ?? {\n base: new BigNumber(0),\n quote: new BigNumber(0),\n };\n if (\n !amount(child.filledBaseAmount).eq(sum.base) ||\n !amount(child.filledQuoteAmount).eq(sum.quote)\n ) {\n throw new Error(\n 'Lighter TWAP child fill totals do not match complete trade history',\n );\n }\n executed = executed.plus(sum.base);\n notional = notional.plus(sum.quote);\n }\n if (\n !amount(parent.filledBaseAmount).eq(executed) ||\n !amount(parent.filledQuoteAmount).eq(notional) ||\n executed.gt(intent.size)\n ) {\n throw new Error(\n 'Lighter TWAP parent fill totals do not match complete child history',\n );\n }\n let status: TwapOrderStatus;\n if (['in-progress', 'pending', 'open'].includes(parent.status)) {\n status = 'active';\n } else if (parent.status === 'filled') {\n if (!executed.eq(intent.size)) {\n throw new Error('Lighter TWAP filled parent is underfilled');\n }\n status = 'completed';\n } else if (parent.status === 'canceled-expired') {\n status = executed.eq(intent.size) ? 'completed' : 'completed_underfilled';\n } else if (parent.status === 'canceled') {\n status = 'canceled';\n } else {\n throw new Error(\n `Lighter TWAP parent status mapping is unverified: ${parent.status}`,\n );\n }\n if (\n status !== 'active' &&\n children.some((child) =>\n ['in-progress', 'pending', 'open'].includes(child.status),\n )\n ) {\n throw new Error(\n 'Lighter TWAP terminal parent still has active child orders',\n );\n }\n const elapsed = Math.max(\n 0,\n Math.min(observedAt, intent.orderExpiry) - intent.startedAt,\n );\n const order: TwapOrder = {\n orderId: parentOrderId,\n symbol: intent.symbol,\n side: intent.isBuy ? 'buy' : 'sell',\n size: intent.size,\n executedSize: executed.toFixed(),\n remainingSize: new BigNumber(intent.size).minus(executed).toFixed(),\n executedNotional: notional.toFixed(),\n ...(executed.gt(0)\n ? { averagePrice: notional.div(executed).toFixed() }\n : {}),\n fillProgressBps: executed\n .div(intent.size)\n .times(10_000)\n .integerValue(BigNumber.ROUND_FLOOR)\n .toNumber(),\n timeProgressBps: Math.min(\n 10_000,\n Math.floor(\n (elapsed / (intent.durationMinutes * LIGHTER_MINUTE_MS)) * 10_000,\n ),\n ),\n elapsedTimeMilliseconds: elapsed,\n durationMinutes: intent.durationMinutes,\n randomize: false,\n reduceOnly: intent.reduceOnly,\n status,\n startedAt: intent.startedAt,\n lastUpdated: observedAt,\n fills: fills.sort(\n (a, b) => a.timestamp - b.timestamp || a.fillId.localeCompare(b.fillId),\n ),\n providerId: 'lighter',\n };\n return {\n clientOrderId: intent.clientOrderId,\n parentOrderId,\n parent,\n children,\n trades: [...uniqueTrades.values()],\n order,\n terminalObserved: status !== 'active',\n };\n}\n"]}
@@ -1,12 +0,0 @@
1
- import type { UpdatePositionTPSLParams } from '../types/index.js';
2
- /**
3
- * Reject a protection mutation whose caller-owned position no longer matches.
4
- *
5
- * @param expected - Optional immutable caller precondition.
6
- * @param actual - Authoritative current position, if any.
7
- */
8
- export declare function assertExpectedPosition(expected: UpdatePositionTPSLParams['expectedPosition'], actual: {
9
- size: string;
10
- entryPrice: string;
11
- } | undefined): void;
12
- //# sourceMappingURL=positionProtection.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"positionProtection.d.ts","sourceRoot":"","sources":["../../src/utils/positionProtection.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAElE;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,wBAAwB,CAAC,kBAAkB,CAAC,EACtD,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,GACvD,IAAI,CAyBN"}
@@ -1,29 +0,0 @@
1
- import { BigNumber } from 'bignumber.js';
2
- import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
3
- /**
4
- * Reject a protection mutation whose caller-owned position no longer matches.
5
- *
6
- * @param expected - Optional immutable caller precondition.
7
- * @param actual - Authoritative current position, if any.
8
- */
9
- export function assertExpectedPosition(expected, actual) {
10
- if (expected === undefined) {
11
- return;
12
- }
13
- const decimal = /^-?(?:\d+(?:\.\d*)?|\.\d+)$/u;
14
- if (!actual ||
15
- ![expected.size, expected.entryPrice, actual.size, actual.entryPrice].every((value) => typeof value === 'string' && decimal.test(value))) {
16
- throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
17
- }
18
- const expectedSize = new BigNumber(expected.size);
19
- const expectedEntryPrice = new BigNumber(expected.entryPrice);
20
- if (!expectedSize.isFinite() ||
21
- expectedSize.isZero() ||
22
- !expectedEntryPrice.isFinite() ||
23
- !expectedEntryPrice.gt(0) ||
24
- !expectedSize.eq(actual.size) ||
25
- !expectedEntryPrice.eq(actual.entryPrice)) {
26
- throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
27
- }
28
- }
29
- //# sourceMappingURL=positionProtection.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"positionProtection.js","sourceRoot":"","sources":["../../src/utils/positionProtection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG1D;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,QAAsD,EACtD,MAAwD;IAExD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,OAAO;IACT,CAAC;IACD,MAAM,OAAO,GAAG,8BAA8B,CAAC;IAC/C,IACE,CAAC,MAAM;QACP,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC,KAAK,CACzE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAC5D,EACD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,kBAAkB,CAAC,CAAC;IACxD,CAAC;IACD,MAAM,YAAY,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAClD,MAAM,kBAAkB,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAC9D,IACE,CAAC,YAAY,CAAC,QAAQ,EAAE;QACxB,YAAY,CAAC,MAAM,EAAE;QACrB,CAAC,kBAAkB,CAAC,QAAQ,EAAE;QAC9B,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAC,CAAC;QACzB,CAAC,YAAY,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC;QAC7B,CAAC,kBAAkB,CAAC,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,EACzC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,kBAAkB,CAAC,CAAC;IACxD,CAAC;AACH,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type { UpdatePositionTPSLParams } from '../types/index.js';\n\n/**\n * Reject a protection mutation whose caller-owned position no longer matches.\n *\n * @param expected - Optional immutable caller precondition.\n * @param actual - Authoritative current position, if any.\n */\nexport function assertExpectedPosition(\n expected: UpdatePositionTPSLParams['expectedPosition'],\n actual: { size: string; entryPrice: string } | undefined,\n): void {\n if (expected === undefined) {\n return;\n }\n const decimal = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/u;\n if (\n !actual ||\n ![expected.size, expected.entryPrice, actual.size, actual.entryPrice].every(\n (value) => typeof value === 'string' && decimal.test(value),\n )\n ) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n const expectedSize = new BigNumber(expected.size);\n const expectedEntryPrice = new BigNumber(expected.entryPrice);\n if (\n !expectedSize.isFinite() ||\n expectedSize.isZero() ||\n !expectedEntryPrice.isFinite() ||\n !expectedEntryPrice.gt(0) ||\n !expectedSize.eq(actual.size) ||\n !expectedEntryPrice.eq(actual.entryPrice)\n ) {\n throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);\n }\n}\n"]}