-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsClosePositionView.tsx
More file actions
808 lines (739 loc) · 28.3 KB
/
PerpsClosePositionView.tsx
File metadata and controls
808 lines (739 loc) · 28.3 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
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ScrollView, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import {
useNavigation,
useRoute,
type NavigationProp,
type RouteProp,
} from '@react-navigation/native';
import { strings } from '../../../../../../locales/i18n';
import Button, {
ButtonSize,
ButtonVariants,
ButtonWidthTypes,
} from '../../../../../component-library/components/Buttons/Button';
import Text, {
TextColor,
TextVariant,
} from '../../../../../component-library/components/Texts/Text';
import Icon, {
IconColor,
IconName,
IconSize,
} from '../../../../../component-library/components/Icons/Icon';
import KeyValueRow from '../../../../../component-library/components-temp/KeyValueRow';
import { TooltipSizes } from '../../../../../component-library/components-temp/KeyValueRow/KeyValueRow.types';
import { useTheme } from '../../../../../util/theme';
import Keypad from '../../../../Base/Keypad';
import type { OrderType, Position } from '../../controllers/types';
import type { PerpsNavigationParamList } from '../../types/navigation';
import {
useMinimumOrderAmount,
usePerpsOrderFees,
usePerpsClosePositionValidation,
usePerpsClosePosition,
usePerpsMarketData,
} from '../../hooks';
import { usePerpsLivePrices } from '../../hooks/stream';
import { formatPositionSize, formatPrice } from '../../utils/formatUtils';
import {
calculateCloseAmountFromPercentage,
validateCloseAmountLimits,
} from '../../utils/positionCalculations';
import PerpsSlider from '../../components/PerpsSlider/PerpsSlider';
import PerpsAmountDisplay from '../../components/PerpsAmountDisplay';
import PerpsOrderTypeBottomSheet from '../../components/PerpsOrderTypeBottomSheet';
import PerpsLimitPriceBottomSheet from '../../components/PerpsLimitPriceBottomSheet';
import PerpsBottomSheetTooltip from '../../components/PerpsBottomSheetTooltip';
import { PerpsTooltipContentKey } from '../../components/PerpsBottomSheetTooltip/PerpsBottomSheetTooltip.types';
import { createStyles } from './PerpsClosePositionView.styles';
import { PerpsMeasurementName } from '../../constants/performanceMetrics';
import {
PerpsEventProperties,
PerpsEventValues,
} from '../../constants/eventNames';
import { PerpsClosePositionViewSelectorsIDs } from '../../../../../../e2e/selectors/Perps/Perps.selectors';
import { MetaMetricsEvents } from '../../../../hooks/useMetrics';
import { usePerpsEventTracking } from '../../hooks/usePerpsEventTracking';
import { usePerpsScreenTracking } from '../../hooks/usePerpsScreenTracking';
const PerpsClosePositionView: React.FC = () => {
const theme = useTheme();
const styles = createStyles(theme);
const navigation = useNavigation<NavigationProp<PerpsNavigationParamList>>();
const route =
useRoute<RouteProp<PerpsNavigationParamList, 'PerpsClosePosition'>>();
const { position } = route.params as { position: Position };
const hasTrackedCloseView = useRef(false);
const { track } = usePerpsEventTracking();
// Track screen load performance
usePerpsScreenTracking({
screenName: PerpsMeasurementName.CLOSE_SCREEN_LOADED,
dependencies: [],
});
// State for order type and bottom sheets
const [orderType, setOrderType] = useState<OrderType>('market');
const [isOrderTypeVisible, setIsOrderTypeVisible] = useState(false);
const [isLimitPriceVisible, setIsLimitPriceVisible] = useState(false);
const [isInputFocused, setIsInputFocused] = useState(false);
const [isUserInputActive, setIsUserInputActive] = useState(false);
const [selectedTooltip, setSelectedTooltip] =
useState<PerpsTooltipContentKey | null>(null);
const [displayMode, setDisplayMode] = useState<'usd' | 'token'>('usd');
// State for close amount
const [closePercentage, setClosePercentage] = useState(100); // Default to 100% (full close)
const [closeAmount, setCloseAmount] = useState(position.size);
const [closeAmountString, setCloseAmountString] = useState(position.size); // Raw string for token input
const [closeAmountUSD, setCloseAmountUSD] = useState(0);
const [closeAmountUSDString, setCloseAmountUSDString] = useState('0'); // Raw string for USD input
// State for limit price
const [limitPrice, setLimitPrice] = useState('');
// Subscribe to real-time price with 1s debounce for position closing
const priceData = usePerpsLivePrices({
symbols: [position.coin],
throttleMs: 1000,
});
const currentPrice = priceData[position.coin]?.price
? parseFloat(priceData[position.coin].price)
: parseFloat(position.entryPrice);
// Get market data for decimal precision
const { marketData } = usePerpsMarketData(position.coin);
// Determine position direction
const isLong = parseFloat(position.size) > 0;
const absSize = Math.abs(parseFloat(position.size));
// Calculate position value and effective margin
const positionValue = absSize * currentPrice;
// Use the actual margin from the position instead of recalculating
const effectiveMargin = parseFloat(position.marginUsed);
// Use unrealized PnL from position
const pnl = parseFloat(position.unrealizedPnl);
// Calculate fees using the unified fee hook
const closingValue = positionValue * (closePercentage / 100);
const feeResults = usePerpsOrderFees({
orderType,
amount: closingValue.toString(),
isMaker: false, // Closing positions are typically taker orders
});
// Calculate what user will receive (margin - fees, P&L is settled separately)
const receiveAmount =
(closePercentage / 100) * effectiveMargin - feeResults.totalFee;
// Get minimum order amount for this asset
const { minimumOrderAmount } = useMinimumOrderAmount({
asset: position.coin,
});
// Calculate remaining position value after partial close
const remainingPositionValue = positionValue * (1 - closePercentage / 100);
const isPartialClose = closePercentage < 100;
// Use the validation hook
const validationResult = usePerpsClosePositionValidation({
coin: position.coin,
closePercentage,
closeAmount: closeAmount.toString(),
orderType,
limitPrice,
currentPrice,
positionSize: absSize,
positionValue,
minimumOrderAmount,
closingValue,
remainingPositionValue,
receiveAmount,
isPartialClose,
});
const { handleClosePosition, isClosing } = usePerpsClosePosition();
// Track position close screen viewed event
useEffect(() => {
if (!hasTrackedCloseView.current) {
track(MetaMetricsEvents.PERPS_POSITION_CLOSE_SCREEN_VIEWED, {
[PerpsEventProperties.ASSET]: position.coin,
[PerpsEventProperties.DIRECTION]: isLong
? PerpsEventValues.DIRECTION.LONG
: PerpsEventValues.DIRECTION.SHORT,
[PerpsEventProperties.POSITION_SIZE]: absSize,
[PerpsEventProperties.UNREALIZED_PNL_DOLLAR]: pnl,
});
hasTrackedCloseView.current = true;
}
}, [position.coin, isLong, absSize, pnl, track]);
// Initialize USD values when price data is available (only once, not on price updates)
useEffect(() => {
const initialUSDAmount = absSize * currentPrice;
setCloseAmountUSD(initialUSDAmount);
setCloseAmountUSDString(initialUSDAmount.toString());
// eslint-disable-next-line react-hooks/exhaustive-deps -- Intentionally excluding currentPrice to prevent updates on price changes
}, [absSize]);
// Auto-open limit price bottom sheet when switching to limit order
useEffect(() => {
if (orderType === 'limit' && !limitPrice) {
setIsLimitPriceVisible(true);
}
}, [orderType, limitPrice]);
// Update close amount when percentage changes (but not during active input)
useEffect(() => {
// Skip automatic updates when user is actively typing or when input is focused
if (isInputFocused || isUserInputActive) {
return;
}
const { tokenAmount, usdValue } = calculateCloseAmountFromPercentage({
percentage: closePercentage,
positionSize: absSize,
currentPrice,
});
setCloseAmount(tokenAmount.toString());
setCloseAmountString(tokenAmount.toString()); // Update token display string for slider
setCloseAmountUSD(usdValue);
setCloseAmountUSDString(usdValue.toString());
}, [
closePercentage,
absSize,
currentPrice,
isInputFocused,
isUserInputActive,
]);
// Track position close value changes (separate effect for performance)
useEffect(() => {
if (closePercentage !== 100 && !isInputFocused) {
const trackingValue = (closePercentage / 100) * absSize * currentPrice;
track(MetaMetricsEvents.PERPS_POSITION_CLOSE_VALUE_CHANGED, {
[PerpsEventProperties.ASSET]: position.coin,
[PerpsEventProperties.CLOSE_PERCENTAGE]: closePercentage,
[PerpsEventProperties.CLOSE_VALUE]: trackingValue,
});
}
}, [
closePercentage,
absSize,
currentPrice,
position.coin,
track,
isInputFocused,
]);
const handleConfirm = async () => {
// Track position close initiated
track(MetaMetricsEvents.PERPS_POSITION_CLOSE_INITIATED, {
[PerpsEventProperties.ASSET]: position.coin,
[PerpsEventProperties.DIRECTION]: isLong
? PerpsEventValues.DIRECTION.LONG
: PerpsEventValues.DIRECTION.SHORT,
[PerpsEventProperties.ORDER_TYPE]: orderType,
[PerpsEventProperties.CLOSE_PERCENTAGE]: closePercentage,
[PerpsEventProperties.CLOSE_VALUE]: closingValue,
[PerpsEventProperties.PNL_DOLLAR]: pnl * (closePercentage / 100),
[PerpsEventProperties.RECEIVED_AMOUNT]: receiveAmount,
});
// Track position close submitted
track(MetaMetricsEvents.PERPS_POSITION_CLOSE_SUBMITTED, {
[PerpsEventProperties.ASSET]: position.coin,
[PerpsEventProperties.ORDER_TYPE]: orderType,
});
// For full close, don't send size parameter
const sizeToClose = closePercentage === 100 ? undefined : closeAmount;
// For limit orders, validate price
if (orderType === 'limit' && !limitPrice) {
return;
}
// Go back immediately to close the position screen
navigation.goBack();
await handleClosePosition(
position,
sizeToClose || '',
orderType,
orderType === 'limit' ? limitPrice : undefined,
);
};
const handleCancel = () => {
navigation.goBack();
};
const handleAmountPress = () => {
setIsInputFocused(true);
};
const handleKeypadChange = useCallback(
({ value }: { value: string; valueAsNumber: number }) => {
const previousValue =
displayMode === 'usd' ? closeAmountUSDString : closeAmountString;
// Special handling for decimal point deletion
// If previous value had a decimal and new value is the same, force remove the decimal
let adjustedValue = value;
// Check if we're stuck on a decimal (e.g., "2." -> "2." means delete didn't work)
if (previousValue.endsWith('.') && value === previousValue) {
adjustedValue = value.slice(0, -1);
}
// Also handle case where decimal is in middle (e.g., "2.5" -> "2." should become "25")
else if (
previousValue.includes('.') &&
value.endsWith('.') &&
value.length === previousValue.length - 1
) {
// User deleted a digit after decimal, remove the decimal too
adjustedValue = value.replace('.', '');
}
// Set both focus flags immediately to prevent useEffect interference
if (!isInputFocused) {
setIsInputFocused(true);
}
if (!isUserInputActive) {
setIsUserInputActive(true);
}
if (displayMode === 'usd') {
// USD decimal input logic - preserve raw string for display
// Use adjustedValue instead of original value
const numericValue = parseFloat(adjustedValue) || 0;
const clampedValue = validateCloseAmountLimits({
amount: numericValue,
maxAmount: positionValue,
});
// For USD mode, preserve user input exactly as typed for proper delete operations
// Only limit decimal places if there are digits after the decimal point
let formattedUSDString = adjustedValue;
if (adjustedValue.includes('.')) {
const parts = adjustedValue.split('.');
const integerPart = parts[0] || '';
const decimalPart = parts[1] || '';
// If there's a decimal part, limit it to 2 digits
if (decimalPart.length > 0) {
formattedUSDString = integerPart + '.' + decimalPart.slice(0, 2);
} else {
// Keep the decimal point if user just typed it (like "2.")
formattedUSDString = integerPart + '.';
}
}
// Update all states in batch to prevent race conditions
setCloseAmountUSDString(formattedUSDString);
setCloseAmountUSD(clampedValue);
// Calculate percentage and token amount
const newPercentage =
positionValue > 0 ? (clampedValue / positionValue) * 100 : 0;
const newAmount = (newPercentage / 100) * absSize;
// Update percentage and token amount after USD values are set
setCloseAmount(newAmount.toString());
setClosePercentage(newPercentage);
} else {
// Token decimal input logic - preserve raw string for display
// Use adjustedValue for consistency
const numericValue = parseFloat(adjustedValue) || 0;
const clampedTokenAmount = validateCloseAmountLimits({
amount: numericValue,
maxAmount: absSize,
});
// Preserve raw input string for display (to keep decimal points)
// Only show clamped value if it actually exceeds the limit
let displayString = adjustedValue;
if (numericValue > absSize) {
displayString = clampedTokenAmount.toString();
}
// Update states in batch
setCloseAmountString(displayString); // Raw string for display
setCloseAmount(clampedTokenAmount.toString()); // Clamped value for calculations
setCloseAmountUSD(clampedTokenAmount * currentPrice);
// Calculate percentage after token values are set
const newPercentage =
absSize > 0 ? (clampedTokenAmount / absSize) * 100 : 0;
setClosePercentage(newPercentage);
}
},
[
displayMode,
positionValue,
absSize,
currentPrice,
isInputFocused,
isUserInputActive,
closeAmountString,
closeAmountUSDString,
],
);
const handlePercentagePress = (percentage: number) => {
const newPercentage = percentage * 100;
setClosePercentage(newPercentage);
// Immediately update values even when keypad is active
const newAmount = (newPercentage / 100) * absSize;
setCloseAmount(newAmount.toString());
setCloseAmountString(newAmount.toString()); // Update token display string
const newUSDAmount = newAmount * currentPrice;
setCloseAmountUSD(newUSDAmount);
setCloseAmountUSDString(newUSDAmount.toString());
};
const handleMaxPress = () => {
setClosePercentage(100);
// Immediately update values even when keypad is active
setCloseAmount(absSize.toString());
setCloseAmountString(absSize.toString()); // Update token display string
const newUSDAmount = absSize * currentPrice;
setCloseAmountUSD(newUSDAmount);
setCloseAmountUSDString(newUSDAmount.toString());
};
const handleDonePress = () => {
setIsInputFocused(false);
setIsUserInputActive(false);
};
// Tooltip handlers
const handleTooltipPress = useCallback(
(contentKey: PerpsTooltipContentKey) => {
setSelectedTooltip(contentKey);
},
[],
);
const handleTooltipClose = useCallback(() => {
setSelectedTooltip(null);
}, []);
return (
<SafeAreaView style={styles.container}>
{/* Header */}
<View style={styles.header}>
<TouchableOpacity onPress={handleCancel} style={styles.backButton}>
<Icon
name={IconName.ArrowLeft}
size={IconSize.Lg}
color={IconColor.Default}
/>
</TouchableOpacity>
<View style={styles.headerContent}>
<Text variant={TextVariant.HeadingMD}>
{strings('perps.close_position.title')}
</Text>
</View>
<TouchableOpacity
onPress={() => setIsOrderTypeVisible(true)}
testID={PerpsClosePositionViewSelectorsIDs.ORDER_TYPE_BUTTON}
>
<View style={styles.marketButton}>
<Text variant={TextVariant.BodyMD} color={TextColor.Default}>
{orderType === 'market'
? strings('perps.order.market')
: strings('perps.order.limit')}
</Text>
<Icon
name={IconName.ArrowDown}
size={IconSize.Xs}
color={IconColor.Default}
style={styles.marketButtonIcon}
/>
</View>
</TouchableOpacity>
</View>
<ScrollView
style={styles.content}
contentContainerStyle={[
styles.scrollViewContent,
isInputFocused && styles.scrollViewContentWithKeypad,
]}
showsVerticalScrollIndicator={false}
>
{/* Amount Display */}
<PerpsAmountDisplay
label={strings('perps.close_position.select_amount')}
amount={displayMode === 'usd' ? closeAmountUSDString : closeAmount}
showWarning={false}
onPress={handleAmountPress}
isActive={isInputFocused}
showTokenAmount={displayMode === 'token'}
tokenAmount={
displayMode === 'token' && closeAmountString
? closeAmountString
: formatPositionSize(closeAmount)
}
tokenSymbol={position.coin}
showMaxAmount={false}
/>
{/* Toggle Button for USD/Token Display */}
<View style={styles.toggleContainer}>
<TouchableOpacity
style={styles.toggleButton}
onPress={() =>
setDisplayMode(displayMode === 'usd' ? 'token' : 'usd')
}
testID={PerpsClosePositionViewSelectorsIDs.DISPLAY_TOGGLE_BUTTON}
>
<Text variant={TextVariant.BodySM} color={TextColor.Alternative}>
{displayMode === 'usd'
? `${closeAmountString || formatPositionSize(closeAmount)} ${
position.coin
}`
: formatPrice(closeAmountUSD, { maximumDecimals: 2 })}
</Text>
<Icon
name={IconName.SwapVertical}
size={IconSize.Xs}
color={IconColor.Alternative}
/>
</TouchableOpacity>
</View>
{/* Slider - Hide when keypad is active */}
{!isInputFocused && (
<View style={styles.sliderSection}>
<PerpsSlider
value={closePercentage}
onValueChange={setClosePercentage}
minimumValue={0}
maximumValue={100}
step={1}
showPercentageLabels
disabled={isClosing}
/>
</View>
)}
{/* Limit Price - only show for limit orders */}
{orderType === 'limit' && !isInputFocused && (
<View style={styles.detailsSection}>
<TouchableOpacity onPress={() => setIsLimitPriceVisible(true)}>
<KeyValueRow
field={{
label: {
text: strings('perps.order.limit_price'),
variant: TextVariant.BodyMD,
color: TextColor.Alternative,
},
tooltip: {
title: strings('perps.tooltips.limit_price.title'),
content: strings('perps.tooltips.limit_price.content'),
size: TooltipSizes.Sm,
onPress: () => handleTooltipPress('limit_price'),
},
}}
value={{
label: {
text: limitPrice
? `$${formatPrice(limitPrice, { maximumDecimals: 2 })}`
: 'Set price',
variant: TextVariant.BodyMD,
color: TextColor.Default,
},
}}
/>
</TouchableOpacity>
</View>
)}
{/* Order Details - Always visible */}
<View style={styles.detailsSection}>
<View style={styles.detailRow}>
<Text variant={TextVariant.BodyMD} color={TextColor.Alternative}>
{strings('perps.close_position.margin')}
</Text>
<Text variant={TextVariant.BodyMD}>
{formatPrice(effectiveMargin * (closePercentage / 100), {
maximumDecimals: 2,
})}
</Text>
</View>
<View style={styles.detailRow}>
<View style={styles.labelWithTooltip}>
<Text variant={TextVariant.BodyMD} color={TextColor.Alternative}>
{strings('perps.close_position.estimated_pnl')}
</Text>
<TouchableOpacity
onPress={() => handleTooltipPress('estimated_pnl')}
>
<Icon
name={IconName.Info}
size={IconSize.Xs}
color={IconColor.Muted}
/>
</TouchableOpacity>
</View>
<Text
variant={TextVariant.BodyMD}
color={pnl >= 0 ? TextColor.Success : TextColor.Error}
>
{pnl >= 0 ? '+' : '-'}
{formatPrice(Math.abs(pnl * (closePercentage / 100)), {
maximumDecimals: 2,
})}
</Text>
</View>
<View style={styles.detailRow}>
<View style={styles.labelWithTooltip}>
<Text variant={TextVariant.BodyMD} color={TextColor.Alternative}>
{strings('perps.close_position.fees')}
</Text>
<TouchableOpacity
onPress={() => handleTooltipPress('closing_fees')}
>
<Icon
name={IconName.Info}
size={IconSize.Xs}
color={IconColor.Muted}
/>
</TouchableOpacity>
</View>
<Text variant={TextVariant.BodyMD}>
-{formatPrice(feeResults.totalFee, { maximumDecimals: 2 })}
</Text>
</View>
<View style={[styles.detailRow, styles.totalRow]}>
<Text variant={TextVariant.BodyLGMedium}>
{strings('perps.close_position.you_receive')}
</Text>
<Text variant={TextVariant.BodyLGMedium}>
{formatPrice(Math.max(0, receiveAmount), {
maximumDecimals: 2,
})}
</Text>
</View>
</View>
{/* Validation Messages - Hide when keypad is active */}
{!isInputFocused && validationResult.errors.length > 0 && (
<View style={styles.validationSection}>
{validationResult.errors.map((error, index) => (
<View key={index} style={styles.errorMessage}>
<Icon
name={IconName.Danger}
size={IconSize.Sm}
color={IconColor.Error}
/>
<Text variant={TextVariant.BodySM} color={TextColor.Error}>
{error}
</Text>
</View>
))}
</View>
)}
{!isInputFocused && validationResult.warnings.length > 0 && (
<View style={styles.validationSection}>
{validationResult.warnings.map((warning, index) => (
<View key={index} style={styles.warningMessage}>
<Icon
name={IconName.Warning}
size={IconSize.Sm}
color={IconColor.Warning}
/>
<Text variant={TextVariant.BodySM} color={TextColor.Warning}>
{warning}
</Text>
</View>
))}
</View>
)}
</ScrollView>
{/* Keypad Section - Show when input is focused */}
{isInputFocused && (
<View style={styles.bottomSection}>
<View style={styles.percentageButtonsContainer}>
<Button
variant={ButtonVariants.Secondary}
size={ButtonSize.Md}
label="25%"
onPress={() => handlePercentagePress(0.25)}
style={styles.percentageButton}
/>
<Button
variant={ButtonVariants.Secondary}
size={ButtonSize.Md}
label="50%"
onPress={() => handlePercentagePress(0.5)}
style={styles.percentageButton}
/>
<Button
variant={ButtonVariants.Secondary}
size={ButtonSize.Md}
label={strings('perps.deposit.max_button')}
onPress={handleMaxPress}
style={styles.percentageButton}
/>
<Button
variant={ButtonVariants.Secondary}
size={ButtonSize.Md}
label={strings('perps.deposit.done_button')}
onPress={handleDonePress}
style={styles.percentageButton}
/>
</View>
<Keypad
value={
displayMode === 'usd' ? closeAmountUSDString : closeAmountString
}
onChange={handleKeypadChange}
currency={displayMode === 'usd' ? 'USD' : 'native'}
decimals={displayMode === 'usd' ? 2 : marketData?.szDecimals ?? 18}
style={styles.keypad}
/>
</View>
)}
{/* Action Buttons - Hide when keypad is active */}
{!isInputFocused && (
<View style={styles.footer}>
<Button
label={
isClosing
? strings('perps.close_position.closing')
: strings('perps.close_position.button')
}
variant={ButtonVariants.Primary}
size={ButtonSize.Lg}
width={ButtonWidthTypes.Full}
onPress={handleConfirm}
isDisabled={
isClosing ||
(orderType === 'limit' &&
(!limitPrice || parseFloat(limitPrice) <= 0)) ||
(orderType === 'market' && closePercentage === 0) ||
receiveAmount <= 0 ||
!validationResult.isValid
}
loading={isClosing}
testID={
PerpsClosePositionViewSelectorsIDs.CLOSE_POSITION_CONFIRM_BUTTON
}
/>
<Button
label={strings('perps.close_position.cancel')}
variant={ButtonVariants.Secondary}
size={ButtonSize.Lg}
width={ButtonWidthTypes.Full}
onPress={handleCancel}
isDisabled={isClosing}
testID={
PerpsClosePositionViewSelectorsIDs.CLOSE_POSITION_CANCEL_BUTTON
}
/>
</View>
)}
{/* Order Type Bottom Sheet */}
<PerpsOrderTypeBottomSheet
isVisible={isOrderTypeVisible}
onClose={() => setIsOrderTypeVisible(false)}
onSelect={(type) => {
setOrderType(type);
// Clear limit price when switching to market order
if (type === 'market') {
setLimitPrice('');
}
setIsOrderTypeVisible(false);
}}
currentOrderType={orderType}
asset={position.coin}
direction={isLong ? 'long' : 'short'}
/>
{/* Limit Price Bottom Sheet */}
<PerpsLimitPriceBottomSheet
isVisible={isLimitPriceVisible}
onClose={() => setIsLimitPriceVisible(false)}
onConfirm={(price) => {
setLimitPrice(price);
setIsLimitPriceVisible(false);
}}
asset={position.coin}
limitPrice={limitPrice}
currentPrice={currentPrice}
direction={isLong ? 'short' : 'long'} // Opposite direction for closing
/>
{/* Tooltip Bottom Sheet */}
{selectedTooltip && (
<PerpsBottomSheetTooltip
isVisible
onClose={handleTooltipClose}
contentKey={selectedTooltip}
key={selectedTooltip}
{...(selectedTooltip === ('closing_fees' as PerpsTooltipContentKey)
? {
data: {
metamaskFeeRate: feeResults.metamaskFeeRate,
protocolFeeRate: feeResults.protocolFeeRate,
},
}
: {})}
/>
)}
</SafeAreaView>
);
};
export default PerpsClosePositionView;