@metamask-previews/perps-controller 24.1.0-preview-1a6714ed3 → 24.1.0-preview-4ba073b3a
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 +95 -0
- package/README.md +115 -5
- package/dist/PerpsController-method-action-types.d.ts +2 -2
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +19 -6
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +302 -64
- package/dist/PerpsController.js.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.ts +13 -2
- package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.js +27 -13
- package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +2 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +2 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/lighterConfig.d.ts +17 -0
- package/dist/constants/lighterConfig.d.ts.map +1 -1
- package/dist/constants/lighterConfig.js +31 -8
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +3 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +4 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +33 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +688 -41
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +2 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +410 -132
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +9 -2
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +334 -111
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/AccountService.d.ts.map +1 -1
- package/dist/services/AccountService.js +14 -1
- package/dist/services/AccountService.js.map +1 -1
- package/dist/services/DepositService.d.ts +8 -1
- package/dist/services/DepositService.d.ts.map +1 -1
- package/dist/services/DepositService.js +47 -6
- package/dist/services/DepositService.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +1 -1
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +5 -2
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +19 -14
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +612 -191
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/HyperLiquidWalletService.d.ts +7 -0
- package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
- package/dist/services/HyperLiquidWalletService.js +16 -0
- package/dist/services/HyperLiquidWalletService.js.map +1 -1
- package/dist/services/LighterClientService.d.ts.map +1 -1
- package/dist/services/LighterClientService.js +3 -1
- package/dist/services/LighterClientService.js.map +1 -1
- package/dist/services/RewardsIntegrationService.d.ts +2 -1
- package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
- package/dist/services/RewardsIntegrationService.js +9 -2
- package/dist/services/RewardsIntegrationService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +3 -3
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +340 -88
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +321 -14
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/lighter-types.d.ts +1 -1
- package/dist/types/lighter-types.d.ts.map +1 -1
- package/dist/types/lighter-types.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +58 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -0
- package/dist/utils/accountAggregation.js +117 -0
- package/dist/utils/accountAggregation.js.map +1 -0
- package/dist/utils/accountUtils.d.ts +18 -0
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +69 -66
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/batchOperationStatus.d.ts +18 -0
- package/dist/utils/batchOperationStatus.d.ts.map +1 -0
- package/dist/utils/batchOperationStatus.js +26 -0
- package/dist/utils/batchOperationStatus.js.map +1 -0
- package/dist/utils/cancelOrders.d.ts +32 -0
- package/dist/utils/cancelOrders.d.ts.map +1 -0
- package/dist/utils/cancelOrders.js +53 -0
- package/dist/utils/cancelOrders.js.map +1 -0
- package/dist/utils/closePositions.d.ts +24 -0
- package/dist/utils/closePositions.d.ts.map +1 -0
- package/dist/utils/closePositions.js +20 -0
- package/dist/utils/closePositions.js.map +1 -0
- package/dist/utils/feeSupport.d.ts +9 -0
- package/dist/utils/feeSupport.d.ts.map +1 -0
- package/dist/utils/feeSupport.js +11 -0
- package/dist/utils/feeSupport.js.map +1 -0
- package/dist/utils/hyperLiquidAdapter.d.ts +9 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +37 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +46 -0
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +98 -6
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +5 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +3 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts +2 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +32 -16
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +38 -0
- package/dist/utils/orderBookGrouping.d.ts.map +1 -0
- package/dist/utils/orderBookGrouping.js +101 -0
- package/dist/utils/orderBookGrouping.js.map +1 -0
- package/dist/utils/orderTypes.d.ts +2 -0
- package/dist/utils/orderTypes.d.ts.map +1 -1
- package/dist/utils/orderTypes.js +11 -4
- package/dist/utils/orderTypes.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts +33 -0
- package/dist/utils/perpsClientCopy.d.ts.map +1 -0
- package/dist/utils/perpsClientCopy.js +509 -0
- package/dist/utils/perpsClientCopy.js.map +1 -0
- package/dist/utils/standaloneInfoClient.d.ts +20 -3
- package/dist/utils/standaloneInfoClient.d.ts.map +1 -1
- package/dist/utils/standaloneInfoClient.js +35 -10
- package/dist/utils/standaloneInfoClient.js.map +1 -1
- package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
- package/dist/utils/subscriptionFeeWaiver.js +5 -3
- package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
- package/docs/README.md +1 -0
- package/docs/architecture.md +16 -12
- package/docs/client-contract.md +89 -0
- package/docs/contracts/events.md +1 -1
- package/docs/tpsl.md +1 -0
- package/package.json +2 -2
package/dist/PerpsController.js
CHANGED
|
@@ -30,8 +30,12 @@ import { TradingService } from './services/TradingService.js';
|
|
|
30
30
|
import { WebSocketConnectionState, PerpsAnalyticsEvent, PerpsTraceNames, PerpsTraceOperations, isVersionGatedFeatureFlag, MARKET_CATEGORIES,
|
|
31
31
|
// Platform dependencies interface for core migration (bundles all platform-specific deps)
|
|
32
32
|
} from './types/index.js';
|
|
33
|
-
import {
|
|
33
|
+
import { buildAggregatedAccountState } from './utils/accountAggregation.js';
|
|
34
|
+
import { getCaipAccountAddress, getSelectedEvmAccountFromMessenger, } from './utils/accountUtils.js';
|
|
34
35
|
import { createLiveChaseOrderList, createLiveTwapOrderList, } from './utils/advancedOrderLists.js';
|
|
36
|
+
import { withBatchOperationStatus } from './utils/batchOperationStatus.js';
|
|
37
|
+
import { getUnroutedCancelOrdersRefusal, resolveCancelSelection, } from './utils/cancelOrders.js';
|
|
38
|
+
import { resolveCloseSelection } from './utils/closePositions.js';
|
|
35
39
|
import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from './utils/errorContext.js';
|
|
36
40
|
import { ensureError } from './utils/errorUtils.js';
|
|
37
41
|
import { parseAssetName } from './utils/hyperLiquidAdapter.js';
|
|
@@ -66,7 +70,9 @@ function cloneUserDataSnapshot(snapshot) {
|
|
|
66
70
|
positions: snapshot.positions.map((position) => ({
|
|
67
71
|
...position,
|
|
68
72
|
leverage: { ...position.leverage },
|
|
69
|
-
|
|
73
|
+
...(position.cumulativeFunding && {
|
|
74
|
+
cumulativeFunding: { ...position.cumulativeFunding },
|
|
75
|
+
}),
|
|
70
76
|
...(position.takeProfitOrders && {
|
|
71
77
|
takeProfitOrders: position.takeProfitOrders.map((order) => ({
|
|
72
78
|
...order,
|
|
@@ -837,15 +843,21 @@ export class PerpsController extends BaseController {
|
|
|
837
843
|
// must learn the new trading address after every account switch, and the
|
|
838
844
|
// preload-scoped account handler is torn down on disconnect, so it cannot
|
|
839
845
|
// carry this.
|
|
840
|
-
|
|
841
|
-
|
|
846
|
+
// A restored balance does not record which wallet it belongs to.
|
|
847
|
+
this.#hasUnverifiedAccountBalances =
|
|
848
|
+
this.state.accountState !== null ||
|
|
849
|
+
Object.keys(this.state.perpsBalances).length > 0;
|
|
850
|
+
this.#selectedTradingAddress = getSelectedEvmAccountFromMessenger(this.messenger)?.address.toLowerCase();
|
|
851
|
+
const updateSelectedTradingAccount = (switchedAccount) => {
|
|
842
852
|
this.#rewardsIntegrationService.resetRegisteredTradingAddresses();
|
|
853
|
+
this.#setSelectedTradingAddress(switchedAccount === null
|
|
854
|
+
? null
|
|
855
|
+
: switchedAccount?.address.toLowerCase());
|
|
843
856
|
// Clearing alone only guarantees the *next preview* re-registers. An
|
|
844
857
|
// order submitted straight after a switch, with no preview in between,
|
|
845
858
|
// would otherwise be attributed to nothing, so the new address announces
|
|
846
859
|
// itself here. Fire-and-forget: attribution plumbing must not block or
|
|
847
860
|
// fail an account switch.
|
|
848
|
-
const switchedAccount = getSelectedEvmAccountFromMessenger(this.messenger);
|
|
849
861
|
if (switchedAccount) {
|
|
850
862
|
this.#rewardsIntegrationService
|
|
851
863
|
.registerTradingAddress(switchedAccount.address, {
|
|
@@ -856,8 +868,10 @@ export class PerpsController extends BaseController {
|
|
|
856
868
|
});
|
|
857
869
|
}
|
|
858
870
|
};
|
|
859
|
-
this.messenger.subscribe('AccountsController:selectedAccountChange',
|
|
860
|
-
this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange',
|
|
871
|
+
this.messenger.subscribe('AccountsController:selectedAccountChange', () => updateSelectedTradingAccount(getSelectedEvmAccountFromMessenger(this.messenger)));
|
|
872
|
+
this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', (groupId) => updateSelectedTradingAccount(groupId === ''
|
|
873
|
+
? null
|
|
874
|
+
: getSelectedEvmAccountFromMessenger(this.messenger)));
|
|
861
875
|
this.providers = new Map();
|
|
862
876
|
// Migrate old persisted data without accountAddress
|
|
863
877
|
this.#migrateRequestsIfNeeded();
|
|
@@ -1026,29 +1040,39 @@ export class PerpsController extends BaseController {
|
|
|
1026
1040
|
// Assemble from all registered provider entries
|
|
1027
1041
|
const allPositions = [];
|
|
1028
1042
|
const allOrders = [];
|
|
1029
|
-
|
|
1043
|
+
const accountEntries = [];
|
|
1030
1044
|
let hasValidEntry = false;
|
|
1031
|
-
for (const providerId of this.#getAggregatedCacheProviderIds(Object.keys(cache))) {
|
|
1045
|
+
for (const providerId of this.#getAggregatedCacheProviderIds(Object.keys(cache)).filter(isPerpsProviderType)) {
|
|
1032
1046
|
const providerNetworkKey = buildProviderCacheKey(providerId, this.state.isTestnet);
|
|
1033
1047
|
const entry = cache[providerNetworkKey];
|
|
1034
1048
|
if (!isValidEntry(providerId, entry)) {
|
|
1049
|
+
accountEntries.push({ status: 'unavailable', providerId });
|
|
1035
1050
|
continue;
|
|
1036
1051
|
}
|
|
1037
1052
|
hasValidEntry = true;
|
|
1038
1053
|
allPositions.push(...entry.positions);
|
|
1039
1054
|
allOrders.push(...entry.orders);
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1055
|
+
accountEntries.push(entry.accountState
|
|
1056
|
+
? {
|
|
1057
|
+
status: 'available',
|
|
1058
|
+
providerId,
|
|
1059
|
+
state: { ...entry.accountState, providerId },
|
|
1060
|
+
}
|
|
1061
|
+
: { status: 'unavailable', providerId });
|
|
1044
1062
|
}
|
|
1045
1063
|
if (!hasValidEntry) {
|
|
1046
1064
|
return null;
|
|
1047
1065
|
}
|
|
1066
|
+
// Match live reads: combine venue snapshots, but preserve venue-local
|
|
1067
|
+
// detail and the direct shape when only one venue participates.
|
|
1068
|
+
const [onlyEntry] = accountEntries;
|
|
1069
|
+
const accountState = accountEntries.length === 1 && onlyEntry.status === 'available'
|
|
1070
|
+
? onlyEntry.state
|
|
1071
|
+
: buildAggregatedAccountState({ entries: accountEntries });
|
|
1048
1072
|
return {
|
|
1049
1073
|
positions: allPositions,
|
|
1050
1074
|
orders: allOrders,
|
|
1051
|
-
accountState
|
|
1075
|
+
accountState,
|
|
1052
1076
|
};
|
|
1053
1077
|
}
|
|
1054
1078
|
// Single provider mode
|
|
@@ -1476,6 +1500,9 @@ export class PerpsController extends BaseController {
|
|
|
1476
1500
|
: 'hyperliquid';
|
|
1477
1501
|
state.effectiveProvider = null;
|
|
1478
1502
|
state.accountState = null;
|
|
1503
|
+
// The direct stream covers one venue only: entries persisted by the
|
|
1504
|
+
// aggregated session must not keep looking live.
|
|
1505
|
+
state.perpsBalances = {};
|
|
1479
1506
|
}
|
|
1480
1507
|
});
|
|
1481
1508
|
return;
|
|
@@ -2507,8 +2534,8 @@ export class PerpsController extends BaseController {
|
|
|
2507
2534
|
/**
|
|
2508
2535
|
* Structured refusal for an aggregated-mode batch write.
|
|
2509
2536
|
*
|
|
2510
|
-
*
|
|
2511
|
-
* registered they are refused instead of
|
|
2537
|
+
* Legacy symbol-only closes cannot identify a venue, so while multiple
|
|
2538
|
+
* venues are registered they are refused instead of using the default.
|
|
2512
2539
|
*
|
|
2513
2540
|
* @param provider - Resolved provider, when initialization has settled.
|
|
2514
2541
|
* @returns The batch refusal result, or undefined when the batch may proceed.
|
|
@@ -2699,6 +2726,10 @@ export class PerpsController extends BaseController {
|
|
|
2699
2726
|
throw new Error('Chase ownership requires an exact handle and explicit provider');
|
|
2700
2727
|
}
|
|
2701
2728
|
const issuedContext = this.#getActionContext();
|
|
2729
|
+
this.#reconcileSelectedTradingAddress();
|
|
2730
|
+
if (issuedContext !== this.#getActionContext()) {
|
|
2731
|
+
throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
|
|
2732
|
+
}
|
|
2702
2733
|
const issuedGeneration = this.#lifecycleGeneration;
|
|
2703
2734
|
const issuedAccountGeneration = this.#selectedAccountGeneration;
|
|
2704
2735
|
const issuedInstance = this.activeProviderInstance;
|
|
@@ -2760,6 +2791,10 @@ export class PerpsController extends BaseController {
|
|
|
2760
2791
|
throw new Error('Chase cancellation reconciliation requires an exact handle, child and matching owner/provider');
|
|
2761
2792
|
}
|
|
2762
2793
|
const issuedContext = this.#getActionContext();
|
|
2794
|
+
this.#reconcileSelectedTradingAddress();
|
|
2795
|
+
if (issuedContext !== this.#getActionContext()) {
|
|
2796
|
+
throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
|
|
2797
|
+
}
|
|
2763
2798
|
const issuedGeneration = this.#lifecycleGeneration;
|
|
2764
2799
|
const issuedAccountGeneration = this.#selectedAccountGeneration;
|
|
2765
2800
|
const issuedInstance = this.activeProviderInstance;
|
|
@@ -2820,26 +2855,24 @@ export class PerpsController extends BaseController {
|
|
|
2820
2855
|
* Batch version of cancelOrder() that cancels multiple orders simultaneously
|
|
2821
2856
|
*
|
|
2822
2857
|
* @param params - The operation parameters.
|
|
2823
|
-
* @returns
|
|
2858
|
+
* @returns Per-order results, plus `status`: `all`, `partial` or `none`.
|
|
2824
2859
|
*/
|
|
2825
2860
|
async cancelOrders(params) {
|
|
2826
|
-
|
|
2827
|
-
if (unroutedRefusal) {
|
|
2828
|
-
return unroutedRefusal;
|
|
2829
|
-
}
|
|
2861
|
+
// All-order batches fan out; filtered batches must identify their venue.
|
|
2830
2862
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2831
|
-
const
|
|
2832
|
-
if (
|
|
2833
|
-
return
|
|
2863
|
+
const refusal = getUnroutedCancelOrdersRefusal(provider, resolveCancelSelection(params));
|
|
2864
|
+
if (refusal) {
|
|
2865
|
+
return withBatchOperationStatus(refusal);
|
|
2834
2866
|
}
|
|
2835
|
-
|
|
2867
|
+
const result = await this.#tradingService.cancelOrders({
|
|
2836
2868
|
provider,
|
|
2837
2869
|
params,
|
|
2838
2870
|
context: this.#createServiceContext('cancelOrders', {
|
|
2839
|
-
getOpenOrders: () => this.getOpenOrders(),
|
|
2871
|
+
getOpenOrders: (readParams) => this.getOpenOrders(readParams),
|
|
2840
2872
|
}),
|
|
2841
2873
|
withStreamPause: (operation, channels) => this.#withStreamPause(operation, channels),
|
|
2842
2874
|
});
|
|
2875
|
+
return withBatchOperationStatus(result);
|
|
2843
2876
|
}
|
|
2844
2877
|
/**
|
|
2845
2878
|
* Close a position (partial or full)
|
|
@@ -2876,26 +2909,28 @@ export class PerpsController extends BaseController {
|
|
|
2876
2909
|
* Batch version of closePosition() that closes multiple positions simultaneously
|
|
2877
2910
|
*
|
|
2878
2911
|
* @param params - The operation parameters.
|
|
2879
|
-
* @returns
|
|
2912
|
+
* @returns Per-position results, plus `status`: `all`, `partial` or `none`.
|
|
2880
2913
|
*/
|
|
2881
2914
|
async closePositions(params) {
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
}
|
|
2915
|
+
// closeAll fans out to every enabled venue, and explicit targets name
|
|
2916
|
+
// their own venue. A legacy symbols-only close stays ambiguous in
|
|
2917
|
+
// multi-venue aggregated mode and is refused below rather than guessed.
|
|
2886
2918
|
const provider = await this.#getActiveProviderWhenReady();
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2919
|
+
if (resolveCloseSelection(params).kind === 'symbols') {
|
|
2920
|
+
const unroutedRefusal = this.#getUnroutedAggregatedBatchRefusal(provider);
|
|
2921
|
+
if (unroutedRefusal) {
|
|
2922
|
+
return withBatchOperationStatus(unroutedRefusal);
|
|
2923
|
+
}
|
|
2890
2924
|
}
|
|
2891
2925
|
this.#ensureTradingServiceDeps();
|
|
2892
|
-
|
|
2926
|
+
const result = await this.#tradingService.closePositions({
|
|
2893
2927
|
provider,
|
|
2894
2928
|
params,
|
|
2895
2929
|
context: this.#createServiceContext('closePositions', {
|
|
2896
|
-
getPositions: () => this.getPositions(),
|
|
2930
|
+
getPositions: (readParams) => this.getPositions(readParams),
|
|
2897
2931
|
}),
|
|
2898
2932
|
});
|
|
2933
|
+
return withBatchOperationStatus(result);
|
|
2899
2934
|
}
|
|
2900
2935
|
/**
|
|
2901
2936
|
* Update TP/SL for an existing position
|
|
@@ -3046,11 +3081,18 @@ export class PerpsController extends BaseController {
|
|
|
3046
3081
|
let currentDepositId;
|
|
3047
3082
|
try {
|
|
3048
3083
|
const provider = await this.#getActiveProviderWhenReady();
|
|
3049
|
-
const { transaction, assetChainId, currentDepositId: depositId, } = await this.#depositService.prepareTransaction({
|
|
3084
|
+
const { transaction, assetChainId, currentDepositId: depositId, providerId: depositProviderId, } = await this.#depositService.prepareTransaction({
|
|
3085
|
+
provider,
|
|
3086
|
+
...(params.providerId !== undefined && {
|
|
3087
|
+
providerId: params.providerId,
|
|
3088
|
+
}),
|
|
3089
|
+
});
|
|
3050
3090
|
currentDepositId = depositId;
|
|
3051
3091
|
// Get current account address via messenger (outside of update() for proper typing)
|
|
3052
3092
|
const evmAccount = getSelectedEvmAccountFromMessenger(this.messenger);
|
|
3053
3093
|
const accountAddress = evmAccount?.address ?? 'unknown';
|
|
3094
|
+
// Preparation resolves the venue from the route or executing provider,
|
|
3095
|
+
// independent of later active-provider changes.
|
|
3054
3096
|
this.update((state) => {
|
|
3055
3097
|
state.lastDepositResult = null;
|
|
3056
3098
|
// Add deposit request to tracking
|
|
@@ -3060,6 +3102,9 @@ export class PerpsController extends BaseController {
|
|
|
3060
3102
|
amount: amount ?? '0', // Use provided amount or default to '0'
|
|
3061
3103
|
asset: USDC_SYMBOL,
|
|
3062
3104
|
accountAddress, // Track which account initiated deposit
|
|
3105
|
+
...(depositProviderId === undefined
|
|
3106
|
+
? {}
|
|
3107
|
+
: { providerId: depositProviderId }),
|
|
3063
3108
|
success: false, // Will be updated when transaction completes
|
|
3064
3109
|
txHash: undefined,
|
|
3065
3110
|
status: 'pending',
|
|
@@ -3887,19 +3932,50 @@ export class PerpsController extends BaseController {
|
|
|
3887
3932
|
: operation;
|
|
3888
3933
|
}
|
|
3889
3934
|
const provider = this.getActiveProvider();
|
|
3935
|
+
const accountId = params?.accountId;
|
|
3936
|
+
const selectedAddress = this.#reconcileSelectedTradingAddress(accountId);
|
|
3937
|
+
const requestAddress = accountId === undefined
|
|
3938
|
+
? selectedAddress
|
|
3939
|
+
: getCaipAccountAddress(accountId);
|
|
3940
|
+
const selectedAccountGeneration = this.#selectedAccountGeneration;
|
|
3890
3941
|
return this.#marketDataService.getAccountState({
|
|
3891
3942
|
provider,
|
|
3892
3943
|
params,
|
|
3893
3944
|
context: this.#createServiceContext('getAccountState', {
|
|
3894
3945
|
accountDataContext: {
|
|
3895
|
-
// Match the live account
|
|
3896
|
-
//
|
|
3897
|
-
//
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3946
|
+
// Match the live account data context. A combined snapshot is
|
|
3947
|
+
// current only while more than one venue is still registered: an
|
|
3948
|
+
// in-flight result from before a venue was removed must not replace
|
|
3949
|
+
// the remaining venue. A one-venue fallback (no `providerStates`)
|
|
3950
|
+
// is current only while the wrapper still has that single venue
|
|
3951
|
+
// and the result names it. After another venue recovers, that
|
|
3952
|
+
// in-flight fallback must not replace the combined snapshot, even
|
|
3953
|
+
// when it names the routing default. A direct-provider result is
|
|
3954
|
+
// matched against the active venue, so a response from a previous
|
|
3955
|
+
// venue is dropped when the route changed while it was in flight.
|
|
3956
|
+
isCurrent: (accountState) => {
|
|
3957
|
+
const currentAddress = this.#reconcileSelectedTradingAddress(accountId);
|
|
3958
|
+
if (requestAddress === undefined ||
|
|
3959
|
+
requestAddress !== currentAddress ||
|
|
3960
|
+
this.#selectedAccountGeneration !== selectedAccountGeneration) {
|
|
3961
|
+
return false;
|
|
3962
|
+
}
|
|
3963
|
+
const active = this.activeProviderInstance;
|
|
3964
|
+
if (active instanceof AggregatedPerpsProvider) {
|
|
3965
|
+
const venueCount = active.getProviderIds().length;
|
|
3966
|
+
if (accountState.providerStates) {
|
|
3967
|
+
return venueCount > 1;
|
|
3968
|
+
}
|
|
3969
|
+
return (venueCount <= 1 &&
|
|
3970
|
+
(accountState.providerId === undefined ||
|
|
3971
|
+
accountState.providerId === active.getWriteProviderId()));
|
|
3972
|
+
}
|
|
3973
|
+
if (accountState.providerStates) {
|
|
3974
|
+
return false;
|
|
3975
|
+
}
|
|
3976
|
+
return (accountState.providerId === undefined ||
|
|
3977
|
+
accountState.providerId === this.state.activeProvider);
|
|
3978
|
+
},
|
|
3903
3979
|
},
|
|
3904
3980
|
}),
|
|
3905
3981
|
});
|
|
@@ -4081,8 +4157,11 @@ export class PerpsController extends BaseController {
|
|
|
4081
4157
|
#isPreloadingUserData = false;
|
|
4082
4158
|
#userPreloadQueued = false;
|
|
4083
4159
|
#lifecycleGeneration = 0;
|
|
4084
|
-
//
|
|
4160
|
+
// Observed wallet changes also fence round trips to the original address.
|
|
4085
4161
|
#selectedAccountGeneration = 0;
|
|
4162
|
+
// Null records an explicit deselection while legacy selection catches up.
|
|
4163
|
+
#selectedTradingAddress;
|
|
4164
|
+
#hasUnverifiedAccountBalances;
|
|
4086
4165
|
#userSnapshotRequests = new Map();
|
|
4087
4166
|
#preloadStateUnsubscribe = null;
|
|
4088
4167
|
#accountChangeUnsubscribe = null;
|
|
@@ -4579,8 +4658,21 @@ export class PerpsController extends BaseController {
|
|
|
4579
4658
|
for (const order of orders) {
|
|
4580
4659
|
ensureBucket(order.providerId ?? fallbackProviderId).orders.push(order);
|
|
4581
4660
|
}
|
|
4582
|
-
// AccountState — assign to
|
|
4583
|
-
|
|
4661
|
+
// AccountState — assign per-venue snapshots to their own buckets. An
|
|
4662
|
+
// aggregated result's combined total is venue-neutral and is never
|
|
4663
|
+
// stored in a venue bucket merely because the aggregate itself has no
|
|
4664
|
+
// providerId.
|
|
4665
|
+
if (accountState.providerStates) {
|
|
4666
|
+
for (const [pid, entry] of Object.entries(accountState.providerStates)) {
|
|
4667
|
+
if (entry) {
|
|
4668
|
+
ensureBucket(pid).accountState =
|
|
4669
|
+
entry.status === 'available' ? entry.state : null;
|
|
4670
|
+
}
|
|
4671
|
+
}
|
|
4672
|
+
}
|
|
4673
|
+
else {
|
|
4674
|
+
ensureBucket(accountState.providerId ?? fallbackProviderId).accountState = accountState;
|
|
4675
|
+
}
|
|
4584
4676
|
if (discardStalePreload()) {
|
|
4585
4677
|
return;
|
|
4586
4678
|
}
|
|
@@ -4936,6 +5028,8 @@ export class PerpsController extends BaseController {
|
|
|
4936
5028
|
this.update((state) => {
|
|
4937
5029
|
state.isTestnet = !state.isTestnet;
|
|
4938
5030
|
state.effectiveProvider = null;
|
|
5031
|
+
// The previous network's balances are not observations of this one.
|
|
5032
|
+
state.perpsBalances = {};
|
|
4939
5033
|
});
|
|
4940
5034
|
const newNetwork = this.state.isTestnet ? 'testnet' : 'mainnet';
|
|
4941
5035
|
this.#debugLog('PerpsController: Network toggle initiated', {
|
|
@@ -5076,6 +5170,9 @@ export class PerpsController extends BaseController {
|
|
|
5076
5170
|
// network toggle or disconnect/init does not migrate it away.
|
|
5077
5171
|
state.hasExplicitProviderSelection = providerId !== 'aggregated';
|
|
5078
5172
|
state.accountState = null;
|
|
5173
|
+
// The new selection streams a different venue set: persisted entries
|
|
5174
|
+
// from the previous topology must not keep looking live.
|
|
5175
|
+
state.perpsBalances = {};
|
|
5079
5176
|
state.initializationState = InitializationState.Uninitialized;
|
|
5080
5177
|
});
|
|
5081
5178
|
// Reset initialization state and reinitialize
|
|
@@ -5198,9 +5295,14 @@ export class PerpsController extends BaseController {
|
|
|
5198
5295
|
if (aggregatedProvider) {
|
|
5199
5296
|
state.effectiveProvider = providerId;
|
|
5200
5297
|
}
|
|
5201
|
-
//
|
|
5202
|
-
//
|
|
5203
|
-
|
|
5298
|
+
// A single-venue snapshot (for example a one-venue fallback read) was
|
|
5299
|
+
// tied to the previous default route: drop it until matching data
|
|
5300
|
+
// arrives. An aggregate snapshot spans every venue and stays valid
|
|
5301
|
+
// across a routing-default change, so it is kept.
|
|
5302
|
+
if (defaultChanged &&
|
|
5303
|
+
aggregatedProvider &&
|
|
5304
|
+
state.accountState &&
|
|
5305
|
+
!state.accountState.providerStates) {
|
|
5204
5306
|
state.accountState = null;
|
|
5205
5307
|
}
|
|
5206
5308
|
});
|
|
@@ -5691,6 +5793,45 @@ export class PerpsController extends BaseController {
|
|
|
5691
5793
|
};
|
|
5692
5794
|
}
|
|
5693
5795
|
}
|
|
5796
|
+
/**
|
|
5797
|
+
* Refresh the live balance owner if the selected group's membership changed.
|
|
5798
|
+
* Alignment does not always emit a new selection event.
|
|
5799
|
+
*
|
|
5800
|
+
* @param accountId - Explicit scope, when supplied. Reads and streams for
|
|
5801
|
+
* another wallet do not reconcile the selected wallet's state.
|
|
5802
|
+
* @returns The current trading address, if selected.
|
|
5803
|
+
*/
|
|
5804
|
+
#reconcileSelectedTradingAddress(accountId) {
|
|
5805
|
+
if (this.#selectedTradingAddress === null) {
|
|
5806
|
+
return undefined;
|
|
5807
|
+
}
|
|
5808
|
+
const address = getSelectedEvmAccountFromMessenger(this.messenger)?.address.toLowerCase();
|
|
5809
|
+
if (accountId === undefined ||
|
|
5810
|
+
(address !== undefined && getCaipAccountAddress(accountId) === address)) {
|
|
5811
|
+
this.#setSelectedTradingAddress(address);
|
|
5812
|
+
}
|
|
5813
|
+
return address;
|
|
5814
|
+
}
|
|
5815
|
+
/**
|
|
5816
|
+
* Clear balances when the wallet changes or restored ownership is unknown.
|
|
5817
|
+
* Account tree reinitialization may repeat a valid selection.
|
|
5818
|
+
*
|
|
5819
|
+
* @param address - Resolved wallet address, or null for explicit deselection.
|
|
5820
|
+
*/
|
|
5821
|
+
#setSelectedTradingAddress(address) {
|
|
5822
|
+
const walletChanged = (this.#selectedTradingAddress ?? undefined) !== (address ?? undefined);
|
|
5823
|
+
this.#selectedTradingAddress = address;
|
|
5824
|
+
if (walletChanged) {
|
|
5825
|
+
this.#selectedAccountGeneration += 1;
|
|
5826
|
+
}
|
|
5827
|
+
if (walletChanged || this.#hasUnverifiedAccountBalances) {
|
|
5828
|
+
this.#hasUnverifiedAccountBalances = false;
|
|
5829
|
+
this.update((state) => {
|
|
5830
|
+
state.accountState = null;
|
|
5831
|
+
state.perpsBalances = {};
|
|
5832
|
+
});
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
5694
5835
|
/**
|
|
5695
5836
|
* Subscribe to live account updates.
|
|
5696
5837
|
* Updates controller state (Redux) when new account data arrives so consumers
|
|
@@ -5707,20 +5848,117 @@ export class PerpsController extends BaseController {
|
|
|
5707
5848
|
};
|
|
5708
5849
|
}
|
|
5709
5850
|
try {
|
|
5710
|
-
const originalCallback = params
|
|
5711
|
-
return this.#trackProviderSubscription(provider, (nextProvider) =>
|
|
5712
|
-
|
|
5713
|
-
|
|
5714
|
-
|
|
5715
|
-
|
|
5716
|
-
|
|
5717
|
-
|
|
5718
|
-
|
|
5719
|
-
|
|
5851
|
+
const { accountId, callback: originalCallback } = params;
|
|
5852
|
+
return this.#trackProviderSubscription(provider, (nextProvider) => {
|
|
5853
|
+
// Capture each opening's account, including implicit selection, so
|
|
5854
|
+
// late emissions after an account switch cannot own selected state.
|
|
5855
|
+
// A malformed explicit id names no account and never owns state.
|
|
5856
|
+
if (accountId === undefined) {
|
|
5857
|
+
this.#reconcileSelectedTradingAddress();
|
|
5858
|
+
}
|
|
5859
|
+
const streamAddress = accountId === undefined
|
|
5860
|
+
? getSelectedEvmAccountFromMessenger(this.messenger)?.address.toLowerCase()
|
|
5861
|
+
: getCaipAccountAddress(accountId);
|
|
5862
|
+
const subscriptionParams = {
|
|
5863
|
+
...params,
|
|
5864
|
+
callback: (account, aggregate) => {
|
|
5865
|
+
const selectedAddress = this.activeProviderInstance === nextProvider &&
|
|
5866
|
+
streamAddress !== undefined
|
|
5867
|
+
? this.#reconcileSelectedTradingAddress(accountId)
|
|
5868
|
+
: undefined;
|
|
5869
|
+
const ownsState = streamAddress !== undefined &&
|
|
5870
|
+
streamAddress === selectedAddress &&
|
|
5871
|
+
streamAddress === this.#selectedTradingAddress &&
|
|
5872
|
+
this.activeProviderInstance === nextProvider;
|
|
5873
|
+
if (ownsState && account) {
|
|
5874
|
+
this.update((state) => {
|
|
5875
|
+
state.accountState = account;
|
|
5876
|
+
state.lastUpdateTimestamp = Date.now();
|
|
5877
|
+
state.lastError = null;
|
|
5878
|
+
// One balance entry per venue with data, keyed by the venue
|
|
5879
|
+
// that actually served it. Aggregated updates carry explicit
|
|
5880
|
+
// per-venue entries; direct-provider updates are attributed
|
|
5881
|
+
// to their own venue id, or the active direct provider when
|
|
5882
|
+
// the venue does not stamp one.
|
|
5883
|
+
const timestamp = Date.now();
|
|
5884
|
+
const writeBalance = (venueId, balance) => {
|
|
5885
|
+
state.perpsBalances[venueId] = {
|
|
5886
|
+
totalBalance: balance.totalBalance,
|
|
5887
|
+
unrealizedPnl: balance.unrealizedPnl,
|
|
5888
|
+
lastUpdated: timestamp,
|
|
5889
|
+
};
|
|
5890
|
+
};
|
|
5891
|
+
if (account.providerStates) {
|
|
5892
|
+
for (const [providerId, entry] of Object.entries(account.providerStates)) {
|
|
5893
|
+
if (!entry) {
|
|
5894
|
+
continue;
|
|
5895
|
+
}
|
|
5896
|
+
if (entry.status === 'available') {
|
|
5897
|
+
writeBalance(providerId, entry.state);
|
|
5898
|
+
}
|
|
5899
|
+
else if (entry.status === 'unavailable') {
|
|
5900
|
+
// The venue's data is unavailable: drop its entry
|
|
5901
|
+
// rather than keep exposing a stale value as live.
|
|
5902
|
+
delete state.perpsBalances[providerId];
|
|
5903
|
+
}
|
|
5904
|
+
// Keep pending venues' balances only for the same wallet.
|
|
5905
|
+
}
|
|
5906
|
+
}
|
|
5907
|
+
else {
|
|
5908
|
+
const directVenueId = state.activeProvider === 'aggregated'
|
|
5909
|
+
? undefined
|
|
5910
|
+
: state.activeProvider;
|
|
5911
|
+
const venueId = account.providerId ?? directVenueId;
|
|
5912
|
+
if (venueId) {
|
|
5913
|
+
// A direct or single-venue emission is the whole live
|
|
5914
|
+
// topology: entries for venues this stream does not
|
|
5915
|
+
// serve (persisted by a previous session) must not keep
|
|
5916
|
+
// looking live.
|
|
5917
|
+
for (const staleVenue of Object.keys(state.perpsBalances)) {
|
|
5918
|
+
if (staleVenue !== venueId) {
|
|
5919
|
+
delete state.perpsBalances[staleVenue];
|
|
5920
|
+
}
|
|
5921
|
+
}
|
|
5922
|
+
writeBalance(venueId, account);
|
|
5923
|
+
}
|
|
5924
|
+
}
|
|
5925
|
+
});
|
|
5926
|
+
}
|
|
5927
|
+
else if (ownsState) {
|
|
5928
|
+
this.update((state) => {
|
|
5929
|
+
state.accountState = null;
|
|
5930
|
+
state.lastUpdateTimestamp = Date.now();
|
|
5931
|
+
if (aggregate) {
|
|
5932
|
+
// A null total may still contain pending venues. For the
|
|
5933
|
+
// same wallet, only explicit unavailability clears them.
|
|
5934
|
+
for (const providerId of aggregate.unavailableProviders) {
|
|
5935
|
+
delete state.perpsBalances[providerId];
|
|
5936
|
+
}
|
|
5937
|
+
}
|
|
5938
|
+
else {
|
|
5939
|
+
state.perpsBalances = {};
|
|
5940
|
+
}
|
|
5941
|
+
});
|
|
5942
|
+
}
|
|
5943
|
+
if (aggregate) {
|
|
5944
|
+
originalCallback(account, aggregate);
|
|
5945
|
+
}
|
|
5946
|
+
else {
|
|
5947
|
+
originalCallback(account);
|
|
5948
|
+
}
|
|
5949
|
+
},
|
|
5950
|
+
};
|
|
5951
|
+
try {
|
|
5952
|
+
return nextProvider.subscribeToAccount(subscriptionParams);
|
|
5953
|
+
}
|
|
5954
|
+
catch (error) {
|
|
5955
|
+
if (error instanceof Error &&
|
|
5956
|
+
error.message === PERPS_ERROR_CODES.PROVIDER_NOT_AVAILABLE) {
|
|
5957
|
+
subscriptionParams.callback(null);
|
|
5720
5958
|
}
|
|
5721
|
-
|
|
5722
|
-
}
|
|
5723
|
-
}
|
|
5959
|
+
throw error;
|
|
5960
|
+
}
|
|
5961
|
+
}, () => originalCallback(null));
|
|
5724
5962
|
}
|
|
5725
5963
|
catch (error) {
|
|
5726
5964
|
this.#logError(ensureError(error, 'PerpsController.subscribeToAccount'), this.#getErrorContext('subscribeToAccount', {
|