Skip to content

Commit 52520eb

Browse files
authored
feat(perps): always on socket connection (#27103)
## **Description** Replaces per-section \`PerpsConnectionProvider\` connect/disconnect calls with a single top-level \`PerpsAlwaysOnProvider\` mounted at the wallet root. **Problem**: Multiple \`PerpsConnectionProvider\` instances (Homepage, PerpsTabView, ActivityView, TrendingView, ExploreSearchScreen, UrlAutocomplete) each called \`connect()\`/\`disconnect()\`, creating reference-count races in \`PerpsConnectionManager\`. This caused intermittent bugs — positions not showing, 24h values missing — after long app backgrounding sessions. **Solution**: \`PerpsAlwaysOnProvider\` is the sole caller of \`PerpsConnectionManager.connect()\` and \`disconnect()\`. \`PerpsConnectionProvider\` is now a pure React context source — it polls singleton state and exposes it via \`PerpsConnectionContext\`, but never calls connect/disconnect itself. Key changes: - New \`PerpsAlwaysOnProvider\` — mounts once **inside** \`ErrorBoundary\` at \`Wallet/index.tsx\`, owns \`AppState\` listener, sole connect/disconnect owner - \`PerpsConnectionProvider\` stripped of all lifecycle management: removed \`manageLifecycle\` prop, \`isVisible\` prop, and the \`usePerpsConnectionLifecycle\` hook call - Deleted \`usePerpsConnectionLifecycle\` hook (its responsibilities moved to \`PerpsAlwaysOnProvider\`) - All section-level \`PerpsConnectionProvider\` instances kept as context sources (required by \`useContext(PerpsConnectionContext)\` consumers in \`sections.config.tsx\` et al.) - Restored \`PerpsConnectionProvider\` (context-only) in \`ExploreSearchScreen\`, \`UrlAutocomplete\`, and \`TrendingView\` \`SectionWrapper\` — these render \`useSectionData\` which reads \`PerpsConnectionContext\` - Removed visibility callback plumbing (\`onVisibilityChange\`, \`perpsVisibilityCallback\`) from \`WalletTokensTabView\` and \`PerpsTabViewWithProvider\` - Updated architecture docs ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: ## **Manual testing steps** \`\`\`gherkin Feature: Perps always-on connection Scenario: user backgrounds and foregrounds the app Given perps feature flag is enabled And user is on the Wallet screen When user opens the Perps tab Then positions and market data load correctly When user backgrounds the app for 30+ seconds And user foregrounds the app Then Perps data reconnects and loads correctly Scenario: user switches between tabs Given perps feature flag is enabled When user navigates between Wallet / Activity / Trending tabs Then perps data remains connected without errors And connectionRefCount stays at 1 Scenario: user switches accounts Given perps feature flag is enabled When user switches to a different account Then Perps data refreshes for the new account \`\`\` ## **Screenshots/Recordings** ### **Before** Multiple providers each managing lifecycle → reference-count races on background/foreground. ### **After** Single \`PerpsAlwaysOnProvider\` owns the lifecycle — \`connectionRefCount\` stays exactly 1. \`PerpsConnectionProvider\` is a context-only provider with no lifecycle responsibilities. ## **Pre-merge author checklist** - [ ] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile Coding Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [ ] I've completed the PR template to the best of my ability - [ ] I've included tests if applicable - [ ] I've documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [ ] I've applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes Perps WebSocket connection ownership from many screen-scoped providers to a single wallet-root lifecycle manager, which can impact reconnect behavior, resource usage, and perps data availability across the app. > > **Overview** > **Centralizes Perps WebSocket lifecycle management** by introducing `PerpsAlwaysOnProvider` (mounted at the `Wallet` root) as the *only* component that calls `PerpsConnectionManager.connect()`/`disconnect()`, driven by `AppState` background/foreground transitions with a delayed reconnect and error logging. > > `PerpsConnectionProvider` is simplified to a context/state wrapper only: it no longer takes `isVisible`, no longer unmounts children when hidden, and removes the `usePerpsConnectionLifecycle` hook entirely (hook + tests deleted, barrel export removed). Call sites (Perps tab, Activity perps transactions tab, homepage Perps section, Explore search, UrlAutocomplete, Trending sections) are updated to stop passing visibility props and to use `suppressErrorView` where needed. > > Tests and docs are updated to match the new always-on architecture, including new coverage for `PerpsAlwaysOnProvider` and adjusted `PerpsConnectionProvider` retry/error behavior. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1644485. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 8099e72 commit 52520eb

17 files changed

Lines changed: 535 additions & 1129 deletions

File tree

app/components/UI/Perps/Views/PerpsTabView/index.tsx

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
import React, { useEffect, useState } from 'react';
2-
import { NavigationProp, ParamListBase } from '@react-navigation/native';
1+
import React from 'react';
32
import { PerpsConnectionProvider } from '../../providers/PerpsConnectionProvider';
43
import { PerpsStreamProvider } from '../../providers/PerpsStreamManager';
5-
import { DevLogger } from '../../../../../core/SDKConnect/utils/DevLogger';
64
import PerpsTabView from './PerpsTabView';
75
import PerpsStreamBridge from '../../components/PerpsStreamBridge';
86
import { useSelector } from 'react-redux';
@@ -13,10 +11,7 @@ import { strings } from '../../../../../../locales/i18n';
1311
import { IconName } from '@metamask/design-system-react-native';
1412

1513
interface PerpsTabViewWithProviderProps {
16-
navigation?: NavigationProp<ParamListBase>;
1714
tabLabel?: string;
18-
isVisible?: boolean;
19-
onVisibilityChange?: (callback: (visible: boolean) => void) => void;
2015
}
2116

2217
const styles = StyleSheet.create({
@@ -26,32 +21,16 @@ const styles = StyleSheet.create({
2621
});
2722

2823
/**
29-
* PerpsTabView wrapped with both PerpsConnectionProvider and PerpsStreamProvider
30-
* This ensures the usePerpsConnection and usePerpsStream hooks work properly when used in the main wallet tab view
31-
* Visibility is managed internally with updates from parent via callback
24+
* PerpsTabView wrapped with PerpsConnectionProvider (context only) and PerpsStreamProvider.
25+
* Connection lifecycle is managed by the top-level PerpsAlwaysOnProvider.
3226
*/
33-
const PerpsTabViewWithProvider: React.FC<PerpsTabViewWithProviderProps> = (
34-
props,
35-
) => {
36-
const { isVisible: initialVisible = false, onVisibilityChange } = props;
37-
const [isVisible, setIsVisible] = useState(initialVisible);
27+
const PerpsTabViewWithProvider: React.FC<
28+
PerpsTabViewWithProviderProps
29+
> = () => {
3830
const isBasicFunctionalityEnabled = useSelector(
3931
selectBasicFunctionalityEnabled,
4032
);
4133

42-
// Register callback with parent
43-
useEffect(() => {
44-
if (onVisibilityChange) {
45-
onVisibilityChange((visible: boolean) => {
46-
DevLogger.log('PerpsTabView: Visibility updated via callback', {
47-
visible,
48-
timestamp: new Date().toISOString(),
49-
});
50-
setIsVisible(visible);
51-
});
52-
}
53-
}, [onVisibilityChange]);
54-
5534
if (!isBasicFunctionalityEnabled) {
5635
return (
5736
<View style={styles.container}>
@@ -64,7 +43,7 @@ const PerpsTabViewWithProvider: React.FC<PerpsTabViewWithProviderProps> = (
6443
}
6544

6645
return (
67-
<PerpsConnectionProvider isVisible={isVisible}>
46+
<PerpsConnectionProvider>
6847
<PerpsStreamProvider>
6948
<PerpsStreamBridge />
7049
<PerpsTabView />

app/components/UI/Perps/hooks/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ export { usePerpsSorting } from './usePerpsSorting';
1717
export { usePerpsNavigation } from './usePerpsNavigation';
1818

1919
// Connection management hooks
20-
export { usePerpsConnectionLifecycle } from './usePerpsConnectionLifecycle';
2120
export { usePerpsConnection } from './usePerpsConnection';
2221
export { useWebSocketHealthToast } from './useWebSocketHealthToast';
2322

0 commit comments

Comments
 (0)