@metamask-previews/perps-controller 23.1.0-preview-d0ecc4dd6 → 23.1.0-preview-fe3c580ff

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 (84) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +35 -0
  3. package/dist/PerpsController-method-action-types.d.ts +96 -7
  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 +131 -52
  7. package/dist/PerpsController.d.ts.map +1 -1
  8. package/dist/PerpsController.js +854 -54
  9. package/dist/PerpsController.js.map +1 -1
  10. package/dist/constants/lighterConfig.d.ts +4 -0
  11. package/dist/constants/lighterConfig.d.ts.map +1 -1
  12. package/dist/constants/lighterConfig.js +4 -0
  13. package/dist/constants/lighterConfig.js.map +1 -1
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/perpsErrorCodes.d.ts +1 -0
  18. package/dist/perpsErrorCodes.d.ts.map +1 -1
  19. package/dist/perpsErrorCodes.js +2 -0
  20. package/dist/perpsErrorCodes.js.map +1 -1
  21. package/dist/providers/AggregatedPerpsProvider.d.ts +31 -1
  22. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  23. package/dist/providers/AggregatedPerpsProvider.js +250 -38
  24. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  25. package/dist/providers/HyperLiquidProvider.d.ts +20 -1
  26. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  27. package/dist/providers/HyperLiquidProvider.js +227 -67
  28. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  29. package/dist/providers/LighterProvider.d.ts +3 -1
  30. package/dist/providers/LighterProvider.d.ts.map +1 -1
  31. package/dist/providers/LighterProvider.js +100 -2
  32. package/dist/providers/LighterProvider.js.map +1 -1
  33. package/dist/routing/isPerpsProviderType.d.ts +10 -0
  34. package/dist/routing/isPerpsProviderType.d.ts.map +1 -0
  35. package/dist/routing/isPerpsProviderType.js +11 -0
  36. package/dist/routing/isPerpsProviderType.js.map +1 -0
  37. package/dist/routing/resolveTradeConfigProviderKey.d.ts +22 -0
  38. package/dist/routing/resolveTradeConfigProviderKey.d.ts.map +1 -0
  39. package/dist/routing/resolveTradeConfigProviderKey.js +25 -0
  40. package/dist/routing/resolveTradeConfigProviderKey.js.map +1 -0
  41. package/dist/selectors.d.ts +35 -233
  42. package/dist/selectors.d.ts.map +1 -1
  43. package/dist/selectors.js +36 -13
  44. package/dist/selectors.js.map +1 -1
  45. package/dist/services/HyperLiquidClientService.d.ts +26 -0
  46. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  47. package/dist/services/HyperLiquidClientService.js +73 -0
  48. package/dist/services/HyperLiquidClientService.js.map +1 -1
  49. package/dist/services/LighterClientService.d.ts +9 -1
  50. package/dist/services/LighterClientService.d.ts.map +1 -1
  51. package/dist/services/LighterClientService.js +32 -1
  52. package/dist/services/LighterClientService.js.map +1 -1
  53. package/dist/services/MarketDataService.d.ts.map +1 -1
  54. package/dist/services/MarketDataService.js +12 -6
  55. package/dist/services/MarketDataService.js.map +1 -1
  56. package/dist/services/ServiceContext.d.ts +15 -3
  57. package/dist/services/ServiceContext.d.ts.map +1 -1
  58. package/dist/services/ServiceContext.js.map +1 -1
  59. package/dist/services/TradingService.d.ts +3 -1
  60. package/dist/services/TradingService.d.ts.map +1 -1
  61. package/dist/services/TradingService.js +9 -4
  62. package/dist/services/TradingService.js.map +1 -1
  63. package/dist/types/hyperliquid-types.d.ts +2 -1
  64. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  65. package/dist/types/hyperliquid-types.js.map +1 -1
  66. package/dist/types/index.d.ts +125 -2
  67. package/dist/types/index.d.ts.map +1 -1
  68. package/dist/types/index.js.map +1 -1
  69. package/dist/types/lighter-types.d.ts +31 -0
  70. package/dist/types/lighter-types.d.ts.map +1 -1
  71. package/dist/types/lighter-types.js.map +1 -1
  72. package/dist/utils/hyperLiquidAdapter.d.ts +14 -2
  73. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  74. package/dist/utils/hyperLiquidAdapter.js +41 -0
  75. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  76. package/dist/utils/lighterAdapter.d.ts +13 -1
  77. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  78. package/dist/utils/lighterAdapter.js +47 -0
  79. package/dist/utils/lighterAdapter.js.map +1 -1
  80. package/dist/utils/publicTrades.d.ts +30 -0
  81. package/dist/utils/publicTrades.d.ts.map +1 -0
  82. package/dist/utils/publicTrades.js +45 -0
  83. package/dist/utils/publicTrades.js.map +1 -0
  84. package/package.json +1 -1
