@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,496 +0,0 @@
1
- import { BigNumber } from 'bignumber.js';
2
- import { LIGHTER_MAX_WIRE_PRICE, LIGHTER_MAX_BASE_AMOUNT, LIGHTER_MIN_TRADING_API_KEY_INDEX, LIGHTER_MAX_TRADING_API_KEY_INDEX, } from '../constants/lighterConfig.js';
3
- import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
4
- import { computeScalePriceLadder, splitScaleSizes, } from './orderCalculations.js';
5
- import { SCALE_ORDER_COUNT } from './orderTypes.js';
6
- const LIGHTER_SCALE_MAX_DECIMALS = 18;
7
- const LIGHTER_SCALE_MAX_JOURNAL_LENGTH = 2_000_000;
8
- const LIGHTER_SCALE_MAX_GROUP_ID_LENGTH = 256;
9
- const LIGHTER_SCALE_MAX_SYMBOL_LENGTH = 100;
10
- const LIGHTER_SCALE_CLIENT_ID_LIMIT = 2 ** 48;
11
- const LIGHTER_SCALE_MAX_HASH_LENGTH = 128;
12
- export const LIGHTER_SCALE_JOURNAL_PREFIX = 'lighterScaleOrders:';
13
- export const LIGHTER_SCALE_PREFIX = 'lighter-scale:';
14
- export const LIGHTER_SCALE_MAX_GROUPS = 64;
15
- /** Parse a full positive decimal without binary rounding or numeric prefixes.
16
- * @param raw - Caller or venue decimal.
17
- * @returns Exact positive quantity.
18
- */
19
- export function parseScaleDecimal(raw) {
20
- if (typeof raw !== 'string' ||
21
- !/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(raw)) {
22
- throw new Error('Invalid Lighter Scale decimal');
23
- }
24
- const value = new BigNumber(raw);
25
- if (!value.isFinite() || !value.gt(0)) {
26
- throw new Error('Lighter Scale values must be positive');
27
- }
28
- return value;
29
- }
30
- /** Normalize inclusive ascending prices to the fixed venue grid.
31
- * @param min - Exact lower price.
32
- * @param max - Exact upper price.
33
- * @param count - Number of rungs.
34
- * @param decimals - Venue price precision.
35
- * @returns Distinct canonical price strings.
36
- */
37
- export function normalizeLighterScalePrices(min, max, count, decimals) {
38
- if (!Number.isInteger(decimals) ||
39
- decimals < 0 ||
40
- decimals > LIGHTER_SCALE_MAX_DECIMALS) {
41
- throw new Error('Invalid Lighter Scale precision');
42
- }
43
- let low;
44
- let high;
45
- try {
46
- low = parseScaleDecimal(min);
47
- high = parseScaleDecimal(max);
48
- }
49
- catch {
50
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
51
- }
52
- if (!low.shiftedBy(decimals).isInteger() ||
53
- !high.shiftedBy(decimals).isInteger()) {
54
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
55
- }
56
- computeScalePriceLadder({
57
- minPrice: low.toNumber(),
58
- maxPrice: high.toNumber(),
59
- count,
60
- });
61
- const prices = Array.from({ length: count }, (_, index) => low
62
- .plus(high
63
- .minus(low)
64
- .times(index)
65
- .div(count - 1))
66
- .decimalPlaces(decimals, BigNumber.ROUND_DOWN));
67
- const wire = prices.map((price) => price.shiftedBy(decimals));
68
- if (wire.some((price) => !price.isInteger() || price.lt(1) || price.gt(LIGHTER_MAX_WIRE_PRICE)) ||
69
- new Set(wire.map(String)).size !== count) {
70
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
71
- }
72
- return prices.map((price) => price.toFixed());
73
- }
74
- /** Capture a preview constraint before the first asynchronous operation.
75
- * @param expected - Caller-supplied normalized intent.
76
- * @returns An independent snapshot, or an explicit malformed-preview refusal.
77
- */
78
- export function captureExpectedScaleLadder(expected) {
79
- if (expected === undefined) {
80
- return undefined;
81
- }
82
- if (expected === null || typeof expected !== 'object') {
83
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);
84
- }
85
- const { prices, sizes } = expected;
86
- if (!Array.isArray(expected.prices) ||
87
- !Array.isArray(expected.sizes) ||
88
- Object.keys(expected).some((key) => ![
89
- 'prices',
90
- 'sizes',
91
- 'totalSize',
92
- 'totalNotional',
93
- 'minimumBaseSize',
94
- 'minimumQuoteAmount',
95
- 'sizeDecimals',
96
- ].includes(key))) {
97
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);
98
- }
99
- return {
100
- ...expected,
101
- prices: [...prices],
102
- sizes: [...sizes],
103
- };
104
- }
105
- /** Own financial request values before routing or fee resolution can yield.
106
- * @param params - Caller-owned order request.
107
- * @returns An independent request preserving legacy preview omission.
108
- */
109
- export function captureScaleOrderParams(params) {
110
- const captured = { ...params };
111
- if (captured.expectedScaleLadder !== undefined) {
112
- captured.expectedScaleLadder = captureExpectedScaleLadder(captured.expectedScaleLadder);
113
- }
114
- return captured;
115
- }
116
- /** Refuse any change to the approved normalized financial intent.
117
- * @param expected - Optional caller constraint; omission is legacy unbound placement.
118
- * @param ladder - Fresh normalized placement quantities and prices.
119
- * @param market - Fresh venue minimums and quantity grid.
120
- */
121
- export function assertExpectedScaleLadder(expected, ladder, market) {
122
- if (expected === undefined) {
123
- return;
124
- }
125
- const captured = captureExpectedScaleLadder(expected);
126
- if (!captured ||
127
- captured.prices.length !== ladder.prices.length ||
128
- captured.sizes.length !== ladder.sizes.length ||
129
- ladder.prices.some((price, index) => price !== captured.prices[index]) ||
130
- ladder.sizes.some((size, index) => size !== captured.sizes[index]) ||
131
- captured.totalSize !== ladder.size ||
132
- captured.totalNotional !== ladder.notional ||
133
- captured.minimumBaseSize !== market.minBaseAmount ||
134
- captured.minimumQuoteAmount !== market.minQuoteAmount ||
135
- captured.sizeDecimals !== market.supportedSizeDecimals) {
136
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);
137
- }
138
- }
139
- /** Build all rungs and prove exact base and quote bounds before any write.
140
- * @param params - Scale intent.
141
- * @param market - Active venue metadata.
142
- * @returns Exact normalized rungs and totals.
143
- */
144
- export function buildLighterScaleLadder(params, market) {
145
- const unsupported = [
146
- 'price',
147
- 'triggerPrice',
148
- 'timeInForce',
149
- 'takeProfitPrice',
150
- 'stopLossPrice',
151
- 'takeProfitSize',
152
- 'stopLossSize',
153
- 'tpslLinkage',
154
- 'grouping',
155
- 'clientOrderId',
156
- 'twapDuration',
157
- 'twapRandomize',
158
- 'chaseIntervalMs',
159
- 'chaseMaxDurationMs',
160
- 'chaseMaxRepricings',
161
- 'chaseMaxDistanceBps',
162
- 'marginMode',
163
- 'slippage',
164
- 'maxSlippageBps',
165
- 'priceAtCalculation',
166
- 'isFullClose',
167
- ];
168
- const field = unsupported.find((key) => params[key] !== undefined);
169
- if (field) {
170
- throw new Error(`Lighter Scale does not support ${field}`);
171
- }
172
- if (market.status !== 'active' ||
173
- market.marketType !== 'perp' ||
174
- params.orderType !== 'scale') {
175
- throw new Error('Lighter Scale requires an active perpetual market');
176
- }
177
- const { scaleNumOrders: count, scaleMinPrice: min, scaleMaxPrice: max, } = params;
178
- if (min === undefined || max === undefined) {
179
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);
180
- }
181
- if (count === undefined) {
182
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);
183
- }
184
- const prices = normalizeLighterScalePrices(min, max, count, market.supportedPriceDecimals);
185
- const decimals = market.supportedSizeDecimals;
186
- if (!Number.isInteger(decimals) ||
187
- decimals < 0 ||
188
- decimals > LIGHTER_SCALE_MAX_DECIMALS) {
189
- throw new Error('Invalid Lighter Scale precision');
190
- }
191
- if (params.scaleSkew !== undefined &&
192
- (!Number.isFinite(params.scaleSkew) || params.scaleSkew <= 0)) {
193
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
194
- }
195
- let budget;
196
- let rawSize;
197
- try {
198
- budget =
199
- params.usdAmount === undefined
200
- ? undefined
201
- : parseScaleDecimal(params.usdAmount);
202
- rawSize = budget ? budget.div(prices[0]) : parseScaleDecimal(params.size);
203
- }
204
- catch {
205
- throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);
206
- }
207
- const units = rawSize.shiftedBy(decimals).integerValue(BigNumber.ROUND_DOWN);
208
- if (units.gt(Number.MAX_SAFE_INTEGER) || units.lt(count)) {
209
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
210
- }
211
- const split = (total) => {
212
- const sizes = splitScaleSizes({
213
- totalSize: new BigNumber(total).shiftedBy(-decimals).toNumber(),
214
- count,
215
- szDecimals: decimals,
216
- skew: params.scaleSkew,
217
- });
218
- const sum = sizes.reduce((value, size) => value.plus(size), new BigNumber(0));
219
- if (!sum.shiftedBy(decimals).eq(total) ||
220
- sizes.some((size) => !new BigNumber(size).shiftedBy(decimals).isInteger())) {
221
- throw new Error('Lighter Scale size conservation failed');
222
- }
223
- return sizes;
224
- };
225
- const quote = (sizes) => sizes.reduce((total, size, index) => total.plus(new BigNumber(size).times(prices[index])), new BigNumber(0));
226
- let total = units.toNumber();
227
- if (budget) {
228
- let low = count;
229
- let high = total;
230
- let feasible;
231
- while (low <= high) {
232
- const candidate = low + Math.floor((high - low) / 2);
233
- let sizes;
234
- try {
235
- sizes = split(candidate);
236
- }
237
- catch {
238
- low = candidate + 1;
239
- continue;
240
- }
241
- if (quote(sizes).lte(budget)) {
242
- feasible = candidate;
243
- low = candidate + 1;
244
- }
245
- else {
246
- high = candidate - 1;
247
- }
248
- }
249
- if (feasible === undefined) {
250
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
251
- }
252
- total = feasible;
253
- }
254
- const sizes = split(total);
255
- const minimumBase = parseScaleDecimal(market.minBaseAmount);
256
- const minimumQuote = parseScaleDecimal(market.minQuoteAmount);
257
- for (const [index, size] of sizes.entries()) {
258
- if (new BigNumber(size).shiftedBy(decimals).gt(LIGHTER_MAX_BASE_AMOUNT)) {
259
- throw new Error('Lighter Scale child exceeds native base amount');
260
- }
261
- if (new BigNumber(size).lt(minimumBase)) {
262
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
263
- }
264
- if (new BigNumber(size).times(prices[index]).lt(minimumQuote)) {
265
- throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL);
266
- }
267
- }
268
- const normalized = new BigNumber(total).shiftedBy(-decimals);
269
- if (normalized.gt(rawSize) || (budget && quote(sizes).gt(budget))) {
270
- throw new Error('Lighter Scale exposure exceeds intent');
271
- }
272
- return {
273
- prices,
274
- sizes,
275
- size: normalized.toFixed(),
276
- notional: quote(sizes).toFixed(),
277
- };
278
- }
279
- /** Whether every leg is proven unable to execute again.
280
- * @param group - Durable ownership.
281
- * @returns Terminal status.
282
- */
283
- export function isLighterScaleTerminal(group) {
284
- return (group.placementStopped &&
285
- group.rungs.every((rung) => ['filled', 'canceled', 'rejected', 'prepared'].includes(rung.state)));
286
- }
287
- /** Project actual accepted and submitted exposure without invented identities.
288
- * @param group - Durable ownership.
289
- * @returns Shared receipt plus durable scope.
290
- */
291
- export function toLighterScaleGroup(group) {
292
- const submitted = group.rungs.filter((rung) => rung.state !== 'prepared');
293
- const uncertain = group.rungs.some((rung) => rung.state === 'unknown' || rung.state === 'submitted');
294
- const accepted = group.rungs.filter((rung) => ['accepted', 'resting', 'filled', 'canceled'].includes(rung.state));
295
- const total = (rungs) => rungs.reduce((sum, rung) => sum.plus(rung.size), new BigNumber(0));
296
- const acceptedSize = total(accepted);
297
- const acceptedChildren = accepted.map((rung) => {
298
- if (rung.orderId !== undefined &&
299
- (rung.state === 'resting' ||
300
- rung.state === 'filled' ||
301
- rung.state === 'canceled')) {
302
- return { state: rung.state, orderId: rung.orderId };
303
- }
304
- return { state: 'waitingForFill' };
305
- });
306
- const fillsKnown = !uncertain &&
307
- accepted.length > 0 &&
308
- accepted.every((rung) => rung.filledSize !== undefined);
309
- const filledSize = accepted.reduce((sum, rung) => rung.filledSize === undefined ? sum : sum.plus(rung.filledSize), new BigNumber(0));
310
- let state = 'placing';
311
- if (group.placementStopped) {
312
- state = 'stopped';
313
- }
314
- if (uncertain) {
315
- state = 'unknown';
316
- }
317
- if (isLighterScaleTerminal(group)) {
318
- state = 'terminal';
319
- }
320
- return {
321
- groupId: group.groupId,
322
- orderId: group.groupId,
323
- symbol: group.symbol,
324
- providerId: 'lighter',
325
- accountIndex: group.accountIndex,
326
- apiKeyIndex: group.apiKeyIndex,
327
- walletAddress: group.walletAddress,
328
- network: group.network,
329
- state,
330
- submittedSize: total(submitted).toFixed(),
331
- ...(uncertain ? {} : { acceptedSize: acceptedSize.toFixed() }),
332
- acceptedChildren,
333
- childOrderIds: accepted.flatMap((rung) => rung.state === 'resting' && rung.orderId !== undefined
334
- ? [rung.orderId]
335
- : []),
336
- ...(!uncertain && acceptedSize.gt(0)
337
- ? {
338
- weightedAverageLimitPrice: accepted
339
- .reduce((sum, rung) => sum.plus(new BigNumber(rung.size).times(rung.price)), new BigNumber(0))
340
- .div(acceptedSize)
341
- .toFixed(),
342
- }
343
- : {}),
344
- ...(fillsKnown ? { filledSize: filledSize.toFixed() } : {}),
345
- };
346
- }
347
- /** Validate an account journal before using durable financial ownership.
348
- * @param raw - Serialized journal.
349
- * @returns Bounded validated groups.
350
- */
351
- export function parseLighterScaleGroups(raw) {
352
- if (raw === null) {
353
- return [];
354
- }
355
- if (raw.length > LIGHTER_SCALE_MAX_JOURNAL_LENGTH) {
356
- throw new Error('Lighter Scale journal exceeds its storage bound');
357
- }
358
- const groups = JSON.parse(raw);
359
- if (!Array.isArray(groups) || groups.length > LIGHTER_SCALE_MAX_GROUPS) {
360
- throw new Error('Invalid Lighter Scale journal');
361
- }
362
- const ids = new Set();
363
- const groupsSeen = new Set();
364
- const integer = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
365
- for (const value of groups) {
366
- const group = value;
367
- if (group?.version !== 1 ||
368
- typeof group.groupId !== 'string' ||
369
- !group.groupId.startsWith(LIGHTER_SCALE_PREFIX) ||
370
- group.groupId.length > LIGHTER_SCALE_MAX_GROUP_ID_LENGTH ||
371
- groupsSeen.has(group.groupId) ||
372
- typeof group.symbol !== 'string' ||
373
- !group.symbol ||
374
- group.symbol.length > LIGHTER_SCALE_MAX_SYMBOL_LENGTH ||
375
- !integer(group.accountIndex) ||
376
- !integer(group.apiKeyIndex) ||
377
- group.apiKeyIndex < LIGHTER_MIN_TRADING_API_KEY_INDEX ||
378
- group.apiKeyIndex > LIGHTER_MAX_TRADING_API_KEY_INDEX ||
379
- !integer(group.marketId) ||
380
- !integer(group.createdAt) ||
381
- typeof group.walletAddress !== 'string' ||
382
- !/^0x[0-9a-f]{40}$/u.test(group.walletAddress) ||
383
- !['mainnet', 'testnet'].includes(group.network ?? '') ||
384
- !integer(group.sizeDecimals) ||
385
- group.sizeDecimals > LIGHTER_SCALE_MAX_DECIMALS ||
386
- !integer(group.priceDecimals) ||
387
- group.priceDecimals > LIGHTER_SCALE_MAX_DECIMALS ||
388
- typeof group.isBuy !== 'boolean' ||
389
- typeof group.reduceOnly !== 'boolean' ||
390
- typeof group.placementStopped !== 'boolean' ||
391
- !Array.isArray(group.rungs) ||
392
- group.rungs.length < SCALE_ORDER_COUNT.min ||
393
- group.rungs.length > SCALE_ORDER_COUNT.max) {
394
- throw new Error('Invalid Lighter Scale group');
395
- }
396
- groupsSeen.add(group.groupId);
397
- let previousPrice = 0;
398
- const orderIds = new Set();
399
- for (const rung of group.rungs) {
400
- if (!rung ||
401
- !integer(rung.clientOrderId) ||
402
- rung.clientOrderId === 0 ||
403
- rung.clientOrderId >= LIGHTER_SCALE_CLIENT_ID_LIMIT ||
404
- ids.has(rung.clientOrderId) ||
405
- !integer(rung.priceInt) ||
406
- rung.priceInt < 1 ||
407
- rung.priceInt > LIGHTER_MAX_WIRE_PRICE ||
408
- !integer(rung.sizeInt) ||
409
- rung.sizeInt < 1 ||
410
- new BigNumber(rung.sizeInt).gt(LIGHTER_MAX_BASE_AMOUNT) ||
411
- ![
412
- 'prepared',
413
- 'unknown',
414
- 'submitted',
415
- 'accepted',
416
- 'resting',
417
- 'filled',
418
- 'canceled',
419
- 'rejected',
420
- ].includes(rung.state) ||
421
- !(rung.nonce === null || integer(rung.nonce)) ||
422
- !(rung.txHash === null ||
423
- (typeof rung.txHash === 'string' &&
424
- /^[a-f\d]+$/iu.test(rung.txHash) &&
425
- rung.txHash.length <= LIGHTER_SCALE_MAX_HASH_LENGTH)) ||
426
- !(rung.expiresAt === null ||
427
- (integer(rung.expiresAt) && rung.expiresAt > 0)) ||
428
- (rung.orderId !== undefined && !/^\d{1,20}$/u.test(rung.orderId))) {
429
- throw new Error('Invalid Lighter Scale rung');
430
- }
431
- if (rung.cancelAttempt !== undefined &&
432
- (rung.cancelAttempt === null ||
433
- typeof rung.cancelAttempt !== 'object' ||
434
- rung.orderId === undefined ||
435
- !group.placementStopped ||
436
- (rung.cancelAttempt.acknowledged !== undefined &&
437
- typeof rung.cancelAttempt.acknowledged !== 'boolean') ||
438
- !integer(rung.cancelAttempt.apiKeyIndex) ||
439
- rung.cancelAttempt.apiKeyIndex < LIGHTER_MIN_TRADING_API_KEY_INDEX ||
440
- rung.cancelAttempt.apiKeyIndex > LIGHTER_MAX_TRADING_API_KEY_INDEX ||
441
- !integer(rung.cancelAttempt.nonce) ||
442
- typeof rung.cancelAttempt.txHash !== 'string' ||
443
- !/^[a-f\d]{8,128}$/u.test(rung.cancelAttempt.txHash) ||
444
- !integer(rung.cancelAttempt.expiresAt) ||
445
- rung.cancelAttempt.expiresAt === 0)) {
446
- throw new Error('Invalid Lighter Scale cancellation attempt');
447
- }
448
- if (!parseScaleDecimal(rung.price)
449
- .shiftedBy(group.priceDecimals)
450
- .eq(rung.priceInt) ||
451
- !parseScaleDecimal(rung.size)
452
- .shiftedBy(group.sizeDecimals)
453
- .eq(rung.sizeInt)) {
454
- throw new Error('Lighter Scale wire quantities differ from intent');
455
- }
456
- if (rung.priceInt <= previousPrice ||
457
- (rung.orderId !== undefined && orderIds.has(rung.orderId))) {
458
- throw new Error('Invalid Lighter Scale ladder ordering or duplicate venue identity');
459
- }
460
- previousPrice = rung.priceInt;
461
- if (rung.orderId !== undefined) {
462
- orderIds.add(rung.orderId);
463
- }
464
- ids.add(rung.clientOrderId);
465
- if (!(rung.orderExpiry === null ||
466
- (integer(rung.orderExpiry) && rung.orderExpiry > 0)) ||
467
- (rung.state !== 'prepared' && rung.orderExpiry === null)) {
468
- throw new Error('Invalid Lighter Scale order expiry');
469
- }
470
- if (rung.nonAcceptance !== undefined &&
471
- (!['failed', 'expired', 'nonce-consumed'].includes(rung.nonAcceptance) ||
472
- !['unknown', 'rejected'].includes(rung.state) ||
473
- rung.orderId !== undefined)) {
474
- throw new Error('Invalid Lighter Scale non-acceptance proof');
475
- }
476
- if (rung.state !== 'prepared' &&
477
- (rung.nonce === null || rung.txHash === null || rung.expiresAt === null)) {
478
- throw new Error('Invalid Lighter Scale dispatch identity');
479
- }
480
- if ((rung.state === 'resting' ||
481
- rung.state === 'filled' ||
482
- rung.state === 'canceled') &&
483
- rung.orderId === undefined) {
484
- throw new Error('Missing Lighter Scale venue identity');
485
- }
486
- if (rung.filledSize !== undefined &&
487
- (typeof rung.filledSize !== 'string' ||
488
- !/^\d+(?:\.\d+)?$/u.test(rung.filledSize) ||
489
- new BigNumber(rung.filledSize).gt(rung.size))) {
490
- throw new Error('Invalid Lighter Scale fill');
491
- }
492
- }
493
- }
494
- return groups;
495
- }
496
- //# sourceMappingURL=lighterScaleOrders.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lighterScaleOrders.js","s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SAAS,KAAK,IAAI,CAAC,EACxE,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;YAC7D,CAAC;YACD,IACE,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS;gBACvB,IAAI,CAAC,KAAK,KAAK,QAAQ;gBACvB,IAAI,CAAC,KAAK,KAAK,UAAU,CAAC;gBAC5B,IAAI,CAAC,OAAO,KAAK,SAAS,EAC1B,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;YAC1D,CAAC;YACD,IACE,IAAI,CAAC,UAAU,KAAK,SAAS;gBAC7B,CAAC,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ;oBAClC,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC;oBACzC,IAAI,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAC/C,CAAC;gBACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;YAChD,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,MAA6B,CAAC;AACvC,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport {\n LIGHTER_MAX_WIRE_PRICE,\n LIGHTER_MAX_BASE_AMOUNT,\n LIGHTER_MIN_TRADING_API_KEY_INDEX,\n LIGHTER_MAX_TRADING_API_KEY_INDEX,\n} from '../constants/lighterConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n OrderParams,\n ExpectedScaleLadder,\n OrderResult,\n ScaleOrderGroup,\n} from '../types/index.js';\nimport type { LighterOrderBookMeta } from '../types/lighter-types.js';\nimport {\n computeScalePriceLadder,\n splitScaleSizes,\n} from './orderCalculations.js';\nimport { SCALE_ORDER_COUNT } from './orderTypes.js';\n\nconst LIGHTER_SCALE_MAX_DECIMALS = 18;\nconst LIGHTER_SCALE_MAX_JOURNAL_LENGTH = 2_000_000;\nconst LIGHTER_SCALE_MAX_GROUP_ID_LENGTH = 256;\nconst LIGHTER_SCALE_MAX_SYMBOL_LENGTH = 100;\nconst LIGHTER_SCALE_CLIENT_ID_LIMIT = 2 ** 48;\nconst LIGHTER_SCALE_MAX_HASH_LENGTH = 128;\nexport const LIGHTER_SCALE_JOURNAL_PREFIX = 'lighterScaleOrders:';\n\nexport const LIGHTER_SCALE_PREFIX = 'lighter-scale:';\nexport const LIGHTER_SCALE_MAX_GROUPS = 64;\n\nexport type LighterScaleRung = {\n clientOrderId: number;\n price: string;\n size: string;\n priceInt: number;\n sizeInt: number;\n state:\n | 'prepared'\n | 'unknown'\n | 'submitted'\n | 'accepted'\n | 'resting'\n | 'filled'\n | 'canceled'\n | 'rejected';\n nonAcceptance?: 'failed' | 'expired' | 'nonce-consumed';\n orderExpiry: number | null;\n nonce: number | null;\n txHash: string | null;\n expiresAt: number | null;\n orderId?: string;\n filledSize?: string;\n cancelAttempt?: {\n acknowledged?: boolean;\n apiKeyIndex: number;\n nonce: number;\n txHash: string;\n expiresAt: number;\n };\n};\nexport type LighterScaleGroup = {\n version: 1;\n groupId: string;\n symbol: string;\n accountIndex: number;\n apiKeyIndex: number;\n marketId: number;\n isBuy: boolean;\n reduceOnly: boolean;\n createdAt: number;\n walletAddress: string;\n network: 'mainnet' | 'testnet';\n sizeDecimals: number;\n priceDecimals: number;\n placementStopped: boolean;\n rungs: LighterScaleRung[];\n};\n\n/** Parse a full positive decimal without binary rounding or numeric prefixes.\n * @param raw - Caller or venue decimal.\n * @returns Exact positive quantity.\n */\nexport function parseScaleDecimal(raw: unknown): BigNumber {\n if (\n typeof raw !== 'string' ||\n !/^(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/u.test(raw)\n ) {\n throw new Error('Invalid Lighter Scale decimal');\n }\n const value = new BigNumber(raw);\n if (!value.isFinite() || !value.gt(0)) {\n throw new Error('Lighter Scale values must be positive');\n }\n return value;\n}\n\n/** Normalize inclusive ascending prices to the fixed venue grid.\n * @param min - Exact lower price.\n * @param max - Exact upper price.\n * @param count - Number of rungs.\n * @param decimals - Venue price precision.\n * @returns Distinct canonical price strings.\n */\nexport function normalizeLighterScalePrices(\n min: string,\n max: string,\n count: number,\n decimals: number,\n): string[] {\n if (\n !Number.isInteger(decimals) ||\n decimals < 0 ||\n decimals > LIGHTER_SCALE_MAX_DECIMALS\n ) {\n throw new Error('Invalid Lighter Scale precision');\n }\n let low: BigNumber;\n let high: BigNumber;\n try {\n low = parseScaleDecimal(min);\n high = parseScaleDecimal(max);\n } catch {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n if (\n !low.shiftedBy(decimals).isInteger() ||\n !high.shiftedBy(decimals).isInteger()\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n computeScalePriceLadder({\n minPrice: low.toNumber(),\n maxPrice: high.toNumber(),\n count,\n });\n const prices = Array.from({ length: count }, (_, index) =>\n low\n .plus(\n high\n .minus(low)\n .times(index)\n .div(count - 1),\n )\n .decimalPlaces(decimals, BigNumber.ROUND_DOWN),\n );\n const wire = prices.map((price) => price.shiftedBy(decimals));\n if (\n wire.some(\n (price) =>\n !price.isInteger() || price.lt(1) || price.gt(LIGHTER_MAX_WIRE_PRICE),\n ) ||\n new Set(wire.map(String)).size !== count\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n return prices.map((price) => price.toFixed());\n}\n\n/** Capture a preview constraint before the first asynchronous operation.\n * @param expected - Caller-supplied normalized intent.\n * @returns An independent snapshot, or an explicit malformed-preview refusal.\n */\nexport function captureExpectedScaleLadder(\n expected: ExpectedScaleLadder | undefined,\n): ExpectedScaleLadder | undefined {\n if (expected === undefined) {\n return undefined;\n }\n if (expected === null || typeof expected !== 'object') {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);\n }\n const { prices, sizes } = expected;\n if (\n !Array.isArray(expected.prices) ||\n !Array.isArray(expected.sizes) ||\n Object.keys(expected).some(\n (key) =>\n ![\n 'prices',\n 'sizes',\n 'totalSize',\n 'totalNotional',\n 'minimumBaseSize',\n 'minimumQuoteAmount',\n 'sizeDecimals',\n ].includes(key),\n )\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);\n }\n return {\n ...expected,\n prices: [...prices],\n sizes: [...sizes],\n };\n}\n\n/** Own financial request values before routing or fee resolution can yield.\n * @param params - Caller-owned order request.\n * @returns An independent request preserving legacy preview omission.\n */\nexport function captureScaleOrderParams(params: OrderParams): OrderParams {\n const captured = { ...params };\n if (captured.expectedScaleLadder !== undefined) {\n captured.expectedScaleLadder = captureExpectedScaleLadder(\n captured.expectedScaleLadder,\n );\n }\n return captured;\n}\n\n/** Refuse any change to the approved normalized financial intent.\n * @param expected - Optional caller constraint; omission is legacy unbound placement.\n * @param ladder - Fresh normalized placement quantities and prices.\n * @param market - Fresh venue minimums and quantity grid.\n */\nexport function assertExpectedScaleLadder(\n expected: ExpectedScaleLadder | undefined,\n ladder: { prices: string[]; sizes: string[]; size: string; notional: string },\n market: LighterOrderBookMeta,\n): void {\n if (expected === undefined) {\n return;\n }\n const captured = captureExpectedScaleLadder(expected);\n if (\n !captured ||\n captured.prices.length !== ladder.prices.length ||\n captured.sizes.length !== ladder.sizes.length ||\n ladder.prices.some((price, index) => price !== captured.prices[index]) ||\n ladder.sizes.some((size, index) => size !== captured.sizes[index]) ||\n captured.totalSize !== ladder.size ||\n captured.totalNotional !== ladder.notional ||\n captured.minimumBaseSize !== market.minBaseAmount ||\n captured.minimumQuoteAmount !== market.minQuoteAmount ||\n captured.sizeDecimals !== market.supportedSizeDecimals\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_PREVIEW_STALE);\n }\n}\n\n/** Build all rungs and prove exact base and quote bounds before any write.\n * @param params - Scale intent.\n * @param market - Active venue metadata.\n * @returns Exact normalized rungs and totals.\n */\nexport function buildLighterScaleLadder(\n params: Omit<OrderParams, 'size' | 'isBuy'> &\n Partial<Pick<OrderParams, 'size' | 'isBuy'>>,\n market: LighterOrderBookMeta,\n): { prices: string[]; sizes: string[]; size: string; notional: string } {\n const unsupported = [\n 'price',\n 'triggerPrice',\n 'timeInForce',\n 'takeProfitPrice',\n 'stopLossPrice',\n 'takeProfitSize',\n 'stopLossSize',\n 'tpslLinkage',\n 'grouping',\n 'clientOrderId',\n 'twapDuration',\n 'twapRandomize',\n 'chaseIntervalMs',\n 'chaseMaxDurationMs',\n 'chaseMaxRepricings',\n 'chaseMaxDistanceBps',\n 'marginMode',\n 'slippage',\n 'maxSlippageBps',\n 'priceAtCalculation',\n 'isFullClose',\n ] as const;\n const field = unsupported.find((key) => params[key] !== undefined);\n if (field) {\n throw new Error(`Lighter Scale does not support ${field}`);\n }\n if (\n market.status !== 'active' ||\n market.marketType !== 'perp' ||\n params.orderType !== 'scale'\n ) {\n throw new Error('Lighter Scale requires an active perpetual market');\n }\n const {\n scaleNumOrders: count,\n scaleMinPrice: min,\n scaleMaxPrice: max,\n } = params;\n if (min === undefined || max === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED);\n }\n if (count === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);\n }\n const prices = normalizeLighterScalePrices(\n min,\n max,\n count,\n market.supportedPriceDecimals,\n );\n const decimals = market.supportedSizeDecimals;\n if (\n !Number.isInteger(decimals) ||\n decimals < 0 ||\n decimals > LIGHTER_SCALE_MAX_DECIMALS\n ) {\n throw new Error('Invalid Lighter Scale precision');\n }\n if (\n params.scaleSkew !== undefined &&\n (!Number.isFinite(params.scaleSkew) || params.scaleSkew <= 0)\n ) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);\n }\n let budget: BigNumber | undefined;\n let rawSize: BigNumber;\n try {\n budget =\n params.usdAmount === undefined\n ? undefined\n : parseScaleDecimal(params.usdAmount);\n rawSize = budget ? budget.div(prices[0]) : parseScaleDecimal(params.size);\n } catch {\n throw new Error(PERPS_ERROR_CODES.ORDER_SIZE_POSITIVE);\n }\n const units = rawSize.shiftedBy(decimals).integerValue(BigNumber.ROUND_DOWN);\n if (units.gt(Number.MAX_SAFE_INTEGER) || units.lt(count)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n const split = (total: number): string[] => {\n const sizes = splitScaleSizes({\n totalSize: new BigNumber(total).shiftedBy(-decimals).toNumber(),\n count,\n szDecimals: decimals,\n skew: params.scaleSkew,\n });\n const sum = sizes.reduce(\n (value, size) => value.plus(size),\n new BigNumber(0),\n );\n if (\n !sum.shiftedBy(decimals).eq(total) ||\n sizes.some((size) => !new BigNumber(size).shiftedBy(decimals).isInteger())\n ) {\n throw new Error('Lighter Scale size conservation failed');\n }\n return sizes;\n };\n const quote = (sizes: string[]): BigNumber =>\n sizes.reduce(\n (total, size, index) =>\n total.plus(new BigNumber(size).times(prices[index])),\n new BigNumber(0),\n );\n let total = units.toNumber();\n if (budget) {\n let low = count;\n let high = total;\n let feasible: number | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n let sizes: string[];\n try {\n sizes = split(candidate);\n } catch {\n low = candidate + 1;\n continue;\n }\n if (quote(sizes).lte(budget)) {\n feasible = candidate;\n low = candidate + 1;\n } else {\n high = candidate - 1;\n }\n }\n if (feasible === undefined) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n total = feasible;\n }\n const sizes = split(total);\n const minimumBase = parseScaleDecimal(market.minBaseAmount);\n const minimumQuote = parseScaleDecimal(market.minQuoteAmount);\n for (const [index, size] of sizes.entries()) {\n if (new BigNumber(size).shiftedBy(decimals).gt(LIGHTER_MAX_BASE_AMOUNT)) {\n throw new Error('Lighter Scale child exceeds native base amount');\n }\n if (new BigNumber(size).lt(minimumBase)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);\n }\n if (new BigNumber(size).times(prices[index]).lt(minimumQuote)) {\n throw new Error(PERPS_ERROR_CODES.ORDER_SCALE_NOTIONAL_TOO_SMALL);\n }\n }\n const normalized = new BigNumber(total).shiftedBy(-decimals);\n if (normalized.gt(rawSize) || (budget && quote(sizes).gt(budget))) {\n throw new Error('Lighter Scale exposure exceeds intent');\n }\n return {\n prices,\n sizes,\n size: normalized.toFixed(),\n notional: quote(sizes).toFixed(),\n };\n}\n\n/** Whether every leg is proven unable to execute again.\n * @param group - Durable ownership.\n * @returns Terminal status.\n */\nexport function isLighterScaleTerminal(group: LighterScaleGroup): boolean {\n return (\n group.placementStopped &&\n group.rungs.every((rung) =>\n ['filled', 'canceled', 'rejected', 'prepared'].includes(rung.state),\n )\n );\n}\n\n/** Project actual accepted and submitted exposure without invented identities.\n * @param group - Durable ownership.\n * @returns Shared receipt plus durable scope.\n */\nexport function toLighterScaleGroup(group: LighterScaleGroup): ScaleOrderGroup {\n const submitted = group.rungs.filter((rung) => rung.state !== 'prepared');\n const uncertain = group.rungs.some(\n (rung) => rung.state === 'unknown' || rung.state === 'submitted',\n );\n const accepted = group.rungs.filter((rung) =>\n ['accepted', 'resting', 'filled', 'canceled'].includes(rung.state),\n );\n const total = (rungs: LighterScaleRung[]): BigNumber =>\n rungs.reduce((sum, rung) => sum.plus(rung.size), new BigNumber(0));\n const acceptedSize = total(accepted);\n const acceptedChildren: NonNullable<OrderResult['acceptedChildren']> =\n accepted.map((rung) => {\n if (\n rung.orderId !== undefined &&\n (rung.state === 'resting' ||\n rung.state === 'filled' ||\n rung.state === 'canceled')\n ) {\n return { state: rung.state, orderId: rung.orderId };\n }\n return { state: 'waitingForFill' };\n });\n const fillsKnown =\n !uncertain &&\n accepted.length > 0 &&\n accepted.every((rung) => rung.filledSize !== undefined);\n const filledSize = accepted.reduce(\n (sum, rung) =>\n rung.filledSize === undefined ? sum : sum.plus(rung.filledSize),\n new BigNumber(0),\n );\n let state: ScaleOrderGroup['state'] = 'placing';\n if (group.placementStopped) {\n state = 'stopped';\n }\n if (uncertain) {\n state = 'unknown';\n }\n if (isLighterScaleTerminal(group)) {\n state = 'terminal';\n }\n return {\n groupId: group.groupId,\n orderId: group.groupId,\n symbol: group.symbol,\n providerId: 'lighter',\n accountIndex: group.accountIndex,\n apiKeyIndex: group.apiKeyIndex,\n walletAddress: group.walletAddress,\n network: group.network,\n state,\n submittedSize: total(submitted).toFixed(),\n ...(uncertain ? {} : { acceptedSize: acceptedSize.toFixed() }),\n acceptedChildren,\n childOrderIds: accepted.flatMap((rung) =>\n rung.state === 'resting' && rung.orderId !== undefined\n ? [rung.orderId]\n : [],\n ),\n ...(!uncertain && acceptedSize.gt(0)\n ? {\n weightedAverageLimitPrice: accepted\n .reduce(\n (sum, rung) =>\n sum.plus(new BigNumber(rung.size).times(rung.price)),\n new BigNumber(0),\n )\n .div(acceptedSize)\n .toFixed(),\n }\n : {}),\n ...(fillsKnown ? { filledSize: filledSize.toFixed() } : {}),\n };\n}\n\n/** Validate an account journal before using durable financial ownership.\n * @param raw - Serialized journal.\n * @returns Bounded validated groups.\n */\nexport function parseLighterScaleGroups(\n raw: string | null,\n): LighterScaleGroup[] {\n if (raw === null) {\n return [];\n }\n if (raw.length > LIGHTER_SCALE_MAX_JOURNAL_LENGTH) {\n throw new Error('Lighter Scale journal exceeds its storage bound');\n }\n const groups: unknown = JSON.parse(raw);\n if (!Array.isArray(groups) || groups.length > LIGHTER_SCALE_MAX_GROUPS) {\n throw new Error('Invalid Lighter Scale journal');\n }\n const ids = new Set<number>();\n const groupsSeen = new Set<string>();\n const integer = (value: unknown): value is number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n for (const value of groups) {\n const group = value as Partial<LighterScaleGroup>;\n if (\n group?.version !== 1 ||\n typeof group.groupId !== 'string' ||\n !group.groupId.startsWith(LIGHTER_SCALE_PREFIX) ||\n group.groupId.length > LIGHTER_SCALE_MAX_GROUP_ID_LENGTH ||\n groupsSeen.has(group.groupId) ||\n typeof group.symbol !== 'string' ||\n !group.symbol ||\n group.symbol.length > LIGHTER_SCALE_MAX_SYMBOL_LENGTH ||\n !integer(group.accountIndex) ||\n !integer(group.apiKeyIndex) ||\n group.apiKeyIndex < LIGHTER_MIN_TRADING_API_KEY_INDEX ||\n group.apiKeyIndex > LIGHTER_MAX_TRADING_API_KEY_INDEX ||\n !integer(group.marketId) ||\n !integer(group.createdAt) ||\n typeof group.walletAddress !== 'string' ||\n !/^0x[0-9a-f]{40}$/u.test(group.walletAddress) ||\n !['mainnet', 'testnet'].includes(group.network ?? '') ||\n !integer(group.sizeDecimals) ||\n group.sizeDecimals > LIGHTER_SCALE_MAX_DECIMALS ||\n !integer(group.priceDecimals) ||\n group.priceDecimals > LIGHTER_SCALE_MAX_DECIMALS ||\n typeof group.isBuy !== 'boolean' ||\n typeof group.reduceOnly !== 'boolean' ||\n typeof group.placementStopped !== 'boolean' ||\n !Array.isArray(group.rungs) ||\n group.rungs.length < SCALE_ORDER_COUNT.min ||\n group.rungs.length > SCALE_ORDER_COUNT.max\n ) {\n throw new Error('Invalid Lighter Scale group');\n }\n groupsSeen.add(group.groupId);\n let previousPrice = 0;\n const orderIds = new Set<string>();\n for (const rung of group.rungs) {\n if (\n !rung ||\n !integer(rung.clientOrderId) ||\n rung.clientOrderId === 0 ||\n rung.clientOrderId >= LIGHTER_SCALE_CLIENT_ID_LIMIT ||\n ids.has(rung.clientOrderId) ||\n !integer(rung.priceInt) ||\n rung.priceInt < 1 ||\n rung.priceInt > LIGHTER_MAX_WIRE_PRICE ||\n !integer(rung.sizeInt) ||\n rung.sizeInt < 1 ||\n new BigNumber(rung.sizeInt).gt(LIGHTER_MAX_BASE_AMOUNT) ||\n ![\n 'prepared',\n 'unknown',\n 'submitted',\n 'accepted',\n 'resting',\n 'filled',\n 'canceled',\n 'rejected',\n ].includes(rung.state) ||\n !(rung.nonce === null || integer(rung.nonce)) ||\n !(\n rung.txHash === null ||\n (typeof rung.txHash === 'string' &&\n /^[a-f\\d]+$/iu.test(rung.txHash) &&\n rung.txHash.length <= LIGHTER_SCALE_MAX_HASH_LENGTH)\n ) ||\n !(\n rung.expiresAt === null ||\n (integer(rung.expiresAt) && rung.expiresAt > 0)\n ) ||\n (rung.orderId !== undefined && !/^\\d{1,20}$/u.test(rung.orderId))\n ) {\n throw new Error('Invalid Lighter Scale rung');\n }\n if (\n rung.cancelAttempt !== undefined &&\n (rung.cancelAttempt === null ||\n typeof rung.cancelAttempt !== 'object' ||\n rung.orderId === undefined ||\n !group.placementStopped ||\n (rung.cancelAttempt.acknowledged !== undefined &&\n typeof rung.cancelAttempt.acknowledged !== 'boolean') ||\n !integer(rung.cancelAttempt.apiKeyIndex) ||\n rung.cancelAttempt.apiKeyIndex < LIGHTER_MIN_TRADING_API_KEY_INDEX ||\n rung.cancelAttempt.apiKeyIndex > LIGHTER_MAX_TRADING_API_KEY_INDEX ||\n !integer(rung.cancelAttempt.nonce) ||\n typeof rung.cancelAttempt.txHash !== 'string' ||\n !/^[a-f\\d]{8,128}$/u.test(rung.cancelAttempt.txHash) ||\n !integer(rung.cancelAttempt.expiresAt) ||\n rung.cancelAttempt.expiresAt === 0)\n ) {\n throw new Error('Invalid Lighter Scale cancellation attempt');\n }\n if (\n !parseScaleDecimal(rung.price)\n .shiftedBy(group.priceDecimals)\n .eq(rung.priceInt) ||\n !parseScaleDecimal(rung.size)\n .shiftedBy(group.sizeDecimals)\n .eq(rung.sizeInt)\n ) {\n throw new Error('Lighter Scale wire quantities differ from intent');\n }\n if (\n rung.priceInt <= previousPrice ||\n (rung.orderId !== undefined && orderIds.has(rung.orderId))\n ) {\n throw new Error(\n 'Invalid Lighter Scale ladder ordering or duplicate venue identity',\n );\n }\n previousPrice = rung.priceInt;\n if (rung.orderId !== undefined) {\n orderIds.add(rung.orderId);\n }\n ids.add(rung.clientOrderId);\n if (\n !(\n rung.orderExpiry === null ||\n (integer(rung.orderExpiry) && rung.orderExpiry > 0)\n ) ||\n (rung.state !== 'prepared' && rung.orderExpiry === null)\n ) {\n throw new Error('Invalid Lighter Scale order expiry');\n }\n if (\n rung.nonAcceptance !== undefined &&\n (!['failed', 'expired', 'nonce-consumed'].includes(\n rung.nonAcceptance,\n ) ||\n !['unknown', 'rejected'].includes(rung.state) ||\n rung.orderId !== undefined)\n ) {\n throw new Error('Invalid Lighter Scale non-acceptance proof');\n }\n if (\n rung.state !== 'prepared' &&\n (rung.nonce === null || rung.txHash === null || rung.expiresAt === null)\n ) {\n throw new Error('Invalid Lighter Scale dispatch identity');\n }\n if (\n (rung.state === 'resting' ||\n rung.state === 'filled' ||\n rung.state === 'canceled') &&\n rung.orderId === undefined\n ) {\n throw new Error('Missing Lighter Scale venue identity');\n }\n if (\n rung.filledSize !== undefined &&\n (typeof rung.filledSize !== 'string' ||\n !/^\\d+(?:\\.\\d+)?$/u.test(rung.filledSize) ||\n new BigNumber(rung.filledSize).gt(rung.size))\n ) {\n throw new Error('Invalid Lighter Scale fill');\n }\n }\n }\n return groups as LighterScaleGroup[];\n}\n"]}
@@ -1,42 +0,0 @@
1
- import { LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME } from '../constants/lighterConfig.js';
2
- /** Inputs for native TWAP wire preparation; this does not authorize dispatch. */
3
- type LighterTwapWireIntent = {
4
- size: string;
5
- referencePrice: string;
6
- sizeDecimals: number;
7
- priceDecimals: number;
8
- isBuy: boolean;
9
- /** Fractional slippage, represented as an exact decimal. */
10
- slippage: string;
11
- durationMinutes: number;
12
- /** Millisecond clock reading captured by the caller, never venue seconds. */
13
- nowMilliseconds: number;
14
- randomize: boolean;
15
- reduceOnly: boolean;
16
- };
17
- type LighterTwapWireOrder = Readonly<{
18
- baseAmount: string;
19
- price: string;
20
- isAsk: 0 | 1;
21
- orderType: 6;
22
- timeInForce: typeof LIGHTER_TIME_IN_FORCE_GOOD_TILL_TIME;
23
- reduceOnly: 0 | 1;
24
- triggerPrice: '0';
25
- orderExpiry: number;
26
- }>;
27
- /**
28
- * Prepare the verified type6 CreateOrder fields without signing or dispatching.
29
- *
30
- * This primitive deliberately supplies no lifecycle or acceptance claim. Lighter
31
- * TWAP remains unavailable until authoritative parent fills and termination are
32
- * established. The uint32 price and 48-bit amount bounds come from the pinned Lighter
33
- * Go constants. Schedule expiry is a safe JavaScript integer within int64;
34
- * transaction ExpiredAt has a separate bound. Numeric narrowing is not validation.
35
- * No unverified venue duration minimum or maximum is imposed here.
36
- *
37
- * @param intent - Exact amount, market precision, price protection, and clock.
38
- * @returns Immutable native order fields suitable for later lifecycle wiring.
39
- */
40
- export declare function prepareLighterTwapOrder(intent: LighterTwapWireIntent): LighterTwapWireOrder;
41
- export {};
42
- //# sourceMappingURL=lighterTwap.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lighterTwap.d.ts","sourceRoot":"","sources":["../../src/utils/lighterTwap.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,oCAAoC,EACrC,MAAM,+BAA+B,CAAC;AAMvC,iFAAiF;AACjF,KAAK,qBAAqB,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,OAAO,CAAC;IACf,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,6EAA6E;IAC7E,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF,KAAK,oBAAoB,GAAG,QAAQ,CAAC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACb,SAAS,EAAE,CAAC,CAAC;IACb,WAAW,EAAE,OAAO,oCAAoC,CAAC;IACzD,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC;IAClB,YAAY,EAAE,GAAG,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC,CAAC;AAEH;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,qBAAqB,GAC5B,oBAAoB,CAwEtB"}