-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathPerpsClosePositionView.tsx
More file actions
861 lines (781 loc) · 31.3 KB
/
Copy pathPerpsClosePositionView.tsx
File metadata and controls
861 lines (781 loc) · 31.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
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
import {
useNavigation,
useRoute,
type RouteProp,
} from '@react-navigation/native';
import type { AppNavigationProp } from '../../../../../core/NavigationService/types';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { ScrollView, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useSelector } from 'react-redux';
import { PerpsClosePositionViewSelectorsIDs } from '../../Perps.testIds';
import { strings } from '../../../../../../locales/i18n';
import {
Button,
ButtonSize,
ButtonVariant,
Icon,
IconColor,
IconName,
IconSize,
KeyValueRow,
KeyValueRowVariant,
} from '@metamask/design-system-react-native';
import Text, {
TextColor,
TextVariant,
} from '../../../../../component-library/components/Texts/Text';
import { useTheme } from '../../../../../util/theme';
import Keypad from '../../../../Base/Keypad';
import {
DECIMAL_PRECISION_CONFIG,
ORDER_SLIPPAGE_CONFIG,
PERPS_EVENT_PROPERTY,
PERPS_EVENT_VALUE,
getPerpsDisplaySymbol,
type InputMethod,
type OrderType,
type Position,
} from '@metamask/perps-controller';
import type { PerpsNavigationParamList } from '../../types/navigation';
import {
useMinimumOrderAmount,
usePerpsClosePosition,
usePerpsClosePositionValidation,
usePerpsOrderFees,
usePerpsRewards,
usePerpsToasts,
usePerpsMarketData,
} from '../../hooks';
import {
usePerpsLivePositions,
usePerpsLivePrices,
usePerpsTopOfBook,
} from '../../hooks/stream';
import { usePerpsEventTracking } from '../../hooks/usePerpsEventTracking';
import { usePerpsMeasurement } from '../../hooks/usePerpsMeasurement';
import {
formatPositionSize,
formatPerpsFiat,
PRICE_RANGES_UNIVERSAL,
} from '../../utils/formatUtils';
import {
calculateCloseAmountFromPercentage,
validateCloseAmountLimits,
formatCloseAmountUSD,
} from '../../utils/positionCalculations';
import { createStyles } from './PerpsClosePositionView.styles';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import { TraceName } from '../../../../../util/trace';
import PerpsOrderHeader from '../../components/PerpsOrderHeader';
import PerpsAmountDisplay from '../../components/PerpsAmountDisplay';
import PerpsLimitPriceBottomSheet from '../../components/PerpsLimitPriceBottomSheet';
import PerpsOrderTypeBottomSheet from '../../components/PerpsOrderTypeBottomSheet';
import PerpsSlider from '../../components/PerpsSlider/PerpsSlider';
import PerpsCloseSummary from '../../components/PerpsCloseSummary';
import { useVipTier } from '../../../Rewards/hooks/useVipTier';
import { selectPerpsClosePositionLimitOrderEnabledFlag } from '../../selectors/featureFlags';
const PerpsClosePositionView: React.FC = () => {
const theme = useTheme();
const styles = createStyles(theme);
const navigation = useNavigation<AppNavigationProp>();
const route =
useRoute<RouteProp<PerpsNavigationParamList, 'PerpsClosePosition'>>();
const { position, source: routeSource } = route.params as {
position: Position;
source?: string;
};
const inputMethodRef = useRef<InputMethod>('default');
const isAmountInitializedRef = useRef(false);
const { showToast, PerpsToastOptions } = usePerpsToasts();
// Get market data for szDecimals with automatic error toast handling
const { marketData, isLoading: isLoadingMarketData } = usePerpsMarketData({
asset: position.symbol,
showErrorToast: true,
});
// Track screen load performance with unified hook (immediate measurement)
usePerpsMeasurement({
traceName: TraceName.PerpsClosePositionView,
});
// Feature flag gating the Market/Limit order-type selector on the close screen.
// Defaults to off so it can be rolled out/rolled back independently of the release.
const isClosePositionLimitOrderEnabled = useSelector(
selectPerpsClosePositionLimitOrderEnabledFlag,
);
// State for order type and bottom sheets
const [orderType, setOrderType] = useState<OrderType>('market');
const [isLimitPriceVisible, setIsLimitPriceVisible] = useState(false);
const [isOrderTypeVisible, setIsOrderTypeVisible] = useState(false);
const [isInputFocused, setIsInputFocused] = useState(false);
const [isUserInputActive, setIsUserInputActive] = useState(false);
// State for close amount
const [closePercentage, setClosePercentage] = useState(100); // Default to 100% (full close)
const [closeAmountUSDString, setCloseAmountUSDString] = useState('0'); // Raw string for USD input (user input only)
// State for limit price
const [limitPrice, setLimitPrice] = useState('');
// Gate the order type on the feature flag. Deriving it (instead of only
// resetting state in an effect) guarantees that a disabled — or mid-session
// flipped-off — flag can never drive limit UI, calculations, validation, or
// submission, with no one-render window before an effect would run.
const effectiveOrderType: OrderType = isClosePositionLimitOrderEnabled
? orderType
: 'market';
// Subscribe to real-time price with 1s debounce for position closing
const priceData = usePerpsLivePrices({
symbols: [position.symbol],
throttleMs: 1000,
});
const currentPrice = priceData[position.symbol]?.price
? parseFloat(priceData[position.symbol].price)
: parseFloat(position.entryPrice);
// Mark price used as the reference for HyperLiquid's oracle price band. Falls
// back to the mid/mark currentPrice when the mark price is missing or does
// not parse to a finite positive number (otherwise a NaN reference would
// silently skip the band check).
const markPrice = priceData[position.symbol]?.markPrice;
const parsedMarkPrice = markPrice ? parseFloat(markPrice) : NaN;
const referencePrice =
Number.isFinite(parsedMarkPrice) && parsedMarkPrice > 0
? parsedMarkPrice
: currentPrice;
// Use ref to access latest price without triggering fee recalculations
// This prevents continuous recalculations on every WebSocket price update
const currentPriceRef = useRef(currentPrice);
currentPriceRef.current = currentPrice;
// Get top of book data for maker/taker fee determination
const currentTopOfBook = usePerpsTopOfBook({
symbol: position.symbol,
});
// Subscribe to live position updates for this coin
// This ensures margin and PnL values include real-time funding fees
const { positions: livePositions } = usePerpsLivePositions({
throttleMs: 1000,
});
const livePosition = useMemo(
() => livePositions.find((p) => p.symbol === position.symbol) || position,
[livePositions, position],
);
// Determine position direction using live position data
const isLong = parseFloat(livePosition.size) > 0;
const absSize = Math.abs(parseFloat(livePosition.size));
// Calculate effective price for calculations
// For limit orders, use limit price when available; otherwise use current market price
const effectivePrice = useMemo(() => {
if (effectiveOrderType === 'limit' && limitPrice) {
const parsed = parseFloat(limitPrice);
if (!isNaN(parsed) && parsed > 0) {
return parsed;
}
}
return currentPrice;
}, [effectiveOrderType, limitPrice, currentPrice]);
// Calculate display values directly from closePercentage for immediate updates
const { closeAmount, calculatedUSDString } = useMemo(() => {
// During loading, return '0' as temporary state (not a default - intentional for loading UX)
if (isLoadingMarketData) {
return {
closeAmount: '0',
calculatedUSDString: '0.00',
};
}
// Defensive fallback if market data fails to load - prevents crashes
// Real szDecimals should come from market data (varies by asset)
const szDecimals =
marketData?.szDecimals ?? DECIMAL_PRECISION_CONFIG.FallbackSizeDecimals;
const { tokenAmount, usdValue } = calculateCloseAmountFromPercentage({
percentage: closePercentage,
positionSize: absSize,
currentPrice: effectivePrice,
szDecimals,
});
return {
closeAmount: tokenAmount.toString(),
calculatedUSDString: formatCloseAmountUSD(usdValue),
};
}, [
closePercentage,
absSize,
effectivePrice,
marketData?.szDecimals,
isLoadingMarketData,
]);
// Use calculated USD string when not in input mode, user input when typing
const displayUSDString =
isInputFocused || isUserInputActive
? closeAmountUSDString
: calculatedUSDString;
// Use live position data which includes real-time funding fees
// HyperLiquid's marginUsed already includes accumulated PnL
const marginUsed = parseFloat(livePosition.marginUsed);
// Use unrealizedPnl from live position (includes funding fees)
const unrealizedPnl = parseFloat(livePosition.unrealizedPnl);
// Keep pnl reference for backwards compatibility with event tracking
const pnl = unrealizedPnl;
// Position value at the effective price (limit price for limit orders)
const positionValue = useMemo(
() => absSize * effectivePrice,
[absSize, effectivePrice],
);
// P&L at the effective price. For limit orders this recomputes when the
// effective (limit or mark) price changes; for market orders it uses the
// live unrealized PnL.
const entryPrice = parseFloat(position.entryPrice);
const effectivePnL = useMemo(() => {
// For long positions: (effectivePrice - entryPrice) * absSize
// For short positions: (entryPrice - effectivePrice) * absSize
if (effectiveOrderType === 'market') {
return pnl;
}
const priceDiff = isLong
? effectivePrice - entryPrice
: entryPrice - effectivePrice;
return priceDiff * absSize;
}, [entryPrice, absSize, isLong, effectiveOrderType, effectivePrice, pnl]);
// Margin returned on close, adjusted for the price the order will settle at.
// marginUsed embeds unrealized PnL at the current mark price, so for limit
// orders we swap that current-price PnL for the limit-price PnL (effectivePnL).
// For market orders effectivePnL equals unrealizedPnl, so this is a no-op.
//
// "You'll receive" is intentionally an estimate: this swaps out the full
// current unrealizedPnl (price + accrued funding) and adds back only the
// limit-price price spread. Funding that accrues between now and when the
// limit order fills is unknowable, so we deliberately do not project it here.
const effectiveMargin = useMemo(
() => marginUsed - unrealizedPnl + effectivePnL,
[marginUsed, unrealizedPnl, effectivePnL],
);
// Calculate fees using the unified fee hook
const closingValue = useMemo(
() => positionValue * (closePercentage / 100),
[positionValue, closePercentage],
);
const closingValueString = useMemo(
() => closingValue.toString(),
[closingValue],
);
const feeResults = usePerpsOrderFees({
orderType: effectiveOrderType,
amount: closingValueString,
symbol: position.symbol,
isClosing: true,
limitPrice,
direction: isLong ? 'short' : 'long',
currentAskPrice: currentTopOfBook?.bestAsk
? Number.parseFloat(currentTopOfBook.bestAsk)
: undefined,
currentBidPrice: currentTopOfBook?.bestBid
? Number.parseFloat(currentTopOfBook.bestBid)
: undefined,
});
// Simple boolean calculation for rewards state
const hasValidAmount = useMemo(
() => closePercentage > 0 && closingValue > 0,
[closePercentage, closingValue],
);
// Get rewards state using the new hook
const rewardsState = usePerpsRewards({
feeResults,
hasValidAmount,
isFeesLoading: feeResults.isLoadingMetamaskFee,
orderAmount: closingValueString,
});
const vipTier = useVipTier();
// Calculate what user will receive (margin - fees)
// Round each component separately to match what user sees in UI
// This ensures: displayed margin - displayed fees = displayed receive amount
const receiveAmount = useMemo(() => {
const marginPortion = (closePercentage / 100) * effectiveMargin;
// Round margin and fees to 2 decimals (what user sees)
const roundedMargin = Math.round(marginPortion * 100) / 100;
const roundedFees = Math.round(feeResults.totalFee * 100) / 100;
// Subtract rounded values for transparent calculation
return roundedMargin - roundedFees;
}, [closePercentage, effectiveMargin, feeResults.totalFee]);
// Get minimum order amount for this asset
const { minimumOrderAmount } = useMinimumOrderAmount({
asset: position.symbol,
});
// Calculate remaining position value after partial close
const remainingPositionValue = positionValue * (1 - closePercentage / 100);
const isPartialClose = closePercentage < 100;
// Use the validation hook
const validationResult = usePerpsClosePositionValidation({
symbol: position.symbol,
closePercentage,
closeAmount: closeAmount.toString(),
orderType: effectiveOrderType,
limitPrice,
// Pass the live mark price (not the limit price) so the "limit price far
// from market" warning and protocol validation compare against the real
// market. Limit-price valuation is applied separately via positionValue/
// closingValue below.
currentPrice,
referencePrice,
positionSize: absSize,
positionValue,
minimumOrderAmount,
closingValue,
remainingPositionValue,
receiveAmount,
isPartialClose,
skipValidation: isInputFocused,
});
const { handleClosePosition, isClosing } = usePerpsClosePosition();
const unrealizedPnlPercent = useMemo(() => {
const initialMargin = marginUsed - pnl; // Back-calculate initial margin
return initialMargin > 0 ? (pnl / initialMargin) * 100 : 0;
}, [marginUsed, pnl]);
usePerpsEventTracking({
eventName: MetaMetricsEvents.PERPS_SCREEN_VIEWED,
properties: {
[PERPS_EVENT_PROPERTY.SCREEN_TYPE]:
PERPS_EVENT_VALUE.SCREEN_TYPE.POSITION_CLOSE,
[PERPS_EVENT_PROPERTY.ASSET]: position.symbol,
[PERPS_EVENT_PROPERTY.DIRECTION]: isLong
? PERPS_EVENT_VALUE.DIRECTION.LONG
: PERPS_EVENT_VALUE.DIRECTION.SHORT,
[PERPS_EVENT_PROPERTY.POSITION_SIZE]: absSize,
[PERPS_EVENT_PROPERTY.UNREALIZED_PNL_DOLLAR]: pnl,
[PERPS_EVENT_PROPERTY.UNREALIZED_PNL_PERCENT]: unrealizedPnlPercent,
[PERPS_EVENT_PROPERTY.SOURCE]: PERPS_EVENT_VALUE.SOURCE.PERP_ASSET_SCREEN,
[PERPS_EVENT_PROPERTY.RECEIVED_AMOUNT]: receiveAmount,
},
});
// Initialize USD values when price data is available (only once, not on price updates)
useEffect(() => {
if (!isAmountInitializedRef.current && absSize > 0 && effectivePrice > 0) {
const initialUSDAmount = absSize * effectivePrice;
setCloseAmountUSDString(formatCloseAmountUSD(initialUSDAmount));
isAmountInitializedRef.current = true;
}
}, [absSize, effectivePrice]);
// Sync closeAmountUSDString with calculatedUSDString when user is not actively editing
// This prevents the jump when focusing input after price updates
useEffect(() => {
if (!isUserInputActive && isAmountInitializedRef.current) {
setCloseAmountUSDString(calculatedUSDString);
}
}, [calculatedUSDString, isUserInputActive]);
// Auto-open limit price bottom sheet when switching to limit order
useEffect(() => {
if (effectiveOrderType === 'limit' && !limitPrice) {
setIsLimitPriceVisible(true);
}
}, [effectiveOrderType, limitPrice]);
const handleConfirm = async () => {
// For full close, don't send size parameter
const sizeToClose = closePercentage === 100 ? undefined : closeAmount;
const isFullClose = closePercentage === 100;
// For limit orders, validate price
if (effectiveOrderType === 'limit' && !limitPrice) {
return;
}
// Go back immediately to close the position screen
navigation.goBack();
await handleClosePosition({
position: livePosition,
size: sizeToClose || '',
orderType: effectiveOrderType,
limitPrice: effectiveOrderType === 'limit' ? limitPrice : undefined,
trackingData: {
totalFee: feeResults.totalFee,
marketPrice: currentPrice,
receivedAmount: receiveAmount,
realizedPnl: effectivePnL * (closePercentage / 100),
metamaskFeeRate: feeResults.metamaskFeeRate,
feeDiscountPercentage: feeResults.feeDiscountPercentage,
metamaskFee: feeResults.metamaskFee,
estimatedPoints: rewardsState.estimatedPoints,
inputMethod: inputMethodRef.current,
source: routeSource,
vipTier: vipTier ?? undefined,
vipDiscount: feeResults.feeDiscountPercentage,
},
marketPrice: priceData[position.symbol]?.price,
// Always pass slippage parameters for price context
// For 100% closes, omit usdAmount to bypass $10 minimum validation
slippage: {
usdAmount: isFullClose ? undefined : closingValueString,
priceAtCalculation: effectivePrice,
maxSlippageBps:
effectiveOrderType === 'limit'
? ORDER_SLIPPAGE_CONFIG.DefaultLimitSlippageBps
: ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps,
},
});
};
const handleAmountPress = () => {
setIsInputFocused(true);
};
const handleKeypadChange = useCallback(
({ value }: { value: string; valueAsNumber: number }) => {
inputMethodRef.current = 'keypad';
const previousValue = closeAmountUSDString;
// 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);
}
// Enforce 9-digit limit (ignoring non-digits). Block the change if exceeded.
const digitCount = (adjustedValue.match(/\d/g) || []).length;
if (digitCount > 9) {
return; // Ignore input that would exceed 9 digits
}
// 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);
// Calculate percentage and token amount
const newPercentage =
positionValue > 0 ? (clampedValue / positionValue) * 100 : 0;
// Update percentage (amount and token values are calculated automatically)
setClosePercentage(newPercentage);
},
[positionValue, isInputFocused, isUserInputActive, closeAmountUSDString],
);
const handlePercentagePress = (percentage: number) => {
inputMethodRef.current = 'percentage';
const newPercentage = percentage * 100;
setClosePercentage(newPercentage);
// Update USD input to match calculated value for keypad display consistency
const newUSDAmount = (newPercentage / 100) * absSize * effectivePrice;
setCloseAmountUSDString(formatCloseAmountUSD(newUSDAmount));
};
const handleMaxPress = () => {
inputMethodRef.current = 'max';
setClosePercentage(100);
// Update USD input to match calculated value for keypad display consistency
const newUSDAmount = absSize * effectivePrice;
setCloseAmountUSDString(formatCloseAmountUSD(newUSDAmount));
};
const handleDonePress = () => {
setIsInputFocused(false);
setIsUserInputActive(false);
};
const handleSliderChange = (value: number) => {
inputMethodRef.current = 'slider';
setClosePercentage(value);
// Update USD input to match calculated value for keypad display consistency
const newUSDAmount = (value / 100) * absSize * effectivePrice;
setCloseAmountUSDString(formatCloseAmountUSD(newUSDAmount));
};
// Hide provider-level limit price required error on this UI. Surface the
// minimum amount error (e.g. minimum $10) and the "limit price too far"
// band error — both are blocking, so Close must explain why it is disabled.
const filteredErrors = useMemo(() => {
const minimumAmountErrorPrefix = strings(
'perps.order.validation.minimum_amount',
{
amount: '',
},
).replace(/\s+$/, '');
const limitPriceTooFarError = strings(
'perps.order.limit_price_modal.limit_price_too_far',
);
// The actual minimum amount string includes the amount placeholder; match by key detection.
return validationResult.errors.filter(
(err) =>
err.startsWith(minimumAmountErrorPrefix) ||
err === limitPriceTooFarError,
);
}, [validationResult.errors]);
const Summary = (
<PerpsCloseSummary
totalMargin={(closePercentage / 100) * effectiveMargin}
totalPnl={effectivePnL * (closePercentage / 100)}
totalFees={feeResults.totalFee}
originalTotalFees={feeResults.undiscountedTotalFee}
feeDiscountPercentage={rewardsState.feeDiscountPercentage}
metamaskFeeRate={feeResults.metamaskFeeRate}
protocolFeeRate={feeResults.protocolFeeRate}
originalMetamaskFeeRate={feeResults.originalMetamaskFeeRate}
receiveAmount={receiveAmount}
shouldShowRewards={rewardsState.shouldShowRewardsRow}
estimatedPoints={rewardsState.estimatedPoints}
bonusBips={rewardsState.bonusBips}
isLoadingFees={feeResults.isLoadingMetamaskFee}
isLoadingRewards={rewardsState.isLoading}
hasRewardsError={rewardsState.hasError}
accountOptedIn={rewardsState.accountOptedIn}
rewardsAccount={rewardsState.account}
isInputFocused={isInputFocused}
testIDs={{
feesTooltip: PerpsClosePositionViewSelectorsIDs.FEES_TOOLTIP_BUTTON,
receiveTooltip:
PerpsClosePositionViewSelectorsIDs.YOU_RECEIVE_TOOLTIP_BUTTON,
pointsTooltip: PerpsClosePositionViewSelectorsIDs.POINTS_TOOLTIP_BUTTON,
marginValue: PerpsClosePositionViewSelectorsIDs.MARGIN_VALUE,
feesValue: PerpsClosePositionViewSelectorsIDs.FEES_VALUE,
receiveValue: PerpsClosePositionViewSelectorsIDs.RECEIVE_VALUE,
}}
/>
);
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<PerpsOrderHeader
asset={position.symbol}
price={currentPrice}
title={strings('perps.close_position.title')}
isLoading={isClosing}
orderType={
isClosePositionLimitOrderEnabled ? effectiveOrderType : undefined
}
onOrderTypePress={
isClosePositionLimitOrderEnabled
? () => setIsOrderTypeVisible(true)
: undefined
}
/>
<ScrollView
style={styles.content}
alwaysBounceVertical={false}
contentContainerStyle={[
styles.scrollViewContent,
isInputFocused && styles.scrollViewContentWithKeypad,
]}
showsVerticalScrollIndicator={false}
>
{/* Amount Display */}
<PerpsAmountDisplay
label={strings('perps.close_position.select_amount')}
amount={displayUSDString}
showWarning={false}
onPress={handleAmountPress}
isActive={isInputFocused}
tokenAmount={formatPositionSize(closeAmount, marketData?.szDecimals)}
hasError={filteredErrors.length > 0}
tokenSymbol={position.symbol}
showMaxAmount={false}
/>
{/* Toggle Button for USD/Token Display */}
<View style={styles.toggleContainer}>
<Text variant={TextVariant.BodySM} color={TextColor.Alternative}>
{`${formatPositionSize(closeAmount, marketData?.szDecimals)} ${getPerpsDisplaySymbol(position.symbol)}`}
</Text>
</View>
{/* Slider - Hidden when keypad/input is focused */}
{!isInputFocused && (
<View style={styles.sliderSection}>
<PerpsSlider
value={closePercentage}
onValueChange={handleSliderChange}
minimumValue={0}
maximumValue={100}
step={1}
showPercentageLabels
disabled={isClosing}
/>
</View>
)}
{/* Limit Price - only show for limit orders (still hidden during input to avoid overlap) */}
{effectiveOrderType === 'limit' && !isInputFocused && (
<View style={styles.detailsWrapper}>
<View style={styles.inputGroupContainer}>
<TouchableOpacity
testID={PerpsClosePositionViewSelectorsIDs.LIMIT_PRICE_ROW}
onPress={() => setIsLimitPriceVisible(true)}
>
<KeyValueRow
variant={KeyValueRowVariant.Input}
keyLabel={strings('perps.order.limit_price')}
value={
limitPrice
? formatPerpsFiat(limitPrice, {
ranges: PRICE_RANGES_UNIVERSAL,
})
: strings('perps.order.set_price')
}
/>
</TouchableOpacity>
</View>
</View>
)}
{/* Order Details moved to footer summary */}
{/* Validation Messages - keep visible while typing */}
{/* Filter the errors and only show minimum $10 error */}
{filteredErrors.length > 0 && (
<View style={styles.validationSection}>
{filteredErrors.map((error, index) => (
<View key={`error-${index}`} style={styles.errorMessage}>
<Icon
name={IconName.Danger}
size={IconSize.Sm}
color={IconColor.ErrorDefault}
/>
<Text variant={TextVariant.BodySM} color={TextColor.Error}>
{error}
</Text>
</View>
))}
</View>
)}
</ScrollView>
{/* Keypad Section - Show when input is focused; keep summary and slider above */}
{isInputFocused && (
<View style={styles.bottomSection}>
{/* Summary shown above keypad while editing */}
{Summary}
<View style={styles.percentageButtonsContainer}>
<Button
variant={ButtonVariant.Secondary}
size={ButtonSize.Md}
onPress={() => handlePercentagePress(0.25)}
style={styles.percentageButton}
>
25%
</Button>
<Button
variant={ButtonVariant.Secondary}
size={ButtonSize.Md}
onPress={() => handlePercentagePress(0.5)}
style={styles.percentageButton}
>
50%
</Button>
<Button
variant={ButtonVariant.Secondary}
size={ButtonSize.Md}
onPress={handleMaxPress}
style={styles.percentageButton}
>
{strings('perps.deposit.max_button')}
</Button>
<Button
variant={ButtonVariant.Secondary}
size={ButtonSize.Md}
onPress={handleDonePress}
style={styles.percentageButton}
>
{strings('perps.deposit.done_button')}
</Button>
</View>
<Keypad
value={closeAmountUSDString}
onChange={handleKeypadChange}
currency={'USD'}
decimals={2}
style={styles.keypad}
/>
</View>
)}
{/* Summary + Action Buttons - Always visible (button hidden when keypad active) */}
<View style={[styles.footer, styles.footerWithSummary]}>
{/* Summary Section (not shown here if input focused, as it's rendered above keypad) */}
{!isInputFocused && Summary}
{!isInputFocused && (
<Button
variant={ButtonVariant.Primary}
size={ButtonSize.Lg}
isFullWidth
onPress={handleConfirm}
isDisabled={
isClosing ||
(effectiveOrderType === 'limit' &&
(!limitPrice || parseFloat(limitPrice) <= 0)) ||
(effectiveOrderType === 'market' && closePercentage === 0) ||
!validationResult.isValid
}
isLoading={isClosing}
testID={
PerpsClosePositionViewSelectorsIDs.CLOSE_POSITION_CONFIRM_BUTTON
}
>
{isClosing
? strings('perps.close_position.closing')
: strings('perps.close_position.button')}
</Button>
)}
</View>
{/* Limit Price Bottom Sheet - gated on the derived order type so a
mid-session flag flip closes it immediately (effectiveOrderType can
only be 'limit' while the feature flag is enabled). */}
<PerpsLimitPriceBottomSheet
isVisible={isLimitPriceVisible && effectiveOrderType === 'limit'}
onClose={() => {
setIsLimitPriceVisible(false);
// If user dismisses without entering a price, revert order type to market
if (orderType === 'limit' && !limitPrice) {
setOrderType('market');
showToast(
PerpsToastOptions.positionManagement.closePosition.limitClose
.partial.switchToMarketOrderMissingLimitPrice,
);
}
}}
onConfirm={(price) => {
setLimitPrice(price);
// Close after confirmation explicitly
setIsLimitPriceVisible(false);
}}
asset={position.symbol}
limitPrice={limitPrice}
currentPrice={currentPrice}
direction={isLong ? 'short' : 'long'} // Opposite direction for closing
isClosingPosition
/>
{/* Order Type Bottom Sheet - gated behind feature flag */}
{isClosePositionLimitOrderEnabled && (
<PerpsOrderTypeBottomSheet
isVisible={isOrderTypeVisible}
onClose={() => setIsOrderTypeVisible(false)}
onSelect={(type) => {
setOrderType(type);
// Clear limit price when switching back to market order
if (type === 'market') {
setLimitPrice('');
}
setIsOrderTypeVisible(false);
}}
currentOrderType={orderType}
asset={position.symbol}
direction={isLong ? 'short' : 'long'} // Opposite direction for closing
/>
)}
</SafeAreaView>
);
};
export default PerpsClosePositionView;