@@ -11,6 +11,8 @@ import { PERPS_CONSTANTS, MARKET_SORTING_CONFIG, buildProviderCacheKey, MAX_SLIP
11
11
  import { PERPS_ERROR_CODES } from './perpsErrorCodes.js';
12
12
  import { AggregatedPerpsProvider } from './providers/AggregatedPerpsProvider.js';
13
13
  import { HyperLiquidProvider } from './providers/HyperLiquidProvider.js';
14
+ import { isPerpsProviderType } from './routing/isPerpsProviderType.js';
15
+ import { resolveTradeConfigProviderKey } from './routing/resolveTradeConfigProviderKey.js';
14
16
  import { AccountService } from './services/AccountService.js';
15
17
  import { isMainAccountSignerReady } from './services/accountSigner.js';
16
18
  import { AgentBindings } from './services/agentSigner.js';
@@ -37,6 +39,16 @@ import { clonePerpsMarketData, compileMarketPattern, shouldIncludeMarket, } from
37
39
  import { isStrategyOrderType } from './utils/orderTypes.js';
38
40
  import { hydrateFromDiskSync, persistMarketEntriesToDisk, persistUserEntriesToDisk, } from './utils/perpsDiskPersistence.js';
39
41
  import { wait } from './utils/wait.js';
42
+ /**
43
+ * Keys that must never index into a persisted state record. Assigning under
44
+ * `__proto__` on a plain object redirects its prototype instead of adding an
45
+ * own entry, and `constructor`/`prototype` shadow built-ins. Mirrors the
46
+ * `isOwnStringKey` guard in `advanced-chart-core`.
47
+ *
48
+ * @param key - A caller-supplied record key.
49
+ * @returns True when the key must not be used.
50
+ */
51
+ const isUnsafeRecordKey = (key) => key === '__proto__' || key === 'constructor' || key === 'prototype';
40
52
  const CONNECTION_ERROR_TAGS = {
41
53
  operation: PERPS_ERROR_OPERATION.ConnectionManagement,
42
54
  component: PERPS_ERROR_COMPONENT.ConnectionManager,
@@ -141,6 +153,11 @@ export { PerpsMode, DEFAULT_ORDER_BOOK_PREFERENCES, DEFAULT_PERPS_MODE, DEFAULT_
141
153
  */
142
154
  export const getDefaultPerpsControllerState = () => ({
143
155
  activeProvider: 'hyperliquid',
156
+ defaultProvider: 'hyperliquid',
157
+ effectiveProvider: null,
158
+ hasExplicitDefaultProviderSelection: false,
159
+ hasMigratedToMultiProvider: false,
160
+ hasExplicitProviderSelection: false,
144
161
  isTestnet: false, // Default to mainnet
145
162
  initializationState: InitializationState.Uninitialized,
146
163
  initializationError: null,
@@ -226,6 +243,36 @@ const metadata = {
226
243
  includeInDebugSnapshot: false,
227
244
  usedInUi: true,
228
245
  },
246
+ defaultProvider: {
247
+ includeInStateLogs: true,
248
+ persist: true,
249
+ includeInDebugSnapshot: false,
250
+ usedInUi: true,
251
+ },
252
+ effectiveProvider: {
253
+ includeInStateLogs: true,
254
+ persist: false,
255
+ includeInDebugSnapshot: false,
256
+ usedInUi: true,
257
+ },
258
+ hasExplicitDefaultProviderSelection: {
259
+ includeInStateLogs: true,
260
+ persist: true,
261
+ includeInDebugSnapshot: false,
262
+ usedInUi: false,
263
+ },
264
+ hasMigratedToMultiProvider: {
265
+ includeInStateLogs: true,
266
+ persist: true,
267
+ includeInDebugSnapshot: false,
268
+ usedInUi: false,
269
+ },
270
+ hasExplicitProviderSelection: {
271
+ includeInStateLogs: true,
272
+ persist: true,
273
+ includeInDebugSnapshot: false,
274
+ usedInUi: false,
275
+ },
229
276
  initializationState: {
230
277
  includeInStateLogs: true,
231
278
  persist: false,
@@ -419,6 +466,10 @@ const metadata = {
419
466
  usedInUi: true,
420
467
  },
421
468
  };
469
+ /**
470
+ * Number of public trades `getPublicTrades` returns when no limit is given.
471
+ */
472
+ const PUBLIC_TRADES_DEFAULT_LIMIT = 50;
422
473
  const MESSENGER_EXPOSED_METHODS = [
423
474
  'approveSubscriptionBuilderFee',
424
475
  'calculateFees',
@@ -475,6 +526,7 @@ const MESSENGER_EXPOSED_METHODS = [
475
526
  'getPendingManualRecoveries',
476
527
  'getPendingTradeConfiguration',
477
528
  'getPositions',
529
+ 'getPublicTrades',
478
530
  'getSelectedOrderType',
479
531
  'getRecoveredDispatches',
480
532
  'getAttachedOrderGroups',
@@ -522,6 +574,7 @@ const MESSENGER_EXPOSED_METHODS = [
522
574
  'saveTradeConfiguration',
523
575
  'setAgentSigner',
524
576
  'setAttributionContext',
577
+ 'setDefaultProvider',
525
578
  'setLiveDataConfig',
526
579
  'setSelectedPaymentToken',
527
580
  'setVisibleCandleCount',
@@ -539,6 +592,7 @@ const MESSENGER_EXPOSED_METHODS = [
539
592
  'subscribeToOrders',
540
593
  'subscribeToPositions',
541
594
  'subscribeToPrices',
595
+ 'subscribeToPublicTrades',
542
596
  'subscribeToTwapOrders',
543
597
  'suspendChaseOrders',
544
598
  'switchProvider',
@@ -681,6 +735,9 @@ export class PerpsController extends BaseController {
681
735
  */
682
736
  #pendingWatchlistToggles = new Map();
683
737
  #userDiskWrite = Promise.resolve();
738
+ #providerSubscriptions = new Set();
739
+ // A failed automatic rollback does not end the consumers' subscription context.
740
+ #hasPendingSubscriptionRecovery = false;
684
741
  // Store options for dependency injection (allows core package to inject platform-specific services)
685
742
  #options;
686
743
  // Service instances (instantiated with platform dependencies)
@@ -700,7 +757,12 @@ export class PerpsController extends BaseController {
700
757
  name: 'PerpsController',
701
758
  metadata,
702
759
  messenger,
703
- state: { ...getDefaultPerpsControllerState(), ...state },
760
+ state: {
761
+ ...getDefaultPerpsControllerState(),
762
+ ...state,
763
+ // A live routing decision must never be restored from a snapshot.
764
+ effectiveProvider: null,
765
+ },
704
766
  });
705
767
  this.#eligibilityCheckDeferred = deferEligibilityCheck;
706
768
  // Store options for dependency injection
@@ -791,6 +853,11 @@ export class PerpsController extends BaseController {
791
853
  this.providers = new Map();
792
854
  // Migrate old persisted data without accountAddress
793
855
  this.#migrateRequestsIfNeeded();
856
+ // Migrate persisted state shapes/values written by older versions. Trade
857
+ // configurations must move under their venue key before the multi-provider
858
+ // migration can flip `activeProvider` (the venue key is derived from it).
859
+ this.#migrateTradeConfigurationsIfNeeded();
860
+ this.#migrateActiveProviderForMultiProviderIfNeeded();
794
861
  // Eagerly hydrate in-memory caches from disk so hooks see data on first render.
795
862
  // Must happen at construction time — before any React component mounts.
796
863
  this.#hydrateCacheFromDiskSync();
@@ -1301,6 +1368,162 @@ export class PerpsController extends BaseController {
1301
1368
  state.depositRequests = state.depositRequests.filter((req) => Boolean(req.accountAddress));
1302
1369
  });
1303
1370
  }
1371
+ /**
1372
+ * Re-key persisted trade configurations from `{ network: { symbol: config } }`
1373
+ * to `{ network: { provider: { symbol: config } } }`.
1374
+ *
1375
+ * Entries saved by older versions were written under whichever venue was
1376
+ * active, so they move under that venue's key: `activeProvider` when it is a
1377
+ * direct venue, else `defaultProvider`. Idempotent: the legacy shape is
1378
+ * detected by a config field (`leverage`, `orderBookGrouping`, `marginMode`,
1379
+ * `pendingConfig`) sitting directly under a symbol key.
1380
+ */
1381
+ #migrateTradeConfigurationsIfNeeded() {
1382
+ const configFieldNames = [
1383
+ 'leverage',
1384
+ 'orderBookGrouping',
1385
+ 'marginMode',
1386
+ 'pendingConfig',
1387
+ ];
1388
+ const { activeProvider, defaultProvider } = this.state;
1389
+ // Both ids come from persisted state, so the destination is validated
1390
+ // against the closed set of venues: an unexpected value (including
1391
+ // `__proto__`) must never become a record key.
1392
+ let destinationProvider = 'hyperliquid';
1393
+ if (isPerpsProviderType(activeProvider)) {
1394
+ destinationProvider = activeProvider;
1395
+ }
1396
+ else if (isPerpsProviderType(defaultProvider)) {
1397
+ destinationProvider = defaultProvider;
1398
+ }
1399
+ this.update((state) => {
1400
+ for (const network of ['testnet', 'mainnet']) {
1401
+ const entries = state.tradeConfigurations?.[network];
1402
+ if (!entries) {
1403
+ continue;
1404
+ }
1405
+ const isLegacyShape = Object.values(entries).some((symbolEntry) => symbolEntry !== null &&
1406
+ typeof symbolEntry === 'object' &&
1407
+ configFieldNames.some((field) => field in symbolEntry));
1408
+ if (!isLegacyShape) {
1409
+ continue;
1410
+ }
1411
+ state.tradeConfigurations[network] = {
1412
+ [destinationProvider]: entries,
1413
+ };
1414
+ this.#debugLog('PerpsController: Migrated trade configurations to provider-keyed shape', { network, provider: destinationProvider });
1415
+ }
1416
+ });
1417
+ }
1418
+ /**
1419
+ * Whether the multi-provider (aggregated) mode flag is on.
1420
+ *
1421
+ * Version-gated like `perpsLighterProviderEnabled`: enabled only when the
1422
+ * flag is on and the app version meets its minimum.
1423
+ *
1424
+ * @returns Whether the flag is enabled for the current app version, or
1425
+ * undefined when flags or version validation are not available yet.
1426
+ */
1427
+ #getMultiProviderModeEnabled() {
1428
+ try {
1429
+ const remoteState = this.messenger.call('RemoteFeatureFlagController:getState');
1430
+ const remoteFlag = remoteState.remoteFeatureFlags?.perpsMultiProviderModeEnabled;
1431
+ if (isVersionGatedFeatureFlag(remoteFlag)) {
1432
+ // An explicit kill switch does not require version validation. Missing
1433
+ // flags/validation, on the other hand, must not undo a persisted mode.
1434
+ if (!remoteFlag.enabled) {
1435
+ return false;
1436
+ }
1437
+ return this.#options.infrastructure.featureFlags.validateVersionGated(remoteFlag);
1438
+ }
1439
+ return undefined;
1440
+ }
1441
+ catch {
1442
+ return undefined;
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Migrate a persisted direct `activeProvider` to aggregated mode.
1447
+ *
1448
+ * When the multi-provider flag is on and the persisted mode is a direct
1449
+ * venue, the venue becomes the persisted `defaultProvider` only on the first
1450
+ * migration and unless the user explicitly saved one. The mode becomes
1451
+ * `aggregated`, so both venues' positions and balances are read at the same
1452
+ * time and each order goes to the venue the user picks. Idempotent;
1453
+ * runs at construction (flags may not be loaded yet, in which case it also
1454
+ * runs from `#performInitialization` before the active provider is assigned).
1455
+ * An explicitly disabled flag restores direct mode using the saved default,
1456
+ * without recording an explicit user selection or erasing the preference.
1457
+ */
1458
+ #migrateActiveProviderForMultiProviderIfNeeded() {
1459
+ const enabled = this.#getMultiProviderModeEnabled();
1460
+ if (this.state.activeProvider === 'aggregated') {
1461
+ this.update((state) => {
1462
+ // Existing aggregated snapshots already have an established default,
1463
+ // even if they predate this marker or the flag is not loaded yet.
1464
+ state.hasMigratedToMultiProvider = true;
1465
+ if (enabled === false) {
1466
+ state.activeProvider = isPerpsProviderType(state.defaultProvider)
1467
+ ? state.defaultProvider
1468
+ : 'hyperliquid';
1469
+ state.effectiveProvider = null;
1470
+ state.accountState = null;
1471
+ }
1472
+ });
1473
+ return;
1474
+ }
1475
+ if (enabled !== true) {
1476
+ return;
1477
+ }
1478
+ // An explicit selection is a user choice, not unmigrated legacy state, so
1479
+ // ordinary initialization must not reinterpret it.
1480
+ if (this.state.hasExplicitProviderSelection) {
1481
+ return;
1482
+ }
1483
+ const { activeProvider } = this.state;
1484
+ if (!isPerpsProviderType(activeProvider)) {
1485
+ return;
1486
+ }
1487
+ this.update((state) => {
1488
+ if (!state.hasExplicitDefaultProviderSelection &&
1489
+ !state.hasMigratedToMultiProvider) {
1490
+ state.defaultProvider = activeProvider;
1491
+ }
1492
+ state.hasMigratedToMultiProvider = true;
1493
+ state.activeProvider = 'aggregated';
1494
+ });
1495
+ this.#debugLog('PerpsController: Migrated direct provider to aggregated mode', {
1496
+ previousProvider: activeProvider,
1497
+ defaultProvider: this.state.defaultProvider,
1498
+ });
1499
+ }
1500
+ /**
1501
+ * Apply the multi-provider kill switch to an already connected session.
1502
+ * In-flight lifecycle operations reconcile the flag during initialization;
1503
+ * otherwise claim the same lifecycle lock used by provider/network switches.
1504
+ */
1505
+ #refreshMultiProviderModeOnFeatureFlagChange() {
1506
+ if (this.state.activeProvider !== 'aggregated' ||
1507
+ this.#getMultiProviderModeEnabled() !== false ||
1508
+ this.isCurrentlyReinitializing() ||
1509
+ this.#disconnectOperationPromise ||
1510
+ this.state.initializationState === InitializationState.Initializing) {
1511
+ return;
1512
+ }
1513
+ if (!this.isInitialized) {
1514
+ this.#migrateActiveProviderForMultiProviderIfNeeded();
1515
+ return;
1516
+ }
1517
+ const completeReinitialization = this.#beginReinitialization();
1518
+ this.#migrateActiveProviderForMultiProviderIfNeeded();
1519
+ this.isInitialized = false;
1520
+ this.#initializationPromise = null;
1521
+ this.#initWithoutDisconnectWait(true)
1522
+ .catch((error) => {
1523
+ this.#logError(ensureError(error, 'PerpsController.multiProviderRollback'), this.#getErrorContext('multiProviderRollback'));
1524
+ })
1525
+ .finally(completeReinitialization);
1526
+ }
1304
1527
  setBlockedRegionList(list, source) {
1305
1528
  this.#featureFlagConfigurationService.setBlockedRegions({
1306
1529
  list,
@@ -1362,6 +1585,7 @@ export class PerpsController extends BaseController {
1362
1585
  },
1363
1586
  }),
1364
1587
  });
1588
+ this.#refreshMultiProviderModeOnFeatureFlagChange();
1365
1589
  }
