@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
@@ -30,7 +30,6 @@ import { WebSocketConnectionState, PerpsAnalyticsEvent, PerpsTraceNames, PerpsTr
30
30
  import { getSelectedEvmAccountFromMessenger } from './utils/accountUtils.js';
31
31
  import { ensureError } from './utils/errorUtils.js';
32
32
  import { parseAssetName } from './utils/hyperLiquidAdapter.js';
33
- import { captureScaleOrderParams } from './utils/lighterScaleOrders.js';
34
33
  import { clonePerpsMarketData, compileMarketPattern, shouldIncludeMarket, } from './utils/marketUtils.js';
35
34
  import { isStrategyOrderType } from './utils/orderTypes.js';
36
35
  import { hydrateFromDiskSync, persistMarketEntriesToDisk, persistUserEntriesToDisk, } from './utils/perpsDiskPersistence.js';
@@ -438,8 +437,6 @@ const MESSENGER_EXPOSED_METHODS = [
438
437
  'getCachedMarketDataForActiveProvider',
439
438
  'getCachedUserDataForActiveProvider',
440
439
  'getChaseOrders',
441
- 'getChaseOrderOwnership',
442
- 'reconcileChaseOrderCancellation',
443
440
  'getTwapOrders',
444
441
  'getUserDataSnapshot',
445
442
  'getCurrentNetwork',
@@ -464,13 +461,6 @@ const MESSENGER_EXPOSED_METHODS = [
464
461
  'getPositions',
465
462
  'getSelectedOrderType',
466
463
  'getRecoveredDispatches',
467
- 'getAttachedOrderGroups',
468
- 'reviewAttachedOrderGroups',
469
- 'getScaleOrderGroups',
470
- 'reviewScaleOrderGroups',
471
- 'reconcileRecoveredDispatches',
472
- 'reviewRecoveryVenue',
473
- 'resolveRecoveryProtection',
474
464
  'acknowledgeRecoveredDispatch',
475
465
  'getTradeConfiguration',
476
466
  'getRecentlyViewedMarkets',
@@ -641,9 +631,6 @@ export class PerpsController extends BaseController {
641
631
  *
642
632
  * - A toggle that fires immediately after init() always runs *after* the
643
633
  * init hydration finishes (Bug 3).
644
- * - A hydration started by a re-initialization (`toggleTestnet`,
645
- * `switchProvider`) waits for earlier toggles' writes, so its read sees
646
- * them instead of overwriting them.
647
634
  * - Concurrent toggles are serialised so the last PUT reflects all changes
648
635
  * rather than racing with each other (Bug 4).
649
636
  *
@@ -652,17 +639,11 @@ export class PerpsController extends BaseController {
652
639
  */
653
640
  #ausQueue = Promise.resolve();
654
641
  /**
655
- * Toggles made while an AUS hydration is queued or in flight, one list per
642
+ * Toggles made while an AUS hydration read is in flight, one list per
656
643
  * hydration. They are replayed onto the remote watchlist when it arrives,
657
644
  * so a late read does not drop changes the user already sees.
658
645
  */
659
646
  #watchlistEditsDuringHydration = new Set();
660
- /**
661
- * Latest toggle number per `network:symbol` whose write is still pending,
662
- * so a failed write is undone only when no later toggle of the same market
663
- * has superseded it.
664
- */
665
- #pendingWatchlistToggles = new Map();
666
647
  #userDiskWrite = Promise.resolve();
667
648
  // Store options for dependency injection (allows core package to inject platform-specific services)
668
649
  #options;
@@ -751,7 +732,6 @@ export class PerpsController extends BaseController {
751
732
  // preload-scoped account handler is torn down on disconnect, so it cannot
752
733
  // carry this.
753
734
  const forgetRegisteredTradingAddresses = () => {
754
- this.#selectedAccountGeneration += 1;
755
735
  this.#rewardsIntegrationService.resetRegisteredTradingAddresses();
756
736
  // Clearing alone only guarantees the *next preview* re-registers. An
757
737
  // order submitted straight after a switch, with no preview in between,
@@ -1552,19 +1532,10 @@ export class PerpsController extends BaseController {
1552
1532
  });
1553
1533
  // Hydrate watchlist from AUS (non-blocking — transient failures are
1554
1534
  // caught inside and must not prevent init from completing).
1555
- // Chaining onto #ausQueue makes the read wait for earlier toggles'
1556
- // writes, and makes later toggles wait for hydration before running
1557
- // their own GET-merge-PUT. Toggles are recorded from the moment the
1558
- // hydration is queued, so one made while it waits is replayed too.
1559
- const editsDuringHydration = [];
1560
- this.#watchlistEditsDuringHydration.add(editsDuringHydration);
1561
- this.#ausQueue = this.#ausQueue
1562
- .then(() => this.#syncWatchlistFromRemote(editsDuringHydration))
1563
- .catch(() => {
1535
+ // Assigning to #ausQueue ensures subsequent toggleWatchlistMarket
1536
+ // calls wait for hydration before running their own GET-merge-PUT.
1537
+ this.#ausQueue = this.#syncWatchlistFromRemote().catch(() => {
1564
1538
  // Errors are already logged inside #syncWatchlistFromRemote.
1565
- })
1566
- .finally(() => {
1567
- this.#watchlistEditsDuringHydration.delete(editsDuringHydration);
1568
1539
  });
1569
1540
  return; // Exit retry loop on success
1570
1541
  }
@@ -1675,9 +1646,6 @@ export class PerpsController extends BaseController {
1675
1646
  const lighter = this.#options.clientConfig?.providerCredentials?.lighter ?? {};
1676
1647
  const lighterProvider = new LighterProviderClass({
1677
1648
  isTestnet: lighterIsTestnet,
1678
- ...(lighterIsTestnet && lighter.chaseTestnetProbe === true
1679
- ? { chaseTestnetProbe: true }
1680
- : {}),
1681
1649
  platformDependencies: this.#options.infrastructure,
1682
1650
  messenger: this.messenger,
1683
1651
  signerBridge: lighter.signerBridge,
@@ -1987,7 +1955,7 @@ export class PerpsController extends BaseController {
1987
1955
  return this.activeProviderInstance ?? null;
1988
1956
  }
1989
1957
  /**
1990
- * Get order capabilities through the active provider route used by order
1958
+ * Get strategy capabilities through the active provider route used by order
1991
1959
  * placement. The query waits for in-flight initialization and reports an
1992
1960
  * explicit unavailable status when no provider route can answer reliably.
1993
1961
  *
@@ -2080,15 +2048,11 @@ export class PerpsController extends BaseController {
2080
2048
  /**
2081
2049
  * Build a Scale price ladder using the active provider's venue rules.
2082
2050
  *
2083
- * @param params - Market, ladder bounds, count, optional sizing and explicit route.
2084
- * @returns Provider-normalized prices with sizingPreview when supported, or a typed unavailable result.
2085
- * @throws When bounds or sizing violate the provider's venue rules.
2051
+ * @param params - Market, ladder bounds, count, and optional explicit route.
2052
+ * @returns Provider-normalized prices or a typed unavailable result.
2053
+ * @throws When the provider cannot normalize the requested ladder.
2086
2054
  */
2087
2055
  async getScalePriceLadder(params) {
2088
- const intent = {
2089
- ...params,
2090
- sizing: params.sizing === undefined ? undefined : { ...params.sizing },
2091
- };
2092
2056
  let activeProvider;
2093
2057
  try {
2094
2058
  activeProvider = await this.#getActiveProviderWhenReady();
@@ -2098,16 +2062,16 @@ export class PerpsController extends BaseController {
2098
2062
  error: ensureError(error, 'PerpsController.getScalePriceLadder')
2099
2063
  .message,
2100
2064
  });
2101
- return this.#getUnavailableScalePriceLadder('provider_unavailable', intent.providerId);
2065
+ return this.#getUnavailableScalePriceLadder('provider_unavailable', params.providerId);
2102
2066
  }
2103
- const resolvedProviderId = intent.providerId ?? this.#getDirectProviderId(activeProvider);
2104
- if (this.#hasConflictingProviderRoute(intent.providerId, activeProvider)) {
2067
+ const resolvedProviderId = params.providerId ?? this.#getDirectProviderId(activeProvider);
2068
+ if (this.#hasConflictingProviderRoute(params.providerId, activeProvider)) {
2105
2069
  return this.#getUnavailableScalePriceLadder('provider_not_routable', resolvedProviderId);
2106
2070
  }
2107
2071
  if (!activeProvider.getScalePriceLadder) {
2108
2072
  return this.#getUnavailableScalePriceLadder('not_implemented', resolvedProviderId);
2109
2073
  }
2110
- const result = await activeProvider.getScalePriceLadder(intent);
2074
+ const result = await activeProvider.getScalePriceLadder(params);
2111
2075
  if (result.status === 'unavailable' &&
2112
2076
  result.providerId === undefined &&
2113
2077
  resolvedProviderId !== undefined) {
@@ -2184,32 +2148,21 @@ export class PerpsController extends BaseController {
2184
2148
  * @returns The order result with order ID and status.
2185
2149
  */
2186
2150
  async placeOrder(params) {
2187
- let capturedParams;
2188
- try {
2189
- capturedParams = captureScaleOrderParams(params);
2190
- }
2191
- catch (error) {
2192
- return {
2193
- success: false,
2194
- error: ensureError(error, 'PerpsController.captureScaleOrderParams')
2195
- .message,
2196
- };
2197
- }
2198
2151
  const provider = await this.#resolveRoutedOrderProvider({
2199
- orderType: capturedParams.orderType,
2200
- providerId: capturedParams.providerId,
2152
+ orderType: params.orderType,
2153
+ providerId: params.providerId,
2201
2154
  });
2202
2155
  this.#ensureTradingServiceDeps();
2203
2156
  const result = await this.#tradingService.placeOrder({
2204
2157
  provider,
2205
- params: capturedParams,
2158
+ params,
2206
2159
  context: this.#createServiceContext('placeOrder', {
2207
2160
  saveTradeConfiguration: (symbol, leverage) => this.saveTradeConfiguration(symbol, leverage),
2208
2161
  }),
2209
2162
  reportOrderToDataLake: (dataLakeParams) => this.reportOrderToDataLake(dataLakeParams),
2210
2163
  });
2211
2164
  if (result.success) {
2212
- this.clearPendingTradeConfiguration(capturedParams.symbol);
2165
+ this.clearPendingTradeConfiguration(params.symbol);
2213
2166
  }
2214
2167
  return result;
2215
2168
  }
@@ -2276,129 +2229,8 @@ export class PerpsController extends BaseController {
2276
2229
  return provider.getChaseOrders ? await provider.getChaseOrders() : [];
2277
2230
  }
2278
2231
  /**
2279
- * Observe durable ownership for an exact Chase handle through one provider.
2280
- * Starts no signing, transport, continuation, cancellation or durable writes.
2281
- * Original owner/child IDs are observations, never permission for cleanup in
2282
- * a different context. Providers without durable history report unsupported.
2283
- *
2284
- * @param input - Opaque handle, explicit route and optional original owner.
2285
- * @returns Complete local child history, unsupported, or explicit absence.
2286
- * @throws On corrupt storage or account/network/provider/lifetime changes.
2287
- */
2288
- async getChaseOrderOwnership(input) {
2289
- const params = {
2290
- ...input,
2291
- owner: input.owner ? { ...input.owner } : undefined,
2292
- };
2293
- if (!params.providerId || !params.handle) {
2294
- throw new Error('Chase ownership requires an exact handle and explicit provider');
2295
- }
2296
- const issuedContext = this.#getActionContext();
2297
- const issuedGeneration = this.#lifecycleGeneration;
2298
- const issuedAccountGeneration = this.#selectedAccountGeneration;
2299
- const issuedInstance = this.activeProviderInstance;
2300
- const assertCurrent = () => {
2301
- if (issuedContext !== this.#getActionContext() ||
2302
- issuedGeneration !== this.#lifecycleGeneration ||
2303
- issuedAccountGeneration !== this.#selectedAccountGeneration ||
2304
- (issuedInstance !== null &&
2305
- this.activeProviderInstance !== issuedInstance)) {
2306
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
2307
- }
2308
- };
2309
- let provider;
2310
- try {
2311
- provider = await this.#getActiveProviderWhenReady();
2312
- }
2313
- catch (error) {
2314
- assertCurrent();
2315
- throw error;
2316
- }
2317
- assertCurrent();
2318
- if (this.state.activeProvider !== 'aggregated' &&
2319
- params.providerId !== this.state.activeProvider) {
2320
- throw new Error('Chase ownership provider does not match the active context');
2321
- }
2322
- if (!provider.getChaseOrderOwnership) {
2323
- return {
2324
- status: 'unsupported',
2325
- providerId: params.providerId,
2326
- handle: params.handle,
2327
- reason: 'Durable Chase ownership is unavailable for this provider',
2328
- };
2329
- }
2330
- const ownership = await provider.getChaseOrderOwnership(params);
2331
- assertCurrent();
2332
- if (this.getActiveProviderOrNull() !== provider) {
2333
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
2334
- }
2335
- return ownership;
2336
- }
2337
- /**
2338
- * Reconcile one retained exact Chase cancellation without any new cancellation.
2339
- * Unsupported providers are never routed to ordinary financial cancellation.
2340
- *
2341
- * @param input - Original handle, owner, child and transaction identity.
2342
- * @returns Proven terminal state, unresolved cleanup or unsupported capability.
2343
- * @throws On invalid ownership or stale provider/account/network lifetime.
2344
- */
2345
- async reconcileChaseOrderCancellation(input) {
2346
- const params = {
2347
- ...input,
2348
- owner: { ...input.owner },
2349
- cancellation: { ...input.cancellation },
2350
- };
2351
- if (!params.providerId ||
2352
- !params.handle ||
2353
- !params.clientOrderId ||
2354
- params.owner.providerId !== params.providerId) {
2355
- throw new Error('Chase cancellation reconciliation requires an exact handle, child and matching owner/provider');
2356
- }
2357
- const issuedContext = this.#getActionContext();
2358
- const issuedGeneration = this.#lifecycleGeneration;
2359
- const issuedAccountGeneration = this.#selectedAccountGeneration;
2360
- const issuedInstance = this.activeProviderInstance;
2361
- const assertCurrent = () => {
2362
- if (issuedContext !== this.#getActionContext() ||
2363
- issuedGeneration !== this.#lifecycleGeneration ||
2364
- issuedAccountGeneration !== this.#selectedAccountGeneration ||
2365
- (issuedInstance !== null &&
2366
- this.activeProviderInstance !== issuedInstance)) {
2367
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
2368
- }
2369
- };
2370
- let provider;
2371
- try {
2372
- provider = await this.#getActiveProviderWhenReady();
2373
- }
2374
- catch (error) {
2375
- assertCurrent();
2376
- throw error;
2377
- }
2378
- assertCurrent();
2379
- if (this.state.activeProvider !== 'aggregated' &&
2380
- params.providerId !== this.state.activeProvider) {
2381
- throw new Error('Chase cancellation reconciliation provider does not match the active context');
2382
- }
2383
- if (!provider.reconcileChaseOrderCancellation) {
2384
- return {
2385
- status: 'unsupported',
2386
- providerId: params.providerId,
2387
- handle: params.handle,
2388
- reason: 'Chase cancellation reconciliation is unavailable for this provider',
2389
- };
2390
- }
2391
- const ownership = await provider.reconcileChaseOrderCancellation(params);
2392
- assertCurrent();
2393
- if (this.getActiveProviderOrNull() !== provider) {
2394
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
2395
- }
2396
- return ownership;
2397
- }
2398
- /**
2399
- * Stop Chase repricing for app backgrounding. HyperLiquid leaves current
2400
- * children resting. The bounded Lighter probe attempts exact cancellation and
2401
- * reports canceled or termination_pending rather than a resting status.
2232
+ * Stop Chase repricing for app backgrounding without cancelling the current
2233
+ * resting children.
2402
2234
  *
2403
2235
  * @returns Chase snapshots after suspension.
2404
2236
  * @throws If an aggregated provider cannot suspend every active venue. Other
@@ -2983,10 +2815,7 @@ export class PerpsController extends BaseController {
2983
2815
  /**
2984
2816
  * List TP/SL protection changes the active provider parked for
2985
2817
  * explicit manual re-establishment. Providers without durable
2986
- * settlement state return an empty list. Lighter includes previous-key and
2987
- * pre-initialization journals for the selected wallet/account, waits for any
2988
- * in-flight key selection and keeps failed-setup obligations visible. A
2989
- * current-key update does not clear an earlier key's unfinished journal.
2818
+ * settlement state return an empty list.
2990
2819
  *
2991
2820
  * @returns Pending manual-recovery entries.
2992
2821
  */
@@ -2997,56 +2826,12 @@ export class PerpsController extends BaseController {
2997
2826
  }
2998
2827
  return provider.getPendingManualRecoveries();
2999
2828
  }
3000
- /**
3001
- * Review native attached lifecycle through provider-owned read authority.
3002
- *
3003
- * @returns Exact venue identities without financial replay or key registration.
3004
- */
3005
- async reviewAttachedOrderGroups() {
3006
- const issuedContext = this.#getActionContext();
3007
- const provider = await this.#getActiveProviderWhenReady();
3008
- if (issuedContext !== this.#getActionContext()) {
3009
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3010
- }
3011
- const groups = (await provider.reviewAttachedOrderGroups?.()) ?? [];
3012
- if (issuedContext !== this.#getActionContext()) {
3013
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3014
- }
3015
- return groups;
3016
- }
3017
- /**
3018
- * List durable attached identities for the selected provider and account.
3019
- *
3020
- * @returns Stored intent without venue writes, signer setup or automatic replay.
3021
- */
3022
- async getAttachedOrderGroups() {
3023
- const issuedContext = this.#getActionContext();
3024
- const provider = await this.#getActiveProviderWhenReady();
3025
- if (issuedContext !== this.#getActionContext()) {
3026
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3027
- }
3028
- const groups = (await provider.getAttachedOrderGroups?.()) ?? [];
3029
- if (issuedContext !== this.#getActionContext()) {
3030
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3031
- }
3032
- return groups;
3033
- }
3034
2829
  /**
3035
2830
  * READ-ONLY list of the active provider's recovered-dispatch outcomes
3036
2831
  * (previously ambiguous submissions later resolved). Providers without
3037
- * durable dispatch state return an empty list. Lighter scans the bounded
3038
- * local trading-slot range, including skipped keys, without signing or
3039
- * changing quarantine. After controller initialization, this works before
3040
- * Lighter signer initialization and after signer setup failure; an in-flight
3041
- * selection settles first. Preserve opaque recovery IDs exactly. Raw pending
3042
- * dispatches report unknown with acknowledgeable:false and cannot be cleared
3043
- * by acknowledgment, including current-session in-flight submissions. Listing
3044
- * starts no background reconciliation. A later financial action re-checks
3045
- * authoritative state for all account slots before dispatch and remains
3046
- * blocked while an obligation is unresolved.
3047
- *
3048
- * @returns Pending recovered-dispatch outcomes, with their original key slot
3049
- * when supplied by the provider.
2832
+ * durable dispatch state return an empty list.
2833
+ *
2834
+ * @returns Pending recovered-dispatch outcomes.
3050
2835
  */
3051
2836
  async getRecoveredDispatches() {
3052
2837
  const provider = await this.#getActiveProviderWhenReady();
@@ -3055,229 +2840,20 @@ export class PerpsController extends BaseController {
3055
2840
  }
3056
2841
  return provider.getRecoveredDispatches();
3057
2842
  }
3058
- /**
3059
- * Execute an explicit successor for one selected durable protection obligation.
3060
- *
3061
- * @param params - Owning provider, opaque source ID and new protection intent.
3062
- * @returns Settled, unresolved or unsupported recovery result.
3063
- */
3064
- async resolveRecoveryProtection(params) {
3065
- const issuedContext = this.#getActionContext();
3066
- const provider = await this.#getActiveProviderWhenReady();
3067
- if (issuedContext !== this.#getActionContext()) {
3068
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3069
- }
3070
- if (this.state.activeProvider === 'aggregated' && !params.providerId) {
3071
- throw new Error('Protection recovery requires an explicit provider');
3072
- }
3073
- if (params.providerId &&
3074
- this.state.activeProvider !== 'aggregated' &&
3075
- params.providerId !== this.state.activeProvider) {
3076
- throw new Error('Protection recovery provider does not match the active context');
3077
- }
3078
- const providerId = params.providerId ?? this.state.activeProvider;
3079
- if (providerId === 'aggregated') {
3080
- throw new Error('Protection recovery requires an explicit provider');
3081
- }
3082
- if (!provider.resolveRecoveryProtection) {
3083
- return {
3084
- status: 'unsupported',
3085
- providerId,
3086
- success: false,
3087
- error: 'Selected protection recovery is unavailable for this provider',
3088
- };
3089
- }
3090
- const traceId = uuidv4();
3091
- this.#options.infrastructure.tracer.trace({
3092
- name: PerpsTraceNames.UpdateTpsl,
3093
- op: PerpsTraceOperations.PositionManagement,
3094
- id: traceId,
3095
- tags: { provider: providerId },
3096
- });
3097
- try {
3098
- const result = await provider.resolveRecoveryProtection(params);
3099
- if (issuedContext !== this.#getActionContext()) {
3100
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3101
- }
3102
- if (result.status === 'settled' && result.success) {
3103
- this.update((state) => {
3104
- state.lastUpdateTimestamp = Date.now();
3105
- });
3106
- }
3107
- this.#options.infrastructure.tracer.addBreadcrumb({
3108
- category: 'perps.recovery',
3109
- message: 'Explicit protection recovery completed',
3110
- level: result.status === 'settled' ? 'info' : 'warning',
3111
- data: { providerId, status: result.status },
3112
- });
3113
- return result;
3114
- }
3115
- catch (error) {
3116
- this.#logError(ensureError(error, 'PerpsController.resolveRecoveryProtection'), this.#getErrorContext('resolveRecoveryProtection'));
3117
- throw error;
3118
- }
3119
- finally {
3120
- this.#options.infrastructure.tracer.endTrace({
3121
- name: PerpsTraceNames.UpdateTpsl,
3122
- id: traceId,
3123
- });
3124
- }
3125
- }
3126
- /**
3127
- * Read durable Scale groups without placing or replaying any child.
3128
- * @returns Groups belonging to the issuing controller context.
3129
- */
3130
- async getScaleOrderGroups() {
3131
- const context = this.#getActionContext();
3132
- const provider = await this.#getActiveProviderWhenReady();
3133
- if (context !== this.#getActionContext()) {
3134
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3135
- }
3136
- const groups = (await provider.getScaleOrderGroups?.()) ?? [];
3137
- if (context !== this.#getActionContext()) {
3138
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3139
- }
3140
- return groups;
3141
- }
3142
- /**
3143
- * Reconcile durable Scale groups for an explicitly selected provider.
3144
- * @param params - Issuing provider route.
3145
- * @param params.providerId - Provider to review.
3146
- * @returns Fresh durable groups; never replays placement.
3147
- */
3148
- async reviewScaleOrderGroups(params = {}) {
3149
- const context = this.#getActionContext();
3150
- const provider = await this.#getActiveProviderWhenReady();
3151
- if (context !== this.#getActionContext()) {
3152
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3153
- }
3154
- if (this.state.activeProvider === 'aggregated' && !params.providerId) {
3155
- throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
3156
- }
3157
- if (params.providerId &&
3158
- this.state.activeProvider !== 'aggregated' &&
3159
- params.providerId !== this.state.activeProvider) {
3160
- throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
3161
- }
3162
- if (!provider.reviewScaleOrderGroups) {
3163
- throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE);
3164
- }
3165
- const groups = await provider.reviewScaleOrderGroups(params);
3166
- if (context !== this.#getActionContext()) {
3167
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3168
- }
3169
- return groups;
3170
- }
3171
- /**
3172
- * Review fresh venue positions and orders for one issuing provider context.
3173
- * Auth signing may be required; registration and financial writes are forbidden.
3174
- *
3175
- * @param params - Owning provider route.
3176
- * @param params.providerId - Explicit provider identifier.
3177
- * @returns Strict venue review or honest unsupported capability.
3178
- */
3179
- async reviewRecoveryVenue(params = {}) {
3180
- const issuedContext = this.#getActionContext();
3181
- const provider = await this.#getActiveProviderWhenReady();
3182
- if (issuedContext !== this.#getActionContext()) {
3183
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3184
- }
3185
- if (this.state.activeProvider === 'aggregated' && !params.providerId) {
3186
- throw new Error('Recovery review requires an explicit provider');
3187
- }
3188
- if (params.providerId &&
3189
- this.state.activeProvider !== 'aggregated' &&
3190
- params.providerId !== this.state.activeProvider) {
3191
- throw new Error('Recovery review provider does not match the active context');
3192
- }
3193
- if (!provider.reviewRecoveryVenue) {
3194
- const providerId = params.providerId ?? this.state.activeProvider;
3195
- if (providerId === 'aggregated') {
3196
- throw new Error('Recovery review requires an explicit provider');
3197
- }
3198
- return {
3199
- status: 'unsupported',
3200
- providerId,
3201
- reason: 'Authoritative recovery review is unavailable for this provider',
3202
- };
3203
- }
3204
- const review = await provider.reviewRecoveryVenue(params);
3205
- if (issuedContext !== this.#getActionContext()) {
3206
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3207
- }
3208
- return review;
3209
- }
3210
- /**
3211
- * Explicit non-financial reconciliation with local persistence. Never signs,
3212
- * retries or acknowledges dispatches. Unsupported providers return their local
3213
- * listed state, or an empty list when neither capability is available.
3214
- * Rejects account, network or provider changes while controller readiness,
3215
- * reconciliation or fallback listing completes. Provider rejections propagate
3216
- * unchanged.
3217
- *
3218
- * @returns Newly scoped pending and recovered dispatches.
3219
- */
3220
- async reconcileRecoveredDispatches() {
3221
- const issuedContext = this.#getActionContext();
3222
- const provider = await this.#getActiveProviderWhenReady();
3223
- if (this.#getActionContext() !== issuedContext) {
3224
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3225
- }
3226
- const dispatches = provider.reconcileRecoveredDispatches
3227
- ? await provider.reconcileRecoveredDispatches()
3228
- : ((await provider.getRecoveredDispatches?.()) ?? []);
3229
- if (this.#getActionContext() !== issuedContext) {
3230
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3231
- }
3232
- return dispatches;
3233
- }
3234
2843
  /**
3235
2844
  * Acknowledge ONE recovered-dispatch outcome by its stable id, after
3236
2845
  * refreshing venue state. Throws when the active provider has no
3237
- * durable dispatch state or the id no longer matches. Lighter scopes IDs to
3238
- * wallet/network/account/key and accepts legacy IDs only when unambiguous
3239
- * across local account ledgers. Acknowledgment removes one stored outcome,
3240
- * never an unresolved dispatch or a TP/SL journal, and authorizes no retry.
3241
- * Rejects account, network, provider or lifecycle changes while readiness or
3242
- * acknowledgment completes. A stale rejection after provider success does
3243
- * not undo removal in the issuing account. Re-list outcomes before acting
3244
- * again. Provider rejections propagate unchanged.
3245
- *
3246
- * @param recoveryId - Opaque stable id from {@link getRecoveredDispatches}.
2846
+ * durable dispatch state or the id no longer matches.
2847
+ *
2848
+ * @param recoveryId - Stable id from {@link getRecoveredDispatches}.
3247
2849
  * @returns Resolves when the outcome is acknowledged.
3248
2850
  */
