Repository navigation
feat(perps-controller): shared stream channel manager and live subscriptions for every client - #11742
Conversation
|
@metamaskbot publish-preview |
|
The "Publish preview" workflow has been updated to a new version that uses OIDC for authentication. Please use the new workflow instead of this one. To trigger the new workflow, go to the Publish a preview build workflow, click "Run workflow", and enter |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
🛑 Files requiring codeowner reviewTo merge this PR, you'll need to get approvals from the following owners. @MetaMask/perps (53 files)
ℹ️ Files co-owned by
|
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
juanmigdr
left a comment
There was a problem hiding this comment.
VERDICT: APPROVE
COMMIT: 85b5080
Stream layer is coherent and its recovery, rebind and pause paths hold up on static trace. The asks below are non-blocking.
67205e853bd; head is 2cd622db98.
| Severity | file:line | Problem | Ask |
|---|---|---|---|
| packages/perps-controller/src/PerpsController.ts:4348 | subscribeToFeeRates ignores snapshot fills, so fills missed during a socket drop never refresh the rates (open Bugbot thread, no reply). |
Refresh on the first snapshot after a reopen. Add a test. | |
| packages/perps-controller/src/PerpsController.ts:1186 | MARKET_CHANGE_SETTLE_MS, FEE_CHANGE_SETTLE_MS and MAX_TIMEOUT_MS are file-local; MAX_TIMEOUT_MS is duplicated in HyperLiquidProvider.ts:1114. |
Move them to perpsConfig.ts and import. |
|
| PR | Merge state is DIRTY. | Rebase on main and re-run the package suite on the new head. | |
| 💬 Nit | packages/perps-controller/src/services/HyperLiquidClientService.ts:394 | Pong match is a substring test on every frame while a ping is pending. | Parse the frame and check channel === 'pong'. |
Details for agents
| Status | Item | Evidence or gap | Ask |
|---|---|---|---|
| Test execution | Static review only. The PR reports 169 files / 9207 passed at 67205e853bd; later commits (4e40e1a78a0, e55789ff19b, 342f76aae55, bb632813f21, up to 2cd622db98) are not covered by that figure. |
Show CI green on the final head. | |
| Mobile/Extension/Terminal compatibility | No client checkout read. Compatibility rests on the PR's consumption table; the BREAKING onReset change (no null/[]/unavailable on provider swap) was not checked against client code. |
Link the paired client PRs, or confirm the clients handle onReset. |
|
feeAmountUsd ?? 0 in estimateCrossLiquidation |
Unchanged from before (feeAmountUsd: 0); the PR now documents it, so omitting the fee is intentional. |
None. |
➖ Rules not applicable to this diff are recorded in artifacts/review-ledger.md.
…iptions for every client Every PerpsController subscribeTo* method now goes through one StreamChannelManager: a ref-counted channel per stream, provider, account, market and options, the last value replayed to late readers, per-reader throttling on one venue subscription, and a REST read only while the transport is down. Order book and public trade channels are reopened by the manager when the connection returns; a failed channel detaches so the next subscriber opens a fresh one. Adds subscriptions with initial values for fee rates, trading-agent validity, market metadata, margin adjustment limits and connection latency, and feeAmountUsd on estimateCrossLiquidation.
…arate order book sockets The shared stream channels now own reconnect and resubscribe: a failed source is reopened with a bounded backoff, moves stop every stale source before any starts, and a stopped source is never heard. Prices merge per symbol, fills replay their snapshot, and default-routed streams follow setDefaultProvider. Chase and TWAP lists, market metadata and fee rates read on venue pushes, not on timers. Books of one coin with different precision or cadence use separate sockets. Positions, orders, account, prices and open interest caps report a stream that cannot open.
…g through a failure One venue's failure in aggregated mode reopens only that venue, a failed source stays attached until it is reopened, and market metadata is read whole or not at all. Lighter reports retired markets and reads them afresh; chase lists catch fills missed while the stream was down.
…erps listed before it
…say when market meta reads afresh
…ce fills; say why a dropped DEX's feed is cleaned up
…when a later one throws
…e another registers
85b5080 to
769cf92
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 769cf92. Configure here.
|
Preview builds have been published. Learn how to use preview builds in other projects. Expand for full list of packages and versions. |
juanmigdr
left a comment
There was a problem hiding this comment.
VERDICT: REQUEST_CHANGES
COMMIT: 53b9b7d
Post-merge review: this PR merged as 05a942a before the review was done, so these items need a follow-up PR.
The stream layer holds up overall. Ref counting, generation guards, rebind ordering, pause nesting and timer cleanup all trace correctly, and every earlier-round fix is still in place at this head. Three problems block merge. A disconnect() that races an in-flight init can reopen every channel on the provider it then tears down. The new fee-rate stream can quietly publish base rates as if they were the account's own. The new agent-validity stream can keep reporting a broken agent while trading works.
| Severity | file:line | Problem | Ask |
|---|---|---|---|
| ❌ Major | packages/perps-controller/src/PerpsController.ts:8626 | A disconnect that races an in-flight init or re-init reopens every pending channel on the provider it then disconnects. The channels stay keyed to the dead provider and retry into errors. | Make #rebindStreams stop while a disconnect is pending, or move the channels back to pending before provider.disconnect(). |
| ❌ Major | packages/perps-controller/src/PerpsController.ts:4382 | The first fee-rate read uses the cache path. If the venue read fails there, the provider falls back to base rates with no onError and no retry, and the stream holds those rates until the next fill or context change. |
Make stream reads strict: reject instead of falling back, so onError and the backoff apply. |
| ❌ Major | packages/perps-controller/src/providers/HyperLiquidProvider.ts:2559 | Agent validity is refreshed only on set or clear, on a rejection and on expiry. An agent that getAgentSigner resolves later (after unlock or re-approval) never refreshes it. A failed client init or a failed getAgentSigner call ends at account_unknown with no onError, so nothing retries. |
Refresh subscribers when #resolveAgentSigner resolves a different agent, and report account_unknown failures through onError. |
| packages/perps-controller/src/services/StreamChannelManager.ts:720 | When getSnapshotAfterError replaces the snapshot, it drops readers' throttled or paused deliveries. A cleared snapshot also sets hasValue = false, so the next move skips onReset. |
Re-queue the replacement for each reader, and keep hasValue meaning "something was delivered". |
|
| packages/perps-controller/src/services/StreamChannelManager.ts:697 | After 5 attempts (31 s) a channel on a healthy socket never retries again and readers get no final signal. #start clears failed before the attempt's outcome is known, so a failure that lands after a reconnect is never reopened. |
Keep retrying at MaxDelayMs while readers exist, or send a distinct "gave up" error. Clear failed on the first delivery. |
|
| packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts:4990 | List readers get openInterest and volume24h from #marketDataCache even after the assetCtxs feed is released or was never restored, so they show frozen values as if live. |
Emit these fields only while the DEX feed is held, or make every price subscription hold the feed. | |
| packages/perps-controller/src/services/HyperLiquidClientService.ts:1021 | isConnectionTerminated() checks the transport that is current now. On reconnect() the old socket's asynchronous close checks the new transport, so trades and candles readers get a spurious onError and an extra retry. |
Check the transport the subscription was opened on. | |
| packages/perps-controller/src/PerpsController.ts:8785 | Every connection drop seeds positions and orders through the public getters. Those open trace spans, write state.lastError and call logger.error from a background read, and the PR gives no estimate of the span volume. |
Seed through an untraced read that leaves state alone, or record the per-drop span estimate. | |
| packages/perps-controller/src/PerpsController.ts:4376 | Each burst of fills forces a fresh venue userFees read for every open fee channel; a running TWAP or chase makes about one read per second. In aggregated mode the second venue's initial fills snapshot counts as a reconnect and triggers an extra read. |
Throttle refreshes driven by fills, and track the initial snapshot per providerId. |
Details for agents
| Status | Item | Evidence or gap | Ask |
|---|---|---|---|
| HyperLiquid chase change listeners | #notifyChaseChange does not wrap each listener in try/catch. One call is chained into #chaseTickQueue and another runs in a finally, so a listener that throws breaks the tick queue or replaces the cancel result. |
Wrap each listener call, as LighterChaseService does. |
|
| Market-change hold after a failed restore | #scheduleRestoreRetry reports a failed assetCtxs retry only to the prices:dex:* feed. The DEX stays in #marketChangeDexs, so listings there go unseen until the next reconnect. |
Report the failure to the marketChanges feed and drop the hold. |
|
| Market-meta stale mark | A fresh read that started before a change can clear that change's stale mark when it resolves (PerpsController.ts:4091). |
Clear the mark only if no change arrived after the read started. | |
| Multiplexer retry logging | Every per-venue retry calls logger.error, up to 6 errors per stream per episode, and the count resets on every reconnect. |
Log once per failure episode. | |
FILLS_REPLAY_LIMIT = 2000 |
Declared inline in PerpsController.ts:405; the PR already moved the other stream constants into perpsConfig.ts. |
Move it there too. | |
| Stale docstrings | subscribeToPublicTrades and subscribeToProviderHealth still tell callers to subscribe again after a provider change. |
Update them. | |
| Emit after unsubscribe | #emit loops over a copy of the readers without checking membership, so a reader that a sibling callback removed or moved can still receive the old value. |
Check channel.readers.has(reader) before delivering. |
|
| Terminal parity | mm-harness gives no references.terminal and MM_HARNESS_REF_TERMINAL is unset, yet Terminal pins this preview and is the main consumer of onReset, latency and agent validity. |
Link the Terminal PR, or paste its consumption evidence. | |
| Runtime | Static review only. The PR's vitest/CI results were not reproduced. | None. |
➖ 33 rules not applicable to this diff (client UI, navigation, Pro mode, MetaMetrics, signer, i18n); full ledger in the run artifacts: artifacts/review-ledger.md.
| #rebindStreams( | ||
| route: { defaultProvider?: PerpsProviderType; onStopped?: () => void } = {}, | ||
| ): void { | ||
| if (!this.getActiveProviderOrNull()) { |
There was a problem hiding this comment.
[must_fix] Disconnect racing an in-flight init reopens channels on the provider being torn down. #performDisconnect detaches channels to pending (:10089) and only then awaits #reinitializationOperationPromise / #initializationPromise (:10115-10138). When that pending operation succeeds it calls #rebindStreams() (:3063, or the release in #beginReinitialization at :2955). The only guard here is getActiveProviderOrNull(), so every pending channel opens venue subscriptions, plus the connection watch, on the new provider. provider.disconnect() then runs (:10143) and nothing moves the channels back to pending. They stay keyed to a dead provider with no onReset. Their sources fail and retry into PROVIDER_NOT_FOUND errors for about 31 s, until the next init(). This is the 'cleanup has no owner for in-flight setup' pattern. Ask: make #rebindStreams bail while #disconnectOperationPromise is set, or rebind to PENDING_PROVIDER_CHANNEL_ID again after the awaits and before provider.disconnect(). Add a test that holds init open, calls disconnect(), and then asserts that no source is opened on the disconnected provider.
| }, FEE_CHANGE_SETTLE_MS); | ||
| }, | ||
| }); | ||
| read(skipCache); |
There was a problem hiding this comment.
[must_fix] The fee-rate stream can publish base rates as the account's rates. The first open calls read(false). If the HyperLiquid fee cache is cold and userFees (or getUserAddressWithDefault) fails, HyperLiquidProvider.calculateFees sees mustRead === false and falls back to FEE_RATES (HyperLiquidProvider.ts:19229, :19274, :19446). The quote resolves, so onError never fires and the channel never retries. Nothing reads on a timer, so a VIP, staking or referral account shows undiscounted rates until its next fill, account switch or Rewards change. mustRead is also set after the address lookup, so even a skipCache read falls back when that lookup throws. Ask: add a strict mode for stream reads, separate from cache bypass and set before the address lookup, so a failed venue read rejects. Add a test that runs the provider fallback; today every fee-rate test mocks calculateFees.
| accountId ?? (await this.getCurrentAccountId()), | ||
| ); | ||
| account = { mainAddress, isTestnet: this.#clientService.isTestnetMode() }; | ||
| } catch { |
There was a problem hiding this comment.
[must_fix] Agent validity goes stale or ends at account_unknown. (1) Subscribers refresh only on setAgentSigner/clearAgentSigners, a venue rejection and the validUntil timer. When #resolveAgentSigner (:3144-3155) resolves a new agent through getAgentSigner, nobody is told. Unlock: the lock calls clearAgentSigners and getAgentSigner returns null, so the stream says no_agent; after unlock the next order signs with the agent, but the stream still says no_agent. Re-approval after rejected behaves the same way. The host contract (types/index.ts:1910-1918) asks for no call on unlock. (2) Here and at :2573-2578, a failed #ensureClientsInitialized or a getAgentSigner that throws becomes unknown/account_unknown with no onError. Only read_failed reaches the channel's retry, so nothing re-reads until an account switch. Ask: when #resolveAgentSigner stores an agent (or null) that differs from a subscriber's agentAddress for that account key, refresh those subscribers. Report the two account_unknown failure paths through onError. Cover both scenarios with tests.
| channel.last, | ||
| ...detail, | ||
| ); | ||
| if (replacement) { |
There was a problem hiding this comment.
[suggestion] A replacement snapshot drops readers' pending and held deliveries. In aggregated subscribeToOrders, HyperLiquid emits [h1], which is delivered. A throttled reader then queues [h1,h2] as pending. Lighter then reports ORDERS_STREAM_PAUSED, and getSnapshotAfterError (PerpsController.ts:9143) returns a replacement. This block clears held and every reader's pending, so [h1,h2] is never delivered while getStreamSnapshot returns it. A held post-cancel push during the cancelOrders pause is lost the same way. A cleared snapshot also sets hasValue = false, so the next account or provider move skips onReset even though readers still show the old orders. Ask: queue the replacement as each reader's pending or held value, and keep hasValue meaning 'readers were delivered something since the last move'.
| channel.attempts = 0; | ||
| } | ||
| channel.failed = true; | ||
| if ( |
There was a problem hiding this comment.
[suggestion] An exhausted retry budget leaves the channel silent on a healthy socket. After MaxAttempts (1+2+4+8+16 s) #fail only reports. Recovery then needs a reconnect, reopenAll, a rebind or a new reader. SubscriptionMultiplexer venue keys are unique, so no new reader ever arrives there. #start (:564) clears failed before the attempt's outcome is known: if the last attempt fails just after a reconnect, #onConnectionState has already skipped the channel. MaxDelayMs: 30000 can never be reached with 5 attempts. Ask: keep retrying at MaxDelayMs while readers exist, or emit a distinguishable 'gave up' error. Keep failed set until the first delivery.
| volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined, | ||
| // The per-DEX assetCtxs feed every price subscription keeps open caches | ||
| // these for every market, so list readers get them too. | ||
| openInterest: marketData?.openInterest, |
There was a problem hiding this comment.
[suggestion] List readers get frozen openInterest and volume24h. The comment says every price subscription keeps the per-DEX assetCtxs feed open, but subscribeToPrices opens it with incrementRefCount: includeMarketData (:2309-2316). A list reader stays after a detail screen (includeMarketData: true) closes; #cleanupAssetCtxsSubscription drops the feed but #marketDataCache keeps its entries, so each allMids tick re-emits stale values. A restore with only plain price readers does not reopen assetCtxs either. Before this PR those fields were undefined for list readers. Ask: emit the fields only while the DEX feed is installed, or hold the feed for every price subscription and restore it when there are price subscribers. Add a test for the release path.
| { | ||
| // A confirmed subscription the venue did not take back. | ||
| onError: (error) => { | ||
| if (!isUnsubscribed && !this.isConnectionTerminated()) { |
There was a problem hiding this comment.
[suggestion] The terminated-connection guard reads the replacement transport. isConnectionTerminated() checks the current #wsTransport. On reconnect(), #handleConnectionDrop closes the old transport and installs a new one synchronously (:1676-1693). The old socket's close event arrives asynchronously and fails the confirmed subscriptions, the guard checks the new socket and returns false, and every trades and candles reader gets onError plus an extra channel retry, although reopenOnReconnect already covers it. Ask: capture the subscription's transport at subscribe time and check its terminationSignal.
| { | ||
| read: async (): Promise<[Position[], boolean?] | undefined> => | ||
| params.accountId === undefined | ||
| ? [await this.getPositions(), params.includeSnapshotStatus] |
There was a problem hiding this comment.
[suggestion] Seed reads after each drop go through traced getters that write state. The positions and orders seed reads call getPositions() and getOpenOrders() on every Connected→down transition, and when a channel opens while the socket is down. Each one opens a trace span; a failed positions seed writes state.lastError and a successful one clears it; a failed orders seed calls logger.error. On HyperLiquid the default info client is the WebSocket one, so these reads will often fail exactly when they run. The Sentry rule for reconnect instrumentation asks for a span estimate, and the PR has none. Ask: seed through an untraced read that leaves state alone, or record the per-drop span volume and sampling.
| return; | ||
| } | ||
| // Fills come in bursts; one read after they settle covers them all. | ||
| settleTimer ??= setTimeout(() => { |
There was a problem hiding this comment.
[suggestion] Fills force fresh userFees reads at up to about 1/s per fee channel. Each fill burst schedules refresh() → read(true) with skipCache, bypassing the 5-minute fee cache; a running TWAP or chase fills steadily while an order form is open. In aggregated mode, hasReceivedFills is a single flag but the multiplexer delivers one initial snapshot per venue, so the second venue's baseline counts as a reconnect snapshot and triggers an extra fresh read on every open. Ask: throttle refreshes driven by fills, for example at most one fresh read per N seconds, and track the initial snapshot per providerId (the callback's third argument).

Summary
One stream layer for perps in
@metamask/perps-controller, so Mobile, Extension and Terminal stop polling.StreamChannelManager: everysubscribeTo*butsubscribeToConnectionStateandsubscribeToProviderHealthgoes through one ref-counted channel per (stream, provider, account, market, options). Later subscribers get the last value, each subscriber has its own throttle, and REST is read only to seed a channel or while the socket is down. Prices merge per symbol and fills queue, so a throttle or a replay drops nothing.initopens when init succeeds. On re-init, provider or default change and account switch, every stale channel stops before any of the new context opens. Readers keep their unsubscribe, getonReset, then the new data.subscribeToMarketMeta: margin tiers, delisting, max leverage and Cross support. Re-read when the venue's market push shows a listing, or a delisting that lasts a minute, with no client preload.subscribeToMarginAdjustmentLimits: HyperLiquid computes it from its live account and position streams.subscribeToConnectionLatency: round trip of the keepalive ping the HyperLiquid transport already sends.subscribeToFeeRates: taker and makercalculateFeesresults for an optionalamount, always for the selected account. Re-read past the cache (FeeCalculationParams.skipCache) on its fills, account switch,invalidateSubscriptionBenefitsand a grant's expiry.subscribeToTradingAgentValidity:valid/invalid/unknown/not_required. HyperLiquid readsextraAgentsonce, then pushes on agent set or cleared, venue rejection, account switch and one timeout atvalidUntil.estimateCrossLiquidationtakes an optionalfeeAmountUsd, andgetMarketsan optionalskipCacheandrequireComplete.#withStreamPausepauses Core's own channels: the latest value is kept and delivered once when the write ends.infrastructure.streamManageris still called for one release and is deprecated.getStreamSnapshot(stream, params)returns a channel's last value synchronously, foruseSyncExternalStore.resubscribeStreams()restarts every open venue subscription, for a socket that looks open but stopped delivering.Lighter has no margin limits, keepalive measurement or agent step here, so it reports
unavailable/provider, no latency andnot_required.Consumption per client
How each client consumes the five reads that are new in this layer, by today's code (Mobile
470f558798, Extension54976daace):subscribeToMarketMetausePerpsMarketData(agetMarketsread per symbol today)perps-cache.ts(perpsGetMarketstoday)subscribeToMarginAdjustmentLimitsusePerpsAdjustMarginData, which computes the limits in the client todayedit-margin-modal-content.tsx, which computes them withmarginUtils.tstodaysubscribeToConnectionLatencysubscribeToFeeRatesusePerpsOrderFees(takes an amount; acalculateFeesread today)usePerpsOrderFees(takes an amount;perpsCalculateFeestoday)subscribeToTradingAgentValidityNeither Mobile's nor Extension's
PerpsStreamManagerhas a channel for these five; the hooks named above subscribe directly. Their existing channels (prices, positions, orders, fills, account, open interest caps, order book, candles) are replaced by the same Core subscriptions in their own PRs. Their separate order book socket (AggregatedOrderBookConnection) is then not needed, sincesubscribeToOrderBookkeeps precisions apart; until then both can run side by side.Validation
npx vitest runinpackages/perps-controller(typecheck on, Node 22) at67205e853bd: 169 files, 9207 passed, 46 skipped (6 need Node 24)yarn build, oxlint, oxfmt, messenger action types, no new tsc errors over the suppressed baseline. The fullyarn lintruns in CI, green at that commit.HyperLiquidSubscriptionService.stream-owner.test.ts): account switch order, price merge, book transports, market changes, TWAP slice fills.PerpsController.stream-context.test.ts,stream-channel-manager.test.ts): a subscribe before init opens on init; re-init moves readers to the new provider; an account switch moves account streams (onReset, then new data) and leaves market streams alone; pause keeps the latest and flushes once, nested; snapshot equals the channel's last value;resubscribeStreamsreopens sources; symbol order shares one channel.How Mobile and Extension migrate
Mobile
@metamask/perps-controllerto the release with this PR.hooks/stream/usePerpsLive*hook as a thin binding:useSyncExternalStoreoverPerpsController.subscribeTo*, withgetStreamSnapshot(stream, params)as the snapshot, the hook's ownthrottleMsdefault and its existing filtering (hideTpSl, live PnL). Show loading ononReset.clearCachefan-out inPerpsConnectionManager. Core moves the channels.PerpsConnectionManager: hold no-opsubscribeTo*subscriptions (positions, orders, account, fills, oiCaps, all-markets prices) while in Perps.PerpsController.resubscribeStreams()on foreground resume of a zombie socket instead ofclearAllChannels.streamManagerinmobileInfrastructureas no-ops until Core removes the field.Mobile deletes: the channel classes in
providers/PerpsStreamManager.tsx(StreamChannel,PriceStreamChannel,OrderStreamChannel,PositionStreamChannel,FillStreamChannel,AccountStreamChannel,OICapStreamChannel,TopOfBookStreamChannel,FocusedPriceStreamChannel), theensureReadywait loop, pause/resume andclearAllChannelsplumbing increateStreamManagerAdapter,retryOrderStreams, and their tests.MarketDataChannelandCandleStreamChannelstay until the gaps below land.Mobile keeps: the
usePerpsLive*hooks as bindings,PerpsConnectionManagerand its providers (one connection owner), CUF and first-data telemetry in hook callbacks, the E2E controller mock, a small disk writer over Core channels, and optimistic order/TP-SL patches until Core has them.Extension
Core runs in the background;
perps-stream-bridge.tsforwards frames toui/providers/perps/PerpsStreamManager.ts.onResetas they are. It stops clearing and re-requesting on account or provider change.useSyncExternalStoreacross the process boundary. No throttle, account or reconnect logic there.streamManageris a no-op today, so it had no pause; it now gets Core's pause duringcancelOrders.Gaps Mobile relies on that this PR does not cover
getSnapshotForSymbol→ shardsubscribeToPricesper symbol (one channel per symbol, merged into the caller's callback).editOrder/updatePositionTPSL, orStreamChannelManager.update(key, fn).StreamChannelSource.reduce(last, next)plus a fills history view.fetchHistoricalCandlesprepend →reduceplusupdate, exposed asloadMoreCandles; key candles by symbol + interval.subscribeToMarketDataseeded fromgetCachedMarketDataForActiveProvider(), plusrefreshMarketData().StreamChannelSource.lingerMs.StreamChannelSource.initial()fromcachedUserDataByProvider, thengetUserDataSnapshot().onDelivery({ source }).flushThrottledDeliverieson confirmation →StreamChannelManager.flush(key).PublicTradecarries no venue order id, so a client can't tell whether fills sharing a tx hash belong to one order → add the order id (or a single-order flag) where the venue exposes it. Until then Terminal shows each fill on its own row.Status
Terminal pins this PR's preview package until the release ships. Mobile and Extension switch to the Core manager in their own PRs.
References
Note
High Risk
Large refactor of all live WebSocket subscriptions and breaking stream semantics on provider/account changes; touches trading data paths, fees, and multi-venue aggregation.
Overview
Introduces
StreamChannelManagerso almost everysubscribeTo*call shares one ref-counted venue subscription per parameter set, with per-subscriber throttling, last-value replay, bounded reopen on failure/reconnect, andonResetwhen provider or account context changes (replacing priornull/[]invalidation on provider swap).New streams:
subscribeToMarketMeta,subscribeToMarginAdjustmentLimits,subscribeToConnectionLatency,subscribeToFeeRates, andsubscribeToTradingAgentValidity, plus optional provider hooks for market and chase-order changes.getStreamSnapshotandresubscribeStreams()supportuseSyncExternalStoreand foreground “zombie socket” recovery.Behavior changes: TWAP and chase live lists are push/event-driven (
refreshIntervalMsremoved ); HyperLiquid prices add OI/volume, TWAP carries slice fills, order books isolate colliding precisions; aggregated mode reopens failed venues independently via multiplexer-owned managers.onErroris wired through more subscription params; Core now pauses its own channels during writes while deprecatingstreamManager.pauseChannel/resumeChannel.Breaking: Clients must handle
onResetinstead of trusting stale data after default-provider or aggregated provider changes.Reviewed by Cursor Bugbot for commit 53b9b7d. Bugbot is set up for automated code reviews on this repo. Configure here.