-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsCloseAllPositionsView.tsx
More file actions
368 lines (345 loc) · 12.1 KB
/
Copy pathPerpsCloseAllPositionsView.tsx
File metadata and controls
368 lines (345 loc) · 12.1 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
import { useNavigation } from '@react-navigation/native';
import type { AppNavigationProp } from '../../../../../core/NavigationService/types';
import React, { useCallback, useMemo, useRef } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { NotificationMoment } from '../../../../../util/haptics';
import { strings } from '../../../../../../locales/i18n';
import BottomSheet, {
BottomSheetRef,
} from '../../../../../component-library/components/BottomSheets/BottomSheet';
import BottomSheetHeader from '../../../../../component-library/components/BottomSheets/BottomSheetHeader';
import BottomSheetFooter, {
ButtonsAlignment,
} from '../../../../../component-library/components/BottomSheets/BottomSheetFooter';
import Text, {
TextColor,
TextVariant,
} from '../../../../../component-library/components/Texts/Text';
import {
ButtonSize,
ButtonVariants,
} from '../../../../../component-library/components/Buttons/Button';
import { IconName } from '../../../../../component-library/components/Icons/Icon';
import { ToastVariants } from '../../../../../component-library/components/Toast/Toast.types';
import {
usePerpsLivePositions,
usePerpsCloseAllCalculations,
usePerpsCloseAllPositions,
usePerpsRewardAccountOptedIn,
} from '../../hooks';
import { usePerpsLivePrices } from '../../hooks/stream';
import usePerpsToasts, {
type PerpsToastOptions,
} from '../../hooks/usePerpsToasts';
import PerpsCloseSummary from '../../components/PerpsCloseSummary';
import { createStyles } from './PerpsCloseAllPositionsView.styles';
import { useTheme } from '../../../../../util/theme';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import { usePerpsEventTracking } from '../../hooks/usePerpsEventTracking';
import {
PERPS_EVENT_PROPERTY,
PERPS_EVENT_VALUE,
type ClosePositionsResult,
} from '@metamask/perps-controller';
interface PerpsCloseAllPositionsViewProps {
sheetRef?: React.RefObject<BottomSheetRef | null>;
onClose?: () => void;
}
const PerpsCloseAllPositionsView: React.FC<PerpsCloseAllPositionsViewProps> = ({
sheetRef: externalSheetRef,
onClose: onExternalClose,
}) => {
const theme = useTheme();
const styles = createStyles(theme);
const navigation = useNavigation<AppNavigationProp>();
const internalSheetRef = useRef<BottomSheetRef>(null);
const sheetRef = externalSheetRef || internalSheetRef;
const { showToast } = usePerpsToasts();
// Fetch positions from live stream
const { positions, isInitialLoading } = usePerpsLivePositions({
throttleMs: 1000,
});
// Fetch current prices for fee calculations (throttled to avoid excessive updates)
const symbols = useMemo(
() => (positions || []).map((pos) => pos.symbol),
[positions],
);
const priceData = usePerpsLivePrices({
symbols,
throttleMs: 1000,
});
// Use hook for accurate fee and rewards calculations
const calculations = usePerpsCloseAllCalculations({
positions: positions || [],
priceData,
});
// Check opt-in status for rewards
const { accountOptedIn, account: rewardsAccount } =
usePerpsRewardAccountOptedIn(calculations?.totalEstimatedPoints);
// Track screen viewed event
usePerpsEventTracking({
eventName: MetaMetricsEvents.PERPS_SCREEN_VIEWED,
conditions: [!isInitialLoading],
properties: {
[PERPS_EVENT_PROPERTY.SCREEN_TYPE]:
PERPS_EVENT_VALUE.SCREEN_TYPE.CLOSE_ALL_POSITIONS,
[PERPS_EVENT_PROPERTY.OPEN_POSITION]: positions?.length || 0,
[PERPS_EVENT_PROPERTY.SOURCE]:
PERPS_EVENT_VALUE.SOURCE.CLOSE_ALL_POSITIONS_BUTTON,
},
});
// Toast helper for success
const showSuccessToast = useCallback(
(title: string, message?: string) => {
const toastConfig: PerpsToastOptions = {
variant: ToastVariants.Icon,
iconName: IconName.CheckBold,
backgroundColor: theme.colors.accent03.normal,
iconColor: theme.colors.accent03.dark,
hapticsType: NotificationMoment.Success,
hasNoTimeout: false,
labelOptions: message
? [
{ label: title, isBold: true },
{ label: '\n', isBold: false },
{ label: message, isBold: false },
]
: [{ label: title, isBold: true }],
} as PerpsToastOptions;
showToast(toastConfig);
},
[showToast, theme.colors.accent03],
);
// Toast helper for errors
const showErrorToast = useCallback(
(title: string, message?: string) => {
const toastConfig: PerpsToastOptions = {
variant: ToastVariants.Icon,
iconName: IconName.Warning,
backgroundColor: theme.colors.accent01.light,
iconColor: theme.colors.accent01.dark,
hapticsType: NotificationMoment.Error,
hasNoTimeout: false,
labelOptions: message
? [
{ label: title, isBold: true },
{ label: '\n', isBold: false },
{ label: message, isBold: false },
]
: [{ label: title, isBold: true }],
} as PerpsToastOptions;
showToast(toastConfig);
},
[showToast, theme.colors.accent01],
);
// Handle success callback from hook
const handleSuccess = useCallback(
(result: ClosePositionsResult) => {
if (result.success && result.successCount > 0) {
showSuccessToast(
strings('perps.close_all_modal.success_title'),
strings('perps.close_all_modal.success_message', {
count: result.successCount,
}),
);
// Close sheet after success when using external ref
if (externalSheetRef && result.successCount > 0) {
sheetRef.current?.onCloseBottomSheet(() => {
onExternalClose?.();
});
}
} else if (result.successCount > 0 && result.failureCount > 0) {
showSuccessToast(
strings('perps.close_all_modal.success_title'),
strings('perps.close_all_modal.partial_success', {
successCount: result.successCount,
totalCount: result.successCount + result.failureCount,
}),
);
// Close sheet after partial success when using external ref
if (externalSheetRef && result.successCount > 0) {
sheetRef.current?.onCloseBottomSheet(() => {
onExternalClose?.();
});
}
}
},
[showSuccessToast, externalSheetRef, sheetRef, onExternalClose],
);
// Handle error callback from hook
const handleError = useCallback(
(error: Error) => {
showErrorToast(
strings('perps.close_all_modal.error_title'),
error.message || 'Unknown error',
);
},
[showErrorToast],
);
// Use close all positions hook for business logic
const { isClosing, handleCloseAll, handleKeepPositions } =
usePerpsCloseAllPositions(positions, {
onSuccess: handleSuccess,
onError: handleError,
navigateBackOnSuccess: !externalSheetRef, // Don't navigate if using external ref
calculations: {
totalMargin: String(calculations.totalMargin),
totalPnl: String(calculations.totalPnl),
totalFees: String(calculations.totalFees),
receiveAmount: String(calculations.receiveAmount),
},
});
const handleClose = useCallback(() => {
if (externalSheetRef) {
sheetRef.current?.onCloseBottomSheet(() => {
onExternalClose?.();
});
} else {
navigation.goBack();
}
}, [navigation, externalSheetRef, sheetRef, onExternalClose]);
// Wrapper for "Keep Positions" button that properly handles overlay dismissal
const handleKeepButtonPress = useCallback(() => {
if (externalSheetRef) {
// When used as overlay, close the sheet properly to remove overlay
handleClose();
} else {
// When used as standalone screen, use hook's navigation
handleKeepPositions();
}
}, [externalSheetRef, handleClose, handleKeepPositions]);
const footerButtons = useMemo(
() => [
{
label: strings('perps.close_all_modal.keep_positions'),
onPress: handleKeepButtonPress,
variant: ButtonVariants.Secondary,
size: ButtonSize.Lg,
style: styles.footerButtonSecondary,
disabled: isClosing,
},
{
label: isClosing
? strings('perps.close_all_modal.closing')
: strings('perps.close_all_modal.close_all'),
onPress: handleCloseAll,
variant: ButtonVariants.Primary,
size: ButtonSize.Lg,
disabled: isClosing,
danger: true,
},
],
[
handleKeepButtonPress,
handleCloseAll,
isClosing,
styles.footerButtonSecondary,
],
);
// Show loading state while fetching positions
if (isInitialLoading) {
return (
<BottomSheet
ref={sheetRef}
shouldNavigateBack={!externalSheetRef}
onClose={externalSheetRef ? onExternalClose : undefined}
>
<BottomSheetHeader onClose={handleClose}>
<Text variant={TextVariant.HeadingMD}>
{strings('perps.close_all_modal.title')}
</Text>
</BottomSheetHeader>
<View style={styles.loadingContainer}>
<ActivityIndicator
size="large"
color={theme.colors.primary.default}
/>
</View>
</BottomSheet>
);
}
// Show empty state if no positions
if (!positions || positions.length === 0) {
return (
<BottomSheet
ref={sheetRef}
shouldNavigateBack={!externalSheetRef}
onClose={externalSheetRef ? onExternalClose : undefined}
>
<BottomSheetHeader onClose={handleClose}>
<Text variant={TextVariant.HeadingMD}>
{strings('perps.close_all_modal.title')}
</Text>
</BottomSheetHeader>
<View style={styles.emptyContainer}>
<Text variant={TextVariant.BodyMD} color={TextColor.Alternative}>
{strings('perps.position.no_positions')}
</Text>
</View>
</BottomSheet>
);
}
return (
<BottomSheet
ref={sheetRef}
shouldNavigateBack={!externalSheetRef}
onClose={externalSheetRef ? onExternalClose : undefined}
>
<BottomSheetHeader onClose={handleClose}>
<Text variant={TextVariant.HeadingMD}>
{strings('perps.close_all_modal.title')}
</Text>
</BottomSheetHeader>
<View style={styles.contentContainer}>
<Text
variant={TextVariant.BodyMD}
color={TextColor.Alternative}
style={styles.description}
>
{strings('perps.close_all_modal.description')}
</Text>
{isClosing ? (
<View style={styles.loadingContainer}>
<ActivityIndicator
size="large"
color={theme.colors.primary.default}
/>
<Text
variant={TextVariant.BodyMD}
color={TextColor.Alternative}
style={styles.loadingText}
>
{strings('perps.close_all_modal.closing')}
</Text>
</View>
) : (
<PerpsCloseSummary
totalMargin={calculations.totalMargin}
totalPnl={calculations.totalPnl}
totalFees={calculations.totalFees}
feeDiscountPercentage={calculations.avgFeeDiscountPercentage}
metamaskFeeRate={calculations.avgMetamaskFeeRate}
protocolFeeRate={calculations.avgProtocolFeeRate}
originalMetamaskFeeRate={calculations.avgOriginalMetamaskFeeRate}
receiveAmount={calculations.receiveAmount}
shouldShowRewards={calculations.shouldShowRewards}
estimatedPoints={calculations.totalEstimatedPoints}
bonusBips={calculations.avgBonusBips}
isLoadingFees={calculations.isLoading}
isLoadingRewards={calculations.isLoading}
hasRewardsError={calculations.hasError}
accountOptedIn={accountOptedIn}
rewardsAccount={rewardsAccount}
enableTooltips={false}
/>
)}
</View>
<BottomSheetFooter
buttonsAlignment={ButtonsAlignment.Horizontal}
buttonPropsArray={footerButtons}
style={styles.footerContainer}
/>
</BottomSheet>
);
};
export default PerpsCloseAllPositionsView;