1366
1590
  /**
1367
1591
  * Execute an operation while temporarily pausing specified stream channels
@@ -1447,16 +1671,17 @@ export class PerpsController extends BaseController {
1447
1671
  await pendingReinitialization;
1448
1672
  continue;
1449
1673
  }
1450
- return this.#initWithoutDisconnectWait();
1674
+ return this.#initWithoutDisconnectWait(this.#hasPendingSubscriptionRecovery);
1451
1675
  }
1452
1676
  }
1453
1677
  /**
1454
1678
  * Initialize without waiting for disconnect. Reinitialization operations use
1455
1679
  * this after they have claimed the controller lifecycle.
1456
1680
  *
1681
+ * @param preserveSubscriptions - Keep Core registrations during rollback or recovery.
1457
1682
  * @returns A promise that resolves when initialization finishes.
1458
1683
  */
1459
- async #initWithoutDisconnectWait() {
1684
+ async #initWithoutDisconnectWait(preserveSubscriptions = false) {
1460
1685
  if (!this.#handlersRegistered) {
1461
1686
  this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
1462
1687
  this.#handlersRegistered = true;
@@ -1467,7 +1692,7 @@ export class PerpsController extends BaseController {
1467
1692
  if (this.#initializationPromise) {
1468
1693
  return this.#initializationPromise;
1469
1694
  }
1470
- this.#initializationPromise = this.#performInitialization();
1695
+ this.#initializationPromise = this.#performInitialization(preserveSubscriptions);
1471
1696
  this.#initializationStartWaiters.forEach((notifyStarted) => notifyStarted());
1472
1697
  return this.#initializationPromise;
1473
1698
  }
@@ -1514,13 +1739,19 @@ export class PerpsController extends BaseController {
1514
1739
  };
1515
1740
  }
1516
1741
  /**
1517
- * Actual initialization implementation with retry logic
1742
+ * Actual initialization implementation with retry logic.
1743
+ *
1744
+ * @param preserveSubscriptions - Keep Core registrations for automatic rollback.
1518
1745
  */
1519
- async #performInitialization() {
1746
+ async #performInitialization(preserveSubscriptions) {
1520
1747
  const maxAttempts = 3;
1521
1748
  const baseDelay = 1000;
1749
+ this.#detachProviderSubscriptions(!preserveSubscriptions);
1522
1750
  this.update((state) => {
1523
1751
  state.initializationState = InitializationState.Initializing;
1752
+ // The previous route is no longer authoritative during reconnection.
1753
+ // Implicit configurations use the selected destination until assignment.
1754
+ state.effectiveProvider = null;
1524
1755
  state.initializationError = null;
1525
1756
  state.initializationAttempts = 0;
1526
1757
  });
@@ -1555,6 +1786,11 @@ export class PerpsController extends BaseController {
1555
1786
  this.#lighterRegistrationPromise,
1556
1787
  ]);
1557
1788
  this.#lighterRegistrationPromise = null;
1789
+ // Flags may have arrived after construction; re-run the idempotent
1790
+ // migration so the aggregated wrapper (when the flag is on) is built
1791
+ // from the migrated state. The migration skips an explicit provider
1792
+ // selection, so a direct switch survives this initialization.
1793
+ this.#migrateActiveProviderForMultiProviderIfNeeded();
1558
1794
  this.#assignActiveProvider();
1559
1795
  this.isInitialized = true;
1560
1796
  this.update((state) => {
@@ -1583,6 +1819,9 @@ export class PerpsController extends BaseController {
1583
1819
  .finally(() => {
1584
1820
  this.#watchlistEditsDuringHydration.delete(editsDuringHydration);
1585
1821
  });
1822
+ if (preserveSubscriptions) {
1823
+ this.#restoreProviderSubscriptions();
1824
+ }
1586
1825
  return; // Exit retry loop on success
1587
1826
  }
1588
1827
  catch (error) {
@@ -1606,6 +1845,7 @@ export class PerpsController extends BaseController {
1606
1845
  this.isInitialized = false;
1607
1846
  this.update((state) => {
1608
1847
  state.initializationState = InitializationState.Failed;
1848
+ state.effectiveProvider = null;
1609
1849
  state.initializationError = lastError?.message ?? 'Unknown error';
1610
1850
  });
1611
1851
  this.#initializationPromise = null; // Clear promise to allow retry
@@ -1756,9 +1996,17 @@ export class PerpsController extends BaseController {
1756
1996
  throw new Error('HyperLiquid provider not registered — cannot assign active provider');
1757
1997
  }
1758
1998
  if (activeProvider === 'aggregated') {
1999
+ // The persisted default venue routes writes that do not name one and
2000
+ // backs default-routed reads. Fall back to HyperLiquid in memory when
2001
+ // the saved default is not registered (for example Lighter failed to
2002
+ // load), but preserve the preference for a later successful initialization.
2003
+ const defaultProvider = isPerpsProviderType(this.state.defaultProvider) &&
2004
+ this.providers.has(this.state.defaultProvider)
2005
+ ? this.state.defaultProvider
2006
+ : 'hyperliquid';
1759
2007
  this.activeProviderInstance = new AggregatedPerpsProvider({
1760
2008
  providers: this.providers,
1761
- defaultProvider: 'hyperliquid',
2009
+ defaultProvider,
1762
2010
  infrastructure: this.#options.infrastructure,
1763
2011
  isTestnet: this.state.isTestnet,
1764
2012
  });
@@ -1786,6 +2034,14 @@ export class PerpsController extends BaseController {
1786
2034
  }
1787
2035
  this.#debugLog(`PerpsController: Using direct provider (${this.activeProviderInstance === hyperLiquidProvider ? 'hyperliquid' : activeProvider})`);
1788
2036
  }
2037
+ const effectiveProvider = this.activeProviderInstance instanceof AggregatedPerpsProvider
2038
+ ? this.activeProviderInstance.getWriteProviderId()
2039
+ : this.state.activeProvider;
2040
+ this.update((state) => {
2041
+ state.effectiveProvider = isPerpsProviderType(effectiveProvider)
2042
+ ? effectiveProvider
2043
+ : 'hyperliquid';
2044
+ });
1789
2045
  }
1790
2046
  /**
1791
2047
  * Generate standard error context for Logger.error calls with searchable tags and context.
@@ -2204,6 +2460,52 @@ export class PerpsController extends BaseController {
2204
2460
  !provider.routesOrdersByProviderId &&
2205
2461
  providerId !== provider.protocolId);
2206
2462
  }
2463
+ /**
2464
+ * Structured refusal for an aggregated-mode write that does not name a venue.
2465
+ *
2466
+ * When multiple venues are registered, a write without a `providerId` has
2467
+ * no unambiguous destination and is refused with `PROVIDER_ROUTE_REQUIRED`.
2468
+ * Direct modes and aggregated wrappers with one registered venue already
2469
+ * have exactly one destination, so their writes need no explicit route.
2470
+ *
2471
+ * Call it once before any expensive work (using the current state) and again
2472
+ * after the provider is resolved: a cold start can migrate direct state to
2473
+ * aggregated, so a write queued across that transition must be checked
2474
+ * against the provider it actually reaches.
2475
+ *
2476
+ * @param providerId - Explicit provider route, when supplied.
2477
+ * @param provider - Resolved provider, when initialization has settled.
2478
+ * @returns The refusal result, or undefined when the write may proceed.
2479
+ */
2480
+ #getUnroutedAggregatedWriteRefusal(providerId, provider) {
2481
+ if (providerId !== undefined) {
2482
+ return undefined;
2483
+ }
2484
+ // Before initialization the actual membership is unknown. Defer to the
2485
+ // check after provider resolution rather than refusing a one-venue fallback.
2486
+ const resolvedProvider = provider ?? this.getActiveProviderOrNull();
2487
+ if (resolvedProvider?.protocolId !== 'aggregated') {
2488
+ return undefined;
2489
+ }
2490
+ if (resolvedProvider instanceof AggregatedPerpsProvider &&
2491
+ resolvedProvider.getProviderIds().length <= 1) {
2492
+ return undefined;
2493
+ }
2494
+ return { success: false, error: PERPS_ERROR_CODES.PROVIDER_ROUTE_REQUIRED };
2495
+ }
2496
+ /**
2497
+ * Structured refusal for an aggregated-mode batch write.
2498
+ *
2499
+ * Batch cancel and close cannot name a venue, so while multiple venues are
2500
+ * registered they are refused instead of being sent to the default venue.
2501
+ *
2502
+ * @param provider - Resolved provider, when initialization has settled.
2503
+ * @returns The batch refusal result, or undefined when the batch may proceed.
2504
+ */
2505
+ #getUnroutedAggregatedBatchRefusal(provider) {
2506
+ const refusal = this.#getUnroutedAggregatedWriteRefusal(undefined, provider);
2507
+ return (refusal && { ...refusal, successCount: 0, failureCount: 0, results: [] });
2508
+ }
2207
2509
  /**
2208
2510
  * Resolve one routed order operation after any in-flight initialization.
2209
2511
  *
@@ -2230,6 +2532,10 @@ export class PerpsController extends BaseController {
2230
2532
  * @returns The order result with order ID and status.
2231
2533
  */
2232
2534
  async placeOrder(params) {
2535
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2536
+ if (unroutedRefusal) {
2537
+ return unroutedRefusal;
2538
+ }
2233
2539
  let capturedParams;
2234
2540
  try {
2235
2541
  capturedParams = captureScaleOrderParams(params);
@@ -2245,17 +2551,21 @@ export class PerpsController extends BaseController {
2245
2551
  orderType: capturedParams.orderType,
2246
2552
  providerId: capturedParams.providerId,
2247
2553
  });
2554
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(capturedParams.providerId, provider);
2555
+ if (resolvedRefusal) {
2556
+ return resolvedRefusal;
2557
+ }
2248
2558
  this.#ensureTradingServiceDeps();
2249
2559
  const result = await this.#tradingService.placeOrder({
2250
2560
  provider,
2251
2561
  params: capturedParams,
2252
2562
  context: this.#createServiceContext('placeOrder', {
2253
- saveTradeConfiguration: (symbol, leverage) => this.saveTradeConfiguration(symbol, leverage),
2563
+ saveTradeConfiguration: (symbol, leverage, providerId) => this.saveTradeConfiguration(symbol, leverage, providerId),
2254
2564
  }),