3249
2851
  async acknowledgeRecoveredDispatch(recoveryId) {
3250
- const issuedContext = this.#getActionContext();
3251
- const issuedGeneration = this.#lifecycleGeneration;
3252
- const issuedInstance = this.isInitialized || this.isCurrentlyReinitializing()
3253
- ? this.activeProviderInstance
3254
- : null;
3255
- const isIssuingLifetimeStale = () => issuedGeneration !== this.#lifecycleGeneration ||
3256
- issuedContext !== this.#getActionContext() ||
3257
- (issuedInstance !== null &&
3258
- this.getActiveProviderOrNull() !== issuedInstance);
3259
- let provider;
3260
- try {
3261
- provider = await this.#getActiveProviderWhenReady();
3262
- }
3263
- catch (error) {
3264
- if (isIssuingLifetimeStale()) {
3265
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3266
- }
3267
- throw error;
3268
- }
3269
- if (isIssuingLifetimeStale() ||
3270
- this.getActiveProviderOrNull() !== provider) {
3271
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3272
- }
2852
+ const provider = await this.#getActiveProviderWhenReady();
3273
2853
  if (!provider.acknowledgeRecoveredDispatch) {
3274
2854
  throw new Error('The active perps provider has no recovered dispatches to acknowledge');
3275
2855
  }
3276
- await provider.acknowledgeRecoveredDispatch(recoveryId);
3277
- if (isIssuingLifetimeStale() ||
3278
- this.getActiveProviderOrNull() !== provider) {
3279
- throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
3280
- }
2856
+ return provider.acknowledgeRecoveredDispatch(recoveryId);
3281
2857
  }
