-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathindex.tsx
More file actions
537 lines (484 loc) · 19.5 KB
/
index.tsx
File metadata and controls
537 lines (484 loc) · 19.5 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
import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import ScreenView from '../../../../Base/ScreenView';
import {
MAX_INPUT_LENGTH,
TokenInputArea,
TokenInputAreaRef,
TokenInputAreaType,
} from '../../components/TokenInputArea';
import { useStyles } from '../../../../../component-library/hooks';
import { Box } from '../../../Box/Box';
import { FlexDirection, AlignItems } from '../../../Box/box.types';
import Text, {
TextColor,
TextVariant,
} from '../../../../../component-library/components/Texts/Text';
import { getNetworkImageSource } from '../../../../../util/networks';
import { useLatestBalance } from '../../hooks/useLatestBalance';
import {
selectSourceAmount,
selectSelectedDestChainId,
setSourceAmount,
setSourceAmountAsMax,
resetBridgeState,
selectDestToken,
selectSourceToken,
selectBridgeControllerState,
selectIsEvmNonEvmBridge,
selectIsSubmittingTx,
selectDestAddress,
selectIsSolanaSourced,
selectBridgeViewMode,
setBridgeViewMode,
selectIsNonEvmNonEvmBridge,
} from '../../../../../core/redux/slices/bridge';
import {
useNavigation,
useRoute,
type RouteProp,
} from '@react-navigation/native';
import { getBridgeNavbar } from '../../../Navbar';
import { useTheme } from '../../../../../util/theme';
import { strings } from '../../../../../../locales/i18n';
import Engine from '../../../../../core/Engine';
import Routes from '../../../../../constants/navigation/Routes';
import QuoteDetailsCard from '../../components/QuoteDetailsCard';
import { useBridgeQuoteRequest } from '../../hooks/useBridgeQuoteRequest';
import { useBridgeQuoteData } from '../../hooks/useBridgeQuoteData';
import BannerAlert from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert';
import { BannerAlertSeverity } from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.types';
import { createStyles } from './BridgeView.styles';
import { useInitialSourceToken } from '../../hooks/useInitialSourceToken';
import { useInitialDestToken } from '../../hooks/useInitialDestToken';
import { useGasFeeEstimates } from '../../../../Views/confirmations/hooks/gas/useGasFeeEstimates';
import { selectSelectedNetworkClientId } from '../../../../../selectors/networkController';
import { useIsNetworkEnabled } from '../../hooks/useIsNetworkEnabled';
import { BridgeToken } from '../../types';
import { useSwitchTokens } from '../../hooks/useSwitchTokens';
import { ScrollView } from 'react-native';
import useIsInsufficientBalance from '../../hooks/useInsufficientBalance';
import { selectSelectedInternalAccountFormattedAddress } from '../../../../../selectors/accountsController';
import { isHardwareAccount } from '../../../../../util/address';
import { endTrace, TraceName } from '../../../../../util/trace.ts';
import { useInitialSlippage } from '../../hooks/useInitialSlippage/index.ts';
import { useHasSufficientGas } from '../../hooks/useHasSufficientGas/index.ts';
import { useRecipientInitialization } from '../../hooks/useRecipientInitialization';
import ApprovalTooltip from '../../components/ApprovalText';
import { BRIDGE_MM_FEE_RATE } from '@metamask/bridge-controller';
import { selectSourceWalletAddress } from '../../../../../selectors/bridge';
import { isNullOrUndefined, Hex } from '@metamask/utils';
import { useBridgeQuoteEvents } from '../../hooks/useBridgeQuoteEvents/index.ts';
import { SwapsKeypad } from '../../components/SwapsKeypad/index.tsx';
import { getGasFeesSponsoredNetworkEnabled } from '../../../../../selectors/featureFlagController/gasFeesSponsored';
import { trimTrailingZeros } from '../../utils/trimTrailingZeros.ts';
import { FLipQuoteButton } from '../../components/FlipQuoteButton/index.tsx';
import { useIsGasIncludedSTXSendBundleSupported } from '../../hooks/useIsGasIncludedSTXSendBundleSupported/index.ts';
import { useIsGasIncluded7702Supported } from '../../hooks/useIsGasIncluded7702Supported/index.ts';
import { useRefreshSmartTransactionsLiveness } from '../../../../hooks/useRefreshSmartTransactionsLiveness';
import { BridgeViewSelectorsIDs } from './BridgeView.testIds';
import { useRWAToken } from '../../hooks/useRWAToken.ts';
import { SwapsKeypadRef } from '../../components/SwapsKeypad/types.ts';
import { GaslessQuickPickOptions } from '../../components/GaslessQuickPickOptions/index.tsx';
import { SwapsConfirmButton } from '../../components/SwapsConfirmButton/index.tsx';
import { useBridgeViewOnFocus } from '../../hooks/useBridgeViewOnFocus/index.ts';
import { useRenderQuoteExpireModal } from '../../hooks/useRenderQuoteExpireModal/index.ts';
import { type BridgeRouteParams } from '../../hooks/useSwapBridgeNavigation/index.ts';
import { useTrackSwapPageViewed } from '../../hooks/useTrackSwapPageViewed/index.ts';
const BridgeView = () => {
const [isErrorBannerVisible, setIsErrorBannerVisible] = useState(true);
const isSubmittingTx = useSelector(selectIsSubmittingTx);
const { styles } = useStyles(createStyles);
const dispatch = useDispatch();
const navigation = useNavigation();
const route = useRoute<RouteProp<{ params: BridgeRouteParams }, 'params'>>();
const { colors } = useTheme();
const keypadRef = useRef<SwapsKeypadRef>(null);
// Needed to get gas fee estimates
const selectedNetworkClientId = useSelector(selectSelectedNetworkClientId);
useGasFeeEstimates(selectedNetworkClientId);
const sourceAmount = useSelector(selectSourceAmount);
const sourceToken = useSelector(selectSourceToken);
const destToken = useSelector(selectDestToken);
const destChainId = useSelector(selectSelectedDestChainId);
const destAddress = useSelector(selectDestAddress);
const bridgeViewMode = useSelector(selectBridgeViewMode);
const { quotesLastFetched } = useSelector(selectBridgeControllerState);
const { handleSwitchTokens } = useSwitchTokens();
const { isStockToken } = useRWAToken();
const selectedAddress = useSelector(
selectSelectedInternalAccountFormattedAddress,
);
const isHardwareAddress = selectedAddress
? !!isHardwareAccount(selectedAddress)
: false;
const walletAddress = useSelector(selectSourceWalletAddress);
const isEvmNonEvmBridge = useSelector(selectIsEvmNonEvmBridge);
const isNonEvmNonEvmBridge = useSelector(selectIsNonEvmNonEvmBridge);
const isSolanaSourced = useSelector(selectIsSolanaSourced);
const isDestNetworkEnabled = useIsNetworkEnabled(destToken?.chainId);
/** The entry point location for analytics (e.g. Main View, Token View, Trending Explore) */
const location = route.params?.location;
// inputRef is used to programmatically blur the input field after a delay
// This gives users time to type before the keyboard disappears
// The ref is typed to only expose the blur method we need
const inputRef = useRef<TokenInputAreaRef>(null);
// Fetch STX liveness for the source chain
useRefreshSmartTransactionsLiveness(sourceToken?.chainId);
// Update isGasIncludedSTXSendBundleSupported state based on source chain capabilities
useIsGasIncludedSTXSendBundleSupported(sourceToken?.chainId);
// Update isGasIncluded7702Supported state
useIsGasIncluded7702Supported(sourceToken?.chainId);
const initialSourceToken = route.params?.sourceToken;
const initialSourceAmount = route.params?.sourceAmount;
const initialDestToken = route.params?.destToken;
useInitialSourceToken(initialSourceToken, initialSourceAmount);
useInitialDestToken(initialSourceToken, initialDestToken);
// Initialize recipient account
const hasInitializedRecipient = useRef(false);
useRecipientInitialization(hasInitializedRecipient);
useBridgeViewOnFocus({ inputRef, keypadRef });
useEffect(() => {
if (route.params?.bridgeViewMode && bridgeViewMode === undefined) {
dispatch(setBridgeViewMode(route.params?.bridgeViewMode));
}
}, [route.params?.bridgeViewMode, dispatch, bridgeViewMode]);
// End trace when component mounts
useEffect(() => {
endTrace({ name: TraceName.SwapViewLoaded, timestamp: Date.now() });
}, []);
useInitialSlippage();
const hasDestinationPicker = isEvmNonEvmBridge || isNonEvmNonEvmBridge;
const latestSourceBalance = useLatestBalance({
address: sourceToken?.address,
decimals: sourceToken?.decimals,
chainId: sourceToken?.chainId,
balance: sourceToken?.balance,
});
const updateQuoteParams = useBridgeQuoteRequest({
latestSourceAtomicBalance: latestSourceBalance?.atomicBalance,
});
const {
activeQuote,
isLoading,
destTokenAmount,
quoteFetchError,
isNoQuotesAvailable,
blockaidError,
shouldShowPriceImpactWarning,
} = useBridgeQuoteData({
latestSourceAtomicBalance: latestSourceBalance?.atomicBalance,
});
const isValidSourceAmount =
sourceAmount !== undefined && sourceAmount !== '.' && sourceToken?.decimals;
const hasValidBridgeInputs =
isValidSourceAmount &&
!!sourceToken &&
!!destToken &&
// Prevent quote fetching when destination address is not set
// Destination address is only needed for EVM <> Non-EVM bridges, or Non-EVM <> Non-EVM bridges (when different)
(!hasDestinationPicker || (hasDestinationPicker && Boolean(destAddress)));
const hasSufficientGas = useHasSufficientGas({ quote: activeQuote });
const hasInsufficientBalance = useIsInsufficientBalance({
amount: sourceAmount,
token: sourceToken,
latestAtomicBalance: latestSourceBalance?.atomicBalance,
});
const isGasFeesSponsoredNetworkEnabled = useSelector(
getGasFeesSponsoredNetworkEnabled,
);
// Check if quote is sponsored: both tokens must be on the same chain and that chain must be sponsored
const isQuoteSponsored = useMemo(() => {
if (!sourceToken?.chainId || !destToken?.chainId) return false;
// Both tokens must be on the same chain
if (sourceToken.chainId !== destToken.chainId) return false;
// Check if the chain is sponsored
return isGasFeesSponsoredNetworkEnabled(sourceToken.chainId as Hex);
}, [
sourceToken?.chainId,
destToken?.chainId,
isGasFeesSponsoredNetworkEnabled,
]);
const isSubmitDisabled =
(isLoading && !activeQuote) ||
hasInsufficientBalance ||
isSubmittingTx ||
(isHardwareAddress && isSolanaSourced) ||
!!blockaidError ||
!hasSufficientGas ||
!walletAddress;
useBridgeQuoteEvents({
hasInsufficientBalance,
hasNoQuotesAvailable: isNoQuotesAvailable,
hasInsufficientGas: !hasSufficientGas,
hasTxAlert: Boolean(blockaidError),
isSubmitDisabled,
isPriceImpactWarningVisible: shouldShowPriceImpactWarning,
});
// Compute error state directly from dependencies
const isError = isNoQuotesAvailable || quoteFetchError;
// Always show quote details when there's an active quote
const shouldDisplayQuoteDetails = !!activeQuote;
// Update quote parameters when relevant state changes
useEffect(() => {
if (hasValidBridgeInputs) {
updateQuoteParams();
}
return () => {
updateQuoteParams.cancel();
};
}, [hasValidBridgeInputs, updateQuoteParams]);
// Reset bridge state when component unmounts
useEffect(
() => () => {
dispatch(resetBridgeState());
// Clear bridge controller state if available
if (Engine.context.BridgeController?.resetState) {
Engine.context.BridgeController.resetState();
}
},
[dispatch],
);
useEffect(() => {
navigation.setOptions(getBridgeNavbar(navigation, bridgeViewMode, colors));
}, [navigation, bridgeViewMode, colors]);
useTrackSwapPageViewed();
// Reset isErrorBannerVisible when error state changes
useEffect(() => {
if (isError) {
setIsErrorBannerVisible(true);
}
}, [isError]);
// Keypad already handles max token decimals, so we don't need to check here
const handleKeypadChange = ({
value,
}: {
value: string;
valueAsNumber: number;
pressedKey: string;
}) => {
if (value.length >= MAX_INPUT_LENGTH) {
return;
}
dispatch(setSourceAmount(value || undefined));
};
const handleSourceMaxPress = () => {
if (latestSourceBalance?.displayBalance) {
const balance = latestSourceBalance.displayBalance;
const cleaned = trimTrailingZeros(balance);
dispatch(setSourceAmountAsMax(cleaned));
}
};
const handleSourceTokenPress = () =>
navigation.navigate(Routes.BRIDGE.TOKEN_SELECTOR, {
type: 'source',
});
const handleDestTokenPress = () =>
navigation.navigate(Routes.BRIDGE.TOKEN_SELECTOR, {
type: 'dest',
});
useRenderQuoteExpireModal({ inputRef, latestSourceBalance });
const isRWATokenSelected = useMemo(
() =>
(sourceToken && isStockToken(sourceToken as BridgeToken)) ||
(destToken && isStockToken(destToken as BridgeToken)),
[isStockToken, sourceToken, destToken],
);
const genericErrorMessage = isRWATokenSelected
? strings('bridge.stock_token_error_banner_description')
: strings('bridge.error_banner_description');
const renderBottomContent = () => {
if (isLoading && !activeQuote) {
return (
<Box style={styles.buttonContainer}>
<Text color={TextColor.Alternative}>
{strings('bridge.fetching_quote')}
</Text>
</Box>
);
}
// Prevent bottom section from rendering when no active
// quotes exist and none are being fetching.
// This resolves edge cases when users are redirected back from
// Select Quote page due to quotes expiry.
if (!activeQuote) {
return null;
}
// TODO: remove this once controller types are updated
// @ts-expect-error: controller types are not up to date yet
const quoteBpsFee = activeQuote?.quote?.feeData?.metabridge?.quoteBpsFee;
const feePercentage = !isNullOrUndefined(quoteBpsFee)
? quoteBpsFee / 100
: BRIDGE_MM_FEE_RATE;
const hasFee = activeQuote && feePercentage > 0;
const approval =
activeQuote?.approval && sourceAmount && sourceToken
? { amount: sourceAmount, symbol: sourceToken.symbol }
: null;
return (
isValidSourceAmount &&
activeQuote &&
quotesLastFetched && (
<Box style={styles.buttonContainer}>
{isHardwareAddress && isSolanaSourced && (
<BannerAlert
severity={BannerAlertSeverity.Error}
description={strings(
'bridge.hardware_wallet_not_supported_solana',
)}
/>
)}
{blockaidError && (
<BannerAlert
severity={BannerAlertSeverity.Error}
title={strings('bridge.blockaid_error_title')}
description={blockaidError}
/>
)}
<SwapsConfirmButton
location={location}
latestSourceBalance={latestSourceBalance}
/>
<Box flexDirection={FlexDirection.Row} alignItems={AlignItems.center}>
<Text variant={TextVariant.BodySM} color={TextColor.Alternative}>
{hasFee
? strings('bridge.fee_disclaimer', {
feePercentage,
})
: strings('bridge.no_mm_fee_disclaimer', {
destTokenSymbol: destToken?.symbol,
})}
{approval
? ` ${strings('bridge.approval_needed', approval)}`
: ''}{' '}
</Text>
{approval && (
<ApprovalTooltip
amount={approval.amount}
symbol={approval.symbol}
/>
)}
</Box>
</Box>
)
);
};
return (
// Need this to be full height of screen
// @ts-expect-error The type is incorrect, this will work
<ScreenView contentContainerStyle={styles.screen}>
<Box
style={styles.content}
onStartShouldSetResponder={() => true}
onResponderRelease={() => {
inputRef.current?.blur();
keypadRef.current?.close();
}}
>
<Box style={styles.inputsContainer}>
<TokenInputArea
ref={inputRef}
amount={sourceAmount}
token={sourceToken}
tokenBalance={latestSourceBalance?.displayBalance}
networkImageSource={
sourceToken?.chainId
? getNetworkImageSource({
chainId: sourceToken?.chainId,
})
: undefined
}
testID={BridgeViewSelectorsIDs.SOURCE_TOKEN_AREA}
tokenType={TokenInputAreaType.Source}
onInputPress={() => keypadRef.current?.open()}
onTokenPress={handleSourceTokenPress}
onMaxPress={handleSourceMaxPress}
latestAtomicBalance={latestSourceBalance?.atomicBalance}
isSourceToken
isQuoteSponsored={isQuoteSponsored}
/>
<FLipQuoteButton
onPress={handleSwitchTokens(destTokenAmount)}
disabled={
!destChainId ||
!destToken ||
!sourceToken ||
!isDestNetworkEnabled
}
/>
<TokenInputArea
amount={destTokenAmount}
token={destToken}
networkImageSource={
destToken
? getNetworkImageSource({ chainId: destToken?.chainId })
: undefined
}
testID={BridgeViewSelectorsIDs.DESTINATION_TOKEN_AREA}
tokenType={TokenInputAreaType.Destination}
onInputPress={() => keypadRef.current?.close()}
onTokenPress={handleDestTokenPress}
isLoading={!destTokenAmount && isLoading}
style={styles.destTokenArea}
isQuoteSponsored={isQuoteSponsored}
/>
</Box>
{/* Scrollable Dynamic Content */}
<ScrollView
testID={BridgeViewSelectorsIDs.BRIDGE_VIEW_SCROLL}
style={styles.scrollView}
contentContainerStyle={styles.scrollViewContent}
showsVerticalScrollIndicator={false}
>
<Box style={styles.dynamicContent}>
{isError && isErrorBannerVisible && (
<Box style={styles.buttonContainer}>
<BannerAlert
severity={BannerAlertSeverity.Error}
description={genericErrorMessage}
onClose={() => {
setIsErrorBannerVisible(false);
inputRef.current?.focus();
keypadRef.current?.open();
}}
/>
</Box>
)}
{shouldDisplayQuoteDetails && (
<Box style={styles.quoteContainer}>
<QuoteDetailsCard
location={location}
hasInsufficientBalance={hasInsufficientBalance}
/>
</Box>
)}
</Box>
</ScrollView>
{renderBottomContent()}
<SwapsKeypad
ref={keypadRef}
value={sourceAmount || '0'}
onChange={handleKeypadChange}
currency={sourceToken?.symbol || 'ETH'}
decimals={sourceToken?.decimals ?? Infinity}
>
{sourceAmount && sourceAmount !== '0' ? (
<SwapsConfirmButton
location={location}
latestSourceBalance={latestSourceBalance}
testID={BridgeViewSelectorsIDs.CONFIRM_BUTTON_KEYPAD}
/>
) : (
<GaslessQuickPickOptions
token={sourceToken}
onMaxPress={handleSourceMaxPress}
isQuoteSponsored={isQuoteSponsored}
onChange={handleKeypadChange}
/>
)}
</SwapsKeypad>
</Box>
</ScreenView>
);
};
export default BridgeView;