2255
2565
  reportOrderToDataLake: (dataLakeParams) => this.reportOrderToDataLake(dataLakeParams),
2256
2566
  });
2257
2567
  if (result.success) {
2258
- this.clearPendingTradeConfiguration(capturedParams.symbol);
2568
+ this.clearPendingTradeConfiguration(capturedParams.symbol, capturedParams.providerId);
2259
2569
  }
2260
2570
  return result;
2261
2571
  }
@@ -2273,10 +2583,18 @@ export class PerpsController extends BaseController {
2273
2583
  error: PERPS_ERROR_CODES.ORDER_EDIT_STRATEGY_UNSUPPORTED,
2274
2584
  };
2275
2585
  }
2586
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.newOrder.providerId);
2587
+ if (unroutedRefusal) {
2588
+ return unroutedRefusal;
2589
+ }
2276
2590
  const provider = await this.#resolveRoutedOrderProvider({
2277
2591
  orderType: params.newOrder.orderType,
2278
2592
  providerId: params.newOrder.providerId,
2279
2593
  });
2594
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.newOrder.providerId, provider);
2595
+ if (resolvedRefusal) {
2596
+ return resolvedRefusal;
2597
+ }
2280
2598
  this.#ensureTradingServiceDeps();
2281
2599
  return this.#tradingService.editOrder({
2282
2600
  provider,
@@ -2291,10 +2609,18 @@ export class PerpsController extends BaseController {
2291
2609
  * @returns The cancellation result with status.
2292
2610
  */
2293
2611
  async cancelOrder(params) {
2612
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2613
+ if (unroutedRefusal) {
2614
+ return unroutedRefusal;
2615
+ }
2294
2616
  const provider = await this.#resolveRoutedOrderProvider({
2295
2617
  orderType: params.orderType,
2296
2618
  providerId: params.providerId,
2297
2619
  });
2620
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
2621
+ if (resolvedRefusal) {
2622
+ return resolvedRefusal;
2623
+ }
2298
2624
  return this.#tradingService.cancelOrder({
2299
2625
  provider,
2300
2626
  params,
