-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsHomeView.tsx
More file actions
1228 lines (1150 loc) · 42.7 KB
/
Copy pathPerpsHomeView.tsx
File metadata and controls
1228 lines (1150 loc) · 42.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, {
useCallback,
useState,
useRef,
useEffect,
useMemo,
} from 'react';
import { View, Modal, NativeScrollEvent } from 'react-native';
import { useSelector } from 'react-redux';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
useNavigation,
useRoute,
useFocusEffect,
type RouteProp,
} from '@react-navigation/native';
import {
Button,
ButtonVariant,
ButtonSize,
TextColor,
Box,
BoxFlexDirection,
HeaderStandardAnimated,
IconName,
useHeaderStandardAnimated,
SensitiveText,
SensitiveTextLength,
Tag,
TagSeverity,
Text,
TextVariant,
TitleHub,
} from '@metamask/design-system-react-native';
import { useStyles } from '../../../../../component-library/hooks';
import { strings } from '../../../../../../locales/i18n';
import {
formatPnl,
formatPercentage,
formatPerpsBalance,
} from '../../utils/formatUtils';
import Routes from '../../../../../constants/navigation/Routes';
import {
usePerpsHomeData,
usePerpsNavigation,
usePerpsMeasurement,
usePerpsHomeSectionTracking,
} from '../../hooks';
import { usePerpsHomeActions } from '../../hooks/usePerpsHomeActions';
import { usePerpsNetworkManagement } from '../../hooks/usePerpsNetworkManagement';
import PerpsBottomSheetTooltip from '../../components/PerpsBottomSheetTooltip';
import { BigNumber } from 'bignumber.js';
import { usePerpsLivePositions, usePerpsLiveAccount } from '../../hooks/stream';
import {
HOME_SCREEN_CONFIG,
LEARN_MORE_CONFIG,
SUPPORT_CONFIG,
FEEDBACK_CONFIG,
} from '../../constants/perpsConfig';
import {
selectPerpsFeedbackEnabledFlag,
selectPerpsServiceInterruptionBannerEnabledFlag,
selectPerpsProductsEnabledFlag,
selectPerpsTopMoversEnabledFlag,
selectPerpsRecentlyAddedEnabledFlag,
selectPerpsWatchlistEnabledFlag,
} from '../../selectors/featureFlags';
import { usePerpsCategories } from '../../hooks/usePerpsCategories';
import { selectPrivacyMode } from '../../../../../selectors/preferencesController';
import PerpsMarketBalanceActions from '../../components/PerpsMarketBalanceActions';
import PerpsCard from '../../components/PerpsCard';
import PerpsWatchlistMarkets from '../../components/PerpsWatchlistMarkets/PerpsWatchlistMarkets';
import PerpsMarketTypeSection from '../../components/PerpsMarketTypeSection';
import PerpsRecentActivityList from '../../components/PerpsRecentActivityList/PerpsRecentActivityList';
import PerpsHomeSection from '../../components/PerpsHomeSection';
import PerpsHomeSectionList from '../../components/PerpsHomeSectionList';
import PerpsRowSkeleton from '../../components/PerpsRowSkeleton';
import { usePerpsProvider } from '../../hooks/usePerpsProvider';
import {
selectPerpsNetwork,
selectPerpsWatchlistMarkets,
} from '../../selectors/perpsController';
import { PerpsProviderSelectorBadge } from '../../components/PerpsProviderSelector';
import WhatsHappeningSection from '../../../../UI/WhatsHappening';
import {
WhatsHappeningSource,
MAX_ITEMS_DISPLAYED,
} from '../../../../UI/WhatsHappening/constants';
import {
useWhatsHappening,
isWhatsHappeningSectionVisible,
} from '../../../../UI/WhatsHappening/hooks';
import { selectWhatsHappeningEnabled } from '../../../../../selectors/featureFlagController/whatsHappening';
import type { PerpsNavigationParamList } from '../../types/navigation';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import { useAnalytics } from '../../../../hooks/useAnalytics/useAnalytics';
import Reanimated, { SharedValue } from 'react-native-reanimated';
import { useDiscoveryScrollManager } from '../../../Predict/hooks/useDiscoveryScrollManager';
import styleSheet from './PerpsHomeView.styles';
import { TraceName } from '../../../../../util/trace';
import { buildPerpsCufStartTags } from '../../utils/perpsCufTrace';
import { PERPS_CUF_TAG, PERPS_CUF_VARIANT } from '../../constants/perpsCufTags';
import {
PERPS_EVENT_PROPERTY,
PERPS_EVENT_VALUE,
type PerpsMarketData,
} from '@metamask/perps-controller';
import { usePerpsEventTracking } from '../../hooks/usePerpsEventTracking';
import {
PerpsHomeViewSelectorsIDs,
PerpsMarketBalanceActionsSelectorsIDs,
} from '../../Perps.testIds';
import PerpsCloseAllPositionsView from '../PerpsCloseAllPositionsView/PerpsCloseAllPositionsView';
import PerpsCancelAllOrdersView from '../PerpsCancelAllOrdersView/PerpsCancelAllOrdersView';
import { BottomSheetRef } from '../../../../../component-library/components/BottomSheets/BottomSheet';
import PerpsNavigationCard, {
NavigationItem,
} from '../../components/PerpsNavigationCard/PerpsNavigationCard';
import PerpsServiceInterruptionBanner from '../../components/PerpsServiceInterruptionBanner';
import PerpsCompetitionBanner from '../../components/PerpsCompetitionBanner';
import PerpsProducts from '../../components/PerpsProducts';
import PerpsTopMoversSection from '../../components/PerpsTopMoversSection';
import PerpsRecentlyAddedSection from '../../components/PerpsRecentlyAddedSection';
import {
isPerpsTopMoversSectionVisible,
usePerpsTopMovers,
} from '../../hooks/usePerpsTopMovers';
interface PerpsHomeViewProps {
hideHeader?: boolean;
walletHeaderTranslateY?: SharedValue<number>;
walletHeaderHeight?: number;
/** Ref populated with this tab's onTabEnter so the parent can call it on tab switch. */
tabEnterCallbackRef?: React.MutableRefObject<(() => void) | null>;
/** Forwarded to useDiscoveryScrollManager to sync icon animations with header hide/show. */
onHeaderHiddenChange?: (hidden: boolean) => void;
/**
* Top padding applied inside the scroll content container when embedded in
* HomepageDiscoveryTabs — keeps the perps background flush under the discovery
* tab bar and adds spacing before the screen title (32px in discovery tabs).
*/
topInset?: number;
}
const PerpsHomeView = ({
hideHeader = false,
walletHeaderTranslateY,
walletHeaderHeight = 0,
tabEnterCallbackRef,
onHeaderHiddenChange,
topInset = 0,
}: PerpsHomeViewProps) => {
const { styles } = useStyles(styleSheet, {});
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const route =
useRoute<RouteProp<PerpsNavigationParamList, 'PerpsMarketListView'>>();
const transactionActiveAbTests = route.params?.transactionActiveAbTests;
const { trackEvent, createEventBuilder } = useAnalytics();
// Feature flags
const isFeedbackEnabled = useSelector(selectPerpsFeedbackEnabledFlag);
const isServiceInterruptionBannerEnabled = useSelector(
selectPerpsServiceInterruptionBannerEnabledFlag,
);
const privacyMode = useSelector(selectPrivacyMode);
const isWhatsHappeningEnabled = useSelector(selectWhatsHappeningEnabled);
const isProductsEnabled = useSelector(selectPerpsProductsEnabledFlag);
const isTopMoversEnabled = useSelector(selectPerpsTopMoversEnabledFlag);
const isRecentlyAddedEnabled = useSelector(
selectPerpsRecentlyAddedEnabledFlag,
);
const isWatchlistEnabled = useSelector(selectPerpsWatchlistEnabledFlag);
// Mirrors PerpsProducts' own visibility check (enabled + has categories).
const productCategories = usePerpsCategories();
const topMoversFeed = usePerpsTopMovers({
direction: 'desc',
enabled: isTopMoversEnabled,
});
const isTopMoversVisible =
isTopMoversEnabled &&
isPerpsTopMoversSectionVisible({
isLoading: topMoversFeed.isLoading,
data: topMoversFeed.data,
});
const whatsHappeningFeed = useWhatsHappening(MAX_ITEMS_DISPLAYED);
const isWhatsHappeningVisible =
isWhatsHappeningEnabled &&
isWhatsHappeningSectionVisible({
isLoading: whatsHappeningFeed.isLoading,
items: whatsHappeningFeed.items,
error: whatsHappeningFeed.error,
});
// Use centralized navigation hook
const perpsNavigation = usePerpsNavigation();
const { ensureArbitrumNetworkExists } = usePerpsNetworkManagement();
// Ensure Arbitrum network exists when user lands on the main perps screen (not on button click)
useFocusEffect(
useCallback(() => {
ensureArbitrumNetworkExists().catch(() => {
// Error already logged in usePerpsNetworkManagement
});
}, [ensureArbitrumNetworkExists]),
);
// Bottom sheet state and refs
const [showCloseAllSheet, setShowCloseAllSheet] = useState(false);
const [showCancelAllSheet, setShowCancelAllSheet] = useState(false);
const closeAllSheetRef = useRef<BottomSheetRef>(null);
const cancelAllSheetRef = useRef<BottomSheetRef>(null);
// Use hook for eligibility checks and action handlers
// Pass button location for tracking deposit entry point
const {
handleAddFunds,
handleWithdraw,
isEligible,
isEligibilityModalVisible,
closeEligibilityModal,
} = usePerpsHomeActions({
buttonLocation: PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
});
// Separate geo-block modal state for close all / cancel all actions
const [isCloseAllGeoBlockVisible, setIsCloseAllGeoBlockVisible] =
useState(false);
const { track } = usePerpsEventTracking();
// Section scroll tracking for analytics
const { handleSectionLayout, handleScroll, resetTracking } =
usePerpsHomeSectionTracking();
// Bridge analytics handler into the Reanimated worklet via onScrollEvent
const handleScrollEvent = useCallback(
(scrollY: number, viewportHeight: number) => {
handleScroll({
nativeEvent: {
contentOffset: { x: 0, y: scrollY },
layoutMeasurement: { width: 0, height: viewportHeight },
} as NativeScrollEvent,
});
},
[handleScroll],
);
const {
scrollY: headerScrollY,
setTitleSectionHeight,
titleSectionHeightSv,
} = useHeaderStandardAnimated();
const perpsScreenTitle = strings('perps.title');
const { scrollHandler: perpsScrollHandler, onTabEnter: perpsOnTabEnter } =
useDiscoveryScrollManager({
walletHeaderHeight,
walletHeaderTranslateY,
scrollY: hideHeader ? undefined : headerScrollY,
onScrollEvent: handleScrollEvent,
onHeaderHiddenChange,
});
// Expose onTabEnter to the parent so it can restore this tab's header state on switch.
useEffect(() => {
if (tabEnterCallbackRef) {
tabEnterCallbackRef.current = perpsOnTabEnter;
return () => {
tabEnterCallbackRef.current = null;
};
}
return undefined;
}, [tabEnterCallbackRef, perpsOnTabEnter]);
// Get balance state directly from Redux
const { account: perpsAccount } = usePerpsLiveAccount({ throttleMs: 1000 });
const totalBalance = perpsAccount?.totalBalance || '0';
const spendableBalance = perpsAccount?.spendableBalance || '0';
const totalBn = BigNumber(totalBalance);
const isBalanceEmpty = !totalBn.isFinite() || totalBn.isZero();
const network = useSelector(selectPerpsNetwork);
const isTestnet = network === 'testnet';
const { isMultiProviderEnabled } = usePerpsProvider();
// Calculate P&L for positions subtitle
const unrealizedPnl = perpsAccount?.unrealizedPnl || '0';
const roe = parseFloat(perpsAccount?.returnOnEquity || '0');
// Fetch all home screen data
const {
positions,
orders,
watchlistMarkets,
suggestedWatchlistMarkets,
perpsMarkets, // Crypto markets (renamed from trendingMarkets)
commoditiesMarkets, // Commodity markets
stocksMarkets, // Equity markets only
forexMarkets,
recentlyAddedMarkets,
hasMarkets,
recentActivity,
sortBy,
isLoading,
} = usePerpsHomeData({});
// Independently gates the section from the Terminal backend flag that
// supplies `listedAt` data, so it can be hidden even when that data flows.
const isRecentlyAddedVisible =
isRecentlyAddedEnabled && recentlyAddedMarkets.length > 0;
// Mirrors PerpsWatchlistMarkets V1/V2 gating: suggestions only count toward
// section visibility when the redesigned watchlist flag is on.
const isWatchlistVisible =
isLoading.markets ||
watchlistMarkets.length > 0 ||
(isWatchlistEnabled && (suggestedWatchlistMarkets?.length ?? 0) > 0);
// Calculate positions subtitle with P&L
const hasPositions = positions.length > 0;
const { positionsSubtitle, positionsSubtitleColor, positionsSubtitleSuffix } =
useMemo(() => {
const pnlNum = parseFloat(unrealizedPnl);
// Open (filled) positions only — hide when flat so spacing matches homepage sections
if (!hasPositions) {
return {
positionsSubtitle: undefined,
positionsSubtitleColor: undefined,
positionsSubtitleSuffix: undefined,
};
}
const color =
pnlNum > 0
? TextColor.SuccessDefault
: pnlNum < 0
? TextColor.ErrorDefault
: TextColor.TextDefault;
const subtitle = `${formatPnl(pnlNum)} (${formatPercentage(roe, 1)})`;
const suffix = strings('perps.unrealized_pnl');
return {
positionsSubtitle: subtitle,
positionsSubtitleColor: color,
positionsSubtitleSuffix: suffix,
};
}, [hasPositions, unrealizedPnl, roe]);
// Determine if any data is loading for initial load tracking
// Orders and activity load via WebSocket instantly, only track positions and markets
const isAnyLoading = isLoading.positions || isLoading.markets;
// Performance tracking: Measure screen load time until data is displayed
usePerpsMeasurement({
traceName: TraceName.PerpsMarketListView, // Keep same trace name for consistency
conditions: [!isAnyLoading],
});
const entryCufVariant = hasPositions
? PERPS_CUF_VARIANT.POSITION
: PERPS_CUF_VARIANT.EMPTY;
const entryCufEndData = {
[PERPS_CUF_TAG.VARIANT]:
orders.length > 0 ? PERPS_CUF_VARIANT.ORDER : entryCufVariant,
};
// Entry CUF: enter Perps -> live market list. Starts at mount; launch-context
// tag splits cold from warm p75. Captured at mount so the tag is the launch
// context, not the post-settle value.
const entryCufTags = useMemo(() => buildPerpsCufStartTags(), []);
usePerpsMeasurement({
traceName: TraceName.PerpsEntryToLiveMarketList,
// endConditions (not the simple `conditions` API): this span must measure
// mount -> live data. The simple API auto-resets whenever its first
// condition is false, which for a readiness flag means the span restarts on
// every render during loading and under-reports the true latency. Using
// endConditions starts at mount and never resets.
// The variant endData reads orders.length, so — unlike the screen-load
// metric above, which deliberately ignores orders for speed — this span
// must wait for the orders stream too, or a user with open orders is
// misrecorded as empty/position.
endConditions: [!isAnyLoading, !isLoading.orders],
tags: entryCufTags,
endData: entryCufEndData,
});
// Reset section tracking when screen comes into focus
// This ensures sections can be tracked again when navigating back to the screen
useFocusEffect(
useCallback(() => {
resetTracking();
}, [resetTracking]),
);
// Track home screen viewed event
const source =
route.params?.source || PERPS_EVENT_VALUE.SOURCE.MAIN_ACTION_BUTTON;
// Get perp balance status for tracking
const livePositions = usePerpsLivePositions({ throttleMs: 5000 });
const hasPerpBalance =
livePositions.positions.length > 0 ||
(!!perpsAccount?.totalBalance && parseFloat(perpsAccount.totalBalance) > 0);
// Extract button_clicked and button_location from route params
const buttonClicked = route.params?.button_clicked;
const buttonLocation = route.params?.button_location;
// Raw watchlist symbols for analytics (unfiltered/uncapped list)
const rawWatchlistSymbols = useSelector(selectPerpsWatchlistMarkets);
// Build the ordered list of visible section names for sections_displayed.
// Each condition mirrors the matching section component's own render gating
// (content OR loading skeleton), so the array reflects what the user actually
// sees and stays consistent with per-section scroll impressions.
const sectionsDisplayed = useMemo(() => {
const sections: string[] = [PERPS_EVENT_VALUE.SECTION_NAME.BALANCE];
// Positions/orders render a skeleton while loading, then self-hide when empty.
if (isLoading.positions || positions.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.POSITIONS);
if (isLoading.orders || orders.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.ORDERS);
if (isWhatsHappeningVisible)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.WHATS_HAPPENING);
if (isWatchlistVisible) {
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.WATCHLIST);
}
// Products self-hides when disabled or when no categories are available.
if (isProductsEnabled && productCategories.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.PRODUCTS);
// Top Movers self-hides when its feed finishes empty; mirror that here so
// PerpsHomeSectionList does not render an orphan divider.
if (isTopMoversVisible)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.TOP_MOVERS);
// Explore category lists render a skeleton while markets load, then self-hide
// when their own market array is empty.
if (isLoading.markets || perpsMarkets.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_CRYPTO);
if (isLoading.markets || commoditiesMarkets.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_COMMODITIES);
if (isLoading.markets || stocksMarkets.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_STOCKS);
if (isLoading.markets || forexMarkets.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_FOREX);
// Recently Added self-hides when there are no markets listed in the last
// 30 days, or when the feature flag is off.
if (isRecentlyAddedVisible) sections.push('recently_added');
// Recent activity shows a skeleton while loading, then self-hides when empty.
if (isLoading.activity || recentActivity.length > 0)
sections.push(PERPS_EVENT_VALUE.SECTION_NAME.RECENT_ACTIVITY);
return sections;
}, [
isLoading,
positions,
orders,
isWhatsHappeningVisible,
isWatchlistVisible,
isProductsEnabled,
productCategories,
isTopMoversVisible,
isRecentlyAddedVisible,
perpsMarkets,
commoditiesMarkets,
stocksMarkets,
forexMarkets,
recentActivity,
]);
usePerpsEventTracking({
eventName: MetaMetricsEvents.PERPS_SCREEN_VIEWED,
conditions: [!isAnyLoading],
properties: {
[PERPS_EVENT_PROPERTY.SCREEN_TYPE]:
PERPS_EVENT_VALUE.SCREEN_TYPE.PERPS_HOME,
[PERPS_EVENT_PROPERTY.SOURCE]: source,
[PERPS_EVENT_PROPERTY.HAS_PERP_BALANCE]: hasPerpBalance,
[PERPS_EVENT_PROPERTY.OPEN_POSITION]: livePositions.positions.length,
[PERPS_EVENT_PROPERTY.OPEN_ORDER]: orders?.length || 0,
[PERPS_EVENT_PROPERTY.OUTAGE_BANNER_SHOWN]:
isServiceInterruptionBannerEnabled,
[PERPS_EVENT_PROPERTY.SECTIONS_DISPLAYED]: sectionsDisplayed,
[PERPS_EVENT_PROPERTY.WATCHLIST_COUNT]: rawWatchlistSymbols.length,
[PERPS_EVENT_PROPERTY.WATCHLIST_MARKETS]: rawWatchlistSymbols,
...(buttonClicked && {
[PERPS_EVENT_PROPERTY.BUTTON_CLICKED]: buttonClicked,
}),
...(buttonLocation && {
[PERPS_EVENT_PROPERTY.BUTTON_LOCATION]: buttonLocation,
}),
},
});
const handleSearchToggle = useCallback(() => {
// Track button click
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PERPS_EVENT_PROPERTY.INTERACTION_TYPE]:
PERPS_EVENT_VALUE.INTERACTION_TYPE.BUTTON_CLICKED,
[PERPS_EVENT_PROPERTY.BUTTON_CLICKED]:
PERPS_EVENT_VALUE.BUTTON_CLICKED.MAGNIFYING_GLASS,
[PERPS_EVENT_PROPERTY.BUTTON_LOCATION]:
PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
perpsNavigation.navigateToMarketList({
defaultMarketTypeFilter: 'all',
source: PERPS_EVENT_VALUE.SOURCE.PERPS_HOME,
fromHome: true,
button_clicked: PERPS_EVENT_VALUE.BUTTON_CLICKED.MAGNIFYING_GLASS,
button_location: PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
...(transactionActiveAbTests?.length ? { transactionActiveAbTests } : {}),
});
}, [
perpsNavigation,
trackEvent,
createEventBuilder,
transactionActiveAbTests,
]);
const handleWhatsHappeningHeaderPress = useCallback(() => {
track(MetaMetricsEvents.PERPS_UI_INTERACTION, {
[PERPS_EVENT_PROPERTY.INTERACTION_TYPE]:
PERPS_EVENT_VALUE.INTERACTION_TYPE.BUTTON_CLICKED,
[PERPS_EVENT_PROPERTY.BUTTON_CLICKED]:
PERPS_EVENT_VALUE.BUTTON_CLICKED.WHATS_HAPPENING,
[PERPS_EVENT_PROPERTY.BUTTON_LOCATION]:
PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
});
}, [track]);
const handleRecentlyAddedMarketPress = useCallback(
(market: PerpsMarketData) => {
perpsNavigation.navigateToMarketDetails(
market,
PERPS_EVENT_VALUE.SOURCE.PERPS_HOME,
);
},
[perpsNavigation],
);
const handleRecentlyAddedHeaderPress = useCallback(() => {
perpsNavigation.navigateToMarketList({
defaultMarketTypeFilter: 'new',
source: PERPS_EVENT_VALUE.SOURCE.PERPS_HOME,
...(transactionActiveAbTests?.length ? { transactionActiveAbTests } : {}),
});
}, [perpsNavigation, transactionActiveAbTests]);
const navigtateToTutorial = useCallback(() => {
// Track tutorial button click
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PERPS_EVENT_PROPERTY.INTERACTION_TYPE]:
PERPS_EVENT_VALUE.INTERACTION_TYPE.BUTTON_CLICKED,
[PERPS_EVENT_PROPERTY.BUTTON_CLICKED]:
PERPS_EVENT_VALUE.BUTTON_CLICKED.TUTORIAL,
[PERPS_EVENT_PROPERTY.BUTTON_LOCATION]:
PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
navigation.navigate(Routes.PERPS.TUTORIAL, {
source: PERPS_EVENT_VALUE.SOURCE.PERPS_HOME,
});
}, [navigation, trackEvent, createEventBuilder]);
const navigateToContactSupport = useCallback(() => {
navigation.navigate(Routes.WEBVIEW.MAIN, {
screen: Routes.WEBVIEW.SIMPLE,
params: {
url: SUPPORT_CONFIG.Url,
title: strings(SUPPORT_CONFIG.TitleKey),
},
});
// Track contact support interaction for Perps analytics
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PERPS_EVENT_PROPERTY.INTERACTION_TYPE]:
PERPS_EVENT_VALUE.INTERACTION_TYPE.CONTACT_SUPPORT,
[PERPS_EVENT_PROPERTY.LOCATION]:
PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
// Also track the general navigation event
trackEvent(
createEventBuilder(MetaMetricsEvents.NAVIGATION_TAPS_GET_HELP).build(),
);
}, [createEventBuilder, navigation, trackEvent]);
const handleGiveFeedback = useCallback(() => {
// Track feedback button click
trackEvent(
createEventBuilder(MetaMetricsEvents.PERPS_UI_INTERACTION)
.addProperties({
[PERPS_EVENT_PROPERTY.INTERACTION_TYPE]:
PERPS_EVENT_VALUE.INTERACTION_TYPE.BUTTON_CLICKED,
[PERPS_EVENT_PROPERTY.BUTTON_CLICKED]:
PERPS_EVENT_VALUE.BUTTON_CLICKED.GIVE_FEEDBACK,
[PERPS_EVENT_PROPERTY.BUTTON_LOCATION]:
PERPS_EVENT_VALUE.BUTTON_LOCATION.PERPS_HOME,
})
.build(),
);
// Open survey in in-app browser (same pattern as Contact Support)
navigation.navigate(Routes.WEBVIEW.MAIN, {
screen: Routes.WEBVIEW.SIMPLE,
params: {
url: FEEDBACK_CONFIG.Url,
title: strings(FEEDBACK_CONFIG.TitleKey),
},
});
}, [trackEvent, createEventBuilder, navigation]);
const navigationItems: NavigationItem[] = useMemo(() => {
const items: NavigationItem[] = [
{
label: strings(SUPPORT_CONFIG.TitleKey),
onPress: () => navigateToContactSupport(),
testID: PerpsHomeViewSelectorsIDs.SUPPORT_BUTTON,
},
];
// Add feedback button when feature flag is enabled
if (isFeedbackEnabled) {
items.push({
label: strings(FEEDBACK_CONFIG.TitleKey),
onPress: handleGiveFeedback,
testID: PerpsHomeViewSelectorsIDs.FEEDBACK_BUTTON,
});
}
items.push({
label: strings(LEARN_MORE_CONFIG.TitleKey),
onPress: () => navigtateToTutorial(),
testID: PerpsHomeViewSelectorsIDs.LEARN_MORE_BUTTON,
});
return items;
}, [
navigateToContactSupport,
navigtateToTutorial,
isFeedbackEnabled,
handleGiveFeedback,
]);
// Bottom sheet handlers - open sheets directly with geo-restriction check
const handleCloseAllPress = useCallback(() => {
// Geo-restriction check for close all positions
if (!isEligible) {
track(MetaMetricsEvents.PERPS_SCREEN_VIEWED, {
[PERPS_EVENT_PROPERTY.SCREEN_TYPE]:
PERPS_EVENT_VALUE.SCREEN_TYPE.GEO_BLOCK_NOTIF,
[PERPS_EVENT_PROPERTY.SOURCE]:
PERPS_EVENT_VALUE.SOURCE.CLOSE_ALL_POSITIONS_BUTTON,
});
setIsCloseAllGeoBlockVisible(true);
return;
}
setShowCloseAllSheet(true);
}, [isEligible, track]);
const handleCancelAllPress = useCallback(() => {
setShowCancelAllSheet(true);
}, []);
const handleWatchlistSeeAllPress = useCallback(() => {
perpsNavigation.navigateToMarketList({
showWatchlistOnly: true,
source: PERPS_EVENT_VALUE.SOURCE.PERPS_HOME,
});
}, [perpsNavigation]);
const homeSections = useMemo(
() => [
{
key: 'positions',
visible: isLoading.positions || positions.length > 0,
onLayout: handleSectionLayout(PERPS_EVENT_VALUE.SECTION_NAME.POSITIONS),
content: (
<PerpsHomeSection
title={strings('perps.home.positions')}
subtitle={privacyMode ? undefined : positionsSubtitle}
subtitleColor={positionsSubtitleColor}
subtitleSuffix={privacyMode ? undefined : positionsSubtitleSuffix}
subtitleTestID={PerpsHomeViewSelectorsIDs.POSITIONS_PNL_VALUE}
isLoading={isLoading.positions}
isEmpty={positions.length === 0}
showWhenEmpty={false}
onActionPress={handleCloseAllPress}
renderSkeleton={() => <PerpsRowSkeleton count={2} />}
>
<View style={styles.positionsOrdersContainer}>
{positions.map((position, index) => (
<PerpsCard
key={`${position.symbol}-${index}`}
position={position}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.POSITIONS}
testID={`${PerpsHomeViewSelectorsIDs.POSITION_CARD}-${index}`}
/>
))}
</View>
</PerpsHomeSection>
),
},
{
key: 'orders',
visible: isLoading.orders || orders.length > 0,
onLayout: handleSectionLayout(PERPS_EVENT_VALUE.SECTION_NAME.ORDERS),
content: (
<PerpsHomeSection
title={strings('perps.home.orders')}
isLoading={isLoading.orders}
isEmpty={orders.length === 0}
showWhenEmpty={false}
onActionPress={handleCancelAllPress}
renderSkeleton={() => <PerpsRowSkeleton count={2} />}
>
<View style={styles.positionsOrdersContainer}>
{orders.map((order, index) => (
<PerpsCard
key={order.orderId}
order={order}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.ORDERS}
testID={`${PerpsHomeViewSelectorsIDs.ORDER_CARD}-${index}`}
/>
))}
</View>
</PerpsHomeSection>
),
},
{
key: 'whats-happening',
visible: isWhatsHappeningVisible,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.WHATS_HAPPENING,
),
content: (
<WhatsHappeningSection
source={WhatsHappeningSource.Perps}
feed={whatsHappeningFeed}
onHeaderPress={handleWhatsHappeningHeaderPress}
/>
),
},
{
key: 'watchlist',
visible: isWatchlistVisible,
onLayout: handleSectionLayout(PERPS_EVENT_VALUE.SECTION_NAME.WATCHLIST),
content: (
<PerpsWatchlistMarkets
markets={watchlistMarkets}
suggestedMarkets={suggestedWatchlistMarkets}
isLoading={isLoading.markets}
positions={positions}
orders={orders}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.WATCHLIST}
transactionActiveAbTests={transactionActiveAbTests}
showLeadingDivider={false}
onSeeAllPress={
watchlistMarkets.length > 0
? handleWatchlistSeeAllPress
: undefined
}
/>
),
},
{
key: 'products',
visible: isProductsEnabled && productCategories.length > 0,
onLayout: handleSectionLayout(PERPS_EVENT_VALUE.SECTION_NAME.PRODUCTS),
content: (
<PerpsProducts transactionActiveAbTests={transactionActiveAbTests} />
),
},
{
key: 'top-movers',
visible: isTopMoversVisible,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.TOP_MOVERS,
),
content: (
<PerpsTopMoversSection
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
},
{
key: 'crypto',
visible: isLoading.markets || perpsMarkets.length > 0,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_CRYPTO,
),
content: (
<PerpsMarketTypeSection
title={strings('perps.home.crypto')}
markets={perpsMarkets}
marketType="crypto"
sortBy={sortBy}
isLoading={isLoading.markets}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.CRYPTO}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
},
{
key: 'commodities',
visible: isLoading.markets || commoditiesMarkets.length > 0,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_COMMODITIES,
),
content: (
<PerpsMarketTypeSection
title={strings('perps.home.commodities')}
markets={commoditiesMarkets}
marketType="commodity"
sortBy={sortBy}
isLoading={isLoading.markets}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.COMMODITY}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
},
{
key: 'stocks',
visible: isLoading.markets || stocksMarkets.length > 0,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_STOCKS,
),
content: (
<PerpsMarketTypeSection
title={strings('perps.home.stocks')}
markets={stocksMarkets}
marketType="stock"
sortBy={sortBy}
isLoading={isLoading.markets}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.STOCK}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
},
{
key: 'forex',
visible: isLoading.markets || forexMarkets.length > 0,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.EXPLORE_FOREX,
),
content: (
<PerpsMarketTypeSection
title={strings('perps.home.forex')}
markets={forexMarkets}
marketType="forex"
isLoading={isLoading.markets}
source={PERPS_EVENT_VALUE.SOURCE.PERPS_HOME}
source_section={PERPS_EVENT_VALUE.SOURCE_SECTION.FOREX}
transactionActiveAbTests={transactionActiveAbTests}
/>
),
},
{
key: 'recently-added',
// Mirrors PerpsRecentlyAddedSection's own render gate (markets.length
// === 0 -> null) plus the feature flag, so PerpsHomeSectionList does
// not render an orphan divider for an empty/disabled rail.
visible: isRecentlyAddedVisible,
onLayout: handleSectionLayout('recently_added'),
content: (
<PerpsRecentlyAddedSection
markets={recentlyAddedMarkets}
onMarketPress={handleRecentlyAddedMarketPress}
onViewAllPress={handleRecentlyAddedHeaderPress}
/>
),
},
{
key: 'recent-activity',
visible: isLoading.activity || recentActivity.length > 0,
onLayout: handleSectionLayout(
PERPS_EVENT_VALUE.SECTION_NAME.RECENT_ACTIVITY,
),
content: (
<PerpsRecentActivityList
transactions={recentActivity}
isLoading={isLoading.activity}
/>
),
},
],
[
isLoading,
positions,
orders,
privacyMode,
positionsSubtitle,
positionsSubtitleColor,
positionsSubtitleSuffix,
handleCloseAllPress,
handleCancelAllPress,
styles.positionsOrdersContainer,
isWhatsHappeningVisible,
whatsHappeningFeed,
handleWhatsHappeningHeaderPress,
isWatchlistVisible,
watchlistMarkets,
suggestedWatchlistMarkets,
handleWatchlistSeeAllPress,
transactionActiveAbTests,
isProductsEnabled,
productCategories.length,
isTopMoversVisible,
isRecentlyAddedVisible,
recentlyAddedMarkets,
handleRecentlyAddedMarketPress,
handleRecentlyAddedHeaderPress,
perpsMarkets,
commoditiesMarkets,
stocksMarkets,
forexMarkets,
sortBy,
recentActivity,
handleSectionLayout,
],
);
// Open bottom sheets when state changes
useEffect(() => {
if (showCloseAllSheet) {
closeAllSheetRef.current?.onOpenBottomSheet();
}
}, [showCloseAllSheet]);
useEffect(() => {
if (showCancelAllSheet) {
cancelAllSheetRef.current?.onOpenBottomSheet();
}
}, [showCancelAllSheet]);
// Handle sheet close callbacks
const handleCloseAllSheetClose = useCallback(() => {
setShowCloseAllSheet(false);
}, []);
const handleCancelAllSheetClose = useCallback(() => {
setShowCancelAllSheet(false);
}, []);
// Calculate actual footer dimensions
// Footer: paddingTop(16) + button(48) + paddingBottom(16 + insets.bottom)
const footerHeight = 80 + insets.bottom;
const showsFixedFooter =
!isBalanceEmpty &&
!showCloseAllSheet &&
!showCancelAllSheet &&
!HOME_SCREEN_CONFIG.ShowHeaderActionButtons;
const bottomSpacerStyle = useMemo(
() => ({
// Reserve space for the fixed footer only when it is rendered.
height: showsFixedFooter ? footerHeight + 16 : 16,
}),
[showsFixedFooter, footerHeight],
);
// Add safe area inset to footer for Android navigation bar
const fixedFooterStyle = useMemo(
() => [styles.fixedFooter, { paddingBottom: 16 + insets.bottom }],
[styles.fixedFooter, insets.bottom],
);
const scrollContentContainerStyle = useMemo(
() => [
styles.scrollViewContent,
hideHeader && topInset > 0 ? { paddingTop: topInset } : null,
showsFixedFooter
? { paddingBottom: 0 }
: !hideHeader
? { paddingBottom: 16 + insets.bottom }
: null,
],
[
styles.scrollViewContent,
topInset,
hideHeader,
showsFixedFooter,
insets.bottom,