-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathAccountGroupBalance.tsx
More file actions
285 lines (257 loc) · 10.9 KB
/
AccountGroupBalance.tsx
File metadata and controls
285 lines (257 loc) · 10.9 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
import React, {
useCallback,
useMemo,
useState,
useRef,
useEffect,
} from 'react';
import { View, TouchableOpacity } from 'react-native';
import { useSelector } from 'react-redux';
import Engine from '../../../../../core/Engine';
import createStyles from './AccountGroupBalance.styles';
import { selectPrivacyMode } from '../../../../../selectors/preferencesController';
import {
selectBalanceBySelectedAccountGroup,
selectBalanceChangeBySelectedAccountGroup,
selectAccountGroupBalanceForEmptyState,
} from '../../../../../selectors/assets/balances';
import {
selectHomepageSectionsV1Enabled,
selectWalletHomeOnboardingStepsEnabled,
} from '../../../../../selectors/featureFlagController/homepage';
import {
selectShouldShowWalletHomeOnboardingSteps,
selectWalletHomeOnboardingSkipInitialBalanceWait,
} from '../../../../../selectors/onboarding';
import { selectEvmChainId } from '../../../../../selectors/networkController';
import { useNetworkEnablement } from '../../../../hooks/useNetworkEnablement/useNetworkEnablement';
import { TEST_NETWORK_IDS } from '../../../../../constants/network';
import SensitiveText, {
SensitiveTextLength,
} from '../../../../../component-library/components/Texts/SensitiveText';
import { TextVariant } from '../../../../../component-library/components/Texts/Text';
import { WalletViewSelectorsIDs } from '../../../../Views/Wallet/WalletView.testIds';
import { Skeleton } from '../../../../../component-library/components-temp/Skeleton';
import { useFormatters } from '../../../../hooks/useFormatters';
import AccountGroupBalanceChange from '../../components/BalanceChange/AccountGroupBalanceChange';
import BalanceEmptyState from '../../../BalanceEmptyState';
import WalletHomeOnboardingSteps from '../../../WalletHomeOnboardingSteps';
import { useRampNavigation } from '../../../Ramp/hooks/useRampNavigation';
import { useWalletHomeOnboardingChecklistFundPress } from '../../../WalletHomeOnboardingSteps/useWalletHomeOnboardingChecklistFundPress';
/**
* Timeout for account group balance fetch
* This is to prevent a flash of empty state when the balance is not yet fetched
* !TODO: This is a temporary fix for an artificial loading state and should be refactored after Account API v4 integration
*/
const ACCOUNT_GROUP_BALANCE_FETCH_TIMEOUT = 3000;
export interface AccountGroupBalanceProps {
/**
* When set, the last post-onboarding step awaits this handler after the checklist fade.
*/
onCoordinatedFlowExit?: () => Promise<void>;
/**
* While true, pauses checklist Rive during the coordinated Wallet exit (reduces jank).
*/
suspendRiveForCurtain?: boolean;
/** Trade checklist step: Primary invokes this (e.g. open Swaps) before advancing. */
onTradePrimaryPress?: () => void;
/** Notifications checklist step: Primary invokes this (e.g. open settings) before advancing. */
onNotificationsPrimaryPress?: () => void;
}
const AccountGroupBalance = ({
onCoordinatedFlowExit,
suspendRiveForCurtain = false,
onTradePrimaryPress,
onNotificationsPrimaryPress,
}: AccountGroupBalanceProps) => {
const { PreferencesController } = Engine.context;
const styles = createStyles();
const { formatCurrency } = useFormatters();
const isHomepageSectionsV1Enabled = useSelector(
selectHomepageSectionsV1Enabled,
);
const isWalletHomeOnboardingStepsEnabled = useSelector(
selectWalletHomeOnboardingStepsEnabled,
);
const shouldShowWalletHomeOnboardingSteps = useSelector(
selectShouldShowWalletHomeOnboardingSteps,
);
const walletHomeOnboardingSkipInitialBalanceWait = useSelector(
selectWalletHomeOnboardingSkipInitialBalanceWait,
);
const { goToBuy } = useRampNavigation();
const onFundPrimaryPressWithChecklistAnalytics =
useWalletHomeOnboardingChecklistFundPress(goToBuy);
const { popularNetworks } = useNetworkEnablement();
// Stabilize chain IDs by content so selector identity doesn't change every render (avoids max depth / infinite loop).
// FF on: balance for all popular networks; FF off: balance for enabled networks only (selector uses state when undefined).
const popularChainIdsKey = (popularNetworks ?? []).join(',');
const chainIdsForBalance = useMemo(
() =>
isHomepageSectionsV1Enabled ? [...(popularNetworks ?? [])] : undefined,
// popularChainIdsKey stabilizes by content; popularNetworks is a new array ref every render from the hook
// eslint-disable-next-line react-hooks/exhaustive-deps
[isHomepageSectionsV1Enabled, popularChainIdsKey],
);
const groupBalanceSelector = useMemo(
() => selectBalanceBySelectedAccountGroup(chainIdsForBalance),
[chainIdsForBalance],
);
const balanceChange1dSelector = useMemo(
() => selectBalanceChangeBySelectedAccountGroup('1d', chainIdsForBalance),
[chainIdsForBalance],
);
const privacyMode = useSelector(selectPrivacyMode);
const groupBalance = useSelector(groupBalanceSelector) as {
groupId: string;
totalBalanceInUserCurrency: number;
userCurrency: string;
walletId: string;
} | null;
const accountGroupBalance = useSelector(
selectAccountGroupBalanceForEmptyState,
);
const balanceChange1d = useSelector(balanceChange1dSelector);
const selectedChainId = useSelector(selectEvmChainId);
// Track if balance has been fetched to prevent flash of empty state
const [hasBalanceFetched, setHasBalanceFetched] = useState(false);
const initialBalanceRef = useRef<number | null>(null);
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
const currentGroupIdRef = useRef<string | null>(null);
useEffect(() => {
const groupId = groupBalance?.groupId ?? null;
// Check if groupId has changed (account switch)
if (currentGroupIdRef.current !== groupId) {
// Reset all tracking state for new account
setHasBalanceFetched(false);
initialBalanceRef.current = null;
currentGroupIdRef.current = groupId;
// Clear existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Start new timeout for this account (3 seconds)
timeoutRef.current = setTimeout(() => {
setHasBalanceFetched(true);
}, ACCOUNT_GROUP_BALANCE_FETCH_TIMEOUT);
}
// Store initial balance when it first appears
if (initialBalanceRef.current === null && groupBalance) {
initialBalanceRef.current = groupBalance.totalBalanceInUserCurrency;
}
// Track balance changes - if EITHER balance updates from initial value, mark as fetched
// We track both groupBalance AND accountGroupBalance since empty state uses accountGroupBalance
if (groupBalance && initialBalanceRef.current !== null) {
const currentBalance = groupBalance.totalBalanceInUserCurrency;
const accountGroupCurrentBalance =
accountGroupBalance?.totalBalanceInUserCurrency ?? null;
// Mark as fetched if either balance has changed from initial 0, or if both exist and are non-zero
const hasChanged = currentBalance !== initialBalanceRef.current;
const bothExistAndNonZero =
currentBalance > 0 &&
accountGroupCurrentBalance !== null &&
accountGroupCurrentBalance > 0;
if (hasChanged || bothExistAndNonZero) {
setHasBalanceFetched(true);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
}
}
}, [groupBalance, accountGroupBalance]);
// Cleanup timeout on unmount
useEffect(
() => () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
},
[],
);
const togglePrivacy = useCallback(
(value: boolean) => {
PreferencesController.setPrivacyMode(value);
},
[PreferencesController],
);
const totalBalance = groupBalance?.totalBalanceInUserCurrency ?? 0;
const userCurrency = groupBalance?.userCurrency || 'USD';
const displayBalance = formatCurrency(totalBalance, userCurrency);
const isLoading = !groupBalance || !hasBalanceFetched;
const awaitBalanceForPostOnboardingSteps =
isLoading && !walletHomeOnboardingSkipInitialBalanceWait;
// Check if account group balance (across all mainnet networks) is zero for empty state
const hasZeroAccountGroupBalance =
accountGroupBalance != null &&
accountGroupBalance.totalBalanceInUserCurrency === 0;
// Check if current network is a testnet
const isCurrentNetworkTestnet = TEST_NETWORK_IDS.includes(selectedChainId);
// Show empty state on accounts with an aggregated mainnet balance of zero (sections v1)
const shouldShowEmptyState =
hasZeroAccountGroupBalance &&
isHomepageSectionsV1Enabled &&
!isCurrentNetworkTestnet;
const inWalletHomePostOnboardingFlow =
isHomepageSectionsV1Enabled &&
isWalletHomeOnboardingStepsEnabled &&
shouldShowWalletHomeOnboardingSteps;
/** While the flow is active, always use the checklist surface — never the balance row (avoids a flash before loading/empty state is known). */
const showWalletHomeOnboardingStepsTile = inWalletHomePostOnboardingFlow;
const canAdvanceFundStepAfterBalance =
hasBalanceFetched &&
accountGroupBalance != null &&
accountGroupBalance.totalBalanceInUserCurrency > 0;
const renderBalanceOrEmpty = () =>
!isLoading && shouldShowEmptyState ? (
<BalanceEmptyState
testID={WalletViewSelectorsIDs.BALANCE_EMPTY_STATE_CONTAINER}
/>
) : (
<TouchableOpacity
onPress={() => togglePrivacy(!privacyMode)}
testID="balance-container"
style={styles.balanceContainer}
>
<Skeleton hideChildren={isLoading}>
<SensitiveText
isHidden={privacyMode}
length={SensitiveTextLength.Long}
testID={WalletViewSelectorsIDs.TOTAL_BALANCE_TEXT}
variant={TextVariant.DisplayLG}
>
{displayBalance}
</SensitiveText>
</Skeleton>
{balanceChange1d && (
<Skeleton hideChildren={isLoading}>
<AccountGroupBalanceChange
amountChangeInUserCurrency={
balanceChange1d.amountChangeInUserCurrency
}
percentChange={balanceChange1d.percentChange}
userCurrency={balanceChange1d.userCurrency}
/>
</Skeleton>
)}
</TouchableOpacity>
);
return (
<View style={styles.accountGroupBalance}>
{showWalletHomeOnboardingStepsTile ? (
<WalletHomeOnboardingSteps
isAwaitingBalance={awaitBalanceForPostOnboardingSteps}
onCoordinatedFlowExit={onCoordinatedFlowExit}
suspendRiveForCurtain={suspendRiveForCurtain}
onFundPrimaryPress={onFundPrimaryPressWithChecklistAnalytics}
canAdvanceFundStepAfterBalance={canAdvanceFundStepAfterBalance}
onTradePrimaryPress={onTradePrimaryPress}
onNotificationsPrimaryPress={onNotificationsPrimaryPress}
testID={WalletViewSelectorsIDs.BALANCE_EMPTY_STATE_CONTAINER}
/>
) : (
renderBalanceOrEmpty()
)}
</View>
);
};
export default AccountGroupBalance;