@@ -2464,7 +2790,15 @@ export class PerpsController extends BaseController {
2464
2790
  * @returns The batch cancellation results for each order.
2465
2791
  */
2466
2792
  async cancelOrders(params) {
2793
+ const unroutedRefusal = this.#getUnroutedAggregatedBatchRefusal();
2794
+ if (unroutedRefusal) {
2795
+ return unroutedRefusal;
2796
+ }
2467
2797
  const provider = await this.#getActiveProviderWhenReady();
2798
+ const resolvedRefusal = this.#getUnroutedAggregatedBatchRefusal(provider);
2799
+ if (resolvedRefusal) {
2800
+ return resolvedRefusal;
2801
+ }
2468
2802
  return this.#tradingService.cancelOrders({
2469
2803
  provider,
2470
2804
  params,
@@ -2482,10 +2816,18 @@ export class PerpsController extends BaseController {
2482
2816
  * @returns The order result from the close position request.
2483
2817
  */
2484
2818
  async closePosition(params) {
2819
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2820
+ if (unroutedRefusal) {
2821
+ return unroutedRefusal;
2822
+ }
2485
2823
  const provider = await this.#resolveRoutedOrderProvider({
2486
2824
  orderType: params.orderType,
2487
2825
  providerId: params.providerId,
2488
2826
  });
2827
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
2828
+ if (resolvedRefusal) {
2829
+ return resolvedRefusal;
2830
+ }
2489
2831
  this.#ensureTradingServiceDeps();
2490
2832
  return this.#tradingService.closePosition({
2491
2833
  provider,
@@ -2504,7 +2846,15 @@ export class PerpsController extends BaseController {
2504
2846
  * @returns The batch close results for each position.
2505
2847
  */
2506
2848
  async closePositions(params) {
2849
+ const unroutedRefusal = this.#getUnroutedAggregatedBatchRefusal();
2850
+ if (unroutedRefusal) {
2851
+ return unroutedRefusal;
2852
+ }
2507
2853
  const provider = await this.#getActiveProviderWhenReady();
2854
+ const resolvedRefusal = this.#getUnroutedAggregatedBatchRefusal(provider);
2855
+ if (resolvedRefusal) {
2856
+ return resolvedRefusal;
2857
+ }
2508
2858
  this.#ensureTradingServiceDeps();
2509
2859
  return this.#tradingService.closePositions({
2510
2860
  provider,
@@ -2521,10 +2871,18 @@ export class PerpsController extends BaseController {
2521
2871
  * @returns The order result from the TP/SL update.
2522
2872
  */
2523
2873
  async updatePositionTPSL(params) {
2874
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2875
+ if (unroutedRefusal) {
2876
+ return unroutedRefusal;
2877
+ }
2524
2878
  const provider = await this.#resolveRoutedOrderProvider({
2525
2879
  orderType: undefined,
2526
2880
  providerId: params.providerId,
2527
2881
  });
2882
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
2883
+ if (resolvedRefusal) {
2884
+ return resolvedRefusal;
2885
+ }
2528
2886
  this.#ensureTradingServiceDeps();
2529
2887
  return this.#tradingService.updatePositionTPSL({
2530
2888
  provider,
@@ -2542,10 +2900,18 @@ export class PerpsController extends BaseController {
2542
2900
  * @returns The order result from the leg replacement.
2543
2901
  */
2544
2902
  async replacePositionTPSLLeg(params) {
2903
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2904
+ if (unroutedRefusal) {
2905
+ return unroutedRefusal;
2906
+ }
2545
2907
  const provider = await this.#resolveRoutedOrderProvider({
2546
2908
  orderType: undefined,
2547
2909
  providerId: params.providerId,
2548
2910
  });
2911
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
2912
+ if (resolvedRefusal) {
2913
+ return resolvedRefusal;
2914
+ }
2549
2915
  this.#ensureTradingServiceDeps();
2550
2916
  // A market leg uses the caller's tolerance, else the saved preference.
2551
2917
  const maxSlippageBps = params.maxSlippageBps ?? this.state.maxSlippageBps;
@@ -2562,12 +2928,21 @@ export class PerpsController extends BaseController {
2562
2928
  * @returns The margin update result.
2563
2929
  */
2564
2930
  async updateMargin(params) {
2931
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
2932
+ if (unroutedRefusal) {
2933
+ return unroutedRefusal;
2934
+ }
2565
2935
  const provider = await this.#getActiveProviderWhenReady();
2936
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
2937
+ if (resolvedRefusal) {
2938
+ return resolvedRefusal;
2939
+ }
2566
2940
  this.#ensureTradingServiceDeps();
2567
2941
  return this.#tradingService.updateMargin({
2568
2942
  provider,
2569
2943
  symbol: params.symbol,
2570
2944
  amount: params.amount,
2945
+ providerId: params.providerId,
2571
2946
  context: this.#createServiceContext('updateMargin'),
2572
2947
  });
2573
2948
  }
@@ -2578,7 +2953,17 @@ export class PerpsController extends BaseController {
2578
2953
  * @returns The order result from the position flip.
2579
2954
  */
2580
2955
  async flipPosition(params) {
2956
+ // The flip is executed as a placement against the position's venue, so the
2957
+ // position must carry one in aggregated mode.
2958
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.position.providerId);
2959
+ if (unroutedRefusal) {
2960
+ return unroutedRefusal;
2961
+ }
2581
2962
  const provider = await this.#getActiveProviderWhenReady();
2963
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.position.providerId, provider);
2964
+ if (resolvedRefusal) {
2965
+ return resolvedRefusal;
2966
+ }
2582
2967
  this.#ensureTradingServiceDeps();
2583
2968
  return this.#tradingService.flipPosition({
2584
2969
  provider,
@@ -3016,7 +3401,15 @@ export class PerpsController extends BaseController {
3016
3401
  * @returns WithdrawResult with withdrawal ID and tracking info
3017
3402
  */
3018
3403
  async withdraw(params) {
3404
+ const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
3405
+ if (unroutedRefusal) {
3406
+ return unroutedRefusal;
3407
+ }
3019
3408
  const provider = await this.#getActiveProviderWhenReady();
3409
+ const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
3410
+ if (resolvedRefusal) {
3411
+ return resolvedRefusal;
3412
+ }
3020
3413
  return this.#accountService.withdraw({
3021
3414
  provider,
3022
3415
  params,
@@ -3464,7 +3857,18 @@ export class PerpsController extends BaseController {
3464
3857
  return this.#marketDataService.getAccountState({
3465
3858
  provider,
3466
3859
  params,
3467
- context: this.#createServiceContext('getAccountState'),
3860
+ context: this.#createServiceContext('getAccountState', {
3861
+ accountDataContext: {
3862
+ // Match the live account venue, including a temporary fallback when
3863
+ // the saved default is unavailable. Read the route when the response
3864
+ // arrives to reject balances from a previous venue.
3865
+ isCurrent: (accountState) => accountState.providerId === undefined ||
3866
+ accountState.providerId ===
3867
+ (this.activeProviderInstance instanceof AggregatedPerpsProvider
3868
+ ? this.activeProviderInstance.getWriteProviderId()
3869
+ : this.state.activeProvider),
3870
+ },
3871
+ }),
3468
3872
  });
3469
3873
  }
3470
3874
  /**
@@ -4498,6 +4902,7 @@ export class PerpsController extends BaseController {
4498
4902
  const previousNetwork = previousIsTestnet ? 'testnet' : 'mainnet';
4499
4903
  this.update((state) => {
4500
4904
  state.isTestnet = !state.isTestnet;
4905
+ state.effectiveProvider = null;
4501
4906
  });
4502
4907
  const newNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
4503
4908
  this.#debugLog('PerpsController: Network toggle initiated', {
@@ -4526,6 +4931,7 @@ export class PerpsController extends BaseController {
4526
4931
  // Rollback isTestnet to previous value
4527
4932
  this.update((state) => {
4528
4933
  state.isTestnet = previousIsTestnet;
4934
+ state.effectiveProvider = null;
4529
4935
  });
4530
4936
  return {
4531
4937
  success: false,
@@ -4571,6 +4977,7 @@ export class PerpsController extends BaseController {
4571
4977
  }
4572
4978
  const completeReinitialization = this.#beginReinitialization();
4573
4979
  let previousProvider = this.state.activeProvider;
4980
+ const previousSelectionExplicit = this.state.hasExplicitProviderSelection;
4574
4981
  try {
4575
4982
  const pendingInitialization = this.#initializationPromise;
4576
4983
  if (pendingInitialization) {
@@ -4594,12 +5001,22 @@ export class PerpsController extends BaseController {
4594
5001
  // use the state this switch is actually replacing.
4595
5002
  previousProvider = this.state.activeProvider;
4596
5003
  if (previousProvider === providerId) {
5004
+ // Selecting the current direct venue is still an explicit choice, so
5005
+ // record it even though no reinitialization is needed.
5006
+ if (providerId !== 'aggregated' &&
5007
+ !this.state.hasExplicitProviderSelection) {
5008
+ this.update((state) => {
5009
+ state.hasExplicitProviderSelection = true;
5010
+ });
5011
+ }
4597
5012
  return { success: true, providerId };
4598
5013
  }
4599
5014
  // Validate provider only after a pending initialization has rebuilt the
4600
5015
  // registry. Otherwise a switch queued behind disconnect can observe the
4601
5016
  // intentionally empty teardown state.
4602
- const isValidProvider = providerId === 'aggregated' || this.providers.has(providerId);
5017
+ const isValidProvider = providerId === 'aggregated'
5018
+ ? this.#getMultiProviderModeEnabled() !== false
5019
+ : this.providers.has(providerId);
4603
5020
  if (!isValidProvider) {
4604
5021
  return {
4605
5022
  success: false,
@@ -4620,6 +5037,11 @@ export class PerpsController extends BaseController {
4620
5037
  // Update state with new provider (market data cache preserved per-provider)
4621
5038
  this.update((state) => {
4622
5039
  state.activeProvider = providerId;
5040
+ // Publish the new selection and invalidate its old live route together.
5041
+ state.effectiveProvider = null;
5042
+ // Record whether this is an explicit direct selection so a later
5043
+ // network toggle or disconnect/init does not migrate it away.
5044
+ state.hasExplicitProviderSelection = providerId !== 'aggregated';
4623
5045
  state.accountState = null;
4624
5046
  state.initializationState = InitializationState.Uninitialized;
4625
5047
  });
@@ -4632,6 +5054,16 @@ export class PerpsController extends BaseController {
4632
5054
  if (this.state.initializationState === InitializationState.Failed) {
4633
5055
  throw new Error(this.state.initializationError ?? 'Provider initialization failed');
4634
5056
  }
5057
+ // The kill switch may have restored a direct mode while initialization
5058
+ // was pending. Do not report the requested aggregated mode as active.
5059
+ if (providerId === 'aggregated' &&
5060
+ this.state.activeProvider !== 'aggregated') {
5061
+ return {
5062
+ success: false,
5063
+ providerId: this.state.activeProvider,
5064
+ error: 'Provider aggregated not available',
5065
+ };
5066
+ }
4635
5067
  this.#debugLog('PerpsController: Provider switch completed', {
4636
5068
  providerId,
4637
5069
  timestamp: new Date().toISOString(),
@@ -4642,6 +5074,8 @@ export class PerpsController extends BaseController {
4642
5074
  // Rollback state to previous provider
4643
5075
  this.update((state) => {
4644
5076
  state.activeProvider = previousProvider;
5077
+ state.effectiveProvider = null;
5078
+ state.hasExplicitProviderSelection = previousSelectionExplicit;
4645
5079
  });
4646
5080
  this.#logError(ensureError(error, 'PerpsController.switchProvider'), this.#getErrorContext('switchProvider', { providerId }, CONNECTION_ERROR_TAGS));
4647
5081
  // Attempt to reinitialize the previous provider via init(),
@@ -4685,6 +5119,70 @@ export class PerpsController extends BaseController {
4685
5119
  }
4686
5120
  }
4687
5121
  }
5122
+ /**
5123
+ * Set the default provider used by aggregated-mode routing.
5124
+ *
5125
+ * Persists the choice and, when the active provider is the aggregated
5126
+ * wrapper, updates its routing default in place. Unlike `switchProvider`
5127
+ * this never re-initializes the controller or reconnects provider transports:
5128
+ * default-routed streams move, but both venues stay connected and per-venue
5129
+ * writes are unaffected.
5130
+ *
5131
+ * @param providerId - The provider to use as the aggregated default.
5132
+ * @returns The result with the new default provider.
5133
+ */
5134
+ setDefaultProvider(providerId) {
5135
+ // Runtime hardening for JS callers: the value reaches persisted state and
5136
+ // the provider registry, so it must be a known direct venue.
5137
+ if (!isPerpsProviderType(providerId)) {
5138
+ return {
5139
+ success: false,
5140
+ defaultProvider: this.state.defaultProvider,
5141
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,
5142
+ };
5143
+ }
5144
+ // Before initialization the provider registry is empty; accept the
5145
+ // choice so it is persisted and used once providers are created.
5146
+ if (this.providers.size > 0 && !this.providers.has(providerId)) {
5147
+ return {
5148
+ success: false,
5149
+ defaultProvider: this.state.defaultProvider,
5150
+ error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,
5151
+ };
5152
+ }
5153
+ // During reinitialization the instance may still be the previous wrapper.
5154
+ // Persist the preference, but let provider assignment publish the new route.
5155
+ const aggregatedProvider = this.state.activeProvider === 'aggregated' &&
5156
+ this.state.effectiveProvider !== null &&
5157
+ this.activeProviderInstance instanceof AggregatedPerpsProvider
5158
+ ? this.activeProviderInstance
5159
+ : null;
5160
+ const defaultChanged = (aggregatedProvider?.getWriteProviderId() ??
5161
+ this.state.defaultProvider) !== providerId;
5162
+ this.update((state) => {
5163
+ state.defaultProvider = providerId;
5164
+ state.hasExplicitDefaultProviderSelection = true;
5165
+ if (aggregatedProvider) {
5166
+ state.effectiveProvider = providerId;
5167
+ }
5168
+ // The cached snapshot came from the previous default venue's stream, so
5169
+ // drop it until the new venue delivers matching data.
5170
+ if (defaultChanged && aggregatedProvider) {
5171
+ state.accountState = null;
5172
+ }
5173
+ });
5174
+ // Keep the live aggregated wrapper's routing in sync without any
5175
+ // re-initialization or reconnection. Default-routed streams move to the
5176
+ // new venue with it.
5177
+ if (aggregatedProvider) {
5178
+ aggregatedProvider.setDefaultProvider(providerId);
5179
+ }
5180
+ this.#debugLog('PerpsController: Default provider updated', {
5181
+ defaultProvider: providerId,
5182
+ activeProvider: this.state.activeProvider,
5183
+ });
5184
+ return { success: true, defaultProvider: providerId };
5185
+ }
4688
5186
  /**
4689
5187
  * Get current network (mainnet/testnet)
4690
5188
  *
@@ -4734,7 +5232,14 @@ export class PerpsController extends BaseController {
4734
5232
  try {
4735
5233
  const provider = this.getActiveProvider();
4736
5234
  if (provider.subscribeToConnectionState) {
4737
- return provider.subscribeToConnectionState(listener);
5235
+ return this.#trackProviderSubscription(provider, (nextProvider) => {
5236
+ if (nextProvider.subscribeToConnectionState) {
5237
+ return nextProvider.subscribeToConnectionState(listener);
5238
+ }
5239
+ listener(nextProvider.getWebSocketConnectionState?.() ??
5240
+ WebSocketConnectionState.Disconnected, 0);
5241
+ return () => undefined;
5242
+ });
4738
5243
  }
4739
5244
  // Fallback: immediately call with current state and return no-op unsubscribe
4740
5245
  listener(this.getWebSocketConnectionState(), 0);
@@ -4773,6 +5278,98 @@ export class PerpsController extends BaseController {
4773
5278
  }, CONNECTION_ERROR_TAGS));
4774
5279
  }
4775
5280
  }
5281
+ /**
5282
+ * Remember aggregated-session subscriptions for automatic rollback only.
5283
+ * Direct-session and caller-driven reconnect semantics remain unchanged.
5284
+ *
5285
+ * @param provider - Initially active provider.
5286
+ * @param open - Opens this subscription on a provider.
5287
+ * @param onInvalidate - Invalidates a cached value while the route is detached.
5288
+ * @returns Cleanup that always removes the current binding.
5289
+ */
5290
+ #trackProviderSubscription(provider, open, onInvalidate) {
5291
+ if (provider.protocolId !== 'aggregated') {
5292
+ return open(provider);
5293
+ }
5294
+ const subscription = {
5295
+ open,
5296
+ unsubscribe: open(provider),
5297
+ onInvalidate,
5298
+ };
5299
+ this.#providerSubscriptions.add(subscription);
5300
+ return () => {
5301
+ if (!this.#providerSubscriptions.delete(subscription)) {
5302
+ return;
5303
+ }
5304
+ const { unsubscribe } = subscription;
5305
+ subscription.unsubscribe = () => undefined;
5306
+ unsubscribe();
5307
+ };
5308
+ }
5309
+ /**
5310
+ * Detach registrations before their providers are disconnected.
5311
+ *
5312
+ * @param discard - Drop registrations for a caller-initiated lifecycle change.
5313
+ */
5314
+ #detachProviderSubscriptions(discard) {
5315
+ const subscriptions = [...this.#providerSubscriptions];
5316
+ this.#hasPendingSubscriptionRecovery = !discard;
5317
+ if (discard) {
5318
+ this.#providerSubscriptions.clear();
5319
+ }
5320
+ for (const subscription of subscriptions) {
5321
+ const { unsubscribe } = subscription;
5322
+ subscription.unsubscribe = () => undefined;
5323
+ try {
5324
+ unsubscribe();
5325
+ }
5326
+ catch (error) {
5327
+ this.#logProviderSubscriptionError(error);
5328
+ }
5329
+ if (!discard && this.#providerSubscriptions.has(subscription)) {
5330
+ try {
5331
+ subscription.onInvalidate?.();
5332
+ }
5333
+ catch (error) {
5334
+ this.#logProviderSubscriptionError(error);
5335
+ }
5336
+ }
5337
+ }
5338
+ }
5339
+ /** Reattach surviving registrations after rollback or a later recovery. */
5340
+ #restoreProviderSubscriptions() {
5341
+ const provider = this.activeProviderInstance;
5342
+ if (!this.isInitialized || !provider) {
5343
+ return;
5344
+ }
5345
+ this.#hasPendingSubscriptionRecovery = false;
5346
+ for (const subscription of [...this.#providerSubscriptions]) {
5347
+ if (!this.#providerSubscriptions.has(subscription)) {
5348
+ continue;
5349
+ }
5350
+ try {
5351
+ const unsubscribe = subscription.open(provider);
5352
+ // A synchronous first update may cause the caller to unsubscribe.
5353
+ if (this.#providerSubscriptions.has(subscription)) {
5354
+ subscription.unsubscribe = unsubscribe;
5355
+ }
5356
+ else {
5357
+ unsubscribe();
5358
+ }
5359
+ }
5360
+ catch (error) {
5361
+ this.#logProviderSubscriptionError(error);
5362
+ }
5363
+ }
5364
+ }
5365
+ /**
5366
+ * Isolate subscription failures so other consumers can still recover.
5367
+ *
5368
+ * @param error - Subscription cleanup, invalidation or restoration failure.
5369
+ */
5370
+ #logProviderSubscriptionError(error) {
5371
+ this.#logError(ensureError(error, 'PerpsController.providerSubscriptionRollback'), this.#getErrorContext('providerSubscriptionRollback'));
5372
+ }
4776
5373
  // Live data delegation (NO Redux) - delegates to active provider
