@metamask-previews/perps-controller 23.1.0-preview-d8f16be → 23.1.0-preview-682f78a99
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.
- package/CHANGELOG.md +45 -0
- package/README.md +35 -0
- package/dist/PerpsController-method-action-types.d.ts +46 -7
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +87 -52
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +738 -54
- package/dist/PerpsController.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +2 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +10 -0
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +203 -38
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/routing/isPerpsProviderType.d.ts +10 -0
- package/dist/routing/isPerpsProviderType.d.ts.map +1 -0
- package/dist/routing/isPerpsProviderType.js +11 -0
- package/dist/routing/isPerpsProviderType.js.map +1 -0
- package/dist/routing/resolveTradeConfigProviderKey.d.ts +22 -0
- package/dist/routing/resolveTradeConfigProviderKey.d.ts.map +1 -0
- package/dist/routing/resolveTradeConfigProviderKey.js +25 -0
- package/dist/routing/resolveTradeConfigProviderKey.js.map +1 -0
- package/dist/selectors.d.ts +35 -233
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +36 -13
- package/dist/selectors.js.map +1 -1
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +12 -6
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +15 -3
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TradingService.d.ts +3 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +9 -4
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +59 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/package.json +1 -1
package/dist/PerpsController.js
CHANGED
|
@@ -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,
|
|
@@ -522,6 +569,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
522
569
|
'saveTradeConfiguration',
|
|
523
570
|
'setAgentSigner',
|
|
524
571
|
'setAttributionContext',
|
|
572
|
+
'setDefaultProvider',
|
|
525
573
|
'setLiveDataConfig',
|
|
526
574
|
'setSelectedPaymentToken',
|
|
527
575
|
'setVisibleCandleCount',
|
|
@@ -681,6 +729,9 @@ export class PerpsController extends BaseController {
|
|
|
681
729
|
*/
|
|
682
730
|
#pendingWatchlistToggles = new Map();
|
|
683
731
|
#userDiskWrite = Promise.resolve();
|
|
732
|
+
#providerSubscriptions = new Set();
|
|
733
|
+
// A failed automatic rollback does not end the consumers' subscription context.
|
|
734
|
+
#hasPendingSubscriptionRecovery = false;
|
|
684
735
|
// Store options for dependency injection (allows core package to inject platform-specific services)
|
|
685
736
|
#options;
|
|
686
737
|
// Service instances (instantiated with platform dependencies)
|
|
@@ -700,7 +751,12 @@ export class PerpsController extends BaseController {
|
|
|
700
751
|
name: 'PerpsController',
|
|
701
752
|
metadata,
|
|
702
753
|
messenger,
|
|
703
|
-
state: {
|
|
754
|
+
state: {
|
|
755
|
+
...getDefaultPerpsControllerState(),
|
|
756
|
+
...state,
|
|
757
|
+
// A live routing decision must never be restored from a snapshot.
|
|
758
|
+
effectiveProvider: null,
|
|
759
|
+
},
|
|
704
760
|
});
|
|
705
761
|
this.#eligibilityCheckDeferred = deferEligibilityCheck;
|
|
706
762
|
// Store options for dependency injection
|
|
@@ -791,6 +847,11 @@ export class PerpsController extends BaseController {
|
|
|
791
847
|
this.providers = new Map();
|
|
792
848
|
// Migrate old persisted data without accountAddress
|
|
793
849
|
this.#migrateRequestsIfNeeded();
|
|
850
|
+
// Migrate persisted state shapes/values written by older versions. Trade
|
|
851
|
+
// configurations must move under their venue key before the multi-provider
|
|
852
|
+
// migration can flip `activeProvider` (the venue key is derived from it).
|
|
853
|
+
this.#migrateTradeConfigurationsIfNeeded();
|
|
854
|
+
this.#migrateActiveProviderForMultiProviderIfNeeded();
|
|
794
855
|
// Eagerly hydrate in-memory caches from disk so hooks see data on first render.
|
|
795
856
|
// Must happen at construction time — before any React component mounts.
|
|
796
857
|
this.#hydrateCacheFromDiskSync();
|
|
@@ -1301,6 +1362,162 @@ export class PerpsController extends BaseController {
|
|
|
1301
1362
|
state.depositRequests = state.depositRequests.filter((req) => Boolean(req.accountAddress));
|
|
1302
1363
|
});
|
|
1303
1364
|
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Re-key persisted trade configurations from `{ network: { symbol: config } }`
|
|
1367
|
+
* to `{ network: { provider: { symbol: config } } }`.
|
|
1368
|
+
*
|
|
1369
|
+
* Entries saved by older versions were written under whichever venue was
|
|
1370
|
+
* active, so they move under that venue's key: `activeProvider` when it is a
|
|
1371
|
+
* direct venue, else `defaultProvider`. Idempotent: the legacy shape is
|
|
1372
|
+
* detected by a config field (`leverage`, `orderBookGrouping`, `marginMode`,
|
|
1373
|
+
* `pendingConfig`) sitting directly under a symbol key.
|
|
1374
|
+
*/
|
|
1375
|
+
#migrateTradeConfigurationsIfNeeded() {
|
|
1376
|
+
const configFieldNames = [
|
|
1377
|
+
'leverage',
|
|
1378
|
+
'orderBookGrouping',
|
|
1379
|
+
'marginMode',
|
|
1380
|
+
'pendingConfig',
|
|
1381
|
+
];
|
|
1382
|
+
const { activeProvider, defaultProvider } = this.state;
|
|
1383
|
+
// Both ids come from persisted state, so the destination is validated
|
|
1384
|
+
// against the closed set of venues: an unexpected value (including
|
|
1385
|
+
// `__proto__`) must never become a record key.
|
|
1386
|
+
let destinationProvider = 'hyperliquid';
|
|
1387
|
+
if (isPerpsProviderType(activeProvider)) {
|
|
1388
|
+
destinationProvider = activeProvider;
|
|
1389
|
+
}
|
|
1390
|
+
else if (isPerpsProviderType(defaultProvider)) {
|
|
1391
|
+
destinationProvider = defaultProvider;
|
|
1392
|
+
}
|
|
1393
|
+
this.update((state) => {
|
|
1394
|
+
for (const network of ['testnet', 'mainnet']) {
|
|
1395
|
+
const entries = state.tradeConfigurations?.[network];
|
|
1396
|
+
if (!entries) {
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
const isLegacyShape = Object.values(entries).some((symbolEntry) => symbolEntry !== null &&
|
|
1400
|
+
typeof symbolEntry === 'object' &&
|
|
1401
|
+
configFieldNames.some((field) => field in symbolEntry));
|
|
1402
|
+
if (!isLegacyShape) {
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
state.tradeConfigurations[network] = {
|
|
1406
|
+
[destinationProvider]: entries,
|
|
1407
|
+
};
|
|
1408
|
+
this.#debugLog('PerpsController: Migrated trade configurations to provider-keyed shape', { network, provider: destinationProvider });
|
|
1409
|
+
}
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Whether the multi-provider (aggregated) mode flag is on.
|
|
1414
|
+
*
|
|
1415
|
+
* Version-gated like `perpsLighterProviderEnabled`: enabled only when the
|
|
1416
|
+
* flag is on and the app version meets its minimum.
|
|
1417
|
+
*
|
|
1418
|
+
* @returns Whether the flag is enabled for the current app version, or
|
|
1419
|
+
* undefined when flags or version validation are not available yet.
|
|
1420
|
+
*/
|
|
1421
|
+
#getMultiProviderModeEnabled() {
|
|
1422
|
+
try {
|
|
1423
|
+
const remoteState = this.messenger.call('RemoteFeatureFlagController:getState');
|
|
1424
|
+
const remoteFlag = remoteState.remoteFeatureFlags?.perpsMultiProviderModeEnabled;
|
|
1425
|
+
if (isVersionGatedFeatureFlag(remoteFlag)) {
|
|
1426
|
+
// An explicit kill switch does not require version validation. Missing
|
|
1427
|
+
// flags/validation, on the other hand, must not undo a persisted mode.
|
|
1428
|
+
if (!remoteFlag.enabled) {
|
|
1429
|
+
return false;
|
|
1430
|
+
}
|
|
1431
|
+
return this.#options.infrastructure.featureFlags.validateVersionGated(remoteFlag);
|
|
1432
|
+
}
|
|
1433
|
+
return undefined;
|
|
1434
|
+
}
|
|
1435
|
+
catch {
|
|
1436
|
+
return undefined;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Migrate a persisted direct `activeProvider` to aggregated mode.
|
|
1441
|
+
*
|
|
1442
|
+
* When the multi-provider flag is on and the persisted mode is a direct
|
|
1443
|
+
* venue, the venue becomes the persisted `defaultProvider` only on the first
|
|
1444
|
+
* migration and unless the user explicitly saved one. The mode becomes
|
|
1445
|
+
* `aggregated`, so both venues' positions and balances are read at the same
|
|
1446
|
+
* time and each order goes to the venue the user picks. Idempotent;
|
|
1447
|
+
* runs at construction (flags may not be loaded yet, in which case it also
|
|
1448
|
+
* runs from `#performInitialization` before the active provider is assigned).
|
|
1449
|
+
* An explicitly disabled flag restores direct mode using the saved default,
|
|
1450
|
+
* without recording an explicit user selection or erasing the preference.
|
|
1451
|
+
*/
|
|
1452
|
+
#migrateActiveProviderForMultiProviderIfNeeded() {
|
|
1453
|
+
const enabled = this.#getMultiProviderModeEnabled();
|
|
1454
|
+
if (this.state.activeProvider === 'aggregated') {
|
|
1455
|
+
this.update((state) => {
|
|
1456
|
+
// Existing aggregated snapshots already have an established default,
|
|
1457
|
+
// even if they predate this marker or the flag is not loaded yet.
|
|
1458
|
+
state.hasMigratedToMultiProvider = true;
|
|
1459
|
+
if (enabled === false) {
|
|
1460
|
+
state.activeProvider = isPerpsProviderType(state.defaultProvider)
|
|
1461
|
+
? state.defaultProvider
|
|
1462
|
+
: 'hyperliquid';
|
|
1463
|
+
state.effectiveProvider = null;
|
|
1464
|
+
state.accountState = null;
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
if (enabled !== true) {
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
// An explicit selection is a user choice, not unmigrated legacy state, so
|
|
1473
|
+
// ordinary initialization must not reinterpret it.
|
|
1474
|
+
if (this.state.hasExplicitProviderSelection) {
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
const { activeProvider } = this.state;
|
|
1478
|
+
if (!isPerpsProviderType(activeProvider)) {
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
this.update((state) => {
|
|
1482
|
+
if (!state.hasExplicitDefaultProviderSelection &&
|
|
1483
|
+
!state.hasMigratedToMultiProvider) {
|
|
1484
|
+
state.defaultProvider = activeProvider;
|
|
1485
|
+
}
|
|
1486
|
+
state.hasMigratedToMultiProvider = true;
|
|
1487
|
+
state.activeProvider = 'aggregated';
|
|
1488
|
+
});
|
|
1489
|
+
this.#debugLog('PerpsController: Migrated direct provider to aggregated mode', {
|
|
1490
|
+
previousProvider: activeProvider,
|
|
1491
|
+
defaultProvider: this.state.defaultProvider,
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Apply the multi-provider kill switch to an already connected session.
|
|
1496
|
+
* In-flight lifecycle operations reconcile the flag during initialization;
|
|
1497
|
+
* otherwise claim the same lifecycle lock used by provider/network switches.
|
|
1498
|
+
*/
|
|
1499
|
+
#refreshMultiProviderModeOnFeatureFlagChange() {
|
|
1500
|
+
if (this.state.activeProvider !== 'aggregated' ||
|
|
1501
|
+
this.#getMultiProviderModeEnabled() !== false ||
|
|
1502
|
+
this.isCurrentlyReinitializing() ||
|
|
1503
|
+
this.#disconnectOperationPromise ||
|
|
1504
|
+
this.state.initializationState === InitializationState.Initializing) {
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
if (!this.isInitialized) {
|
|
1508
|
+
this.#migrateActiveProviderForMultiProviderIfNeeded();
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
const completeReinitialization = this.#beginReinitialization();
|
|
1512
|
+
this.#migrateActiveProviderForMultiProviderIfNeeded();
|
|
1513
|
+
this.isInitialized = false;
|
|
1514
|
+
this.#initializationPromise = null;
|
|
1515
|
+
this.#initWithoutDisconnectWait(true)
|
|
1516
|
+
.catch((error) => {
|
|
1517
|
+
this.#logError(ensureError(error, 'PerpsController.multiProviderRollback'), this.#getErrorContext('multiProviderRollback'));
|
|
1518
|
+
})
|
|
1519
|
+
.finally(completeReinitialization);
|
|
1520
|
+
}
|
|
1304
1521
|
setBlockedRegionList(list, source) {
|
|
1305
1522
|
this.#featureFlagConfigurationService.setBlockedRegions({
|
|
1306
1523
|
list,
|
|
@@ -1362,6 +1579,7 @@ export class PerpsController extends BaseController {
|
|
|
1362
1579
|
},
|
|
1363
1580
|
}),
|
|
1364
1581
|
});
|
|
1582
|
+
this.#refreshMultiProviderModeOnFeatureFlagChange();
|
|
1365
1583
|
}
|
|
1366
1584
|
/**
|
|
1367
1585
|
* Execute an operation while temporarily pausing specified stream channels
|
|
@@ -1447,16 +1665,17 @@ export class PerpsController extends BaseController {
|
|
|
1447
1665
|
await pendingReinitialization;
|
|
1448
1666
|
continue;
|
|
1449
1667
|
}
|
|
1450
|
-
return this.#initWithoutDisconnectWait();
|
|
1668
|
+
return this.#initWithoutDisconnectWait(this.#hasPendingSubscriptionRecovery);
|
|
1451
1669
|
}
|
|
1452
1670
|
}
|
|
1453
1671
|
/**
|
|
1454
1672
|
* Initialize without waiting for disconnect. Reinitialization operations use
|
|
1455
1673
|
* this after they have claimed the controller lifecycle.
|
|
1456
1674
|
*
|
|
1675
|
+
* @param preserveSubscriptions - Keep Core registrations during rollback or recovery.
|
|
1457
1676
|
* @returns A promise that resolves when initialization finishes.
|
|
1458
1677
|
*/
|
|
1459
|
-
async #initWithoutDisconnectWait() {
|
|
1678
|
+
async #initWithoutDisconnectWait(preserveSubscriptions = false) {
|
|
1460
1679
|
if (!this.#handlersRegistered) {
|
|
1461
1680
|
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
1462
1681
|
this.#handlersRegistered = true;
|
|
@@ -1467,7 +1686,7 @@ export class PerpsController extends BaseController {
|
|
|
1467
1686
|
if (this.#initializationPromise) {
|
|
1468
1687
|
return this.#initializationPromise;
|
|
1469
1688
|
}
|
|
1470
|
-
this.#initializationPromise = this.#performInitialization();
|
|
1689
|
+
this.#initializationPromise = this.#performInitialization(preserveSubscriptions);
|
|
1471
1690
|
this.#initializationStartWaiters.forEach((notifyStarted) => notifyStarted());
|
|
1472
1691
|
return this.#initializationPromise;
|
|
1473
1692
|
}
|
|
@@ -1514,13 +1733,19 @@ export class PerpsController extends BaseController {
|
|
|
1514
1733
|
};
|
|
1515
1734
|
}
|
|
1516
1735
|
/**
|
|
1517
|
-
* Actual initialization implementation with retry logic
|
|
1736
|
+
* Actual initialization implementation with retry logic.
|
|
1737
|
+
*
|
|
1738
|
+
* @param preserveSubscriptions - Keep Core registrations for automatic rollback.
|
|
1518
1739
|
*/
|
|
1519
|
-
async #performInitialization() {
|
|
1740
|
+
async #performInitialization(preserveSubscriptions) {
|
|
1520
1741
|
const maxAttempts = 3;
|
|
1521
1742
|
const baseDelay = 1000;
|
|
1743
|
+
this.#detachProviderSubscriptions(!preserveSubscriptions);
|
|
1522
1744
|
this.update((state) => {
|
|
1523
1745
|
state.initializationState = InitializationState.Initializing;
|
|
1746
|
+
// The previous route is no longer authoritative during reconnection.
|
|
1747
|
+
// Implicit configurations use the selected destination until assignment.
|
|
1748
|
+
state.effectiveProvider = null;
|
|
1524
1749
|
state.initializationError = null;
|
|
1525
1750
|
state.initializationAttempts = 0;
|
|
1526
1751
|
});
|
|
@@ -1555,6 +1780,11 @@ export class PerpsController extends BaseController {
|
|
|
1555
1780
|
this.#lighterRegistrationPromise,
|
|
1556
1781
|
]);
|
|
1557
1782
|
this.#lighterRegistrationPromise = null;
|
|
1783
|
+
// Flags may have arrived after construction; re-run the idempotent
|
|
1784
|
+
// migration so the aggregated wrapper (when the flag is on) is built
|
|
1785
|
+
// from the migrated state. The migration skips an explicit provider
|
|
1786
|
+
// selection, so a direct switch survives this initialization.
|
|
1787
|
+
this.#migrateActiveProviderForMultiProviderIfNeeded();
|
|
1558
1788
|
this.#assignActiveProvider();
|
|
1559
1789
|
this.isInitialized = true;
|
|
1560
1790
|
this.update((state) => {
|
|
@@ -1583,6 +1813,9 @@ export class PerpsController extends BaseController {
|
|
|
1583
1813
|
.finally(() => {
|
|
1584
1814
|
this.#watchlistEditsDuringHydration.delete(editsDuringHydration);
|
|
1585
1815
|
});
|
|
1816
|
+
if (preserveSubscriptions) {
|
|
1817
|
+
this.#restoreProviderSubscriptions();
|
|
1818
|
+
}
|
|
1586
1819
|
return; // Exit retry loop on success
|
|
1587
1820
|
}
|
|
1588
1821
|
catch (error) {
|
|
@@ -1606,6 +1839,7 @@ export class PerpsController extends BaseController {
|
|
|
1606
1839
|
this.isInitialized = false;
|
|
1607
1840
|
this.update((state) => {
|
|
1608
1841
|
state.initializationState = InitializationState.Failed;
|
|
1842
|
+
state.effectiveProvider = null;
|
|
1609
1843
|
state.initializationError = lastError?.message ?? 'Unknown error';
|
|
1610
1844
|
});
|
|
1611
1845
|
this.#initializationPromise = null; // Clear promise to allow retry
|
|
@@ -1756,9 +1990,17 @@ export class PerpsController extends BaseController {
|
|
|
1756
1990
|
throw new Error('HyperLiquid provider not registered — cannot assign active provider');
|
|
1757
1991
|
}
|
|
1758
1992
|
if (activeProvider === 'aggregated') {
|
|
1993
|
+
// The persisted default venue routes writes that do not name one and
|
|
1994
|
+
// backs default-routed reads. Fall back to HyperLiquid in memory when
|
|
1995
|
+
// the saved default is not registered (for example Lighter failed to
|
|
1996
|
+
// load), but preserve the preference for a later successful initialization.
|
|
1997
|
+
const defaultProvider = isPerpsProviderType(this.state.defaultProvider) &&
|
|
1998
|
+
this.providers.has(this.state.defaultProvider)
|
|
1999
|
+
? this.state.defaultProvider
|
|
2000
|
+
: 'hyperliquid';
|
|
1759
2001
|
this.activeProviderInstance = new AggregatedPerpsProvider({
|
|
1760
2002
|
providers: this.providers,
|
|
1761
|
-
defaultProvider
|
|
2003
|
+
defaultProvider,
|
|
1762
2004
|
infrastructure: this.#options.infrastructure,
|
|
1763
2005
|
isTestnet: this.state.isTestnet,
|
|
1764
2006
|
});
|
|
@@ -1786,6 +2028,14 @@ export class PerpsController extends BaseController {
|
|
|
1786
2028
|
}
|
|
1787
2029
|
this.#debugLog(`PerpsController: Using direct provider (${this.activeProviderInstance === hyperLiquidProvider ? 'hyperliquid' : activeProvider})`);
|
|
1788
2030
|
}
|
|
2031
|
+
const effectiveProvider = this.activeProviderInstance instanceof AggregatedPerpsProvider
|
|
2032
|
+
? this.activeProviderInstance.getWriteProviderId()
|
|
2033
|
+
: this.state.activeProvider;
|
|
2034
|
+
this.update((state) => {
|
|
2035
|
+
state.effectiveProvider = isPerpsProviderType(effectiveProvider)
|
|
2036
|
+
? effectiveProvider
|
|
2037
|
+
: 'hyperliquid';
|
|
2038
|
+
});
|
|
1789
2039
|
}
|
|
1790
2040
|
/**
|
|
1791
2041
|
* Generate standard error context for Logger.error calls with searchable tags and context.
|
|
@@ -2204,6 +2454,52 @@ export class PerpsController extends BaseController {
|
|
|
2204
2454
|
!provider.routesOrdersByProviderId &&
|
|
2205
2455
|
providerId !== provider.protocolId);
|
|
2206
2456
|
}
|
|
2457
|
+
/**
|
|
2458
|
+
* Structured refusal for an aggregated-mode write that does not name a venue.
|
|
2459
|
+
*
|
|
2460
|
+
* When multiple venues are registered, a write without a `providerId` has
|
|
2461
|
+
* no unambiguous destination and is refused with `PROVIDER_ROUTE_REQUIRED`.
|
|
2462
|
+
* Direct modes and aggregated wrappers with one registered venue already
|
|
2463
|
+
* have exactly one destination, so their writes need no explicit route.
|
|
2464
|
+
*
|
|
2465
|
+
* Call it once before any expensive work (using the current state) and again
|
|
2466
|
+
* after the provider is resolved: a cold start can migrate direct state to
|
|
2467
|
+
* aggregated, so a write queued across that transition must be checked
|
|
2468
|
+
* against the provider it actually reaches.
|
|
2469
|
+
*
|
|
2470
|
+
* @param providerId - Explicit provider route, when supplied.
|
|
2471
|
+
* @param provider - Resolved provider, when initialization has settled.
|
|
2472
|
+
* @returns The refusal result, or undefined when the write may proceed.
|
|
2473
|
+
*/
|
|
2474
|
+
#getUnroutedAggregatedWriteRefusal(providerId, provider) {
|
|
2475
|
+
if (providerId !== undefined) {
|
|
2476
|
+
return undefined;
|
|
2477
|
+
}
|
|
2478
|
+
// Before initialization the actual membership is unknown. Defer to the
|
|
2479
|
+
// check after provider resolution rather than refusing a one-venue fallback.
|
|
2480
|
+
const resolvedProvider = provider ?? this.getActiveProviderOrNull();
|
|
2481
|
+
if (resolvedProvider?.protocolId !== 'aggregated') {
|
|
2482
|
+
return undefined;
|
|
2483
|
+
}
|
|
2484
|
+
if (resolvedProvider instanceof AggregatedPerpsProvider &&
|
|
2485
|
+
resolvedProvider.getProviderIds().length <= 1) {
|
|
2486
|
+
return undefined;
|
|
2487
|
+
}
|
|
2488
|
+
return { success: false, error: PERPS_ERROR_CODES.PROVIDER_ROUTE_REQUIRED };
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* Structured refusal for an aggregated-mode batch write.
|
|
2492
|
+
*
|
|
2493
|
+
* Batch cancel and close cannot name a venue, so while multiple venues are
|
|
2494
|
+
* registered they are refused instead of being sent to the default venue.
|
|
2495
|
+
*
|
|
2496
|
+
* @param provider - Resolved provider, when initialization has settled.
|
|
2497
|
+
* @returns The batch refusal result, or undefined when the batch may proceed.
|
|
2498
|
+
*/
|
|
2499
|
+
#getUnroutedAggregatedBatchRefusal(provider) {
|
|
2500
|
+
const refusal = this.#getUnroutedAggregatedWriteRefusal(undefined, provider);
|
|
2501
|
+
return (refusal && { ...refusal, successCount: 0, failureCount: 0, results: [] });
|
|
2502
|
+
}
|
|
2207
2503
|
/**
|
|
2208
2504
|
* Resolve one routed order operation after any in-flight initialization.
|
|
2209
2505
|
*
|
|
@@ -2230,6 +2526,10 @@ export class PerpsController extends BaseController {
|
|
|
2230
2526
|
* @returns The order result with order ID and status.
|
|
2231
2527
|
*/
|
|
2232
2528
|
async placeOrder(params) {
|
|
2529
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2530
|
+
if (unroutedRefusal) {
|
|
2531
|
+
return unroutedRefusal;
|
|
2532
|
+
}
|
|
2233
2533
|
let capturedParams;
|
|
2234
2534
|
try {
|
|
2235
2535
|
capturedParams = captureScaleOrderParams(params);
|
|
@@ -2245,17 +2545,21 @@ export class PerpsController extends BaseController {
|
|
|
2245
2545
|
orderType: capturedParams.orderType,
|
|
2246
2546
|
providerId: capturedParams.providerId,
|
|
2247
2547
|
});
|
|
2548
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(capturedParams.providerId, provider);
|
|
2549
|
+
if (resolvedRefusal) {
|
|
2550
|
+
return resolvedRefusal;
|
|
2551
|
+
}
|
|
2248
2552
|
this.#ensureTradingServiceDeps();
|
|
2249
2553
|
const result = await this.#tradingService.placeOrder({
|
|
2250
2554
|
provider,
|
|
2251
2555
|
params: capturedParams,
|
|
2252
2556
|
context: this.#createServiceContext('placeOrder', {
|
|
2253
|
-
saveTradeConfiguration: (symbol, leverage) => this.saveTradeConfiguration(symbol, leverage),
|
|
2557
|
+
saveTradeConfiguration: (symbol, leverage, providerId) => this.saveTradeConfiguration(symbol, leverage, providerId),
|
|
2254
2558
|
}),
|
|
2255
2559
|
reportOrderToDataLake: (dataLakeParams) => this.reportOrderToDataLake(dataLakeParams),
|
|
2256
2560
|
});
|
|
2257
2561
|
if (result.success) {
|
|
2258
|
-
this.clearPendingTradeConfiguration(capturedParams.symbol);
|
|
2562
|
+
this.clearPendingTradeConfiguration(capturedParams.symbol, capturedParams.providerId);
|
|
2259
2563
|
}
|
|
2260
2564
|
return result;
|
|
2261
2565
|
}
|
|
@@ -2273,10 +2577,18 @@ export class PerpsController extends BaseController {
|
|
|
2273
2577
|
error: PERPS_ERROR_CODES.ORDER_EDIT_STRATEGY_UNSUPPORTED,
|
|
2274
2578
|
};
|
|
2275
2579
|
}
|
|
2580
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.newOrder.providerId);
|
|
2581
|
+
if (unroutedRefusal) {
|
|
2582
|
+
return unroutedRefusal;
|
|
2583
|
+
}
|
|
2276
2584
|
const provider = await this.#resolveRoutedOrderProvider({
|
|
2277
2585
|
orderType: params.newOrder.orderType,
|
|
2278
2586
|
providerId: params.newOrder.providerId,
|
|
2279
2587
|
});
|
|
2588
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.newOrder.providerId, provider);
|
|
2589
|
+
if (resolvedRefusal) {
|
|
2590
|
+
return resolvedRefusal;
|
|
2591
|
+
}
|
|
2280
2592
|
this.#ensureTradingServiceDeps();
|
|
2281
2593
|
return this.#tradingService.editOrder({
|
|
2282
2594
|
provider,
|
|
@@ -2291,10 +2603,18 @@ export class PerpsController extends BaseController {
|
|
|
2291
2603
|
* @returns The cancellation result with status.
|
|
2292
2604
|
*/
|
|
2293
2605
|
async cancelOrder(params) {
|
|
2606
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2607
|
+
if (unroutedRefusal) {
|
|
2608
|
+
return unroutedRefusal;
|
|
2609
|
+
}
|
|
2294
2610
|
const provider = await this.#resolveRoutedOrderProvider({
|
|
2295
2611
|
orderType: params.orderType,
|
|
2296
2612
|
providerId: params.providerId,
|
|
2297
2613
|
});
|
|
2614
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
2615
|
+
if (resolvedRefusal) {
|
|
2616
|
+
return resolvedRefusal;
|
|
2617
|
+
}
|
|
2298
2618
|
return this.#tradingService.cancelOrder({
|
|
2299
2619
|
provider,
|
|
2300
2620
|
params,
|
|
@@ -2464,7 +2784,15 @@ export class PerpsController extends BaseController {
|
|
|
2464
2784
|
* @returns The batch cancellation results for each order.
|
|
2465
2785
|
*/
|
|
2466
2786
|
async cancelOrders(params) {
|
|
2787
|
+
const unroutedRefusal = this.#getUnroutedAggregatedBatchRefusal();
|
|
2788
|
+
if (unroutedRefusal) {
|
|
2789
|
+
return unroutedRefusal;
|
|
2790
|
+
}
|
|
2467
2791
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2792
|
+
const resolvedRefusal = this.#getUnroutedAggregatedBatchRefusal(provider);
|
|
2793
|
+
if (resolvedRefusal) {
|
|
2794
|
+
return resolvedRefusal;
|
|
2795
|
+
}
|
|
2468
2796
|
return this.#tradingService.cancelOrders({
|
|
2469
2797
|
provider,
|
|
2470
2798
|
params,
|
|
@@ -2482,10 +2810,18 @@ export class PerpsController extends BaseController {
|
|
|
2482
2810
|
* @returns The order result from the close position request.
|
|
2483
2811
|
*/
|
|
2484
2812
|
async closePosition(params) {
|
|
2813
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2814
|
+
if (unroutedRefusal) {
|
|
2815
|
+
return unroutedRefusal;
|
|
2816
|
+
}
|
|
2485
2817
|
const provider = await this.#resolveRoutedOrderProvider({
|
|
2486
2818
|
orderType: params.orderType,
|
|
2487
2819
|
providerId: params.providerId,
|
|
2488
2820
|
});
|
|
2821
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
2822
|
+
if (resolvedRefusal) {
|
|
2823
|
+
return resolvedRefusal;
|
|
2824
|
+
}
|
|
2489
2825
|
this.#ensureTradingServiceDeps();
|
|
2490
2826
|
return this.#tradingService.closePosition({
|
|
2491
2827
|
provider,
|
|
@@ -2504,7 +2840,15 @@ export class PerpsController extends BaseController {
|
|
|
2504
2840
|
* @returns The batch close results for each position.
|
|
2505
2841
|
*/
|
|
2506
2842
|
async closePositions(params) {
|
|
2843
|
+
const unroutedRefusal = this.#getUnroutedAggregatedBatchRefusal();
|
|
2844
|
+
if (unroutedRefusal) {
|
|
2845
|
+
return unroutedRefusal;
|
|
2846
|
+
}
|
|
2507
2847
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2848
|
+
const resolvedRefusal = this.#getUnroutedAggregatedBatchRefusal(provider);
|
|
2849
|
+
if (resolvedRefusal) {
|
|
2850
|
+
return resolvedRefusal;
|
|
2851
|
+
}
|
|
2508
2852
|
this.#ensureTradingServiceDeps();
|
|
2509
2853
|
return this.#tradingService.closePositions({
|
|
2510
2854
|
provider,
|
|
@@ -2521,10 +2865,18 @@ export class PerpsController extends BaseController {
|
|
|
2521
2865
|
* @returns The order result from the TP/SL update.
|
|
2522
2866
|
*/
|
|
2523
2867
|
async updatePositionTPSL(params) {
|
|
2868
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2869
|
+
if (unroutedRefusal) {
|
|
2870
|
+
return unroutedRefusal;
|
|
2871
|
+
}
|
|
2524
2872
|
const provider = await this.#resolveRoutedOrderProvider({
|
|
2525
2873
|
orderType: undefined,
|
|
2526
2874
|
providerId: params.providerId,
|
|
2527
2875
|
});
|
|
2876
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
2877
|
+
if (resolvedRefusal) {
|
|
2878
|
+
return resolvedRefusal;
|
|
2879
|
+
}
|
|
2528
2880
|
this.#ensureTradingServiceDeps();
|
|
2529
2881
|
return this.#tradingService.updatePositionTPSL({
|
|
2530
2882
|
provider,
|
|
@@ -2542,10 +2894,18 @@ export class PerpsController extends BaseController {
|
|
|
2542
2894
|
* @returns The order result from the leg replacement.
|
|
2543
2895
|
*/
|
|
2544
2896
|
async replacePositionTPSLLeg(params) {
|
|
2897
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2898
|
+
if (unroutedRefusal) {
|
|
2899
|
+
return unroutedRefusal;
|
|
2900
|
+
}
|
|
2545
2901
|
const provider = await this.#resolveRoutedOrderProvider({
|
|
2546
2902
|
orderType: undefined,
|
|
2547
2903
|
providerId: params.providerId,
|
|
2548
2904
|
});
|
|
2905
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
2906
|
+
if (resolvedRefusal) {
|
|
2907
|
+
return resolvedRefusal;
|
|
2908
|
+
}
|
|
2549
2909
|
this.#ensureTradingServiceDeps();
|
|
2550
2910
|
// A market leg uses the caller's tolerance, else the saved preference.
|
|
2551
2911
|
const maxSlippageBps = params.maxSlippageBps ?? this.state.maxSlippageBps;
|
|
@@ -2562,12 +2922,21 @@ export class PerpsController extends BaseController {
|
|
|
2562
2922
|
* @returns The margin update result.
|
|
2563
2923
|
*/
|
|
2564
2924
|
async updateMargin(params) {
|
|
2925
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
2926
|
+
if (unroutedRefusal) {
|
|
2927
|
+
return unroutedRefusal;
|
|
2928
|
+
}
|
|
2565
2929
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2930
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
2931
|
+
if (resolvedRefusal) {
|
|
2932
|
+
return resolvedRefusal;
|
|
2933
|
+
}
|
|
2566
2934
|
this.#ensureTradingServiceDeps();
|
|
2567
2935
|
return this.#tradingService.updateMargin({
|
|
2568
2936
|
provider,
|
|
2569
2937
|
symbol: params.symbol,
|
|
2570
2938
|
amount: params.amount,
|
|
2939
|
+
providerId: params.providerId,
|
|
2571
2940
|
context: this.#createServiceContext('updateMargin'),
|
|
2572
2941
|
});
|
|
2573
2942
|
}
|
|
@@ -2578,7 +2947,17 @@ export class PerpsController extends BaseController {
|
|
|
2578
2947
|
* @returns The order result from the position flip.
|
|
2579
2948
|
*/
|
|
2580
2949
|
async flipPosition(params) {
|
|
2950
|
+
// The flip is executed as a placement against the position's venue, so the
|
|
2951
|
+
// position must carry one in aggregated mode.
|
|
2952
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.position.providerId);
|
|
2953
|
+
if (unroutedRefusal) {
|
|
2954
|
+
return unroutedRefusal;
|
|
2955
|
+
}
|
|
2581
2956
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2957
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.position.providerId, provider);
|
|
2958
|
+
if (resolvedRefusal) {
|
|
2959
|
+
return resolvedRefusal;
|
|
2960
|
+
}
|
|
2582
2961
|
this.#ensureTradingServiceDeps();
|
|
2583
2962
|
return this.#tradingService.flipPosition({
|
|
2584
2963
|
provider,
|
|
@@ -3016,7 +3395,15 @@ export class PerpsController extends BaseController {
|
|
|
3016
3395
|
* @returns WithdrawResult with withdrawal ID and tracking info
|
|
3017
3396
|
*/
|
|
3018
3397
|
async withdraw(params) {
|
|
3398
|
+
const unroutedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId);
|
|
3399
|
+
if (unroutedRefusal) {
|
|
3400
|
+
return unroutedRefusal;
|
|
3401
|
+
}
|
|
3019
3402
|
const provider = await this.#getActiveProviderWhenReady();
|
|
3403
|
+
const resolvedRefusal = this.#getUnroutedAggregatedWriteRefusal(params.providerId, provider);
|
|
3404
|
+
if (resolvedRefusal) {
|
|
3405
|
+
return resolvedRefusal;
|
|
3406
|
+
}
|
|
3020
3407
|
return this.#accountService.withdraw({
|
|
3021
3408
|
provider,
|
|
3022
3409
|
params,
|
|
@@ -3464,7 +3851,18 @@ export class PerpsController extends BaseController {
|
|
|
3464
3851
|
return this.#marketDataService.getAccountState({
|
|
3465
3852
|
provider,
|
|
3466
3853
|
params,
|
|
3467
|
-
context: this.#createServiceContext('getAccountState'
|
|
3854
|
+
context: this.#createServiceContext('getAccountState', {
|
|
3855
|
+
accountDataContext: {
|
|
3856
|
+
// Match the live account venue, including a temporary fallback when
|
|
3857
|
+
// the saved default is unavailable. Read the route when the response
|
|
3858
|
+
// arrives to reject balances from a previous venue.
|
|
3859
|
+
isCurrent: (accountState) => accountState.providerId === undefined ||
|
|
3860
|
+
accountState.providerId ===
|
|
3861
|
+
(this.activeProviderInstance instanceof AggregatedPerpsProvider
|
|
3862
|
+
? this.activeProviderInstance.getWriteProviderId()
|
|
3863
|
+
: this.state.activeProvider),
|
|
3864
|
+
},
|
|
3865
|
+
}),
|
|
3468
3866
|
});
|
|
3469
3867
|
}
|
|
3470
3868
|
/**
|
|
@@ -4498,6 +4896,7 @@ export class PerpsController extends BaseController {
|
|
|
4498
4896
|
const previousNetwork = previousIsTestnet ? 'testnet' : 'mainnet';
|
|
4499
4897
|
this.update((state) => {
|
|
4500
4898
|
state.isTestnet = !state.isTestnet;
|
|
4899
|
+
state.effectiveProvider = null;
|
|
4501
4900
|
});
|
|
4502
4901
|
const newNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
4503
4902
|
this.#debugLog('PerpsController: Network toggle initiated', {
|
|
@@ -4526,6 +4925,7 @@ export class PerpsController extends BaseController {
|
|
|
4526
4925
|
// Rollback isTestnet to previous value
|
|
4527
4926
|
this.update((state) => {
|
|
4528
4927
|
state.isTestnet = previousIsTestnet;
|
|
4928
|
+
state.effectiveProvider = null;
|
|
4529
4929
|
});
|
|
4530
4930
|
return {
|
|
4531
4931
|
success: false,
|
|
@@ -4571,6 +4971,7 @@ export class PerpsController extends BaseController {
|
|
|
4571
4971
|
}
|
|
4572
4972
|
const completeReinitialization = this.#beginReinitialization();
|
|
4573
4973
|
let previousProvider = this.state.activeProvider;
|
|
4974
|
+
const previousSelectionExplicit = this.state.hasExplicitProviderSelection;
|
|
4574
4975
|
try {
|
|
4575
4976
|
const pendingInitialization = this.#initializationPromise;
|
|
4576
4977
|
if (pendingInitialization) {
|
|
@@ -4594,12 +4995,22 @@ export class PerpsController extends BaseController {
|
|
|
4594
4995
|
// use the state this switch is actually replacing.
|
|
4595
4996
|
previousProvider = this.state.activeProvider;
|
|
4596
4997
|
if (previousProvider === providerId) {
|
|
4998
|
+
// Selecting the current direct venue is still an explicit choice, so
|
|
4999
|
+
// record it even though no reinitialization is needed.
|
|
5000
|
+
if (providerId !== 'aggregated' &&
|
|
5001
|
+
!this.state.hasExplicitProviderSelection) {
|
|
5002
|
+
this.update((state) => {
|
|
5003
|
+
state.hasExplicitProviderSelection = true;
|
|
5004
|
+
});
|
|
5005
|
+
}
|
|
4597
5006
|
return { success: true, providerId };
|
|
4598
5007
|
}
|
|
4599
5008
|
// Validate provider only after a pending initialization has rebuilt the
|
|
4600
5009
|
// registry. Otherwise a switch queued behind disconnect can observe the
|
|
4601
5010
|
// intentionally empty teardown state.
|
|
4602
|
-
const isValidProvider = providerId === 'aggregated'
|
|
5011
|
+
const isValidProvider = providerId === 'aggregated'
|
|
5012
|
+
? this.#getMultiProviderModeEnabled() !== false
|
|
5013
|
+
: this.providers.has(providerId);
|
|
4603
5014
|
if (!isValidProvider) {
|
|
4604
5015
|
return {
|
|
4605
5016
|
success: false,
|
|
@@ -4620,6 +5031,11 @@ export class PerpsController extends BaseController {
|
|
|
4620
5031
|
// Update state with new provider (market data cache preserved per-provider)
|
|
4621
5032
|
this.update((state) => {
|
|
4622
5033
|
state.activeProvider = providerId;
|
|
5034
|
+
// Publish the new selection and invalidate its old live route together.
|
|
5035
|
+
state.effectiveProvider = null;
|
|
5036
|
+
// Record whether this is an explicit direct selection so a later
|
|
5037
|
+
// network toggle or disconnect/init does not migrate it away.
|
|
5038
|
+
state.hasExplicitProviderSelection = providerId !== 'aggregated';
|
|
4623
5039
|
state.accountState = null;
|
|
4624
5040
|
state.initializationState = InitializationState.Uninitialized;
|
|
4625
5041
|
});
|
|
@@ -4632,6 +5048,16 @@ export class PerpsController extends BaseController {
|
|
|
4632
5048
|
if (this.state.initializationState === InitializationState.Failed) {
|
|
4633
5049
|
throw new Error(this.state.initializationError ?? 'Provider initialization failed');
|
|
4634
5050
|
}
|
|
5051
|
+
// The kill switch may have restored a direct mode while initialization
|
|
5052
|
+
// was pending. Do not report the requested aggregated mode as active.
|
|
5053
|
+
if (providerId === 'aggregated' &&
|
|
5054
|
+
this.state.activeProvider !== 'aggregated') {
|
|
5055
|
+
return {
|
|
5056
|
+
success: false,
|
|
5057
|
+
providerId: this.state.activeProvider,
|
|
5058
|
+
error: 'Provider aggregated not available',
|
|
5059
|
+
};
|
|
5060
|
+
}
|
|
4635
5061
|
this.#debugLog('PerpsController: Provider switch completed', {
|
|
4636
5062
|
providerId,
|
|
4637
5063
|
timestamp: new Date().toISOString(),
|
|
@@ -4642,6 +5068,8 @@ export class PerpsController extends BaseController {
|
|
|
4642
5068
|
// Rollback state to previous provider
|
|
4643
5069
|
this.update((state) => {
|
|
4644
5070
|
state.activeProvider = previousProvider;
|
|
5071
|
+
state.effectiveProvider = null;
|
|
5072
|
+
state.hasExplicitProviderSelection = previousSelectionExplicit;
|
|
4645
5073
|
});
|
|
4646
5074
|
this.#logError(ensureError(error, 'PerpsController.switchProvider'), this.#getErrorContext('switchProvider', { providerId }, CONNECTION_ERROR_TAGS));
|
|
4647
5075
|
// Attempt to reinitialize the previous provider via init(),
|
|
@@ -4685,6 +5113,70 @@ export class PerpsController extends BaseController {
|
|
|
4685
5113
|
}
|
|
4686
5114
|
}
|
|
4687
5115
|
}
|
|
5116
|
+
/**
|
|
5117
|
+
* Set the default provider used by aggregated-mode routing.
|
|
5118
|
+
*
|
|
5119
|
+
* Persists the choice and, when the active provider is the aggregated
|
|
5120
|
+
* wrapper, updates its routing default in place. Unlike `switchProvider`
|
|
5121
|
+
* this never re-initializes the controller or reconnects provider transports:
|
|
5122
|
+
* default-routed streams move, but both venues stay connected and per-venue
|
|
5123
|
+
* writes are unaffected.
|
|
5124
|
+
*
|
|
5125
|
+
* @param providerId - The provider to use as the aggregated default.
|
|
5126
|
+
* @returns The result with the new default provider.
|
|
5127
|
+
*/
|
|
5128
|
+
setDefaultProvider(providerId) {
|
|
5129
|
+
// Runtime hardening for JS callers: the value reaches persisted state and
|
|
5130
|
+
// the provider registry, so it must be a known direct venue.
|
|
5131
|
+
if (!isPerpsProviderType(providerId)) {
|
|
5132
|
+
return {
|
|
5133
|
+
success: false,
|
|
5134
|
+
defaultProvider: this.state.defaultProvider,
|
|
5135
|
+
error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,
|
|
5136
|
+
};
|
|
5137
|
+
}
|
|
5138
|
+
// Before initialization the provider registry is empty; accept the
|
|
5139
|
+
// choice so it is persisted and used once providers are created.
|
|
5140
|
+
if (this.providers.size > 0 && !this.providers.has(providerId)) {
|
|
5141
|
+
return {
|
|
5142
|
+
success: false,
|
|
5143
|
+
defaultProvider: this.state.defaultProvider,
|
|
5144
|
+
error: PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE,
|
|
5145
|
+
};
|
|
5146
|
+
}
|
|
5147
|
+
// During reinitialization the instance may still be the previous wrapper.
|
|
5148
|
+
// Persist the preference, but let provider assignment publish the new route.
|
|
5149
|
+
const aggregatedProvider = this.state.activeProvider === 'aggregated' &&
|
|
5150
|
+
this.state.effectiveProvider !== null &&
|
|
5151
|
+
this.activeProviderInstance instanceof AggregatedPerpsProvider
|
|
5152
|
+
? this.activeProviderInstance
|
|
5153
|
+
: null;
|
|
5154
|
+
const defaultChanged = (aggregatedProvider?.getWriteProviderId() ??
|
|
5155
|
+
this.state.defaultProvider) !== providerId;
|
|
5156
|
+
this.update((state) => {
|
|
5157
|
+
state.defaultProvider = providerId;
|
|
5158
|
+
state.hasExplicitDefaultProviderSelection = true;
|
|
5159
|
+
if (aggregatedProvider) {
|
|
5160
|
+
state.effectiveProvider = providerId;
|
|
5161
|
+
}
|
|
5162
|
+
// The cached snapshot came from the previous default venue's stream, so
|
|
5163
|
+
// drop it until the new venue delivers matching data.
|
|
5164
|
+
if (defaultChanged && aggregatedProvider) {
|
|
5165
|
+
state.accountState = null;
|
|
5166
|
+
}
|
|
5167
|
+
});
|
|
5168
|
+
// Keep the live aggregated wrapper's routing in sync without any
|
|
5169
|
+
// re-initialization or reconnection. Default-routed streams move to the
|
|
5170
|
+
// new venue with it.
|
|
5171
|
+
if (aggregatedProvider) {
|
|
5172
|
+
aggregatedProvider.setDefaultProvider(providerId);
|
|
5173
|
+
}
|
|
5174
|
+
this.#debugLog('PerpsController: Default provider updated', {
|
|
5175
|
+
defaultProvider: providerId,
|
|
5176
|
+
activeProvider: this.state.activeProvider,
|
|
5177
|
+
});
|
|
5178
|
+
return { success: true, defaultProvider: providerId };
|
|
5179
|
+
}
|
|
4688
5180
|
/**
|
|
4689
5181
|
* Get current network (mainnet/testnet)
|
|
4690
5182
|
*
|
|
@@ -4734,7 +5226,14 @@ export class PerpsController extends BaseController {
|
|
|
4734
5226
|
try {
|
|
4735
5227
|
const provider = this.getActiveProvider();
|
|
4736
5228
|
if (provider.subscribeToConnectionState) {
|
|
4737
|
-
return provider
|
|
5229
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => {
|
|
5230
|
+
if (nextProvider.subscribeToConnectionState) {
|
|
5231
|
+
return nextProvider.subscribeToConnectionState(listener);
|
|
5232
|
+
}
|
|
5233
|
+
listener(nextProvider.getWebSocketConnectionState?.() ??
|
|
5234
|
+
WebSocketConnectionState.Disconnected, 0);
|
|
5235
|
+
return () => undefined;
|
|
5236
|
+
});
|
|
4738
5237
|
}
|
|
4739
5238
|
// Fallback: immediately call with current state and return no-op unsubscribe
|
|
4740
5239
|
listener(this.getWebSocketConnectionState(), 0);
|
|
@@ -4773,6 +5272,98 @@ export class PerpsController extends BaseController {
|
|
|
4773
5272
|
}, CONNECTION_ERROR_TAGS));
|
|
4774
5273
|
}
|
|
4775
5274
|
}
|
|
5275
|
+
/**
|
|
5276
|
+
* Remember aggregated-session subscriptions for automatic rollback only.
|
|
5277
|
+
* Direct-session and caller-driven reconnect semantics remain unchanged.
|
|
5278
|
+
*
|
|
5279
|
+
* @param provider - Initially active provider.
|
|
5280
|
+
* @param open - Opens this subscription on a provider.
|
|
5281
|
+
* @param onInvalidate - Invalidates a cached value while the route is detached.
|
|
5282
|
+
* @returns Cleanup that always removes the current binding.
|
|
5283
|
+
*/
|
|
5284
|
+
#trackProviderSubscription(provider, open, onInvalidate) {
|
|
5285
|
+
if (provider.protocolId !== 'aggregated') {
|
|
5286
|
+
return open(provider);
|
|
5287
|
+
}
|
|
5288
|
+
const subscription = {
|
|
5289
|
+
open,
|
|
5290
|
+
unsubscribe: open(provider),
|
|
5291
|
+
onInvalidate,
|
|
5292
|
+
};
|
|
5293
|
+
this.#providerSubscriptions.add(subscription);
|
|
5294
|
+
return () => {
|
|
5295
|
+
if (!this.#providerSubscriptions.delete(subscription)) {
|
|
5296
|
+
return;
|
|
5297
|
+
}
|
|
5298
|
+
const { unsubscribe } = subscription;
|
|
5299
|
+
subscription.unsubscribe = () => undefined;
|
|
5300
|
+
unsubscribe();
|
|
5301
|
+
};
|
|
5302
|
+
}
|
|
5303
|
+
/**
|
|
5304
|
+
* Detach registrations before their providers are disconnected.
|
|
5305
|
+
*
|
|
5306
|
+
* @param discard - Drop registrations for a caller-initiated lifecycle change.
|
|
5307
|
+
*/
|
|
5308
|
+
#detachProviderSubscriptions(discard) {
|
|
5309
|
+
const subscriptions = [...this.#providerSubscriptions];
|
|
5310
|
+
this.#hasPendingSubscriptionRecovery = !discard;
|
|
5311
|
+
if (discard) {
|
|
5312
|
+
this.#providerSubscriptions.clear();
|
|
5313
|
+
}
|
|
5314
|
+
for (const subscription of subscriptions) {
|
|
5315
|
+
const { unsubscribe } = subscription;
|
|
5316
|
+
subscription.unsubscribe = () => undefined;
|
|
5317
|
+
try {
|
|
5318
|
+
unsubscribe();
|
|
5319
|
+
}
|
|
5320
|
+
catch (error) {
|
|
5321
|
+
this.#logProviderSubscriptionError(error);
|
|
5322
|
+
}
|
|
5323
|
+
if (!discard && this.#providerSubscriptions.has(subscription)) {
|
|
5324
|
+
try {
|
|
5325
|
+
subscription.onInvalidate?.();
|
|
5326
|
+
}
|
|
5327
|
+
catch (error) {
|
|
5328
|
+
this.#logProviderSubscriptionError(error);
|
|
5329
|
+
}
|
|
5330
|
+
}
|
|
5331
|
+
}
|
|
5332
|
+
}
|
|
5333
|
+
/** Reattach surviving registrations after rollback or a later recovery. */
|
|
5334
|
+
#restoreProviderSubscriptions() {
|
|
5335
|
+
const provider = this.activeProviderInstance;
|
|
5336
|
+
if (!this.isInitialized || !provider) {
|
|
5337
|
+
return;
|
|
5338
|
+
}
|
|
5339
|
+
this.#hasPendingSubscriptionRecovery = false;
|
|
5340
|
+
for (const subscription of [...this.#providerSubscriptions]) {
|
|
5341
|
+
if (!this.#providerSubscriptions.has(subscription)) {
|
|
5342
|
+
continue;
|
|
5343
|
+
}
|
|
5344
|
+
try {
|
|
5345
|
+
const unsubscribe = subscription.open(provider);
|
|
5346
|
+
// A synchronous first update may cause the caller to unsubscribe.
|
|
5347
|
+
if (this.#providerSubscriptions.has(subscription)) {
|
|
5348
|
+
subscription.unsubscribe = unsubscribe;
|
|
5349
|
+
}
|
|
5350
|
+
else {
|
|
5351
|
+
unsubscribe();
|
|
5352
|
+
}
|
|
5353
|
+
}
|
|
5354
|
+
catch (error) {
|
|
5355
|
+
this.#logProviderSubscriptionError(error);
|
|
5356
|
+
}
|
|
5357
|
+
}
|
|
5358
|
+
}
|
|
5359
|
+
/**
|
|
5360
|
+
* Isolate subscription failures so other consumers can still recover.
|
|
5361
|
+
*
|
|
5362
|
+
* @param error - Subscription cleanup, invalidation or restoration failure.
|
|
5363
|
+
*/
|
|
5364
|
+
#logProviderSubscriptionError(error) {
|
|
5365
|
+
this.#logError(ensureError(error, 'PerpsController.providerSubscriptionRollback'), this.#getErrorContext('providerSubscriptionRollback'));
|
|
5366
|
+
}
|
|
4776
5367
|
// Live data delegation (NO Redux) - delegates to active provider
|
|
4777
5368
|
/**
|
|
4778
5369
|
* Subscribe to live price updates
|
|
@@ -4788,7 +5379,7 @@ export class PerpsController extends BaseController {
|
|
|
4788
5379
|
};
|
|
4789
5380
|
}
|
|
4790
5381
|
try {
|
|
4791
|
-
return provider.subscribeToPrices(params);
|
|
5382
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToPrices(params));
|
|
4792
5383
|
}
|
|
4793
5384
|
catch (error) {
|
|
4794
5385
|
this.#logError(ensureError(error, 'PerpsController.subscribeToPrices'), this.#getErrorContext('subscribeToPrices', {
|
|
@@ -4813,7 +5404,7 @@ export class PerpsController extends BaseController {
|
|
|
4813
5404
|
};
|
|
4814
5405
|
}
|
|
4815
5406
|
try {
|
|
4816
|
-
return provider.subscribeToPositions(params);
|
|
5407
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToPositions(params));
|
|
4817
5408
|
}
|
|
4818
5409
|
catch (error) {
|
|
4819
5410
|
this.#logError(ensureError(error, 'PerpsController.subscribeToPositions'), this.#getErrorContext('subscribeToPositions', {
|
|
@@ -4838,7 +5429,7 @@ export class PerpsController extends BaseController {
|
|
|
4838
5429
|
};
|
|
4839
5430
|
}
|
|
4840
5431
|
try {
|
|
4841
|
-
return provider.subscribeToOrderFills(params);
|
|
5432
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrderFills(params));
|
|
4842
5433
|
}
|
|
4843
5434
|
catch (error) {
|
|
4844
5435
|
this.#logError(ensureError(error, 'PerpsController.subscribeToOrderFills'), this.#getErrorContext('subscribeToOrderFills', {
|
|
@@ -4867,7 +5458,7 @@ export class PerpsController extends BaseController {
|
|
|
4867
5458
|
};
|
|
4868
5459
|
}
|
|
4869
5460
|
try {
|
|
4870
|
-
return provider.subscribeToTwapOrders(params);
|
|
5461
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToTwapOrders?.(params) ?? (() => undefined), () => params.callback([], true));
|
|
4871
5462
|
}
|
|
4872
5463
|
catch (error) {
|
|
4873
5464
|
this.#logError(ensureError(error, 'PerpsController.subscribeToTwapOrders'), this.#getErrorContext('subscribeToTwapOrders', {
|
|
@@ -4892,7 +5483,7 @@ export class PerpsController extends BaseController {
|
|
|
4892
5483
|
};
|
|
4893
5484
|
}
|
|
4894
5485
|
try {
|
|
4895
|
-
return provider.subscribeToOrders(params);
|
|
5486
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrders(params));
|
|
4896
5487
|
}
|
|
4897
5488
|
catch (error) {
|
|
4898
5489
|
this.#logError(ensureError(error, 'PerpsController.subscribeToOrders'), this.#getErrorContext('subscribeToOrders', {
|
|
@@ -4920,7 +5511,7 @@ export class PerpsController extends BaseController {
|
|
|
4920
5511
|
}
|
|
4921
5512
|
try {
|
|
4922
5513
|
const originalCallback = params.callback;
|
|
4923
|
-
return provider.subscribeToAccount({
|
|
5514
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToAccount({
|
|
4924
5515
|
...params,
|
|
4925
5516
|
callback: (account) => {
|
|
4926
5517
|
if (account) {
|
|
@@ -4932,7 +5523,7 @@ export class PerpsController extends BaseController {
|
|
|
4932
5523
|
}
|
|
4933
5524
|
originalCallback(account);
|
|
4934
5525
|
},
|
|
4935
|
-
});
|
|
5526
|
+
}), () => originalCallback(null));
|
|
4936
5527
|
}
|
|
4937
5528
|
catch (error) {
|
|
4938
5529
|
this.#logError(ensureError(error, 'PerpsController.subscribeToAccount'), this.#getErrorContext('subscribeToAccount', {
|
|
@@ -4958,7 +5549,7 @@ export class PerpsController extends BaseController {
|
|
|
4958
5549
|
};
|
|
4959
5550
|
}
|
|
4960
5551
|
try {
|
|
4961
|
-
return provider.subscribeToOrderBook(params);
|
|
5552
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOrderBook(params));
|
|
4962
5553
|
}
|
|
4963
5554
|
catch (error) {
|
|
4964
5555
|
this.#logError(ensureError(error, 'PerpsController.subscribeToOrderBook'), this.#getErrorContext('subscribeToOrderBook', {
|
|
@@ -4994,7 +5585,10 @@ export class PerpsController extends BaseController {
|
|
|
4994
5585
|
return noop;
|
|
4995
5586
|
}
|
|
4996
5587
|
try {
|
|
4997
|
-
return provider
|
|
5588
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => this.#hasConflictingProviderRoute(params.providerId, nextProvider)
|
|
5589
|
+
? () => undefined
|
|
5590
|
+
: (nextProvider.subscribeToAvailableToTrade?.(params) ??
|
|
5591
|
+
(() => undefined)), () => params.onError?.(new Error('Available-to-trade provider replaced')));
|
|
4998
5592
|
}
|
|
4999
5593
|
catch (error) {
|
|
5000
5594
|
this.#logError(ensureError(error, 'PerpsController.subscribeToAvailableToTrade'), this.#getErrorContext('subscribeToAvailableToTrade', { symbol: params.symbol, providerId: params.providerId }, CONNECTION_ERROR_TAGS));
|
|
@@ -5015,7 +5609,7 @@ export class PerpsController extends BaseController {
|
|
|
5015
5609
|
};
|
|
5016
5610
|
}
|
|
5017
5611
|
try {
|
|
5018
|
-
return provider.subscribeToCandles(params);
|
|
5612
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToCandles(params));
|
|
5019
5613
|
}
|
|
5020
5614
|
catch (error) {
|
|
5021
5615
|
this.#logError(ensureError(error, 'PerpsController.subscribeToCandles'), this.#getErrorContext('subscribeToCandles', {
|
|
@@ -5043,7 +5637,7 @@ export class PerpsController extends BaseController {
|
|
|
5043
5637
|
};
|
|
5044
5638
|
}
|
|
5045
5639
|
try {
|
|
5046
|
-
return provider.subscribeToOICaps(params);
|
|
5640
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => nextProvider.subscribeToOICaps(params));
|
|
5047
5641
|
}
|
|
5048
5642
|
catch (error) {
|
|
5049
5643
|
this.#logError(ensureError(error, 'PerpsController.subscribeToOICaps'), this.#getErrorContext('subscribeToOICaps', {
|
|
@@ -5297,6 +5891,7 @@ export class PerpsController extends BaseController {
|
|
|
5297
5891
|
* @returns A promise that resolves when teardown finishes.
|
|
5298
5892
|
*/
|
|
5299
5893
|
async #performDisconnect() {
|
|
5894
|
+
this.#detachProviderSubscriptions(true);
|
|
5300
5895
|
this.#lifecycleGeneration += 1;
|
|
5301
5896
|
this.#debugLog('PerpsController: Disconnecting provider to cleanup subscriptions', {
|
|
5302
5897
|
timestamp: new Date().toISOString(),
|
|
@@ -5345,6 +5940,9 @@ export class PerpsController extends BaseController {
|
|
|
5345
5940
|
}
|
|
5346
5941
|
// Clear stale reference so standalone reads don't route through old provider
|
|
5347
5942
|
this.activeProviderInstance = null;
|
|
5943
|
+
this.update((state) => {
|
|
5944
|
+
state.effectiveProvider = null;
|
|
5945
|
+
});
|
|
5348
5946
|
// Cleanup cached standalone provider (if any) — awaited to prevent races
|
|
5349
5947
|
await this.#cleanupStandaloneProvider();
|
|
5350
5948
|
// Note: Feature-flag subscription is NOT cleaned up here.
|
|
@@ -5520,35 +6118,51 @@ export class PerpsController extends BaseController {
|
|
|
5520
6118
|
});
|
|
5521
6119
|
}
|
|
5522
6120
|
/**
|
|
5523
|
-
* Get saved trade configuration for a market
|
|
6121
|
+
* Get saved trade configuration for a market on a venue
|
|
5524
6122
|
*
|
|
5525
6123
|
* @param symbol - The trading pair symbol.
|
|
6124
|
+
* @param providerId - Optional venue the configuration was saved for.
|
|
6125
|
+
* Defaults to the live effective venue, or the active/saved default venue
|
|
6126
|
+
* before initialization.
|
|
5526
6127
|
* @returns The resulting string value.
|
|
5527
6128
|
*/
|
|
5528
|
-
getTradeConfiguration(symbol) {
|
|
6129
|
+
getTradeConfiguration(symbol, providerId) {
|
|
5529
6130
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
5530
|
-
const
|
|
6131
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6132
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6133
|
+
return undefined;
|
|
6134
|
+
}
|
|
6135
|
+
const config = this.state.tradeConfigurations[network]?.[provider]?.[symbol];
|
|
5531
6136
|
if (!config?.leverage) {
|
|
5532
6137
|
return undefined;
|
|
5533
6138
|
}
|
|
5534
6139
|
this.#debugLog('PerpsController: Retrieved trade config', {
|
|
5535
6140
|
symbol,
|
|
5536
6141
|
network,
|
|
6142
|
+
provider,
|
|
5537
6143
|
leverage: config.leverage,
|
|
5538
6144
|
});
|
|
5539
6145
|
return { leverage: config.leverage };
|
|
5540
6146
|
}
|
|
5541
6147
|
/**
|
|
5542
|
-
* Save trade configuration for a market
|
|
6148
|
+
* Save trade configuration for a market on a venue
|
|
5543
6149
|
*
|
|
5544
6150
|
* @param symbol - Market symbol
|
|
5545
6151
|
* @param leverage - Leverage value
|
|
6152
|
+
* @param providerId - Optional venue to key the configuration under.
|
|
6153
|
+
* Defaults to the live effective venue, or the active/saved default venue
|
|
6154
|
+
* before initialization.
|
|
5546
6155
|
*/
|
|
5547
|
-
saveTradeConfiguration(symbol, leverage) {
|
|
6156
|
+
saveTradeConfiguration(symbol, leverage, providerId) {
|
|
5548
6157
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
6158
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6159
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6160
|
+
return;
|
|
6161
|
+
}
|
|
5549
6162
|
this.#debugLog('PerpsController: Saving trade configuration', {
|
|
5550
6163
|
symbol,
|
|
5551
6164
|
network,
|
|
6165
|
+
provider,
|
|
5552
6166
|
leverage,
|
|
5553
6167
|
timestamp: new Date().toISOString(),
|
|
5554
6168
|
});
|
|
@@ -5556,8 +6170,11 @@ export class PerpsController extends BaseController {
|
|
|
5556
6170
|
if (!state.tradeConfigurations[network]) {
|
|
5557
6171
|
state.tradeConfigurations[network] = {};
|
|
5558
6172
|
}
|
|
5559
|
-
|
|
5560
|
-
|
|
6173
|
+
if (!state.tradeConfigurations[network][provider]) {
|
|
6174
|
+
state.tradeConfigurations[network][provider] = {};
|
|
6175
|
+
}
|
|
6176
|
+
const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
|
|
6177
|
+
state.tradeConfigurations[network][provider][symbol] = {
|
|
5561
6178
|
...existingConfig,
|
|
5562
6179
|
leverage,
|
|
5563
6180
|
};
|
|
@@ -5578,12 +6195,20 @@ export class PerpsController extends BaseController {
|
|
|
5578
6195
|
* @param config.reduceOnly - Whether the order may only reduce a position.
|
|
5579
6196
|
* @param config.direction - Long or short.
|
|
5580
6197
|
* @param config.selectedPaymentToken - The selected payment token.
|
|
6198
|
+
* @param providerId - Optional venue to key the configuration under.
|
|
6199
|
+
* Defaults to the live effective venue, or the active/saved default venue
|
|
6200
|
+
* before initialization.
|
|
5581
6201
|
*/
|
|
5582
|
-
savePendingTradeConfiguration(symbol, config) {
|
|
6202
|
+
savePendingTradeConfiguration(symbol, config, providerId) {
|
|
5583
6203
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
6204
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6205
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6206
|
+
return;
|
|
6207
|
+
}
|
|
5584
6208
|
this.#debugLog('PerpsController: Saving pending trade configuration', {
|
|
5585
6209
|
symbol,
|
|
5586
6210
|
network,
|
|
6211
|
+
provider,
|
|
5587
6212
|
config,
|
|
5588
6213
|
timestamp: new Date().toISOString(),
|
|
5589
6214
|
});
|
|
@@ -5591,8 +6216,11 @@ export class PerpsController extends BaseController {
|
|
|
5591
6216
|
if (!state.tradeConfigurations[network]) {
|
|
5592
6217
|
state.tradeConfigurations[network] = {};
|
|
5593
6218
|
}
|
|
5594
|
-
|
|
5595
|
-
|
|
6219
|
+
if (!state.tradeConfigurations[network][provider]) {
|
|
6220
|
+
state.tradeConfigurations[network][provider] = {};
|
|
6221
|
+
}
|
|
6222
|
+
const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
|
|
6223
|
+
state.tradeConfigurations[network][provider][symbol] = {
|
|
5596
6224
|
...existingConfig,
|
|
5597
6225
|
pendingConfig: {
|
|
5598
6226
|
...config,
|
|
@@ -5609,11 +6237,19 @@ export class PerpsController extends BaseController {
|
|
|
5609
6237
|
* Returns undefined if config doesn't exist or has expired.
|
|
5610
6238
|
*
|
|
5611
6239
|
* @param symbol - Market 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.
|
|
5612
6243
|
* @returns Pending trade configuration or undefined
|
|
5613
6244
|
*/
|
|
5614
|
-
getPendingTradeConfiguration(symbol) {
|
|
6245
|
+
getPendingTradeConfiguration(symbol, providerId) {
|
|
5615
6246
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
5616
|
-
const
|
|
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]
|
|
6252
|
+
?.pendingConfig;
|
|
5617
6253
|
if (!config) {
|
|
5618
6254
|
return undefined;
|
|
5619
6255
|
}
|
|
@@ -5623,13 +6259,16 @@ export class PerpsController extends BaseController {
|
|
|
5623
6259
|
this.#debugLog('PerpsController: Pending trade config expired', {
|
|
5624
6260
|
symbol,
|
|
5625
6261
|
network,
|
|
6262
|
+
provider,
|
|
5626
6263
|
age,
|
|
5627
6264
|
timestamp: config.timestamp,
|
|
5628
6265
|
});
|
|
5629
6266
|
// Clear expired config
|
|
5630
6267
|
this.update((state) => {
|
|
5631
|
-
if (state.tradeConfigurations[network]?.[symbol]
|
|
5632
|
-
|
|
6268
|
+
if (state.tradeConfigurations[network]?.[provider]?.[symbol]
|
|
6269
|
+
?.pendingConfig) {
|
|
6270
|
+
delete state.tradeConfigurations[network][provider][symbol]
|
|
6271
|
+
.pendingConfig;
|
|
5633
6272
|
}
|
|
5634
6273
|
});
|
|
5635
6274
|
return undefined;
|
|
@@ -5637,6 +6276,7 @@ export class PerpsController extends BaseController {
|
|
|
5637
6276
|
this.#debugLog('PerpsController: Retrieved pending trade config', {
|
|
5638
6277
|
symbol,
|
|
5639
6278
|
network,
|
|
6279
|
+
provider,
|
|
5640
6280
|
config,
|
|
5641
6281
|
age,
|
|
5642
6282
|
});
|
|
@@ -5645,20 +6285,29 @@ export class PerpsController extends BaseController {
|
|
|
5645
6285
|
return configWithoutTimestamp;
|
|
5646
6286
|
}
|
|
5647
6287
|
/**
|
|
5648
|
-
* Clear pending trade configuration for a market
|
|
6288
|
+
* Clear pending trade configuration for a market on a venue
|
|
5649
6289
|
*
|
|
5650
6290
|
* @param symbol - Market symbol
|
|
6291
|
+
* @param providerId - Optional venue the configuration was saved for.
|
|
6292
|
+
* Defaults to the live effective venue, or the active/saved default venue
|
|
6293
|
+
* before initialization.
|
|
5651
6294
|
*/
|
|
5652
|
-
clearPendingTradeConfiguration(symbol) {
|
|
6295
|
+
clearPendingTradeConfiguration(symbol, providerId) {
|
|
5653
6296
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
6297
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6298
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6299
|
+
return;
|
|
6300
|
+
}
|
|
5654
6301
|
this.#debugLog('PerpsController: Clearing pending trade configuration', {
|
|
5655
6302
|
symbol,
|
|
5656
6303
|
network,
|
|
6304
|
+
provider,
|
|
5657
6305
|
timestamp: new Date().toISOString(),
|
|
5658
6306
|
});
|
|
5659
6307
|
this.update((state) => {
|
|
5660
|
-
if (state.tradeConfigurations[network]?.[symbol]?.pendingConfig) {
|
|
5661
|
-
delete state.tradeConfigurations[network][symbol]
|
|
6308
|
+
if (state.tradeConfigurations[network]?.[provider]?.[symbol]?.pendingConfig) {
|
|
6309
|
+
delete state.tradeConfigurations[network][provider][symbol]
|
|
6310
|
+
.pendingConfig;
|
|
5662
6311
|
}
|
|
5663
6312
|
});
|
|
5664
6313
|
}
|
|
@@ -5905,31 +6554,46 @@ export class PerpsController extends BaseController {
|
|
|
5905
6554
|
* Get saved order book grouping for a market
|
|
5906
6555
|
*
|
|
5907
6556
|
* @param symbol - Market symbol
|
|
6557
|
+
* @param providerId - Optional venue the grouping was saved for. Defaults to
|
|
6558
|
+
* the live effective venue (active/saved default before initialization).
|
|
5908
6559
|
* @returns The saved grouping value or undefined if not set
|
|
5909
6560
|
*/
|
|
5910
|
-
getOrderBookGrouping(symbol) {
|
|
6561
|
+
getOrderBookGrouping(symbol, providerId) {
|
|
5911
6562
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
5912
|
-
const
|
|
6563
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6564
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6565
|
+
return undefined;
|
|
6566
|
+
}
|
|
6567
|
+
const grouping = this.state.tradeConfigurations[network]?.[provider]?.[symbol]
|
|
6568
|
+
?.orderBookGrouping;
|
|
5913
6569
|
if (grouping !== undefined) {
|
|
5914
6570
|
this.#debugLog('PerpsController: Retrieved order book grouping', {
|
|
5915
6571
|
symbol,
|
|
5916
6572
|
network,
|
|
6573
|
+
provider,
|
|
5917
6574
|
grouping,
|
|
5918
6575
|
});
|
|
5919
6576
|
}
|
|
5920
6577
|
return grouping;
|
|
5921
6578
|
}
|
|
5922
6579
|
/**
|
|
5923
|
-
* Save order book grouping for a market
|
|
6580
|
+
* Save order book grouping for a market on a venue
|
|
5924
6581
|
*
|
|
5925
6582
|
* @param symbol - Market symbol
|
|
5926
6583
|
* @param grouping - Price grouping value
|
|
6584
|
+
* @param providerId - Optional venue to key the grouping under. Defaults to
|
|
6585
|
+
* the live effective venue (active/saved default before initialization).
|
|
5927
6586
|
*/
|
|
5928
|
-
saveOrderBookGrouping(symbol, grouping) {
|
|
6587
|
+
saveOrderBookGrouping(symbol, grouping, providerId) {
|
|
5929
6588
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
6589
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6590
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6591
|
+
return;
|
|
6592
|
+
}
|
|
5930
6593
|
this.#debugLog('PerpsController: Saving order book grouping', {
|
|
5931
6594
|
symbol,
|
|
5932
6595
|
network,
|
|
6596
|
+
provider,
|
|
5933
6597
|
grouping,
|
|
5934
6598
|
timestamp: new Date().toISOString(),
|
|
5935
6599
|
});
|
|
@@ -5937,8 +6601,11 @@ export class PerpsController extends BaseController {
|
|
|
5937
6601
|
if (!state.tradeConfigurations[network]) {
|
|
5938
6602
|
state.tradeConfigurations[network] = {};
|
|
5939
6603
|
}
|
|
5940
|
-
|
|
5941
|
-
|
|
6604
|
+
if (!state.tradeConfigurations[network][provider]) {
|
|
6605
|
+
state.tradeConfigurations[network][provider] = {};
|
|
6606
|
+
}
|
|
6607
|
+
const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
|
|
6608
|
+
state.tradeConfigurations[network][provider][symbol] = {
|
|
5942
6609
|
...existingConfig,
|
|
5943
6610
|
orderBookGrouping: grouping,
|
|
5944
6611
|
};
|
|
@@ -5949,35 +6616,52 @@ export class PerpsController extends BaseController {
|
|
|
5949
6616
|
* network. Clients should still let a venue-enforced mode take priority.
|
|
5950
6617
|
*
|
|
5951
6618
|
* @param symbol - Market symbol
|
|
6619
|
+
* @param providerId - Optional venue the mode was saved for. Defaults to the
|
|
6620
|
+
* live effective venue (active/saved default before initialization).
|
|
5952
6621
|
* @returns The saved margin mode or undefined if not set
|
|
5953
6622
|
*/
|
|
5954
|
-
getMarginMode(symbol) {
|
|
6623
|
+
getMarginMode(symbol, providerId) {
|
|
5955
6624
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
5956
|
-
|
|
6625
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6626
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6627
|
+
return undefined;
|
|
6628
|
+
}
|
|
6629
|
+
return this.state.tradeConfigurations[network]?.[provider]?.[symbol]
|
|
6630
|
+
?.marginMode;
|
|
5957
6631
|
}
|
|
5958
6632
|
/**
|
|
5959
|
-
* Save the margin mode (Isolated/Cross) picked for a market on
|
|
5960
|
-
* network. Values other than `isolated` or `cross` are ignored.
|
|
6633
|
+
* Save the margin mode (Isolated/Cross) picked for a market on a venue on
|
|
6634
|
+
* the current network. Values other than `isolated` or `cross` are ignored.
|
|
5961
6635
|
*
|
|
5962
6636
|
* @param symbol - Market symbol
|
|
5963
6637
|
* @param marginMode - Margin mode to persist
|
|
6638
|
+
* @param providerId - Optional venue to key the mode under. Defaults to the
|
|
6639
|
+
* live effective venue (active/saved default before initialization).
|
|
5964
6640
|
*/
|
|
5965
|
-
saveMarginMode(symbol, marginMode) {
|
|
6641
|
+
saveMarginMode(symbol, marginMode, providerId) {
|
|
5966
6642
|
if (marginMode !== 'isolated' && marginMode !== 'cross') {
|
|
5967
6643
|
return;
|
|
5968
6644
|
}
|
|
5969
6645
|
const network = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
6646
|
+
const provider = resolveTradeConfigProviderKey(this.state, providerId);
|
|
6647
|
+
if (provider === null || isUnsafeRecordKey(symbol)) {
|
|
6648
|
+
return;
|
|
6649
|
+
}
|
|
5970
6650
|
this.#debugLog('PerpsController: Saving margin mode', {
|
|
5971
6651
|
symbol,
|
|
5972
6652
|
network,
|
|
6653
|
+
provider,
|
|
5973
6654
|
marginMode,
|
|
5974
6655
|
});
|
|
5975
6656
|
this.update((state) => {
|
|
5976
6657
|
if (!state.tradeConfigurations[network]) {
|
|
5977
6658
|
state.tradeConfigurations[network] = {};
|
|
5978
6659
|
}
|
|
5979
|
-
|
|
5980
|
-
|
|
6660
|
+
if (!state.tradeConfigurations[network][provider]) {
|
|
6661
|
+
state.tradeConfigurations[network][provider] = {};
|
|
6662
|
+
}
|
|
6663
|
+
const existingConfig = state.tradeConfigurations[network][provider][symbol] || {};
|
|
6664
|
+
state.tradeConfigurations[network][provider][symbol] = {
|
|
5981
6665
|
...existingConfig,
|
|
5982
6666
|
marginMode,
|
|
5983
6667
|
};
|