@metamask-previews/perps-controller 24.1.0-preview-e9ac9ffe1 → 24.1.0-preview-70269bbdb

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 (88) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/PerpsController-method-action-types.d.ts +26 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +20 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +159 -2
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +0 -6
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +0 -13
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +19 -3
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +21 -5
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/performanceMetrics.d.ts +2 -14
  18. package/dist/constants/performanceMetrics.d.ts.map +1 -1
  19. package/dist/constants/performanceMetrics.js +1 -17
  20. package/dist/constants/performanceMetrics.js.map +1 -1
  21. package/dist/constants/perpsConfig.d.ts +27 -0
  22. package/dist/constants/perpsConfig.d.ts.map +1 -1
  23. package/dist/constants/perpsConfig.js +27 -0
  24. package/dist/constants/perpsConfig.js.map +1 -1
  25. package/dist/index.d.ts +7 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +2 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +2 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/HyperLiquidProvider.d.ts +7 -3
  34. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  35. package/dist/providers/HyperLiquidProvider.js +161 -103
  36. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  37. package/dist/providers/LighterProvider.d.ts +3 -3
  38. package/dist/providers/LighterProvider.d.ts.map +1 -1
  39. package/dist/providers/LighterProvider.js +20 -9
  40. package/dist/providers/LighterProvider.js.map +1 -1
  41. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  42. package/dist/services/TerminalMarketService.js +4 -2
  43. package/dist/services/TerminalMarketService.js.map +1 -1
  44. package/dist/services/TradingService.js +11 -9
  45. package/dist/services/TradingService.js.map +1 -1
  46. package/dist/types/index.d.ts +107 -2
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/index.js +0 -1
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/advancedOrderLists.d.ts +104 -0
  51. package/dist/utils/advancedOrderLists.d.ts.map +1 -0
  52. package/dist/utils/advancedOrderLists.js +421 -0
  53. package/dist/utils/advancedOrderLists.js.map +1 -0
  54. package/dist/utils/advancedOrders.d.ts +275 -0
  55. package/dist/utils/advancedOrders.d.ts.map +1 -0
  56. package/dist/utils/advancedOrders.js +639 -0
  57. package/dist/utils/advancedOrders.js.map +1 -0
  58. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  59. package/dist/utils/hyperLiquidAdapter.js +4 -1
  60. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  61. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  62. package/dist/utils/hyperLiquidValidation.js +22 -57
  63. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  64. package/dist/utils/index.d.ts +2 -0
  65. package/dist/utils/index.d.ts.map +1 -1
  66. package/dist/utils/index.js +2 -0
  67. package/dist/utils/index.js.map +1 -1
  68. package/dist/utils/lighterScaleOrders.d.ts.map +1 -1
  69. package/dist/utils/lighterScaleOrders.js +16 -65
  70. package/dist/utils/lighterScaleOrders.js.map +1 -1
  71. package/dist/utils/perpsFormatters.d.ts +29 -4
  72. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  73. package/dist/utils/perpsFormatters.js +51 -5
  74. package/dist/utils/perpsFormatters.js.map +1 -1
  75. package/docs/README.md +28 -0
  76. package/docs/architecture.md +256 -0
  77. package/docs/contracts/events.md +267 -0
  78. package/docs/contracts/feature-flags.md +39 -0
  79. package/docs/contracts/traces.md +83 -0
  80. package/docs/formatting.md +82 -0
  81. package/docs/tpsl.md +89 -0
  82. package/docs/venues/hyperliquid/README.md +27 -0
  83. package/docs/venues/hyperliquid/init-flow.md +116 -0
  84. package/docs/venues/hyperliquid/order-types.md +60 -0
  85. package/docs/venues/hyperliquid/trading-rules.md +77 -0
  86. package/docs/venues/lighter/api-keys.md +58 -0
  87. package/docs/venues/lighter/capabilities.md +74 -0
  88. package/package.json +4 -3