4777
5374
  /**
4778
5375
  * Subscribe to live price updates
@@ -4788,7 +5385,7 @@ export class PerpsController extends BaseController {
4788
5385
  };
4789
5386
  }
4790
5387
  try {
4791
- return provider.subscribeToPrices(params);
5388
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToPrices(params));
4792
5389
  }
4793
5390
  catch (error) {
4794
5391
  this.#logError(ensureError(error, 'PerpsController.subscribeToPrices'), this.#getErrorContext('subscribeToPrices', {
@@ -4813,7 +5410,7 @@ export class PerpsController extends BaseController {
4813
5410
  };
4814
5411
  }
4815
5412
  try {
4816
- return provider.subscribeToPositions(params);
5413
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToPositions(params));
4817
5414
  }
4818
5415
  catch (error) {
4819
5416
  this.#logError(ensureError(error, 'PerpsController.subscribeToPositions'), this.#getErrorContext('subscribeToPositions', {
@@ -4838,7 +5435,7 @@ export class PerpsController extends BaseController {
4838
5435
  };
4839
5436
  }
4840
5437
  try {
4841
- return provider.subscribeToOrderFills(params);
5438
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrderFills(params));
4842
5439
  }
4843
5440
  catch (error) {
4844
5441
  this.#logError(ensureError(error, 'PerpsController.subscribeToOrderFills'), this.#getErrorContext('subscribeToOrderFills', {
@@ -4867,7 +5464,7 @@ export class PerpsController extends BaseController {
4867
5464
  };
4868
5465
  }
4869
5466
  try {
4870
- return provider.subscribeToTwapOrders(params);
5467
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined), () => params.callback([], true));
4871
5468
  }
4872
5469
  catch (error) {
4873
5470
  this.#logError(ensureError(error, 'PerpsController.subscribeToTwapOrders'), this.#getErrorContext('subscribeToTwapOrders', {
@@ -4892,7 +5489,7 @@ export class PerpsController extends BaseController {
4892
5489
  };
4893
5490
  }
4894
5491
  try {
4895
- return provider.subscribeToOrders(params);
5492
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrders(params));
4896
5493
  }
4897
5494
  catch (error) {
4898
5495
  this.#logError(ensureError(error, 'PerpsController.subscribeToOrders'), this.#getErrorContext('subscribeToOrders', {
@@ -4920,7 +5517,7 @@ export class PerpsController extends BaseController {
4920
5517
  }
4921
5518
  try {
4922
5519
  const originalCallback = params.callback;
4923
- return provider.subscribeToAccount({
5520
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToAccount({
4924
5521
  ...params,
4925
5522
  callback: (account) => {
4926
5523
  if (account) {
@@ -4932,7 +5529,7 @@ export class PerpsController extends BaseController {
4932
5529
  }
4933
5530
  originalCallback(account);
4934
5531
  },
4935
- });
5532
+ }), () => originalCallback(null));
4936
5533
  }
4937
5534
  catch (error) {
4938
5535
  this.#logError(ensureError(error, 'PerpsController.subscribeToAccount'), this.#getErrorContext('subscribeToAccount', {
@@ -4958,7 +5555,7 @@ export class PerpsController extends BaseController {
4958
5555
  };
4959
5556
  }
4960
5557
  try {
4961
- return provider.subscribeToOrderBook(params);
5558
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrderBook(params));
4962
5559
  }
4963
5560
  catch (error) {
4964
5561
  this.#logError(ensureError(error, 'PerpsController.subscribeToOrderBook'), this.#getErrorContext('subscribeToOrderBook', {
@@ -4994,13 +5591,126 @@ export class PerpsController extends BaseController {
4994
5591
  return noop;
4995
5592
  }
4996
5593
  try {
4997
- return provider.subscribeToAvailableToTrade(params);
5594
+ return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
5595
+ ? () => undefined
5596
+ : (nextProvider.subscribeToAvailableToTrade?.(params) ??
5597
+ (() => undefined)), () => params.onError?.(new Error('Available-to-trade provider replaced')));
4998
5598
  }
4999
5599
  catch (error) {
5000
5600
  this.#logError(ensureError(error, 'PerpsController.subscribeToAvailableToTrade'), this.#getErrorContext('subscribeToAvailableToTrade', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
5001
5601
  return noop;
5002
5602
  }
5003
5603
  }
5604
+ /**
5605
+ * Read a market's most recent public trades (every user's trades, not only
5606
+ * the account's fills), newest first, from the active provider.
5607
+ *
5608
+ * Every trade has the same shape on every provider and carries its
5609
+ * `providerId`. If the active provider changes before the venue answers,
5610
+ * or in aggregated mode the default provider changes before an unrouted
5611
+ * read answers, this resolves to an empty list, so a previous provider's
5612
+ * trades never reach a client that already moved on.
5613
+ *
5614
+ * @param params - Market, optional limit (default 50) and provider route.
5615
+ * @returns The trades, newest first.
5616
+ * @throws When no provider is initialized, the route conflicts with the
5617
+ * active provider (`PROVIDER_NOT_FOUND`), the provider has no public trade
5618
+ * feed, `limit` is not a positive integer, or the venue request fails.
5619
+ */
5620
+ async getPublicTrades(params) {
5621
+ const provider = this.getActiveProvider();
5622
+ if (this.#hasConflictingProviderRoute(params.providerId, provider)) {
5623
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_NOT_FOUND);
5624
+ }
5625
+ if (!provider.getPublicTrades) {
5626
+ throw new Error('Public trades not supported by provider');
5627
+ }
5628
+ const limit = params.limit ?? PUBLIC_TRADES_DEFAULT_LIMIT;
5629
+ if (!Number.isInteger(limit) || limit < 1) {
5630
+ throw new Error(`Invalid public trades limit: ${String(params.limit)}`);
5631
+ }
5632
+ try {
5633
+ const trades = await provider.getPublicTrades({ ...params, limit });
5634
+ if (this.getActiveProviderOrNull() !== provider) {
5635
+ return [];
5636
+ }
5637
+ return trades.filter((trade) => trade.symbol === params.symbol);
5638
+ }
5639
+ catch (error) {
5640
+ this.#logError(ensureError(error, 'PerpsController.getPublicTrades'), this.#getErrorContext('getPublicTrades', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
5641
+ throw error;
5642
+ }
5643
+ }
5644
+ /**
5645
+ * Stream a market's public trades (every user's trades) from the active
5646
+ * provider, like the other market-data subscriptions.
5647
+ *
5648
+ * The callback receives each batch of new trades the venue pushes, newest
5649
+ * first. Only a subscription that opens the venue channel may first
5650
+ * receive the venue's recent trades; one that joins a market another
5651
+ * subscription already streams receives only new trades. Seed the list with
5652
+ * `getPublicTrades` and dedupe batches on `id`. Nothing is delivered
5653
+ * after the returned cleanup runs, after the provider that opened the
5654
+ * stream stops being the active one (provider
5655
+ * switch, testnet toggle, reinitialization), or for any other symbol.
5656
+ * Subscribe again once the new provider is active. In aggregated mode an
5657
+ * unrouted stream follows the default provider: `setDefaultProvider` moves
5658
+ * it to the new venue, like `subscribeToCandles`. On Hyperliquid, like
5659
+ * `subscribeToCandles`, the stream is not restored after the client
5660
+ * service reconnects its WebSocket and `onError` is not called, so
5661
+ * resubscribe after a reconnect.
5662
+ *
5663
+ * When no provider is active, the route conflicts with the active
5664
+ * provider, or the provider has no public trade feed, this returns a no-op
5665
+ * cleanup and never calls back.
5666
+ *
5667
+ * @param params - Market, optional route, callback and error handler.
5668
+ * @returns A cleanup function to remove the subscription.
5669
+ */
5670
+ subscribeToPublicTrades(params) {
5671
+ const noop = () => {
5672
+ // No-op: no public trade feed for this route
5673
+ };
5674
+ const provider = this.getActiveProviderOrNull();
5675
+ if (!provider?.subscribeToPublicTrades ||
5676
+ this.#hasConflictingProviderRoute(params.providerId, provider)) {
5677
+ return noop;
5678
+ }
5679
+ let isActive = true;
5680
+ const isCurrent = () => isActive && this.getActiveProviderOrNull() === provider;
5681
+ const { onError } = params;
5682
+ try {
5683
+ const unsubscribe = provider.subscribeToPublicTrades({
5684
+ ...params,
5685
+ callback: (trades) => {
5686
+ if (!isCurrent()) {
5687
+ return;
5688
+ }
5689
+ const matching = trades.filter((trade) => trade.symbol === params.symbol);
5690
+ if (matching.length > 0) {
5691
+ params.callback(matching);
5692
+ }
5693
+ },
5694
+ ...(onError
5695
+ ? {
5696
+ onError: (error) => {
5697
+ if (isCurrent()) {
5698
+ onError(error);
5699
+ }
5700
+ },
5701
+ }
5702
+ : {}),
5703
+ });
5704
+ return () => {
5705
+ isActive = false;
5706
+ unsubscribe();
5707
+ };
5708
+ }
5709
+ catch (error) {
5710
+ this.#logError(ensureError(error, 'PerpsController.subscribeToPublicTrades'), this.#getErrorContext('subscribeToPublicTrades', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
5711
+ return noop;
5712
+ }
5713
+ }
5004
5714
  /**
5005
5715
  * Subscribe to live candle updates
5006
5716
  *
@@ -5015,7 +5725,7 @@ export class PerpsController extends BaseController {
5015
5725
  };
5016
5726
  }
5017
5727
  try {
5018
- return provider.subscribeToCandles(params);
5728
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToCandles(params));
5019
5729
  }
5020
5730
  catch (error) {
5021
5731
  this.#logError(ensureError(error, 'PerpsController.subscribeToCandles'), this.#getErrorContext('subscribeToCandles', {
@@ -5043,7 +5753,7 @@ export class PerpsController extends BaseController {
5043
5753
  };
5044
5754
  }
5045
5755
  try {
5046
- return provider.subscribeToOICaps(params);
5756
+ return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOICaps(params));
5047
5757
  }
5048
5758
  catch (error) {
5049
5759
  this.#logError(ensureError(error, 'PerpsController.subscribeToOICaps'), this.#getErrorContext('subscribeToOICaps', {
@@ -5297,6 +6007,7 @@ export class PerpsController extends BaseController {
5297
6007
  * @returns A promise that resolves when teardown finishes.
5298
6008
  */
