@metamask-previews/perps-controller 24.1.0-preview-e9ac9ffe1 → 24.1.0-preview-70269bbdb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/PerpsController-method-action-types.d.ts +26 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +20 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +159 -2
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +0 -6
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +0 -13
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +19 -3
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +21 -5
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/performanceMetrics.d.ts +2 -14
  18. package/dist/constants/performanceMetrics.d.ts.map +1 -1
  19. package/dist/constants/performanceMetrics.js +1 -17
  20. package/dist/constants/performanceMetrics.js.map +1 -1
  21. package/dist/constants/perpsConfig.d.ts +27 -0
  22. package/dist/constants/perpsConfig.d.ts.map +1 -1
  23. package/dist/constants/perpsConfig.js +27 -0
  24. package/dist/constants/perpsConfig.js.map +1 -1
  25. package/dist/index.d.ts +7 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +2 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +2 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/HyperLiquidProvider.d.ts +7 -3
  34. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  35. package/dist/providers/HyperLiquidProvider.js +161 -103
  36. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  37. package/dist/providers/LighterProvider.d.ts +3 -3
  38. package/dist/providers/LighterProvider.d.ts.map +1 -1
  39. package/dist/providers/LighterProvider.js +20 -9
  40. package/dist/providers/LighterProvider.js.map +1 -1
  41. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  42. package/dist/services/TerminalMarketService.js +4 -2
  43. package/dist/services/TerminalMarketService.js.map +1 -1
  44. package/dist/services/TradingService.js +11 -9
  45. package/dist/services/TradingService.js.map +1 -1
  46. package/dist/types/index.d.ts +107 -2
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/index.js +0 -1
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/advancedOrderLists.d.ts +104 -0
  51. package/dist/utils/advancedOrderLists.d.ts.map +1 -0
  52. package/dist/utils/advancedOrderLists.js +421 -0
  53. package/dist/utils/advancedOrderLists.js.map +1 -0
  54. package/dist/utils/advancedOrders.d.ts +275 -0
  55. package/dist/utils/advancedOrders.d.ts.map +1 -0
  56. package/dist/utils/advancedOrders.js +639 -0
  57. package/dist/utils/advancedOrders.js.map +1 -0
  58. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  59. package/dist/utils/hyperLiquidAdapter.js +4 -1
  60. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  61. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  62. package/dist/utils/hyperLiquidValidation.js +22 -57
  63. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  64. package/dist/utils/index.d.ts +2 -0
  65. package/dist/utils/index.d.ts.map +1 -1
  66. package/dist/utils/index.js +2 -0
  67. package/dist/utils/index.js.map +1 -1
  68. package/dist/utils/lighterScaleOrders.d.ts.map +1 -1
  69. package/dist/utils/lighterScaleOrders.js +16 -65
  70. package/dist/utils/lighterScaleOrders.js.map +1 -1
  71. package/dist/utils/perpsFormatters.d.ts +29 -4
  72. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  73. package/dist/utils/perpsFormatters.js +51 -5
  74. package/dist/utils/perpsFormatters.js.map +1 -1
  75. package/docs/README.md +28 -0
  76. package/docs/architecture.md +256 -0
  77. package/docs/contracts/events.md +267 -0
  78. package/docs/contracts/feature-flags.md +39 -0
  79. package/docs/contracts/traces.md +83 -0
  80. package/docs/formatting.md +82 -0
  81. package/docs/tpsl.md +89 -0
  82. package/docs/venues/hyperliquid/README.md +27 -0
  83. package/docs/venues/hyperliquid/init-flow.md +116 -0
  84. package/docs/venues/hyperliquid/order-types.md +60 -0
  85. package/docs/venues/hyperliquid/trading-rules.md +77 -0
  86. package/docs/venues/lighter/api-keys.md +58 -0
  87. package/docs/venues/lighter/capabilities.md +74 -0
  88. package/package.json +4 -3
