@metamask-previews/perps-controller 24.0.0-preview-e92ccc12d → 24.0.0-preview-d94a14f45

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.
@@ -34,6 +34,13 @@ export declare class LighterApiError extends Error {
34
34
  readonly code: number | undefined;
35
35
  constructor(message: string, code?: number);
36
36
  }
37
+ /** REST health signals the provider folds into its health report. */
38
+ export type LighterRequestHealth = {
39
+ /** Consecutive 5xx responses; reset by any response that is not 5xx, 429 or 405. */
40
+ consecutiveServerErrors: number;
41
+ /** Epoch ms when the current 429/405 cooldown ends, or null when none. */
42
+ cooldownUntil: number | null;
43
+ };
37
44
  /**
38
45
  * REST client for the zkLighter API.
39
46
  */
@@ -41,7 +48,33 @@ export declare class LighterClientService {
41
48
  #private;
42
49
  constructor(deps: PerpsPlatformDependencies, config: {
43
50
  isTestnet: boolean;
51
+ /** Called when the 5xx streak or the rate-limit cooldown changes. */
52
+ onRequestHealthChange?: () => void;
53
+ /** REST budget per minute (defaults to the Standard-account limit). */
54
+ requestsPerMinute?: number;
44
55
  });
56
+ /**
57
+ * Current REST health: the 5xx streak and any active 429/405 cooldown.
58
+ *
59
+ * @returns REST health signals.
60
+ */
61
+ getRequestHealth(): LighterRequestHealth;
62
+ /**
63
+ * Run a venue write flow. Reads it issues skip the budget and cooldown
64
+ * waits like trading calls, so a held read never delays an order or the
65
+ * orders queued behind it. Reads from other callers made meanwhile skip
66
+ * them too.
67
+ *
68
+ * @param section - The write section.
69
+ * @returns The section's result.
70
+ */
71
+ runTradingSection<Result>(section: () => Promise<Result>): Promise<Result>;
72
+ /**
73
+ * End every read held by the budget or a cooldown without sending it, for
74
+ * example when the provider disconnects. Held reads reject; later requests
75
+ * are unaffected.
76
+ */
77
+ cancelHeldRequests(): void;
45
78
  get network(): LighterNetwork;
46
79
  get baseUrl(): string;
47
80
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"LighterClientService.d.ts","sourceRoot":"","sources":["../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,"file":"LighterClientService.d.ts","sourceRoot":"","sources":["../../src/services/LighterClientService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAgCH,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,KAAK,EACV,sBAAsB,EACtB,kCAAkC,EAClC,2BAA2B,EAC3B,6BAA6B,EAC7B,sBAAsB,EACtB,cAAc,EACd,wBAAwB,EACxB,uBAAuB,EACvB,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAE/B,sBAAsB,EACtB,2BAA2B,EAC3B,6BAA6B,EAC7B,6BAA6B,EAC7B,kBAAkB,EAClB,+BAA+B,EAC/B,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAElB,8BAA8B,EAC9B,8BAA8B,EAC/B,MAAM,2BAA2B,CAAC;AAkenC;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,gBAAgB,UAAQ,GACvB,OAAO,CAsBT;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAElC,YAAY,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAIzC;CACF;AAUD,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG;IACjC,oFAAoF;IACpF,uBAAuB,EAAE,MAAM,CAAC;IAChC,0EAA0E;IAC1E,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B,CAAC;AAsBF;;GAEG;AACH,qBAAa,oBAAoB;;IA+B/B,YACE,IAAI,EAAE,yBAAyB,EAC/B,MAAM,EAAE;QACN,SAAS,EAAE,OAAO,CAAC;QACnB,qEAAqE;QACrE,qBAAqB,CAAC,EAAE,MAAM,IAAI,CAAC;QACnC,uEAAuE;QACvE,iBAAiB,CAAC,EAAE,MAAM,CAAC;KAC5B,EAOF;IAED;;;;OAIG;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,CAAC,+BAA+B,CAAC,CAM1C;IAED;;;;;;;;;OASG;IACG,MAAM,CACV,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,CAAC,CAM7B;IAED;;;;;;;;;OASG;IACG,UAAU,CACd,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,sBAAsB,CAAC,CAKjC;IAED;;;;;;OAMG;IACG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAkB3E;CAyLF"}
@@ -16,7 +16,7 @@
16
16
  * - POST /api/v1/sendTx submit signed L2 transaction
17
17
  */
18
18
  import { array, assert, boolean, define, optional, record, refine, string, type, union, } from '@metamask/superstruct';
19
- import { LIGHTER_MAX_BASE_AMOUNT, LIGHTER_MAX_CLIENT_ORDER_INDEX, LIGHTER_MAX_ORDER_ID, LIGHTER_CLIENT_ORDER_LOOKUP_LIMIT, } from '../constants/lighterConfig.js';
19
+ import { LIGHTER_MAX_BASE_AMOUNT, LIGHTER_MAX_CLIENT_ORDER_INDEX, LIGHTER_MAX_ORDER_ID, LIGHTER_CLIENT_ORDER_LOOKUP_LIMIT, LIGHTER_RATE_LIMIT_BASE_COOLDOWN_MS, LIGHTER_RATE_LIMIT_MAX_COOLDOWN_MS, LIGHTER_REST_BUDGET_WINDOW_MS, LIGHTER_REST_REQUESTS_PER_MINUTE, } from '../constants/lighterConfig.js';
20
20
  import { getLighterHttpEndpoint, LIGHTER_DATA_INTEGRITY_PREFIX, LIGHTER_HTTP_TIMEOUT_MS, LIGHTER_RECENT_TRADES_MAX_LIMIT, } from '../constants/lighterConfig.js';
21
21
  import { parseLighterLosslessJson } from '../utils/lighterLosslessJson.js';
22
22
  /**
@@ -443,6 +443,24 @@ export class LighterApiError extends Error {
443
443
  this.code = code;
444
444
  }
445
445
  }
446
+ const RATE_LIMIT_STATUSES = new Set([405, 429]);
447
+ /**
448
+ * Parse a Retry-After header (seconds or an HTTP date) into milliseconds.
449
+ *
450
+ * @param value - Header value.
451
+ * @returns Delay in milliseconds, or null when absent or invalid.
452
+ */
453
+ const parseRetryAfterMs = (value) => {
454
+ if (value === null || value.trim() === '') {
455
+ return null;
456
+ }
457
+ const seconds = Number(value);
458
+ if (Number.isFinite(seconds)) {
459
+ return seconds >= 0 ? seconds * 1000 : null;
460
+ }
461
+ const date = Date.parse(value);
462
+ return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
463
+ };
446
464
  /**
447
465
  * REST client for the zkLighter API.
448
466
  */
@@ -451,9 +469,67 @@ export class LighterClientService {
451
469
  #isTestnet;
452
470
  #marketsCache = null;
453
471
  #marketsCacheTime = 0;
472
+ #onRequestHealthChange;
473
+ #requestsPerMinute;
474
+ /** Start times of requests inside the current budget window. */
475
+ #recentRequests = [];
476
+ #consecutiveServerErrors = 0;
477
+ #rateLimitStrikes = 0;
478
+ #cooldownUntil = null;
479
+ /** Write sections running now; the reads they issue skip the waits. */
480
+ #tradingSections = 0;
481
+ /** Ends the waits of reads held by the budget or a cooldown. */
482
+ #heldRequestReleases = new Set();
483
+ /** Bumped by `cancelHeldRequests`, so a released read knows to stop. */
484
+ #heldRequestGeneration = 0;
454
485
  constructor(deps, config) {
455
486
  this.#deps = deps;
456
487
  this.#isTestnet = config.isTestnet;
488
+ this.#onRequestHealthChange = config.onRequestHealthChange;
489
+ this.#requestsPerMinute =
490
+ config.requestsPerMinute ?? LIGHTER_REST_REQUESTS_PER_MINUTE;
491
+ }
492
+ /**
493
+ * Current REST health: the 5xx streak and any active 429/405 cooldown.
494
+ *
495
+ * @returns REST health signals.
496
+ */
497
+ getRequestHealth() {
498
+ return {
499
+ consecutiveServerErrors: this.#consecutiveServerErrors,
500
+ cooldownUntil: this.#cooldownUntil !== null && this.#cooldownUntil > Date.now()
501
+ ? this.#cooldownUntil
502
+ : null,
503
+ };
504
+ }
505
+ /**
506
+ * Run a venue write flow. Reads it issues skip the budget and cooldown
507
+ * waits like trading calls, so a held read never delays an order or the
508
+ * orders queued behind it. Reads from other callers made meanwhile skip
509
+ * them too.
510
+ *
511
+ * @param section - The write section.
512
+ * @returns The section's result.
513
+ */
514
+ async runTradingSection(section) {
515
+ this.#tradingSections += 1;
516
+ try {
517
+ return await section();
518
+ }
519
+ finally {
520
+ this.#tradingSections -= 1;
521
+ }
522
+ }
523
+ /**
524
+ * End every read held by the budget or a cooldown without sending it, for
525
+ * example when the provider disconnects. Held reads reject; later requests
526
+ * are unaffected.
527
+ */
528
+ cancelHeldRequests() {
529
+ this.#heldRequestGeneration += 1;
530
+ for (const release of [...this.#heldRequestReleases]) {
531
+ release();
532
+ }
457
533
  }
458
534
  get network() {
459
535
  return this.#isTestnet ? 'testnet' : 'mainnet';
@@ -489,7 +565,7 @@ export class LighterClientService {
489
565
  if (!Number.isSafeInteger(marketId) || marketId < 0 || marketId > 32767) {
490
566
  throw new Error('Invalid Lighter market ID');
491
567
  }
492
- return await this.#get(`/api/v1/orderBookOrders?market_id=${marketId}&limit=250`, ResponseStructs.orderBookOrders);
568
+ return await this.#get(`/api/v1/orderBookOrders?market_id=${marketId}&limit=250`, ResponseStructs.orderBookOrders, undefined, 'trading');
493
569
  }
494
570
  /**
495
571
  * Fetch market stats for all markets.
@@ -535,7 +611,7 @@ export class LighterClientService {
535
611
  * @returns Next nonce payload.
536
612
  */
537
613
  async getNextNonce(accountIndex, apiKeyIndex) {
538
- return await this.#get(`/api/v1/nextNonce?account_index=${accountIndex}&api_key_index=${apiKeyIndex}`, ResponseStructs.nextNonce);
614
+ return await this.#get(`/api/v1/nextNonce?account_index=${accountIndex}&api_key_index=${apiKeyIndex}`, ResponseStructs.nextNonce, undefined, 'trading');
539
615
  }
540
616
  /**
541
617
  * Look up a transaction by its exact hash (`GET /api/v1/tx`). Used to
@@ -552,7 +628,7 @@ export class LighterClientService {
552
628
  */
553
629
  async getTx(txHash) {
554
630
  try {
555
- return await this.#get(`/api/v1/tx?by=hash&value=${encodeURIComponent(txHash)}`, ResponseStructs.transaction);
631
+ return await this.#get(`/api/v1/tx?by=hash&value=${encodeURIComponent(txHash)}`, ResponseStructs.transaction, undefined, 'trading');
556
632
  }
557
633
  catch (error) {
558
634
  if (error instanceof LighterApiError && error.code === 21500) {
@@ -593,7 +669,7 @@ export class LighterClientService {
593
669
  BigInt(id) > BigInt(LIGHTER_MAX_CLIENT_ORDER_INDEX))) {
594
670
  throw new Error('Invalid Lighter client order IDs');
595
671
  }
596
- return await this.#get(`/api/v1/accountOrders?account_index=${accountIndex}&client_order_indexes=${encodeURIComponent(clientOrderIds.join(','))}`, ResponseStructs.activeOrders, { authorization: authToken });
672
+ return await this.#get(`/api/v1/accountOrders?account_index=${accountIndex}&client_order_indexes=${encodeURIComponent(clientOrderIds.join(','))}`, ResponseStructs.activeOrders, { authorization: authToken }, 'trading');
597
673
  }
598
674
  /**
599
675
  * Read active targets or exact client-correlated lifecycle rows without rounding int64 venue IDs.
@@ -620,7 +696,7 @@ export class LighterClientService {
620
696
  const path = clientOrderIds
621
697
  ? `/api/v1/accountOrders?account_index=${accountIndex}&client_order_indexes=${encodeURIComponent(clientOrderIds.join(','))}`
622
698
  : `/api/v1/accountActiveOrders?account_index=${accountIndex}`;
623
- return await this.#request(path, { method: 'GET', headers: { authorization: authToken } }, EditableOrdersStruct, true);
699
+ return await this.#request(path, { method: 'GET', headers: { authorization: authToken } }, EditableOrdersStruct, true, 'trading');
624
700
  }
625
701
  /**
626
702
  * Fetch historical (inactive) orders: filled and canceled lifecycle
@@ -755,13 +831,84 @@ export class LighterClientService {
755
831
  method: 'POST',
756
832
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
757
833
  body: body.toString(),
758
- }, ResponseStructs.sendTransaction);
834
+ }, ResponseStructs.sendTransaction, false, 'trading');
759
835
  return response;
760
836
  }
761
- #get = async (path, responseStruct, headers) => {
762
- return await this.#request(path, { method: 'GET', headers }, responseStruct);
837
+ #get = async (path, responseStruct, headers, priority = 'read') => {
838
+ return await this.#request(path, { method: 'GET', headers }, responseStruct, false, priority);
763
839
  };
764
- #request = async (path, init, responseStruct, lossless = false) => {
840
+ /**
841
+ * Take a slot in the REST budget. Reads wait for a free slot and for any
842
+ * rate-limit cooldown; trading calls go out at once but still count.
843
+ *
844
+ * @param priority - Request priority.
845
+ */
846
+ #acquireRequestSlot = async (priority) => {
847
+ const generation = this.#heldRequestGeneration;
848
+ for (;;) {
849
+ const now = Date.now();
850
+ while (this.#recentRequests.length > 0 &&
851
+ this.#recentRequests[0] <= now - LIGHTER_REST_BUDGET_WINDOW_MS) {
852
+ this.#recentRequests.shift();
853
+ }
854
+ const cooldownWait = this.#cooldownUntil === null ? 0 : this.#cooldownUntil - now;
855
+ const budgetWait = this.#recentRequests.length < this.#requestsPerMinute
856
+ ? 0
857
+ : this.#recentRequests[0] + LIGHTER_REST_BUDGET_WINDOW_MS - now;
858
+ const waitMs = priority === 'trading' || this.#tradingSections > 0
859
+ ? 0
860
+ : Math.max(cooldownWait, budgetWait);
861
+ if (waitMs <= 0) {
862
+ this.#recentRequests.push(now);
863
+ return;
864
+ }
865
+ let release = () => undefined;
866
+ const waited = new Promise((resolveWait) => {
867
+ const timer = setTimeout(resolveWait, waitMs);
868
+ release = () => {
869
+ clearTimeout(timer);
870
+ resolveWait();
871
+ };
872
+ });
873
+ this.#heldRequestReleases.add(release);
874
+ await waited;
875
+ this.#heldRequestReleases.delete(release);
876
+ if (this.#heldRequestGeneration !== generation) {
877
+ throw new LighterApiError('Lighter request cancelled while held');
878
+ }
879
+ }
880
+ };
881
+ /**
882
+ * Track the 5xx streak and 429/405 cooldowns from one response status.
883
+ *
884
+ * @param status - HTTP status.
885
+ * @param retryAfter - Retry-After header, read only for rate-limit statuses.
886
+ */
887
+ #recordResponseStatus = (status, retryAfter) => {
888
+ const before = `${this.#consecutiveServerErrors}:${this.#cooldownUntil}`;
889
+ if (RATE_LIMIT_STATUSES.has(status)) {
890
+ this.#rateLimitStrikes += 1;
891
+ const delayMs = Math.min(LIGHTER_RATE_LIMIT_MAX_COOLDOWN_MS, parseRetryAfterMs(retryAfter) ??
892
+ LIGHTER_RATE_LIMIT_BASE_COOLDOWN_MS *
893
+ 2 ** (this.#rateLimitStrikes - 1));
894
+ this.#cooldownUntil = Math.max(this.#cooldownUntil ?? 0, Date.now() + delayMs);
895
+ this.#deps.debugLogger?.log?.('[LighterClientService] rate limited', {
896
+ status,
897
+ strike: this.#rateLimitStrikes,
898
+ cooldownMs: this.#cooldownUntil - Date.now(),
899
+ });
900
+ }
901
+ else {
902
+ this.#rateLimitStrikes = 0;
903
+ this.#consecutiveServerErrors =
904
+ status >= 500 ? this.#consecutiveServerErrors + 1 : 0;
905
+ }
906
+ if (`${this.#consecutiveServerErrors}:${this.#cooldownUntil}` !== before) {
907
+ this.#onRequestHealthChange?.();
908
+ }
909
+ };
910
+ #request = async (path, init, responseStruct, lossless = false, priority = 'read') => {
911
+ await this.#acquireRequestSlot(priority);
765
912
  const url = `${this.baseUrl}${path}`;
766
913
  const controller = new AbortController();
767
914
  const timeout = setTimeout(() => controller.abort(), LIGHTER_HTTP_TIMEOUT_MS);
@@ -772,9 +919,24 @@ export class LighterClientService {
772
919
  body: init.body,
773
920
  signal: controller.signal,
774
921
  });
775
- const payload = convertKeysToCamelCase(lossless
776
- ? parseLighterLosslessJson(await response.text())
777
- : await response.json(), lossless);
922
+ this.#recordResponseStatus(response.status, RATE_LIMIT_STATUSES.has(response.status)
923
+ ? response.headers.get('retry-after')
924
+ : null);
925
+ let body;
926
+ try {
927
+ body = lossless
928
+ ? parseLighterLosslessJson(await response.text())
929
+ : await response.json();
930
+ }
931
+ catch (parseError) {
932
+ // A rate-limit or gateway error page is not JSON: keep its HTTP
933
+ // status as the error code instead of a parser message.
934
+ if (!response.ok) {
935
+ throw new LighterApiError(`Lighter API error (HTTP ${response.status})`, response.status);
936
+ }
937
+ throw parseError;
938
+ }
939
+ const payload = convertKeysToCamelCase(body, lossless);
778
940
  assert(payload, BaseResponseStruct);
779
941
  // Lighter returns HTTP 200 with an application-level error code, and
780
942
  // 4xx/5xx with `{code, message}` bodies — treat both uniformly.