5299
6009
  async #performDisconnect() {
6010
+ this.#detachProviderSubscriptions(true);
5300
6011
  this.#lifecycleGeneration += 1;
5301
6012
  this.#debugLog('PerpsController: Disconnecting provider to cleanup subscriptions', {
5302
6013
  timestamp: new Date().toISOString(),
@@ -5345,6 +6056,9 @@ export class PerpsController extends BaseController {
5345
6056
  }
5346
6057
  // Clear stale reference so standalone reads don't route through old provider
5347
6058
  this.activeProviderInstance = null;
6059
+ this.update((state) => {
6060
+ state.effectiveProvider = null;
6061
+ });
5348
6062
  // Cleanup cached standalone provider (if any) — awaited to prevent races
5349
6063
  await this.#cleanupStandaloneProvider();
5350
6064
  // Note: Feature-flag subscription is NOT cleaned up here.
@@ -5520,35 +6234,51 @@ export class PerpsController extends BaseController {
5520
6234
  });
5521
6235
  }
5522
6236
  /**
5523
- * Get saved trade configuration for a market
6237
+ * Get saved trade configuration for a market on a venue
5524
6238
  *
5525
6239
  * @param symbol - The trading pair symbol.
6240
+ * @param providerId - Optional venue the configuration was saved for.
6241
+ * Defaults to the live effective venue, or the active/saved default venue
6242
+ * before initialization.
5526
6243
  * @returns The resulting string value.
5527
6244
  */
5528
- getTradeConfiguration(symbol) {
6245
+ getTradeConfiguration(symbol, providerId) {
5529
6246
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
5530
- const config = this.state.tradeConfigurations[network]?.[symbol];
6247
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6248
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6249
+ return undefined;
6250
+ }
6251
+ const config = this.state.tradeConfigurations[network]?.[provider]?.[symbol];
5531
6252
  if (!config?.leverage) {
5532
6253
  return undefined;
5533
6254
  }
5534
6255
  this.#debugLog('PerpsController: Retrieved trade config', {
5535
6256
  symbol,
5536
6257
  network,
6258
+ provider,
5537
6259
  leverage: config.leverage,
5538
6260
  });
5539
6261
  return { leverage: config.leverage };
5540
6262
  }
5541
6263
  /**
5542
- * Save trade configuration for a market
6264
+ * Save trade configuration for a market on a venue
5543
6265
  *
5544
6266
  * @param symbol - Market symbol
5545
6267
  * @param leverage - Leverage value
6268
+ * @param providerId - Optional venue to key the configuration under.
6269
+ * Defaults to the live effective venue, or the active/saved default venue
6270
+ * before initialization.
5546
6271
  */
5547
- saveTradeConfiguration(symbol, leverage) {
6272
+ saveTradeConfiguration(symbol, leverage, providerId) {
5548
6273
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
6274
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6275
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6276
+ return;
6277
+ }
5549
6278
  this.#debugLog('PerpsController: Saving trade configuration', {
5550
6279
  symbol,
5551
6280
  network,
6281
+ provider,
5552
6282
  leverage,
5553
6283
  timestamp: new Date().toISOString(),
5554
6284
  });