@@ -0,0 +1,256 @@
1
+ # Perps controller architecture
2
+
3
+ `@metamask/perps-controller` (24.0.0) is the perpetual futures trading controller. It is published from Core and consumed by the MetaMask clients. Client UI, hooks, stream channels and connection timing stay in each client.
4
+
5
+ ## Layers
6
+
7
+ | Layer | What it owns |
8
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
9
+ | Venue | HyperLiquid and Lighter REST and WebSocket APIs. Lighter REST and WebSocket endpoints are Core constants; HyperLiquid REST and WebSocket hosts come from the SDK defaults for `isTestnet`. |
10
+ | Provider adapter | Exchange-specific implementation of the `PerpsProvider` interface, one per venue. Owns venue clients, subscriptions, signing, request formatting, response normalisation and its session caches. |
11
+ | Aggregation | `AggregatedPerpsProvider` wraps the registered providers behind the same `PerpsProvider` interface. |
12
+ | Controller | `PerpsController` extends `BaseController`. Owns the provider registry, active-provider choice, provider lifecycle, state, preload caches, services and the messenger actions. |
13
+ | Client | Implements `PerpsPlatformDependencies`, calls messenger actions, decides when to connect and disconnect. |
14
+
15
+ ```mermaid
16
+ graph TD
17
+ Deps[PerpsPlatformDependencies] -->|injected into| Controller[PerpsController]
18
+ Messenger[PerpsControllerMessenger] -->|actions and events| Controller
19
+ Controller -->|activeProvider aggregated| Agg[AggregatedPerpsProvider]
20
+ Controller -->|direct mode| HL[HyperLiquidProvider]
21
+ Controller -->|direct mode| LT[LighterProvider]
22
+ Agg --> HL
23
+ Agg --> LT
24
+ HL --> HLS[HyperLiquidClientService and HyperLiquidSubscriptionService]
25
+ LT --> LTS[LighterClientService]
26
+ HLS --> HLAPI[SDK default hosts for isTestnet]
27
+ LTS --> LTAPI[LIGHTER_ENDPOINTS]
28
+ ```
29
+
30
+ Code: `src/PerpsController.ts` `PerpsController`; `src/types/index.ts` `PerpsProvider`, `PerpsPlatformDependencies`; `src/providers/`; `src/services/HyperLiquidClientService.ts` `#createTransports`; `src/constants/lighterConfig.ts` `LIGHTER_ENDPOINTS`.
31
+
32
+ ## What the controller owns
33
+
34
+ | Concern | Where it lives |
35
+ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | Order, TP/SL, close and margin math | `src/utils/orderCalculations.ts`, `tpslCalculations.ts`, `closeCalculations.ts`, `marginAdjustment.ts`, `positionProtection.ts`; actions `calculateFees`, `calculateLiquidationPrice`, `calculateMaintenanceMargin` |
37
+ | Fee resolution | `src/services/RewardsIntegrationService.ts`, `src/utils/subscriptionFeeWaiver.ts` |
38
+ | Advanced orders (TWAP, chase, scale) | `src/utils/advancedOrders.ts` (rules from `getOrderCapabilities().strategyRules`, validation, previews, ladder sizing, price warnings), `advancedOrderLists.ts` (live lists); actions `subscribeToLiveTwapOrders`, `subscribeToChaseOrderLists` |
39
+ | Display formatting | `src/utils/perpsFormatters.ts`; locale number formatting injected as `marketDataFormatters` |
40
+ | Venue adapters and validation | `src/utils/hyperLiquidAdapter.ts`, `hyperLiquidOrderBookProcessor.ts`, `hyperLiquidValidation.ts`, `marketDataTransform.ts`, `marketUtils.ts`, `sortMarkets.ts`, `idUtils.ts`, `standaloneInfoClient.ts` |
41
+ | Request reliability | `src/utils/providerHealth.ts`, `coalescePerpsRestRequest.ts`, `guardedHyperLiquidClient.ts` |
42
+ | Constants | `src/constants/` (`perpsConfig.ts` `PERPS_CONSTANTS`, `hyperLiquidConfig.ts`, `lighterConfig.ts` and others) |
43
+ | Connection primitives | `PerpsController` `init`, `disconnect`, `reconnect`, `toggleTestnet`, `switchProvider` |
44
+ | State | `PerpsControllerState`, `getDefaultPerpsControllerState`; selectors in `src/selectors.ts` |
45
+ | Messenger events | `PerpsControllerEvents` |
46
+ | Analytics properties | `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`, `PERPS_EVENT_VALUE`; sent through the injected `metrics` |
47
+ | Errors | `src/perpsErrorCodes.ts`, `src/errors.ts` |
48
+
49
+ Code: `src/utils/`, `src/constants/`, `src/selectors.ts`, `src/PerpsController.ts` `PerpsControllerState`.
50
+
51
+ ## Providers
52
+
53
+ | Provider | Registered as | What it does |
54
+ | ------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
55
+ | `HyperLiquidProvider` | `hyperliquid`, always | HyperLiquid REST and WebSocket through `HyperLiquidClientService`, `HyperLiquidSubscriptionService`, `HyperLiquidWalletService` and `DexDiscoveryCacheManager`. Lifecycle methods are `initialize()`, `disconnect()`, `ping()` (default timeout `WebsocketPingTimeoutMs`, 5 s) and `reconnect()`; there is no `connect()`. |
56
+ | `LighterProvider` | `lighter`, when the gate below passes | zkLighter venue (POC). REST reads plus WebSocket market, account, position, order, fill, order-book and candle streams. Writes are signed by the client's `LighterSignerBridge` (Go/WASM signer). Shipped as the `./providers/lighter` subpath export. |
57
+ | `AggregatedPerpsProvider` | not registered; built as the active instance | List reads (positions, markets, orders, fills, funding and others) aggregate from every provider with `Promise.allSettled`; `getAccountState` and some other reads use the default provider. Writes route through `ProviderRouter` to `params.providerId` or the default provider. Price, position, order and fill subscriptions go through `SubscriptionMultiplexer` (prices with `merge`); account, OI cap, candle, order-book and TWAP subscriptions follow the default provider. `disconnect()` and `prepareTradingWallet()` visit every registered provider. Returned data carries `providerId`. |
58
+
59
+ ### Registration and active-provider choice
60
+
61
+ 1. `#performInitialization` disconnects every registered provider, clears the map, retires the standalone provider and calls `#createProviders`.
62
+ 2. `#createProviders` creates `HyperLiquidProvider`. When Lighter is enabled it loads `LighterProvider` through `providerCredentials.lighter.loadProvider` or a dynamic import, then `registerLighterProvider` adds it.
63
+ 3. Initialization waits for the Lighter registration and `ReconnectionCleanupDelayMs` (500 ms) together, re-runs `#migrateActiveProviderForMultiProviderIfNeeded`, then calls `#assignActiveProvider`.
64
+ 4. `#assignActiveProvider` picks the instance from `state.activeProvider`.
65
+
66
+ | `activeProvider` | Active instance |
67
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | `aggregated` | New `AggregatedPerpsProvider`; its default is `state.defaultProvider` when registered, else `hyperliquid` (the saved preference is kept) |
69
+ | `hyperliquid` | `HyperLiquidProvider` |
70
+ | any other value | That provider when registered; else `HyperLiquidProvider`, and `activeProvider` is rewritten to `hyperliquid` |
71
+
72
+ `activeProvider` defaults to `hyperliquid`. When the `perpsMultiProviderModeEnabled` remote flag is on, the migration moves a direct venue to `aggregated`, unless the user picked a provider explicitly. On the first migration that venue becomes `defaultProvider` when the user has not saved one. A flag set to disabled restores direct mode. `effectiveProvider` records the venue writes go to and is never restored from a persisted snapshot.
73
+
74
+ ### Routing helpers
75
+
76
+ | Helper | Job |
77
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
78
+ | `ProviderRouter` | Phase 1 routing. An explicit `providerId` wins, else the default provider. Only the `default_provider` strategy exists. |
79
+ | `isPerpsProviderType` | Accepts only `hyperliquid` and `lighter`. |
80
+ | `resolveTradeConfigProviderKey` | Picks the venue a trade configuration belongs to. Explicit route first, then `effectiveProvider`, then the direct provider or the aggregated default. Invalid state falls back to `hyperliquid`. |
81
+
82
+ ### Lighter enablement gate
83
+
84
+ `#isLighterProviderEnabled` returns true in two cases.
85
+
86
+ - The local override `providerCredentials.lighter.enabled` is set.
87
+ - The client passed `providerCredentials.lighter.signerBridge` and the remote `perpsLighterProviderEnabled` flag passes `featureFlags.validateVersionGated`.
88
+
89
+ Without a signer bridge the remote flag cannot register Lighter. A missing Lighter module logs at debug level; any other load failure goes to `logger.error`. `switchProvider('lighter')` returns the load error. `isProviderOnTestnet` keeps Lighter on testnet while `PROVIDER_CONFIG.LIGHTER_TESTNET_ONLY` is set (false at this commit).
90
+
91
+ Code: `src/PerpsController.ts` `#createProviders`, `registerLighterProvider`, `handleLighterImportError`, `#assignActiveProvider`, `#isLighterProviderEnabled`, `#migrateActiveProviderForMultiProviderIfNeeded`; `src/providers/`; `src/routing/`; `src/aggregation/SubscriptionMultiplexer.ts`; `src/services/providerNetwork.ts` `isProviderOnTestnet`.
92
+
93
+ ## Services
94
+
95
+ The controller creates `TradingService`, `MarketDataService`, `AccountService`, `EligibilityService`, `DataLakeService`, `DepositService`, `FeatureFlagConfigurationService` and `RewardsIntegrationService` with the platform dependencies (some also get the messenger). Venue services are created by their provider.
96
+
97
+ | File | Job |
98
+ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
99
+ | `AccountService` | Withdrawals and withdrawal validation; stateless, delegates to the provider |
100
+ | `accountSigner.ts` | Readiness checks for an injected main-account signer |
101
+ | `agentSigner.ts` | HyperLiquid agent bindings kept across provider instances (`AgentBindings`) |
102
+ | `AggregatedOrderBookConnection` | Dedicated HyperLiquid socket for the order-book panel's aggregated `l2Book` stream; opens on first subscriber, closes after the last |
103
+ | `causeChain.ts` | Matches an error anywhere in its `cause` chain |
104
+ | `DataLakeService` | Reports order events to the Data Lake API with exponential backoff and tracing |
105
+ | `DepositService` | Prepares and validates deposit transaction data; the controller owns the `TransactionController` call and confirmation |
106
+ | `DexDiscoveryCacheManager` | Single HIP-3 DEX discovery cache for every `perpDexs()` derivative |
107
+ | `EligibilityService` | Eligibility from `GeolocationController` geolocation and blocked regions |
108
+ | `environmentTypeProperty.ts` | Adds the optional UI surface to analytics properties |
109
+ | `FeatureFlagConfigurationService` | HIP-3 and geo-blocking config from remote flags; once remote config loads it never drops back to fallback |
110
+ | `HyperLiquidClientService` | HyperLiquid SDK client initialization, HTTP and WebSocket transports, client lifecycle |
111
+ | `HyperLiquidSubscriptionService` | HyperLiquid WebSocket subscriptions with reference counting; per DEX, `clearinghouseState` carries positions and account and `openOrders` carries orders; one `webData3` subscription carries OI caps for all DEXs |
112
+ | `HyperLiquidWalletService` | Wallet adapter and signing for the HyperLiquid SDK |
113
+ | `LighterChaseService` | Bounded Chase order ownership and serial cancel/replace |
114
+ | `LighterClientService` | zkLighter REST client on the platform `fetch`, no SDK; decodes every response |
115
+ | `lighterDispatchIdentity.ts` | Checks the signed Lighter tx hash and expiry; refuses submission without them |
116
+ | `LighterTwapService` | Durable native Lighter TWAP schedules |
117
+ | `LighterWalletService` | Routes the L1 signatures Lighter needs; the venue key stays in the client signer bridge |
118
+ | `MarketDataService` | Read-only fetches (markets, positions, orders, account state and more); writes state through `stateManager` when given; tries the Terminal API before the provider |
119
+ | `missingActionHandler.ts` | Detects the `Messenger.call` error for an unregistered or undelegated action |
120
+ | `providerNetwork.ts` | Whether a provider runs on testnet |
121
+ | `RewardsIntegrationService` | Unified fee resolver; lowest of `default`, `rewards`, `grant` and `subscription` |
122
+ | `ServiceContext.ts` | Per-call context type (tracing, error context, state callbacks) |
123
+ | `TerminalMarketService` | Market metadata from the MetaMask Terminal API, cached for `TERMINAL_API_CONFIG.CacheTtlMs`, and the schema-v4 global snapshot, cached until `receivedAt` plus the smaller of its `maxAgeMs` and 30 s |
124
+ | `TradingReadinessCache.ts` | Global signing cache (unified account, builder fee, referral) that survives provider recreation so hardware wallets are not prompted again |
125
+ | `TradingService` | Orders, cancels and positions with fee discounts; signals `cacheInvalidator` after changes |
126
+
127
+ Code: `src/services/`; `src/PerpsController.ts` constructor.
128
+
129
+ ## Platform dependencies
130
+
131
+ `PerpsPlatformDependencies` is passed as `infrastructure` to the constructor. Venue credentials and signer hooks come separately through `clientConfig.providerCredentials`.
132
+
133
+ | Member | Required | Job |
134
+ | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
135
+ | `logger` | yes | Error reporting (Sentry on Mobile) |
136
+ | `debugLogger` | yes | Development logging |
137
+ | `metrics` | yes | Analytics events |
138
+ | `performance` | yes | `now()` and the `onControllerConstructed` hook |
139
+ | `tracer` | yes | Trace spans |
140
+ | `streamManager` | yes | `pauseChannel`, `resumeChannel`, `clearAllChannels` on the client stream layer |
141
+ | `featureFlags` | yes | `validateVersionGated` against the app version |
142
+ | `marketDataFormatters` | yes | Volume, fiat and percentage formatting |
143
+ | `cacheInvalidator` | yes | Invalidates client standalone caches (`positions`, `accountState`, `markets`) |
144
+ | `diskCache` | yes | `getItem`, optional `getItemSync`, `setItem`, `removeItem` for cold-start persistence |
145
+ | `terminalApi` | no | `marketDataUrl` and `globalSnapshotUrl` |
146
+ | `terminalApiUrl` | no | Deprecated; use `terminalApi.marketDataUrl` |
147
+ | `terminalMarketService` | no | Custom Terminal market service; the controller builds `TerminalMarketService` when only URLs are given |
148
+ | `rewards` | yes | `getPerpsDiscountForAccount`, optional `getPerpsTradingFeeGrant` |
149
+ | `subscription` | no | `getPerpsBenefits`, optional `registerTradingAddress` |
150
+ | `accountSigner` | no | Main-account signer for clients without a `KeyringController` |
151
+
152
+ Code: `src/types/index.ts` `PerpsPlatformDependencies`, `PerpsCacheInvalidator`, `MarketDataFormatters`; `src/PerpsController.ts` `PerpsControllerOptions`.
153
+
154
+ ## Messenger surface
155
+
156
+ - 139 method actions named `PerpsController:<method>`, generated into `PerpsController-method-action-types.ts` from `MESSENGER_EXPOSED_METHODS`, plus `PerpsController:getState`. Handlers are registered on the first `init()`, not in the constructor.
157
+ - 3 own events: `stateChange`, `stateChanged` and `chaseOrderMaxDistanceReached`.
158
+ - 16 allowed external actions and 3 allowed external events (`RemoteFeatureFlagController:stateChange`, `AccountsController:selectedAccountChange`, `AccountTreeController:selectedAccountGroupChange`).
159
+
160
+ Code: `src/PerpsController-method-action-types.ts`; `src/PerpsController.ts` `MESSENGER_EXPOSED_METHODS`, `PerpsControllerEvents`, `PerpsControllerActions`; `src/types/messenger.ts` `PerpsControllerAllowedActions`, `PerpsControllerAllowedEvents`.
161
+
162
+ ## State, caches and persistence
163
+
164
+ | Cache | Holds | Key | Lifetime |
165
+ | --------------------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
166
+ | `cachedMarketDataByProvider` (state, not persisted) | REST market snapshot | `providerId:network` | Kept on disconnect. Read TTL 300 s unless `skipTTL`. Terminal global-snapshot entries stay valid until `sourceExpiresAt` with a matching HIP-3 version and DEX list. |
167
+ | `cachedUserDataByProvider` (state, not persisted) | Positions, orders, `accountState`, address | `providerId:network` | Kept on disconnect. Read TTL 60 s unless `skipTTL`. Reads return null when the stored address is not the selected EVM account; HyperLiquid entries also need the current HIP-3 version and DEX list. |
168
+ | Standalone `HyperLiquidProvider` | Provider for reads before `init()` | one instance | Recreated when `isTestnet` or `hip3ConfigVersion` changes; retired on init, `toggleTestnet`, `disconnect` and `stopMarketDataPreload` |
169
+ | `TradingReadinessCache` | Signing state and in-flight locks | `network:userAddress`; locks `operationType:network:userAddress` | Global singleton; clear methods exist but nothing in the package calls them |
170
+
171
+ `HyperLiquidProvider.disconnect()` clears the fee cache, referral and builder-fee checks, `#cachedMetaByDex`, `#cachedSpotMeta` and DEX discovery. It keeps `#maxLeverageCache` (TTL) and `#cachedMarketDataWithPrices` (last known-good markets). `#symbolToAssetId` is rebuilt on init.
172
+
173
+ ### Preload
174
+
175
+ - `startMarketDataPreload()` runs the market and user preloads in parallel at once, then every 5 minutes (`#preloadRefreshMs`).
176
+ - It re-runs both preloads when `isTestnet` or `hip3ConfigVersion` changes, and the user preload on `AccountsController:selectedAccountChange` and `AccountTreeController:selectedAccountGroupChange`.
177
+ - `#performMarketDataPreload` skips during reinitialization or when the entry is newer than `#preloadGuardMs` (30 s). It calls `getMarketDataWithPrices({ standalone: true })` and writes `cachedMarketDataByProvider[providerNetworkKey]`; aggregated mode writes one entry per provider plus an empty sentinel.
178
+ - `#performUserDataPreload` needs a selected EVM address. It skips when the matching entry is newer than 30 s, or exists while the WebSocket is connected. It writes `cachedUserDataByProvider[providerNetworkKey]`.
179
+ - `stopMarketDataPreload()` and `disconnect()` both stop the timer and its subscriptions. After a disconnect, preload restarts only when the client calls `startMarketDataPreload()` again.
180
+
181
+ ### Disk hydration
182
+
183
+ - The constructor calls `#hydrateCacheFromDiskSync`, which reads `diskCache.getItemSync`; without it hydration is a no-op.
184
+ - Keys are `PERPS_DISK_CACHE_MARKETS` and `PERPS_DISK_CACHE_USER_DATA` (value `PERPS_DISK_CACHE_USER_DATA_V2`). Each holds one entry or `{ entries: [...] }`.
185
+ - Prices are replaced with `$---`, `--` and `--%`.
186
+ - Hydrated timestamps are set older than 300 s, so only `skipTTL` reads return disk data.
187
+ - User entries are hydrated without an address check; the read-time address guard applies.
188
+ - After each preload the controller writes with `persistMarketEntriesToDisk` and `#persistUserCacheToDisk` (`persistUserEntriesToDisk`). Writes are best effort. `PERPS_DISK_CACHE_THROTTLE_MS` (30 s) is exported for client writers.
189
+
190
+ ### Account and network change
191
+
192
+ - Account change deletes nothing. The address guard makes the old entry unreadable and the user preload refreshes it under the same key. Registered rewards trading addresses are reset and the new address registers.
193
+ - A network toggle does not clear caches; mainnet and testnet use different keys.
194
+
195
+ Code: `src/PerpsController.ts` `cachedMarketDataByProvider`, `cachedUserDataByProvider`, `getCachedMarketDataForActiveProvider`, `getCachedUserDataForActiveProvider`, `#isUserCacheIdentityCurrent`, `#getOrCreateStandaloneProvider`, `startMarketDataPreload`, `#performMarketDataPreload`, `#performUserDataPreload`, `#hydrateCacheFromDiskSync`; `src/utils/perpsDiskPersistence.ts` `hydrateFromDiskSync`; `src/services/TradingReadinessCache.ts`; `src/providers/HyperLiquidProvider.ts` `disconnect`.
196
+
197
+ ## Connection
198
+
199
+ The controller provides the connect and disconnect primitives. The client decides when to call them. Mobile's connection manager and React providers are described in [`metamask-mobile/docs/perps/connection-architecture.md`](https://github.com/MetaMask/metamask-mobile/blob/main/docs/perps/connection-architecture.md).
200
+
201
+ | Event | What the controller does |
202
+ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
203
+ | `init()` | Waits for any disconnect or reinitialization in flight, reuses `#initializationPromise`, runs `#performInitialization`. Up to 3 attempts, with a 1 s then a 2 s wait between them. On final failure it sets `initializationState` to `Failed` and `initializationError`, then resolves without throwing. |
204
+ | Data call before init | `getActiveProvider()` throws `CLIENT_REINITIALIZING`, `CLIENT_NOT_INITIALIZED` or `PROVIDER_NOT_AVAILABLE`. `subscribeTo*` returns a no-op unsubscribe when no provider exists. |
205
+ | `reconnect()` | Delegates to `provider.reconnect()`. HyperLiquid rebuilds its socket through `HyperLiquidClientService` (up to 10 attempts); the SDK transport also retries 5 times. |
206
+ | `disconnect()` | Serialised. Stops the preload timer and subscriptions, waits for init or reinit in flight, disconnects the active provider, clears it and `effectiveProvider`, retires the standalone provider, resets `isInitialized`. State caches and the feature-flag subscription stay. |
207
+ | Network change (`toggleTestnet`) or provider change (`switchProvider`) | `#beginReinitialization` sets `isReinitializing`, the state flips, init runs again. Failure rolls back. When preload is running it re-runs for the new key. |
208
+ | Account change | No reinit. User preload refreshes and the rewards address re-registers. Reconnecting the provider for the new account is the client's call. |
209
+ | HIP-3 remote flag change | `FeatureFlagConfigurationService` bumps `hip3ConfigVersion` and the preload watcher re-preloads. Providers get the new HIP-3 config on the next `init()`. |
210
+
211
+ `PERPS_CONSTANTS` carries the default timings clients use, among them `ConnectionGracePeriodMs` (20 s), `ConnectionAttemptTimeoutMs` (30 s) and `ConnectRetryDelayMs` (200 ms). The controller does not read them; each client's connection owner does.
212
+
213
+ Code: `src/PerpsController.ts` `init`, `#performInitialization`, `#beginReinitialization`, `getActiveProvider`, `reconnect`, `disconnect`, `#performDisconnect`, `toggleTestnet`, `switchProvider`; `src/services/HyperLiquidClientService.ts` `reconnect`; `src/constants/hyperLiquidConfig.ts` `HYPERLIQUID_TRANSPORT_CONFIG`; `src/constants/perpsConfig.ts` `PERPS_CONSTANTS`.
214
+
215
+ ## What a client must do
216
+
217
+ Agreed for every client ([TAT-4656](https://consensyssoftware.atlassian.net/browse/TAT-4656)). Perps review checks each line on Mobile, Extension and Terminal. Bracketed values are the current constants.
218
+
219
+ - One owner per client decides when to call `init` and `disconnect`. Other components read state; they don't connect.
220
+ - Read connection timings from one config per client. It defaults to the `PERPS_CONSTANTS` timings (`ConnectionGracePeriodMs` 20 s, `ConnectionAttemptTimeoutMs` 30 s, `ConnectRetryDelayMs` 200 ms), and an override goes in that config, not in a local literal.
221
+ - On account change, reconnect the provider if the new account needs live data; the controller refreshes preload but does not reconnect.
222
+ - While `initializationState` is not ready, show the loading or failed state; don't call data methods.
223
+ - Every `subscribeTo*` call keeps its unsubscribe and calls it on teardown.
224
+
225
+ ## Balance contract on AccountState
226
+
227
+ Balance display must keep spendable balance, collateral and HyperLiquid account abstraction state apart. `AccountState` balance fields are USD decimal strings; `returnOnEquity` is a percentage. Any of them can be the `--` unavailable sentinel.
228
+
229
+ | Field | Meaning | HyperLiquid value |
230
+ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
231
+ | `totalBalance` | Equity on the venue, collateral plus unrealized PnL | `marginSummary.accountValue` + spot USDC − spot hold |
232
+ | `spendableBalance` | USD that can collateralize a new position now, with no transfer | Unified `withdrawable + freeSpotUSDC`; Standard `withdrawable` |
233
+ | `withdrawableBalance` | USD that can leave the venue to the external wallet | Unified `withdrawable + freeSpotUSDC`; Standard `withdrawable` |
234
+ | `marginUsed`, `unrealizedPnl`, `returnOnEquity` | Margin and PnL summary | |
235
+ | `crossMarginSummary` | Optional `accountValue`, `maintenanceMargin`, `marginUsed`, `notional` | Summed across DEXs |
236
+ | `spotCollateral` | Optional spot USDC counted as cross collateral; pass it to `calculateAccountSummary`. Absent while spot state or abstraction mode is unknown, or when the USDC balance is malformed | `'0'` for Standard (`disabled`, `default`); free spot USDC, `max(0, total - hold)`, for Unified and portfolio margin; `'0'` on Lighter |
237
+ | `subAccountBreakdown` | Optional per-sub-account balances | Main DEX and HIP-3 DEXs |
238
+ | `providerId` | Venue, set by the aggregator | |
239
+
240
+ Clients read `withdrawableBalance` without branching on provider; no client-side spot to perps sweep happens. `hyperLiquidModeFoldsSpot` folds spot into collateral for `unifiedAccount` and `portfolioMargin` only. An unknown mode does not fold.
241
+
242
+ Code: `src/types/index.ts` `AccountState`, `CrossMarginSummary`; `src/utils/hyperLiquidAdapter.ts` `adaptAccountStateFromSDK`; `src/utils/accountUtils.ts` `addSpotBalanceToAccountState`, `aggregateAccountStates`, `getCrossMarginSpotCollateral`; `src/types/hyperliquid-types.ts` `HyperLiquidAbstractionMode`, `hyperLiquidModeFoldsSpot`.
243
+
244
+ ## Errors
245
+
246
+ - `PERPS_ERROR_CODES` holds 104 stable codes returned to clients for translation. `isPerpsErrorCode` checks a value. Adding a code is a minor change, so clients need a catch-all.
247
+ - `PerpsControllerError` carries `errorCode` and optional `errorDetails`. `createPriceMovedError` and `createTpslLegReplaceUnsupportedError` build typed errors. The package entry exports only the detail types from this file.
248
+ - The controller and services log through the injected `logger`.
249
+
250
+ Code: `src/perpsErrorCodes.ts` `PERPS_ERROR_CODES`, `PerpsErrorCode`, `isPerpsErrorCode`; `src/errors.ts` `PerpsControllerError`, `PerpsErrorDetails`.
251
+
252
+ ## Package tests
253
+
254
+ `tests/public-api.test.ts` and `tests/capabilities-public-api.test.ts` cover the public API. `tests/e2e/` holds Lighter and advanced-order end-to-end tests.
255
+
256
+ Code: `tests/public-api.test.ts`, `tests/capabilities-public-api.test.ts`, `tests/e2e/`.