@@ -0,0 +1,104 @@
1
+ import type { ChaseOrder, ChaseOrderLists, PerpsProviderType, SubscribeTwapOrdersParams, TwapOrder } from '../types/index.js';
2
+ /** Where a live TWAP list reads and streams schedules from. */
3
+ export type LiveTwapOrderSource = {
4
+ getTwapOrders: () => Promise<TwapOrder[]>;
5
+ subscribeToTwapOrders: (params: SubscribeTwapOrdersParams) => () => void;
6
+ /**
7
+ * Names the account, provider and network the reads follow. When it
8
+ * changes, held rows are dropped so one context's TWAPs never show in
9
+ * another.
10
+ */
11
+ getContextKey?: () => string;
12
+ /**
13
+ * Calls the listener when the account, provider or network may have
14
+ * changed, so held rows clear at once instead of on the next read.
15
+ */
16
+ subscribeToContextChanges?: (listener: () => void) => () => void;
17
+ };
18
+ /** A chase cancel that succeeded, with the ending the provider reported. */
19
+ export type CanceledChaseOrder = {
20
+ handle: string;
21
+ providerId?: PerpsProviderType;
22
+ /** The chase's final snapshot, from `CancelOrderResult.chaseOrder`. */
23
+ chaseOrder: ChaseOrder;
24
+ };
25
+ /** Where a live chase list reads chase snapshots from. */
26
+ export type LiveChaseOrderSource = {
27
+ getChaseOrders: () => Promise<ChaseOrder[]>;
28
+ /**
29
+ * Names the account, provider and network the reads follow. When it
30
+ * changes, held lists are dropped so one context's chases, and their
31
+ * cancel actions, never show in another.
32
+ */
33
+ getContextKey?: () => string;
34
+ /**
35
+ * Calls the listener when the account, provider or network may have
36
+ * changed, so held lists clear at once instead of on the next read.
37
+ */
38
+ subscribeToContextChanges?: (listener: () => void) => () => void;
39
+ /**
40
+ * Calls the listener after a chase cancel succeeds with a known ending. A
41
+ * provider can drop a canceled chase before the next read, so this is how
42
+ * the list learns how the chase ended rather than guessing from its absence.
43
+ */
44
+ subscribeToChaseCancellations?: (listener: (canceled: CanceledChaseOrder) => void) => () => void;
45
+ };
46
+ /**
47
+ * Keep one merged TWAP list from the venue stream and reads.
48
+ *
49
+ * The read is the authority: a schedule no read lists is dropped, unless the
50
+ * stream still reports it (the stream can know of a TWAP before a read does,
51
+ * for example one placed elsewhere). A push the last read cannot explain
52
+ * triggers one catch-up read. While a schedule runs, or after a failed read,
53
+ * reads repeat so slice fills, and with them execution totals, keep rising.
54
+ * When the source's context key changes, held rows reset and the stream
55
+ * reopens, and pushes from the earlier stream are ignored.
56
+ *
57
+ * Works over any source: the controller passes itself, and a client on the
58
+ * other side of a messenger can pass its messenger calls.
59
+ *
60
+ * @param params - Source, listener and cadence.
61
+ * @param params.source - Reads and stream of TWAP schedules.
62
+ * @param params.callback - Receives the merged list, newest first, on change.
63
+ * @param params.onError - Receives read failures; the list keeps its state.
64
+ * @param params.refreshIntervalMs - Read cadence while a schedule runs.
65
+ * @param params.catchUpIntervalMs - Delay before a catch-up read.
66
+ * @returns A cleanup function that stops reads and the stream.
67
+ */
68
+ export declare function createLiveTwapOrderList(params: {
69
+ source: LiveTwapOrderSource;
70
+ callback: (twapOrders: TwapOrder[]) => void;
71
+ onError?: (error: Error) => void;
72
+ refreshIntervalMs?: number;
73
+ catchUpIntervalMs?: number;
74
+ }): () => void;
75
+ /**
76
+ * Keep running and history chase lists from repeated reads.
77
+ *
78
+ * Ended chases stay in history after a provider drops them, up to
79
+ * `historyLimit`. A running chase a read omits stays for `omissionGraceReads`
80
+ * reads, since an aggregated read drops a provider whose read failed. Reads
81
+ * repeat at `refreshIntervalMs` for as long as the list is subscribed, so a
82
+ * chase placed anywhere appears without a manual refresh. Lists reset when the
83
+ * source's context key changes. When a chase cancel succeeds with a known
84
+ * ending, the list keeps that ending, also for a chase no read has listed yet,
85
+ * and keeps it in history after the provider drops the session.
86
+ *
87
+ * @param params - Source, listener and cadence.
88
+ * @param params.source - Reads of chase snapshots.
89
+ * @param params.callback - Receives the lists on change.
90
+ * @param params.onError - Receives read failures; the lists keep their state.
91
+ * @param params.refreshIntervalMs - Read cadence.
92
+ * @param params.historyLimit - Most ended chases kept.
93
+ * @param params.omissionGraceReads - Reads a running chase survives omission.
94
+ * @returns A cleanup function that stops reads.
95
+ */
96
+ export declare function createLiveChaseOrderList(params: {
97
+ source: LiveChaseOrderSource;
98
+ callback: (lists: ChaseOrderLists) => void;
99
+ onError?: (error: Error) => void;
100
+ refreshIntervalMs?: number;
101
+ historyLimit?: number;
102
+ omissionGraceReads?: number;
103
+ }): () => void;
104
+ //# sourceMappingURL=advancedOrderLists.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advancedOrderLists.d.ts","sourceRoot":"","sources":["../../src/utils/advancedOrderLists.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,yBAAyB,EACzB,SAAS,EACV,MAAM,mBAAmB,CAAC;AAkB3B,+DAA+D;AAC/D,MAAM,MAAM,mBAAmB,GAAG;IAChC,aAAa,EAAE,MAAM,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAC1C,qBAAqB,EAAE,CAAC,MAAM,EAAE,yBAAyB,KAAK,MAAM,IAAI,CAAC;IACzE;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,MAAM,CAAC;IAC7B;;;OAGG;IACH,yBAAyB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,IAA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,EAAE,MAAM,CAAC;IAC3B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B,GAAG,MAAM,IAAI,CA8Kb"}
@@ -0,0 +1,421 @@
1
+ import { CHASE_ORDER_CONFIG, TWAP_ORDER_CONFIG, } from '../constants/perpsConfig.js';
2
+ import { chaseOrderKey, isChaseOrderCancelable, isTwapOrderActive, mergeChaseOrderHistory, mergeTwapOrders, twapOrderKey, } from './advancedOrders.js';
3
+ import { ensureError } from './errorUtils.js';
4
+ /**
5
+ * Do nothing; the cleanup of a stream not yet open.
6
+ *
7
+ * @returns Nothing.
8
+ */
9
+ const noop = () => undefined;
10
+ /**
11
+ * Keep one merged TWAP list from the venue stream and reads.
12
+ *
13
+ * The read is the authority: a schedule no read lists is dropped, unless the
14
+ * stream still reports it (the stream can know of a TWAP before a read does,
15
+ * for example one placed elsewhere). A push the last read cannot explain
16
+ * triggers one catch-up read. While a schedule runs, or after a failed read,
17
+ * reads repeat so slice fills, and with them execution totals, keep rising.
18
+ * When the source's context key changes, held rows reset and the stream
19
+ * reopens, and pushes from the earlier stream are ignored.
20
+ *
21
+ * Works over any source: the controller passes itself, and a client on the
22
+ * other side of a messenger can pass its messenger calls.
23
+ *
24
+ * @param params - Source, listener and cadence.
25
+ * @param params.source - Reads and stream of TWAP schedules.
26
+ * @param params.callback - Receives the merged list, newest first, on change.
27
+ * @param params.onError - Receives read failures; the list keeps its state.
28
+ * @param params.refreshIntervalMs - Read cadence while a schedule runs.
29
+ * @param params.catchUpIntervalMs - Delay before a catch-up read.
30
+ * @returns A cleanup function that stops reads and the stream.
31
+ */
32
+ export function createLiveTwapOrderList(params) {
33
+ const { source, callback, onError } = params;
34
+ const refreshIntervalMs = params.refreshIntervalMs ?? TWAP_ORDER_CONFIG.RefreshIntervalMs;
35
+ const catchUpIntervalMs = params.catchUpIntervalMs ?? TWAP_ORDER_CONFIG.StreamCatchUpIntervalMs;
36
+ let orders = [];
37
+ let emitted;
38
+ let listed = new Set();
39
+ let streamed = new Set();
40
+ let stopped = false;
41
+ let failed = false;
42
+ // Generation of the read in flight, if any. A read for a context the list
43
+ // has left neither blocks nor feeds the new context's reads.
44
+ let activeRead;
45
+ let readAgain = false;
46
+ let timer;
47
+ let timerDueAt = Number.POSITIVE_INFINITY;
48
+ let context = source.getContextKey?.();
49
+ // Bumped on every context reset, so a read can tell it outlived one even
50
+ // when a stream push already moved `context` to the new value.
51
+ let generation = 0;
52
+ let unsubscribeStream = noop;
53
+ const resetOnContextChange = () => {
54
+ const current = source.getContextKey?.();
55
+ if (current === context) {
56
+ return false;
57
+ }
58
+ context = current;
59
+ generation += 1;
60
+ orders = [];
61
+ listed = new Set();
62
+ streamed = new Set();
63
+ // The stream answers for the context it opened in, so open a new one.
64
+ openStream();
65
+ return true;
66
+ };
67
+ const emit = () => {
68
+ const serialized = JSON.stringify(orders);
69
+ if (serialized !== emitted) {
70
+ emitted = serialized;
71
+ callback(orders);
72
+ }
73
+ };
74
+ const schedule = (delayMs) => {
75
+ const dueAt = Date.now() + delayMs;
76
+ if (stopped || (timer !== undefined && timerDueAt <= dueAt)) {
77
+ return;
78
+ }
79
+ clearTimeout(timer);
80
+ timerDueAt = dueAt;
81
+ timer = setTimeout(() => {
82
+ timer = undefined;
83
+ timerDueAt = Number.POSITIVE_INFINITY;
84
+ read().catch(() => undefined);
85
+ }, delayMs);
86
+ };
87
+ const scheduleNext = () => {
88
+ if (failed || orders.some(isTwapOrderActive)) {
89
+ schedule(refreshIntervalMs);
90
+ }
91
+ };
92
+ /**
93
+ * Read the venue, merge the result and schedule the next read.
94
+ */
95
+ async function read() {
96
+ if (resetOnContextChange()) {
97
+ // Clear the old context's rows now, not when this read returns.
98
+ emit();
99
+ }
100
+ if (activeRead === generation) {
101
+ readAgain = true;
102
+ return;
103
+ }
104
+ const readGeneration = generation;
105
+ activeRead = readGeneration;
106
+ let result = [];
107
+ let failure;
108
+ try {
109
+ result = await source.getTwapOrders();
110
+ }
111
+ catch (error) {
112
+ failure = { error };
113
+ }
114
+ if (stopped) {
115
+ return;
116
+ }
117
+ if (resetOnContextChange()) {
118
+ emit();
119
+ }
120
+ if (generation !== readGeneration) {
121
+ // The read answered for a context the list has left. Start a read for
122
+ // the new one unless another read already did.
123
+ if (activeRead === readGeneration) {
124
+ activeRead = undefined;
125
+ readAgain = false;
126
+ schedule(0);
127
+ }
128
+ return;
129
+ }
130
+ activeRead = undefined;
131
+ if (failure) {
132
+ failed = true;
133
+ onError?.(ensureError(failure.error, 'createLiveTwapOrderList'));
134
+ }
135
+ else {
136
+ const readKeys = new Set(result.map(twapOrderKey));
137
+ orders = mergeTwapOrders(orders.filter((order) => {
138
+ const key = twapOrderKey(order);
139
+ return readKeys.has(key) || streamed.has(key);
140
+ }), result);
141
+ listed = readKeys;
142
+ failed = false;
143
+ emit();
144
+ }
145
+ if (readAgain) {
146
+ readAgain = false;
147
+ schedule(0);
148
+ return;
149
+ }
150
+ scheduleNext();
151
+ }
152
+ /**
153
+ * Merge a stream push into the list, unless it comes from a stream opened
154
+ * for an earlier context.
155
+ *
156
+ * @param streamGeneration - Generation the pushing stream was opened in.
157
+ * @param pushed - The pushed schedules.
158
+ */
159
+ function onPush(streamGeneration, pushed) {
160
+ if (stopped || streamGeneration !== generation) {
161
+ return;
162
+ }
163
+ if (resetOnContextChange()) {
164
+ // The push answered for the context the list just left.
165
+ emit();
166
+ readAgain = false;
167
+ schedule(0);
168
+ return;
169
+ }
170
+ const before = new Map(orders.map((order) => [twapOrderKey(order), order]));
171
+ streamed = new Set(pushed.map(twapOrderKey));
172
+ orders = mergeTwapOrders(orders, pushed);
173
+ emit();
174
+ const merged = new Map(orders.map((order) => [twapOrderKey(order), order]));
175
+ const unexplained = [...streamed].some((key) => !listed.has(key) || before.get(key)?.status !== merged.get(key)?.status);
176
+ if (unexplained || pushed.length === 0) {
177
+ schedule(catchUpIntervalMs);
178
+ }
179
+ }
180
+ /**
181
+ * Open the stream for the current context, closing the previous one.
182
+ */
183
+ function openStream() {
184
+ const previous = unsubscribeStream;
185
+ unsubscribeStream = noop;
186
+ previous();
187
+ if (stopped) {
188
+ return;
189
+ }
190
+ const streamGeneration = generation;
191
+ const unsubscribe = source.subscribeToTwapOrders({
192
+ callback: (pushed) => onPush(streamGeneration, pushed),
193
+ });
194
+ if (stopped || streamGeneration !== generation) {
195
+ // A first push already moved the list to another context.
196
+ unsubscribe();
197
+ }
198
+ else {
199
+ unsubscribeStream = unsubscribe;
200
+ }
201
+ }
202
+ openStream();
203
+ const unsubscribeContext = source.subscribeToContextChanges?.(() => {
204
+ if (!stopped && resetOnContextChange()) {
205
+ emit();
206
+ readAgain = false;
207
+ schedule(0);
208
+ }
209
+ });
210
+ read().catch(() => undefined);
211
+ return () => {
212
+ stopped = true;
213
+ clearTimeout(timer);
214
+ unsubscribeStream();
215
+ unsubscribeContext?.();
216
+ };
217
+ }
218
+ /**
219
+ * Whether two snapshots name the same chase. A missing provider matches any,
220
+ * since single-provider reads leave it unset.
221
+ *
222
+ * @param left - One chase.
223
+ * @param right - The other chase.
224
+ * @returns True for the same handle on a compatible provider.
225
+ */
226
+ function isSameChase(left, right) {
227
+ return (left.handle === right.handle &&
228
+ (left.providerId === undefined ||
229
+ right.providerId === undefined ||
230
+ left.providerId === right.providerId));
231
+ }
232
+ /**
233
+ * Copy a snapshot under the provider the list holds it by.
234
+ *
235
+ * @param order - The snapshot.
236
+ * @param providerId - Provider to record, or none.
237
+ * @returns The snapshot with exactly that provider.
238
+ */
239
+ function withProvider(order, providerId) {
240
+ const { providerId: _previous, ...rest } = order;
241
+ return providerId === undefined ? rest : { ...rest, providerId };
242
+ }
243
+ /**
244
+ * Keep running and history chase lists from repeated reads.
245
+ *
246
+ * Ended chases stay in history after a provider drops them, up to
247
+ * `historyLimit`. A running chase a read omits stays for `omissionGraceReads`
248
+ * reads, since an aggregated read drops a provider whose read failed. Reads
249
+ * repeat at `refreshIntervalMs` for as long as the list is subscribed, so a
250
+ * chase placed anywhere appears without a manual refresh. Lists reset when the
251
+ * source's context key changes. When a chase cancel succeeds with a known
252
+ * ending, the list keeps that ending, also for a chase no read has listed yet,
253
+ * and keeps it in history after the provider drops the session.
254
+ *
255
+ * @param params - Source, listener and cadence.
256
+ * @param params.source - Reads of chase snapshots.
257
+ * @param params.callback - Receives the lists on change.
258
+ * @param params.onError - Receives read failures; the lists keep their state.
259
+ * @param params.refreshIntervalMs - Read cadence.
260
+ * @param params.historyLimit - Most ended chases kept.
261
+ * @param params.omissionGraceReads - Reads a running chase survives omission.
262
+ * @returns A cleanup function that stops reads.
263
+ */
264
+ export function createLiveChaseOrderList(params) {
265
+ const { source, callback, onError, historyLimit } = params;
266
+ const refreshIntervalMs = params.refreshIntervalMs ?? CHASE_ORDER_CONFIG.RefreshIntervalMs;
267
+ const omissionGraceReads = params.omissionGraceReads ?? CHASE_ORDER_CONFIG.OmissionGraceReads;
268
+ let lists;
269
+ let emitted;
270
+ let stopped = false;
271
+ let timer;
272
+ let context = source.getContextKey?.();
273
+ let generation = 0;
274
+ let activeRead;
275
+ let omissions = new Map();
276
+ // Endings the provider reported for chases cancelled in this context.
277
+ let endings = [];
278
+ const emit = () => {
279
+ const next = lists ?? { running: [], history: [] };
280
+ const serialized = JSON.stringify(next);
281
+ if (serialized !== emitted) {
282
+ emitted = serialized;
283
+ callback(next);
284
+ }
285
+ };
286
+ const resetOnContextChange = () => {
287
+ const current = source.getContextKey?.();
288
+ if (current === context) {
289
+ return false;
290
+ }
291
+ context = current;
292
+ generation += 1;
293
+ lists = undefined;
294
+ omissions = new Map();
295
+ endings = [];
296
+ return true;
297
+ };
298
+ const endingOf = (order) => endings.find((ending) => isSameChase(ending, order));
299
+ // A read that still offers a cancel (running, or stopped with a child
300
+ // resting) after the cancel reported an ending is stale; the ending replaces
301
+ // it. An ending the read reports wins.
302
+ const settle = (order) => {
303
+ const ending = endingOf(order);
304
+ return ending && isChaseOrderCancelable(order)
305
+ ? withProvider(ending, order.providerId)
306
+ : order;
307
+ };
308
+ // Running chases this read omits, kept while within their grace reads.
309
+ const keepOmitted = (current) => {
310
+ const present = new Set(current.map(chaseOrderKey));
311
+ const kept = [];
312
+ const counts = new Map();
313
+ for (const order of lists?.running ?? []) {
314
+ const key = chaseOrderKey(order);
315
+ const count = (omissions.get(key) ?? 0) + 1;
316
+ if (!present.has(key) && count <= omissionGraceReads) {
317
+ kept.push(order);
318
+ counts.set(key, count);
319
+ }
320
+ }
321
+ omissions = counts;
322
+ return kept;
323
+ };
324
+ const scheduleRead = (delayMs) => {
325
+ clearTimeout(timer);
326
+ timer = setTimeout(() => {
327
+ read().catch(() => undefined);
328
+ }, delayMs);
329
+ };
330
+ /**
331
+ * Read the chases, merge them and schedule the next read.
332
+ */
333
+ async function read() {
334
+ if (resetOnContextChange()) {
335
+ // Clear the old context's chases, and their cancels, now.
336
+ emit();
337
+ }
338
+ if (activeRead === generation) {
339
+ return;
340
+ }
341
+ const readGeneration = generation;
342
+ activeRead = readGeneration;
343
+ let current = [];
344
+ let failure;
345
+ try {
346
+ current = await source.getChaseOrders();
347
+ }
348
+ catch (error) {
349
+ failure = { error };
350
+ }
351
+ if (stopped) {
352
+ return;
353
+ }
354
+ if (resetOnContextChange()) {
355
+ emit();
356
+ }
357
+ if (generation !== readGeneration) {
358
+ // The read answered for a context the list has left. Read the new one
359
+ // now unless another read already started.
360
+ if (activeRead === readGeneration) {
361
+ activeRead = undefined;
362
+ scheduleRead(0);
363
+ }
364
+ return;
365
+ }
366
+ activeRead = undefined;
367
+ if (failure) {
368
+ onError?.(ensureError(failure.error, 'createLiveChaseOrderList'));
369
+ }
370
+ else {
371
+ const settled = current.map(settle);
372
+ lists = mergeChaseOrderHistory({
373
+ previous: lists,
374
+ current: [...settled, ...keepOmitted(settled)],
375
+ historyLimit,
376
+ });
377
+ emit();
378
+ }
379
+ scheduleRead(refreshIntervalMs);
380
+ }
381
+ const unsubscribeContext = source.subscribeToContextChanges?.(() => {
382
+ if (!stopped && resetOnContextChange()) {
383
+ emit();
384
+ scheduleRead(0);
385
+ }
386
+ });
387
+ const unsubscribeCancellations = source.subscribeToChaseCancellations?.(({ handle, providerId, chaseOrder }) => {
388
+ if (stopped) {
389
+ return;
390
+ }
391
+ const ending = withProvider({ ...chaseOrder, handle }, providerId);
392
+ endings = [
393
+ ...endings.filter((held) => !isSameChase(held, ending)),
394
+ ending,
395
+ ];
396
+ // Recorded even before any read lists the chase, so a read still in
397
+ // flight cannot bring it back as running.
398
+ const held = [...(lists?.running ?? []), ...(lists?.history ?? [])];
399
+ const listed = held.find((order) => isSameChase(order, ending));
400
+ lists = mergeChaseOrderHistory({
401
+ previous: {
402
+ running: [],
403
+ history: (lists?.history ?? []).filter((order) => !isSameChase(order, ending)),
404
+ },
405
+ current: [
406
+ ...(lists?.running ?? []).filter((order) => !isSameChase(order, ending)),
407
+ listed ? withProvider(ending, listed.providerId) : ending,
408
+ ],
409
+ historyLimit,
410
+ });
411
+ emit();
412
+ });
413
+ read().catch(() => undefined);
414
+ return () => {
415
+ stopped = true;
416
+ clearTimeout(timer);
417
+ unsubscribeContext?.();
418
+ unsubscribeCancellations?.();
419
+ };
420
+ }
421
+ //# sourceMappingURL=advancedOrderLists.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advancedOrderLists.js","sourceRoot":"","sources":["../../src/utils/advancedOrderLists.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,6BAA6B,CAAC;AAQrC,OAAO,EACL,aAAa,EACb,sBAAsB,EACtB,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;;;GAIG;AACH,MAAM,IAAI,GAAG,GAAS,EAAE,CAAC,SAAS,CAAC;AAmDnC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAMvC;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AAU,CAAC,CAAC,CAAC,CAAC,MAAM;aAC1D;YACD,YAAY;SACb,CAAC,CAAC;QACH,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;IAEF,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAE9B,OAAO,GAAG,EAAE;QACV,OAAO,GAAG,IAAI,CAAC;QACf,YAAY,CAAC,KAAK,CAAC,CAAC;QACpB,kBAAkB,EAAE,EAAE,CAAC;QACvB,wBAAwB,EAAE,EAAE,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n CHASE_ORDER_CONFIG,\n TWAP_ORDER_CONFIG,\n} from '../constants/perpsConfig.js';\nimport type {\n ChaseOrder,\n ChaseOrderLists,\n PerpsProviderType,\n SubscribeTwapOrdersParams,\n TwapOrder,\n} from '../types/index.js';\nimport {\n chaseOrderKey,\n isChaseOrderCancelable,\n isTwapOrderActive,\n mergeChaseOrderHistory,\n mergeTwapOrders,\n twapOrderKey,\n} from './advancedOrders.js';\nimport { ensureError } from './errorUtils.js';\n\n/**\n * Do nothing; the cleanup of a stream not yet open.\n *\n * @returns Nothing.\n */\nconst noop = (): void => undefined;\n\n/** Where a live TWAP list reads and streams schedules from. */\nexport type LiveTwapOrderSource = {\n getTwapOrders: () => Promise<TwapOrder[]>;\n subscribeToTwapOrders: (params: SubscribeTwapOrdersParams) => () => void;\n /**\n * Names the account, provider and network the reads follow. When it\n * changes, held rows are dropped so one context's TWAPs never show in\n * another.\n */\n getContextKey?: () => string;\n /**\n * Calls the listener when the account, provider or network may have\n * changed, so held rows clear at once instead of on the next read.\n */\n subscribeToContextChanges?: (listener: () => void) => () => void;\n};\n\n/** A chase cancel that succeeded, with the ending the provider reported. */\nexport type CanceledChaseOrder = {\n handle: string;\n providerId?: PerpsProviderType;\n /** The chase's final snapshot, from `CancelOrderResult.chaseOrder`. */\n chaseOrder: ChaseOrder;\n};\n\n/** Where a live chase list reads chase snapshots from. */\nexport type LiveChaseOrderSource = {\n getChaseOrders: () => Promise<ChaseOrder[]>;\n /**\n * Names the account, provider and network the reads follow. When it\n * changes, held lists are dropped so one context's chases, and their\n * cancel actions, never show in another.\n */\n getContextKey?: () => string;\n /**\n * Calls the listener when the account, provider or network may have\n * changed, so held lists clear at once instead of on the next read.\n */\n subscribeToContextChanges?: (listener: () => void) => () => void;\n /**\n * Calls the listener after a chase cancel succeeds with a known ending. A\n * provider can drop a canceled chase before the next read, so this is how\n * the list learns how the chase ended rather than guessing from its absence.\n */\n subscribeToChaseCancellations?: (\n listener: (canceled: CanceledChaseOrder) => void,\n ) => () => void;\n};\n\n/**\n * Keep one merged TWAP list from the venue stream and reads.\n *\n * The read is the authority: a schedule no read lists is dropped, unless the\n * stream still reports it (the stream can know of a TWAP before a read does,\n * for example one placed elsewhere). A push the last read cannot explain\n * triggers one catch-up read. While a schedule runs, or after a failed read,\n * reads repeat so slice fills, and with them execution totals, keep rising.\n * When the source's context key changes, held rows reset and the stream\n * reopens, and pushes from the earlier stream are ignored.\n *\n * Works over any source: the controller passes itself, and a client on the\n * other side of a messenger can pass its messenger calls.\n *\n * @param params - Source, listener and cadence.\n * @param params.source - Reads and stream of TWAP schedules.\n * @param params.callback - Receives the merged list, newest first, on change.\n * @param params.onError - Receives read failures; the list keeps its state.\n * @param params.refreshIntervalMs - Read cadence while a schedule runs.\n * @param params.catchUpIntervalMs - Delay before a catch-up read.\n * @returns A cleanup function that stops reads and the stream.\n */\nexport function createLiveTwapOrderList(params: {\n source: LiveTwapOrderSource;\n callback: (twapOrders: TwapOrder[]) => void;\n onError?: (error: Error) => void;\n refreshIntervalMs?: number;\n catchUpIntervalMs?: number;\n}): () => void {\n const { source, callback, onError } = params;\n const refreshIntervalMs =\n params.refreshIntervalMs ?? TWAP_ORDER_CONFIG.RefreshIntervalMs;\n const catchUpIntervalMs =\n params.catchUpIntervalMs ?? TWAP_ORDER_CONFIG.StreamCatchUpIntervalMs;\n\n let orders: TwapOrder[] = [];\n let emitted: string | undefined;\n let listed = new Set<string>();\n let streamed = new Set<string>();\n let stopped = false;\n let failed = false;\n // Generation of the read in flight, if any. A read for a context the list\n // has left neither blocks nor feeds the new context's reads.\n let activeRead: number | undefined;\n let readAgain = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timerDueAt = Number.POSITIVE_INFINITY;\n let context = source.getContextKey?.();\n // Bumped on every context reset, so a read can tell it outlived one even\n // when a stream push already moved `context` to the new value.\n let generation = 0;\n let unsubscribeStream: () => void = noop;\n\n const resetOnContextChange = (): boolean => {\n const current = source.getContextKey?.();\n if (current === context) {\n return false;\n }\n context = current;\n generation += 1;\n orders = [];\n listed = new Set();\n streamed = new Set();\n // The stream answers for the context it opened in, so open a new one.\n openStream();\n return true;\n };\n\n const emit = (): void => {\n const serialized = JSON.stringify(orders);\n if (serialized !== emitted) {\n emitted = serialized;\n callback(orders);\n }\n };\n\n const schedule = (delayMs: number): void => {\n const dueAt = Date.now() + delayMs;\n if (stopped || (timer !== undefined && timerDueAt <= dueAt)) {\n return;\n }\n clearTimeout(timer);\n timerDueAt = dueAt;\n timer = setTimeout(() => {\n timer = undefined;\n timerDueAt = Number.POSITIVE_INFINITY;\n read().catch(() => undefined);\n }, delayMs);\n };\n\n const scheduleNext = (): void => {\n if (failed || orders.some(isTwapOrderActive)) {\n schedule(refreshIntervalMs);\n }\n };\n\n /**\n * Read the venue, merge the result and schedule the next read.\n */\n async function read(): Promise<void> {\n if (resetOnContextChange()) {\n // Clear the old context's rows now, not when this read returns.\n emit();\n }\n if (activeRead === generation) {\n readAgain = true;\n return;\n }\n const readGeneration = generation;\n activeRead = readGeneration;\n let result: TwapOrder[] = [];\n let failure: { error: unknown } | undefined;\n try {\n result = await source.getTwapOrders();\n } catch (error) {\n failure = { error };\n }\n if (stopped) {\n return;\n }\n if (resetOnContextChange()) {\n emit();\n }\n if (generation !== readGeneration) {\n // The read answered for a context the list has left. Start a read for\n // the new one unless another read already did.\n if (activeRead === readGeneration) {\n activeRead = undefined;\n readAgain = false;\n schedule(0);\n }\n return;\n }\n activeRead = undefined;\n if (failure) {\n failed = true;\n onError?.(ensureError(failure.error, 'createLiveTwapOrderList'));\n } else {\n const readKeys = new Set(result.map(twapOrderKey));\n orders = mergeTwapOrders(\n orders.filter((order) => {\n const key = twapOrderKey(order);\n return readKeys.has(key) || streamed.has(key);\n }),\n result,\n );\n listed = readKeys;\n failed = false;\n emit();\n }\n if (readAgain) {\n readAgain = false;\n schedule(0);\n return;\n }\n scheduleNext();\n }\n\n /**\n * Merge a stream push into the list, unless it comes from a stream opened\n * for an earlier context.\n *\n * @param streamGeneration - Generation the pushing stream was opened in.\n * @param pushed - The pushed schedules.\n */\n function onPush(streamGeneration: number, pushed: TwapOrder[]): void {\n if (stopped || streamGeneration !== generation) {\n return;\n }\n if (resetOnContextChange()) {\n // The push answered for the context the list just left.\n emit();\n readAgain = false;\n schedule(0);\n return;\n }\n const before = new Map(orders.map((order) => [twapOrderKey(order), order]));\n streamed = new Set(pushed.map(twapOrderKey));\n orders = mergeTwapOrders(orders, pushed);\n emit();\n const merged = new Map(orders.map((order) => [twapOrderKey(order), order]));\n const unexplained = [...streamed].some(\n (key) =>\n !listed.has(key) || before.get(key)?.status !== merged.get(key)?.status,\n );\n if (unexplained || pushed.length === 0) {\n schedule(catchUpIntervalMs);\n }\n }\n\n /**\n * Open the stream for the current context, closing the previous one.\n */\n function openStream(): void {\n const previous = unsubscribeStream;\n unsubscribeStream = noop;\n previous();\n if (stopped) {\n return;\n }\n const streamGeneration = generation;\n const unsubscribe = source.subscribeToTwapOrders({\n callback: (pushed) => onPush(streamGeneration, pushed),\n });\n if (stopped || streamGeneration !== generation) {\n // A first push already moved the list to another context.\n unsubscribe();\n } else {\n unsubscribeStream = unsubscribe;\n }\n }\n\n openStream();\n\n const unsubscribeContext = source.subscribeToContextChanges?.(() => {\n if (!stopped && resetOnContextChange()) {\n emit();\n readAgain = false;\n schedule(0);\n }\n });\n\n read().catch(() => undefined);\n\n return () => {\n stopped = true;\n clearTimeout(timer);\n unsubscribeStream();\n unsubscribeContext?.();\n };\n}\n\n/**\n * Whether two snapshots name the same chase. A missing provider matches any,\n * since single-provider reads leave it unset.\n *\n * @param left - One chase.\n * @param right - The other chase.\n * @returns True for the same handle on a compatible provider.\n */\nfunction isSameChase(\n left: Pick<ChaseOrder, 'handle' | 'providerId'>,\n right: Pick<ChaseOrder, 'handle' | 'providerId'>,\n): boolean {\n return (\n left.handle === right.handle &&\n (left.providerId === undefined ||\n right.providerId === undefined ||\n left.providerId === right.providerId)\n );\n}\n\n/**\n * Copy a snapshot under the provider the list holds it by.\n *\n * @param order - The snapshot.\n * @param providerId - Provider to record, or none.\n * @returns The snapshot with exactly that provider.\n */\nfunction withProvider(\n order: ChaseOrder,\n providerId: PerpsProviderType | undefined,\n): ChaseOrder {\n const { providerId: _previous, ...rest } = order;\n return providerId === undefined ? rest : { ...rest, providerId };\n}\n\n/**\n * Keep running and history chase lists from repeated reads.\n *\n * Ended chases stay in history after a provider drops them, up to\n * `historyLimit`. A running chase a read omits stays for `omissionGraceReads`\n * reads, since an aggregated read drops a provider whose read failed. Reads\n * repeat at `refreshIntervalMs` for as long as the list is subscribed, so a\n * chase placed anywhere appears without a manual refresh. Lists reset when the\n * source's context key changes. When a chase cancel succeeds with a known\n * ending, the list keeps that ending, also for a chase no read has listed yet,\n * and keeps it in history after the provider drops the session.\n *\n * @param params - Source, listener and cadence.\n * @param params.source - Reads of chase snapshots.\n * @param params.callback - Receives the lists on change.\n * @param params.onError - Receives read failures; the lists keep their state.\n * @param params.refreshIntervalMs - Read cadence.\n * @param params.historyLimit - Most ended chases kept.\n * @param params.omissionGraceReads - Reads a running chase survives omission.\n * @returns A cleanup function that stops reads.\n */\nexport function createLiveChaseOrderList(params: {\n source: LiveChaseOrderSource;\n callback: (lists: ChaseOrderLists) => void;\n onError?: (error: Error) => void;\n refreshIntervalMs?: number;\n historyLimit?: number;\n omissionGraceReads?: number;\n}): () => void {\n const { source, callback, onError, historyLimit } = params;\n const refreshIntervalMs =\n params.refreshIntervalMs ?? CHASE_ORDER_CONFIG.RefreshIntervalMs;\n const omissionGraceReads =\n params.omissionGraceReads ?? CHASE_ORDER_CONFIG.OmissionGraceReads;\n let lists: ChaseOrderLists | undefined;\n let emitted: string | undefined;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let context = source.getContextKey?.();\n let generation = 0;\n let activeRead: number | undefined;\n let omissions = new Map<string, number>();\n // Endings the provider reported for chases cancelled in this context.\n let endings: ChaseOrder[] = [];\n\n const emit = (): void => {\n const next = lists ?? { running: [], history: [] };\n const serialized = JSON.stringify(next);\n if (serialized !== emitted) {\n emitted = serialized;\n callback(next);\n }\n };\n\n const resetOnContextChange = (): boolean => {\n const current = source.getContextKey?.();\n if (current === context) {\n return false;\n }\n context = current;\n generation += 1;\n lists = undefined;\n omissions = new Map();\n endings = [];\n return true;\n };\n\n const endingOf = (order: ChaseOrder): ChaseOrder | undefined =>\n endings.find((ending) => isSameChase(ending, order));\n\n // A read that still offers a cancel (running, or stopped with a child\n // resting) after the cancel reported an ending is stale; the ending replaces\n // it. An ending the read reports wins.\n const settle = (order: ChaseOrder): ChaseOrder => {\n const ending = endingOf(order);\n return ending && isChaseOrderCancelable(order)\n ? withProvider(ending, order.providerId)\n : order;\n };\n\n // Running chases this read omits, kept while within their grace reads.\n const keepOmitted = (current: readonly ChaseOrder[]): ChaseOrder[] => {\n const present = new Set(current.map(chaseOrderKey));\n const kept: ChaseOrder[] = [];\n const counts = new Map<string, number>();\n for (const order of lists?.running ?? []) {\n const key = chaseOrderKey(order);\n const count = (omissions.get(key) ?? 0) + 1;\n if (!present.has(key) && count <= omissionGraceReads) {\n kept.push(order);\n counts.set(key, count);\n }\n }\n omissions = counts;\n return kept;\n };\n\n const scheduleRead = (delayMs: number): void => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n read().catch(() => undefined);\n }, delayMs);\n };\n\n /**\n * Read the chases, merge them and schedule the next read.\n */\n async function read(): Promise<void> {\n if (resetOnContextChange()) {\n // Clear the old context's chases, and their cancels, now.\n emit();\n }\n if (activeRead === generation) {\n return;\n }\n const readGeneration = generation;\n activeRead = readGeneration;\n let current: ChaseOrder[] = [];\n let failure: { error: unknown } | undefined;\n try {\n current = await source.getChaseOrders();\n } catch (error) {\n failure = { error };\n }\n if (stopped) {\n return;\n }\n if (resetOnContextChange()) {\n emit();\n }\n if (generation !== readGeneration) {\n // The read answered for a context the list has left. Read the new one\n // now unless another read already started.\n if (activeRead === readGeneration) {\n activeRead = undefined;\n scheduleRead(0);\n }\n return;\n }\n activeRead = undefined;\n if (failure) {\n onError?.(ensureError(failure.error, 'createLiveChaseOrderList'));\n } else {\n const settled = current.map(settle);\n lists = mergeChaseOrderHistory({\n previous: lists,\n current: [...settled, ...keepOmitted(settled)],\n historyLimit,\n });\n emit();\n }\n scheduleRead(refreshIntervalMs);\n }\n\n const unsubscribeContext = source.subscribeToContextChanges?.(() => {\n if (!stopped && resetOnContextChange()) {\n emit();\n scheduleRead(0);\n }\n });\n\n const unsubscribeCancellations = source.subscribeToChaseCancellations?.(\n ({ handle, providerId, chaseOrder }) => {\n if (stopped) {\n return;\n }\n const ending = withProvider({ ...chaseOrder, handle }, providerId);\n endings = [\n ...endings.filter((held) => !isSameChase(held, ending)),\n ending,\n ];\n // Recorded even before any read lists the chase, so a read still in\n // flight cannot bring it back as running.\n const held = [...(lists?.running ?? []), ...(lists?.history ?? [])];\n const listed = held.find((order) => isSameChase(order, ending));\n lists = mergeChaseOrderHistory({\n previous: {\n running: [],\n history: (lists?.history ?? []).filter(\n (order) => !isSameChase(order, ending),\n ),\n },\n current: [\n ...(lists?.running ?? []).filter(\n (order) => !isSameChase(order, ending),\n ),\n listed ? withProvider(ending, listed.providerId) : ending,\n ],\n historyLimit,\n });\n emit();\n },\n );\n\n read().catch(() => undefined);\n\n return () => {\n stopped = true;\n clearTimeout(timer);\n unsubscribeContext?.();\n unsubscribeCancellations?.();\n };\n}\n"]}