@@ -5556,8 +6286,11 @@ export class PerpsController extends BaseController {
5556
6286
  if (!state.tradeConfigurations[network]) {
5557
6287
  state.tradeConfigurations[network] = {};
5558
6288
  }
5559
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
5560
- state.tradeConfigurations[network][symbol] = {
6289
+ if (!state.tradeConfigurations[network][provider]) {
6290
+ state.tradeConfigurations[network][provider] = {};
6291
+ }
6292
+ const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
6293
+ state.tradeConfigurations[network][provider][symbol] = {
5561
6294
  ...existingConfig,
5562
6295
  leverage,
5563
6296
  };
@@ -5578,12 +6311,20 @@ export class PerpsController extends BaseController {
5578
6311
  * @param config.reduceOnly - Whether the order may only reduce a position.
5579
6312
  * @param config.direction - Long or short.
5580
6313
  * @param config.selectedPaymentToken - The selected payment token.
6314
+ * @param providerId - Optional venue to key the configuration under.
6315
+ * Defaults to the live effective venue, or the active/saved default venue
6316
+ * before initialization.
5581
6317
  */
5582
- savePendingTradeConfiguration(symbol, config) {
6318
+ savePendingTradeConfiguration(symbol, config, providerId) {
5583
6319
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
6320
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6321
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6322
+ return;
6323
+ }
5584
6324
  this.#debugLog('PerpsController: Saving pending trade configuration', {
5585
6325
  symbol,
5586
6326
  network,
6327
+ provider,
5587
6328
  config,
5588
6329
  timestamp: new Date().toISOString(),
5589
6330
  });
@@ -5591,8 +6332,11 @@ export class PerpsController extends BaseController {
5591
6332
  if (!state.tradeConfigurations[network]) {
5592
6333
  state.tradeConfigurations[network] = {};
5593
6334
  }
5594
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
5595
- state.tradeConfigurations[network][symbol] = {
6335
+ if (!state.tradeConfigurations[network][provider]) {
6336
+ state.tradeConfigurations[network][provider] = {};
6337
+ }
6338
+ const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
6339
+ state.tradeConfigurations[network][provider][symbol] = {
5596
6340
  ...existingConfig,
5597
6341
  pendingConfig: {
5598
6342
  ...config,
@@ -5609,11 +6353,19 @@ export class PerpsController extends BaseController {
5609
6353
  * Returns undefined if config doesn't exist or has expired.
5610
6354
  *
5611
6355
  * @param symbol - Market symbol
6356
+ * @param providerId - Optional venue the configuration was saved for.
6357
+ * Defaults to the live effective venue, or the active/saved default venue
6358
+ * before initialization.
5612
6359
  * @returns Pending trade configuration or undefined
5613
6360
  */
5614
- getPendingTradeConfiguration(symbol) {
6361
+ getPendingTradeConfiguration(symbol, providerId) {
5615
6362
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
5616
- const config = this.state.tradeConfigurations[network]?.[symbol]?.pendingConfig;
6363
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6364
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6365
+ return undefined;
6366
+ }
6367
+ const config = this.state.tradeConfigurations[network]?.[provider]?.[symbol]
6368
+ ?.pendingConfig;
5617
6369
  if (!config) {
5618
6370
  return undefined;
5619
6371
  }
@@ -5623,13 +6375,16 @@ export class PerpsController extends BaseController {
5623
6375
  this.#debugLog('PerpsController: Pending trade config expired', {
5624
6376
  symbol,
5625
6377
  network,
6378
+ provider,
5626
6379
  age,
5627
6380
  timestamp: config.timestamp,
5628
6381
  });
5629
6382
  // Clear expired config
5630
6383
  this.update((state) => {
5631
- if (state.tradeConfigurations[network]?.[symbol]?.pendingConfig) {
5632
- delete state.tradeConfigurations[network][symbol].pendingConfig;
6384
+ if (state.tradeConfigurations[network]?.[provider]?.[symbol]
6385
+ ?.pendingConfig) {
6386
+ delete state.tradeConfigurations[network][provider][symbol]
6387
+ .pendingConfig;
5633
6388
  }
5634
6389
  });
5635
6390
  return undefined;
@@ -5637,6 +6392,7 @@ export class PerpsController extends BaseController {
5637
6392
  this.#debugLog('PerpsController: Retrieved pending trade config', {
5638
6393
  symbol,
5639
6394
  network,
6395
+ provider,
5640
6396
  config,
5641
6397
  age,
5642
6398
  });
@@ -5645,20 +6401,29 @@ export class PerpsController extends BaseController {
5645
6401
  return configWithoutTimestamp;
5646
6402
  }
5647
6403
  /**
5648
- * Clear pending trade configuration for a market
6404
+ * Clear pending trade configuration for a market on a venue
5649
6405
  *
5650
6406
  * @param symbol - Market symbol
6407
+ * @param providerId - Optional venue the configuration was saved for.
6408
+ * Defaults to the live effective venue, or the active/saved default venue
6409
+ * before initialization.
5651
6410
  */
5652
- clearPendingTradeConfiguration(symbol) {
6411
+ clearPendingTradeConfiguration(symbol, providerId) {
5653
6412
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
6413
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6414
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6415
+ return;
6416
+ }
5654
6417
  this.#debugLog('PerpsController: Clearing pending trade configuration', {
5655
6418
  symbol,
5656
6419
  network,
6420
+ provider,
5657
6421
  timestamp: new Date().toISOString(),
5658
6422
  });
5659
6423
  this.update((state) => {
5660
- if (state.tradeConfigurations[network]?.[symbol]?.pendingConfig) {
5661
- delete state.tradeConfigurations[network][symbol].pendingConfig;
6424
+ if (state.tradeConfigurations[network]?.[provider]?.[symbol]?.pendingConfig) {
6425
+ delete state.tradeConfigurations[network][provider][symbol]
6426
+ .pendingConfig;
5662
6427
  }
5663
6428
  });
5664
6429
  }
@@ -5905,31 +6670,46 @@ export class PerpsController extends BaseController {
5905
6670
  * Get saved order book grouping for a market
5906
6671
  *
5907
6672
  * @param symbol - Market symbol
6673
+ * @param providerId - Optional venue the grouping was saved for. Defaults to
6674
+ * the live effective venue (active/saved default before initialization).
5908
6675
  * @returns The saved grouping value or undefined if not set
5909
6676
  */
5910
- getOrderBookGrouping(symbol) {
6677
+ getOrderBookGrouping(symbol, providerId) {
5911
6678
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
5912
- const grouping = this.state.tradeConfigurations[network]?.[symbol]?.orderBookGrouping;
6679
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6680
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6681
+ return undefined;
6682
+ }
6683
+ const grouping = this.state.tradeConfigurations[network]?.[provider]?.[symbol]
6684
+ ?.orderBookGrouping;
5913
6685
  if (grouping !== undefined) {
5914
6686
  this.#debugLog('PerpsController: Retrieved order book grouping', {
5915
6687
  symbol,
5916
6688
  network,
6689
+ provider,
5917
6690
  grouping,
5918
6691
  });
5919
6692
  }
5920
6693
  return grouping;
5921
6694
  }
5922
6695
  /**
5923
- * Save order book grouping for a market
6696
+ * Save order book grouping for a market on a venue
5924
6697
  *
5925
6698
  * @param symbol - Market symbol
5926
6699
  * @param grouping - Price grouping value
6700
+ * @param providerId - Optional venue to key the grouping under. Defaults to
6701
+ * the live effective venue (active/saved default before initialization).
5927
6702
  */
5928
- saveOrderBookGrouping(symbol, grouping) {
6703
+ saveOrderBookGrouping(symbol, grouping, providerId) {
5929
6704
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
6705
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6706
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6707
+ return;
6708
+ }
5930
6709
  this.#debugLog('PerpsController: Saving order book grouping', {
5931
6710
  symbol,
5932
6711
  network,
6712
+ provider,
5933
6713
  grouping,
5934
6714
  timestamp: new Date().toISOString(),
5935
6715
  });
@@ -5937,8 +6717,11 @@ export class PerpsController extends BaseController {
5937
6717
  if (!state.tradeConfigurations[network]) {
5938
6718
  state.tradeConfigurations[network] = {};
5939
6719
  }
5940
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
5941
- state.tradeConfigurations[network][symbol] = {
6720
+ if (!state.tradeConfigurations[network][provider]) {
6721
+ state.tradeConfigurations[network][provider] = {};
6722
+ }
6723
+ const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
6724
+ state.tradeConfigurations[network][provider][symbol] = {
5942
6725
  ...existingConfig,
5943
6726
  orderBookGrouping: grouping,
5944
6727
  };
@@ -5949,35 +6732,52 @@ export class PerpsController extends BaseController {
5949
6732
  * network. Clients should still let a venue-enforced mode take priority.
5950
6733
  *
5951
6734
  * @param symbol - Market symbol
6735
+ * @param providerId - Optional venue the mode was saved for. Defaults to the
6736
+ * live effective venue (active/saved default before initialization).
5952
6737
  * @returns The saved margin mode or undefined if not set
5953
6738
  */
5954
- getMarginMode(symbol) {
6739
+ getMarginMode(symbol, providerId) {
5955
6740
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
5956
- return this.state.tradeConfigurations[network]?.[symbol]?.marginMode;
6741
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6742
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6743
+ return undefined;
6744
+ }
6745
+ return this.state.tradeConfigurations[network]?.[provider]?.[symbol]
6746
+ ?.marginMode;
5957
6747
  }
5958
6748
  /**
5959
- * Save the margin mode (Isolated/Cross) picked for a market on the current
5960
- * network. Values other than `isolated` or `cross` are ignored.
6749
+ * Save the margin mode (Isolated/Cross) picked for a market on a venue on
6750
+ * the current network. Values other than `isolated` or `cross` are ignored.
5961
6751
  *
5962
6752
  * @param symbol - Market symbol
5963
6753
  * @param marginMode - Margin mode to persist
6754
+ * @param providerId - Optional venue to key the mode under. Defaults to the
6755
+ * live effective venue (active/saved default before initialization).
5964
6756
  */
5965
- saveMarginMode(symbol, marginMode) {
6757
+ saveMarginMode(symbol, marginMode, providerId) {
5966
6758
  if (marginMode !== 'isolated' && marginMode !== 'cross') {
5967
6759
  return;
5968
6760
  }
5969
6761
  const network = this.state.isTestnet ? 'testnet' : 'mainnet';
6762
+ const provider = resolveTradeConfigProviderKey(this.state, providerId);
6763
+ if (provider === null || isUnsafeRecordKey(symbol)) {
6764
+ return;
6765
+ }
5970
6766
  this.#debugLog('PerpsController: Saving margin mode', {
5971
6767
  symbol,
5972
6768
  network,
6769
+ provider,
5973
6770
  marginMode,
5974
6771
  });
5975
6772
  this.update((state) => {
5976
6773
  if (!state.tradeConfigurations[network]) {
5977
6774
  state.tradeConfigurations[network] = {};
5978
6775
  }
5979
- const existingConfig = state.tradeConfigurations[network][symbol] || {};
5980
- state.tradeConfigurations[network][symbol] = {
6776
+ if (!state.tradeConfigurations[network][provider]) {
6777
+ state.tradeConfigurations[network][provider] = {};
6778
+ }
6779
+ const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
6780
+ state.tradeConfigurations[network][provider][symbol] = {
5981
6781
  ...existingConfig,
5982
6782
  marginMode,
5983
6783
  };