3282
2858
  /**
3283
2859
  * Get historical user orders (order lifecycle)
@@ -3535,8 +3111,6 @@ export class PerpsController extends BaseController {
3535
3111
  #isPreloadingUserData = false;
3536
3112
  #userPreloadQueued = false;
3537
3113
  #lifecycleGeneration = 0;
3538
- // Account events also fence round trips that finish at the original address.
3539
- #selectedAccountGeneration = 0;
3540
3114
  #userSnapshotRequests = new Map();
3541
3115
  #preloadStateUnsubscribe = null;
3542
3116
  #accountChangeUnsubscribe = null;
@@ -4236,27 +3810,12 @@ export class PerpsController extends BaseController {
4236
3810
  * @returns True if the condition is met.
4237
3811
  */
4238
3812
  async validateOrder(params) {
4239
- let capturedParams;
4240
- try {
4241
- capturedParams = captureScaleOrderParams(params);
4242
- }
4243
- catch (error) {
4244
- return {
4245
- isValid: false,
4246
- error: ensureError(error, 'PerpsController.captureScaleOrderParams')
4247
- .message,
4248
- };
4249
- }
4250
3813
  const provider = await this.#resolveRoutedOrderProvider({
4251
- orderType: capturedParams.orderType,
4252
- providerId: capturedParams.providerId,
3814
+ orderType: params.orderType,
3815
+ providerId: params.providerId,
4253
3816
  });
4254
3817
  const context = this.#createServiceContext('validateOrder');
4255
- return this.#marketDataService.validateOrder({
4256
- provider,
4257
- params: capturedParams,
4258
- context,
4259
- });
3818
+ return this.#marketDataService.validateOrder({ provider, params, context });
4260
3819
  }
4261
3820
  /**
4262
3821
  * Validate close position parameters according to protocol-specific rules
@@ -5871,10 +5430,6 @@ export class PerpsController extends BaseController {
5871
5430
  for (const edits of this.#watchlistEditsDuringHydration) {
5872
5431
  edits.push({ network: currentNetwork, symbol, add: !isWatchlisted });
5873
5432
  }
5874
- const toggleKey = `${currentNetwork}:${symbol}`;
5875
- const toggleNumber = (this.#pendingWatchlistToggles.get(toggleKey) ?? 0) + 1;
5876
- this.#pendingWatchlistToggles.set(toggleKey, toggleNumber);
5877
- const isLatestToggle = () => this.#pendingWatchlistToggles.get(toggleKey) === toggleNumber;
5878
5433
  this.#getMetrics().trackPerpsEvent(PerpsAnalyticsEvent.UiInteraction, {
5879
5434
  [PERPS_EVENT_PROPERTY.INTERACTION_TYPE]: PERPS_EVENT_VALUE.INTERACTION_TYPE.FAVORITE_TOGGLED,
5880
5435
  [PERPS_EVENT_PROPERTY.ASSET]: symbol,
@@ -5902,33 +5457,11 @@ export class PerpsController extends BaseController {
5902
5457
  network: currentNetwork,
5903
5458
  action: isWatchlisted ? 'remove' : 'add',
5904
5459
  }));
5905
- // A later toggle of the same market decides its state; its own write
5906
- // persists it.
5907
- if (!isLatestToggle()) {
5908
- return;
5909
- }
5910
- // Undo only this toggle. The list may have changed since it was made
5911
- // (hydration, other toggles), so restoring the earlier snapshot would
5912
- // discard those changes.
5460
+ // Revert the optimistic update.
5913
5461
  this.update((state) => {
5914
- const watchlist = state.watchlistMarkets[currentNetwork];
5915
- if (isWatchlisted) {
5916
- if (!watchlist.includes(symbol)) {
5917
- // Back where it was, as far as the current list allows.
5918
- const index = Math.min(currentWatchlist.indexOf(symbol), watchlist.length);
5919
- watchlist.splice(index, 0, symbol);
5920
- }
5921
- }
5922
- else {
5923
- state.watchlistMarkets[currentNetwork] = watchlist.filter((marketSymbol) => marketSymbol !== symbol);
5924
- }
5462
+ state.watchlistMarkets[currentNetwork] = currentWatchlist;
5925
5463
  });
5926
5464
  }
5927
- finally {
5928
- if (isLatestToggle()) {
5929
- this.#pendingWatchlistToggles.delete(toggleKey);
5930
- }
5931
- }
5932
5465
  }
5933
5466
  /**
5934
5467
  * Check if a market is in the watchlist on the current network
@@ -5998,10 +5531,10 @@ export class PerpsController extends BaseController {
5998
5531
  * the canonical owner that creates the initial blob.
5999
5532
  * - The host does not provide the AUS read or write action. Local state is
6000
5533
  * then the only copy of the change. With the read but not the write, the
6001
- * next hydration from AUS (the source of truth) queued after the toggle
5534
+ * next hydration from AUS (the source of truth) to start after the toggle
6002
5535
  * replaces it. Every initialization hydrates: `init()` (including after
6003
5536
  * `disconnect()`), `toggleTestnet()` and `switchProvider()`. A hydration
6004
- * already queued or in flight when the toggle is made keeps it.
5537
+ * already in flight when the toggle is made keeps it.
6005
5538
  *
6006
5539
  * Throws on remote write failure so the caller can decide whether to revert.
6007
5540
  *
@@ -6067,23 +5600,22 @@ export class PerpsController extends BaseController {
6067
5600
  * controller initialisation.
6068
5601
  *
6069
5602
  * AUS is the source of truth; local state is used as an offline cache.
6070
- * Toggles made since the hydration was queued are applied on top of the
6071
- * remote watchlist rather than overwritten by it.
5603
+ * Toggles made while the read is in flight are applied on top of the remote
5604
+ * watchlist rather than overwritten by it.
6072
5605
  * This method also handles the one-time migration from local-only state to
6073
5606
  * AUS for users who had a watchlist before AUS sync was introduced.
6074
5607
  *
6075
5608
  * All remote errors are swallowed so a transient network failure does not
6076
5609
  * block the rest of `init()`.
6077
- *
6078
- * @param editsDuringHydration - Toggles recorded since this hydration was
6079
- * queued; the caller registers and removes the list.
6080
5610
  */
6081
- async #syncWatchlistFromRemote(editsDuringHydration) {
5611
+ async #syncWatchlistFromRemote() {
6082
5612
  const exchangeKey = resolveWatchlistExchangeKey(this.state.activeProvider);
6083
5613
  if (!exchangeKey) {
6084
5614
  this.#debugLog('PerpsController: Skipping AUS watchlist hydration — provider not mapped', { activeProvider: this.state.activeProvider });
6085
5615
  return;
6086
5616
  }
5617
+ const editsDuringHydration = [];
5618
+ this.#watchlistEditsDuringHydration.add(editsDuringHydration);
6087
5619
  try {
6088
5620
  let prefs;
6089
5621
  try {
@@ -6168,6 +5700,9 @@ export class PerpsController extends BaseController {
6168
5700
  catch (error) {
6169
5701
  this.#logError(ensureError(error, 'PerpsController.syncWatchlistFromRemote'), this.#getErrorContext('syncWatchlistFromRemote'));
6170
5702
  }
5703
+ finally {
5704
+ this.#watchlistEditsDuringHydration.delete(editsDuringHydration);
5705
+ }
6171
5706
  }
6172
5707
  /**
6173
5708
  * Report order events to data lake API with retry (non-blocking)