-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathBuildQuote.tsx
More file actions
891 lines (829 loc) · 28 KB
/
BuildQuote.tsx
File metadata and controls
891 lines (829 loc) · 28 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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Animated, View } from 'react-native';
import {
useNavigation,
useFocusEffect,
useIsFocused,
} from '@react-navigation/native';
import type { CaipChainId } from '@metamask/utils';
import ScreenLayout from '../../Aggregator/components/ScreenLayout';
import { computeAmountUpdate } from '../../utils/computeAmountUpdate';
import { getRampCallbackBaseUrl } from '../../utils/getRampCallbackBaseUrl';
import { providerSupportsAsset } from '../../utils/providerSupportsAsset';
import { normalizeAssetIdForApi } from '../../utils/normalizeAssetIdForApi';
import { useProviderLimits } from '../../hooks/useProviderLimits';
import Keypad, { type KeypadChangeData, Keys } from '../../../../Base/Keypad';
import PaymentMethodPill from '../../components/PaymentMethodPill';
import QuickAmounts from '../../components/QuickAmounts';
import {
Text,
TextVariant,
TextColor,
FontWeight,
Button,
ButtonVariant,
ButtonSize,
IconName,
} from '@metamask/design-system-react-native';
import { strings } from '../../../../../../locales/i18n';
import HeaderCompactStandard from '../../../../../component-library/components-temp/HeaderCompactStandard';
import Routes from '../../../../../constants/navigation/Routes';
import { useStyles } from '../../../../hooks/useStyles';
import styleSheet from './BuildQuote.styles';
import { getFontSizeForInputLength } from './getFontSizeForInputLength';
import { useFormatters } from '../../../../hooks/useFormatters';
import { useTokenNetworkInfo } from '../../hooks/useTokenNetworkInfo';
import {
RampsOrderStatus,
normalizeProviderCode,
} from '@metamask/ramps-controller';
import { useRampsController } from '../../hooks/useRampsController';
import { useRampsQuotes } from '../../hooks/useRampsQuotes';
import { useContinueWithQuote } from '../../hooks/useContinueWithQuote';
import { createSettingsModalNavDetails } from '../Modals/SettingsModal';
import useRampAccountAddress from '../../hooks/useRampAccountAddress';
import { useBlinkingCursor } from '../../hooks/useBlinkingCursor';
import { useDebouncedValue } from '../../../../hooks/useDebouncedValue';
import { BuildQuoteSelectors } from '../../Aggregator/Views/BuildQuote/BuildQuote.testIds';
import { BUILD_QUOTE_TEST_IDS } from './BuildQuote.testIds';
import { createPaymentSelectionModalNavigationDetails } from '../Modals/PaymentSelectionModal';
import { createTokenNotAvailableModalNavigationDetails } from '../Modals/TokenNotAvailableModal';
import { useParams } from '../../../../../util/navigation/navUtils';
import BannerAlert from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert';
import { BannerAlertSeverity } from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.types';
import { parseUserFacingError } from '../../utils/parseUserFacingError';
import { useAnalytics } from '../../../../hooks/useAnalytics/useAnalytics';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import { useSelector } from 'react-redux';
import {
getRampRoutingDecision,
UnifiedRampRoutingType,
} from '../../../../../reducers/fiatOrders';
import TruncatedError from '../../components/TruncatedError';
import { PROVIDER_LINKS } from '../../Aggregator/types';
import { failSession } from '../../headless/sessionRegistry';
const BAILED_ORDER_STATUSES = new Set<RampsOrderStatus>([
RampsOrderStatus.Precreated,
RampsOrderStatus.IdExpired,
RampsOrderStatus.Unknown,
]);
export function isBailedOrderStatus(
status: RampsOrderStatus | undefined,
): boolean {
return status != null && BAILED_ORDER_STATUSES.has(status);
}
/**
* Identifies which flow the user used to enter the Buy screen.
* - 'tokenInfo': Home → Tokens → Token Info → Buy
* - 'homeTokenList': Home → (token list with Buy buttons) → Buy
* - undefined: Home → Buy → Token Selection → BuildQuote (standard flow)
*/
export type BuyFlowOrigin = 'tokenInfo' | 'homeTokenList';
export interface BuildQuoteParams {
assetId?: string;
nativeFlowError?: string;
/** Which flow the user used to enter the Buy screen. */
buyFlowOrigin?: BuyFlowOrigin;
/** Pre-fill the amount input (e.g. when restoring state after a navigation reset). */
amount?: number;
/**
* Legacy param from Phase 3. The headless flow now navigates straight
* to `Routes.RAMP.HEADLESS_HOST` and never lands on BuildQuote, so the
* field is unused. Kept as `optional` for backward compatibility with
* any in-flight deeplinks; safe to remove once we're sure no callers
* pass it.
*
* @deprecated Use `Routes.RAMP.HEADLESS_HOST` instead.
*/
headlessSessionId?: string;
}
/**
* Creates navigation details for the BuildQuote screen (RampAmountInput).
* This screen is nested inside TokenListRoutes, so navigation must go through
* the parent route Routes.RAMP.TOKEN_SELECTION.
*/
export const createBuildQuoteNavDetails = (
params?: BuildQuoteParams,
): readonly [
string,
{
screen: string;
params: {
screen: string;
params?: BuildQuoteParams;
};
},
] =>
[
Routes.RAMP.TOKEN_SELECTION,
{
screen: Routes.RAMP.TOKEN_SELECTION,
params: {
screen: Routes.RAMP.AMOUNT_INPUT,
params,
},
},
] as const;
const DEFAULT_AMOUNT = 100;
function BuildQuote() {
const navigation = useNavigation();
const isOnBuildQuoteScreen = useIsFocused();
const { styles } = useStyles(styleSheet, {});
const { formatCurrency } = useFormatters();
const cursorOpacity = useBlinkingCursor();
const params = useParams<BuildQuoteParams>();
const initialAmount = params?.amount ?? DEFAULT_AMOUNT;
const [amount, setAmount] = useState<string>(() => String(initialAmount));
const [amountAsNumber, setAmountAsNumber] = useState<number>(initialAmount);
const [userHasEnteredAmount, setUserHasEnteredAmount] = useState(
params?.amount != null,
);
const [keyboardIsDirty, setKeyboardIsDirty] = useState(false);
const [isContinueLoading, setIsContinueLoading] = useState(false);
const [rampsError, setRampsError] = useState<string | null>(null);
useEffect(() => {
if (params?.nativeFlowError) {
if (
params.headlessSessionId &&
failSession(
params.headlessSessionId,
{
code: 'AUTH_FAILED',
message: params.nativeFlowError,
},
'AUTH_FAILED',
)
) {
navigation.setParams({ nativeFlowError: undefined });
return;
}
setRampsError(params.nativeFlowError);
navigation.setParams({ nativeFlowError: undefined });
}
}, [params?.headlessSessionId, params?.nativeFlowError, navigation]);
const {
userRegion,
providers,
selectedProvider,
setSelectedProvider,
selectedToken,
paymentMethods,
paymentMethodsLoading,
paymentMethodsFetching,
paymentMethodsStatus,
selectedPaymentMethod,
} = useRampsController();
const { continueWithQuote } = useContinueWithQuote();
const { trackEvent, createEventBuilder } = useAnalytics();
const rampRoutingDecision = useSelector(getRampRoutingDecision);
const prevSelectedProviderRef = useRef(selectedProvider);
/*
* Resets the native flow error if the selected provider changes.
*/
useEffect(() => {
if (prevSelectedProviderRef.current !== selectedProvider) {
prevSelectedProviderRef.current = selectedProvider;
setRampsError(null);
}
}, [selectedProvider]);
const tokenStateIsSettled =
!params?.assetId || selectedToken?.assetId === params.assetId;
// Controller state is the source of truth for the active token;
// route params are only used as bootstrapping input.
const effectiveAssetId = selectedToken?.assetId ?? params?.assetId;
const isTokenUnavailable = useMemo(() => {
if (!selectedProvider || !effectiveAssetId) {
return false;
}
if (!providerSupportsAsset(selectedProvider, effectiveAssetId)) {
return true;
}
// Only determine unavailability after payment methods have fully settled.
// This prevents the modal from flashing during loading/idle/error states
// (e.g. after a provider change while the new query is still in flight).
// Also wait for background refetches to complete — react-query may return
// stale cached data (status='success') while refetching for a new provider.
if (paymentMethodsStatus !== 'success' || paymentMethodsFetching) {
return false;
}
// If payment methods returned results, token IS available
// (payment methods API is more authoritative than supportedCryptoCurrencies)
if (paymentMethods.length > 0) {
return false;
}
// Payment methods loaded but empty
if (tokenStateIsSettled) {
return true;
}
return false;
}, [
selectedProvider,
effectiveAssetId,
paymentMethodsFetching,
tokenStateIsSettled,
paymentMethodsStatus,
paymentMethods.length,
]);
// Tracks which provider:token combination was last shown the modal,
// so we don't duplicate-navigate within the same visit but DO re-show
// when the combination changes.
const lastShownUnavailableKeyRef = useRef<string>('');
// Bump a counter on screen focus so the modal effect re-evaluates
// when the user navigates away (e.g. token selection) and comes back.
const [focusTrigger, setFocusTrigger] = useState(0);
useFocusEffect(
useCallback(() => {
lastShownUnavailableKeyRef.current = '';
setFocusTrigger((c) => c + 1);
}, []),
);
// When no provider is selected (e.g. first-time user in a region without
// Transak), pick the first provider that supports the selected token.
useEffect(() => {
if (
!isOnBuildQuoteScreen ||
selectedProvider ||
!effectiveAssetId ||
providers.length === 0
) {
return;
}
const supportingProvider = providers.find((p) =>
providerSupportsAsset(p, effectiveAssetId),
);
if (supportingProvider) {
setSelectedProvider(supportingProvider, { autoSelected: true });
}
}, [
isOnBuildQuoteScreen,
selectedProvider,
effectiveAssetId,
providers,
setSelectedProvider,
]);
// When the selected token is unavailable for the current provider, silently
// switch to any other provider that supports the token. Only fall through to
// the "Token Not Available" modal when no provider supports the token.
useEffect(() => {
if (!isOnBuildQuoteScreen || !isTokenUnavailable) {
lastShownUnavailableKeyRef.current = '';
return;
}
if (effectiveAssetId) {
const supportingProvider = providers.find(
(p) =>
p.id !== selectedProvider?.id &&
providerSupportsAsset(p, effectiveAssetId),
);
if (supportingProvider) {
setSelectedProvider(supportingProvider, { autoSelected: true });
return;
}
}
const key = `${selectedProvider?.id}:${effectiveAssetId}`;
if (lastShownUnavailableKeyRef.current === key) return;
const timer = setTimeout(() => {
lastShownUnavailableKeyRef.current = key;
navigation.navigate(
...createTokenNotAvailableModalNavigationDetails({
assetId: effectiveAssetId ?? '',
buyFlowOrigin: params?.buyFlowOrigin,
}),
);
}, 600);
return () => clearTimeout(timer);
}, [
isOnBuildQuoteScreen,
params?.buyFlowOrigin,
isTokenUnavailable,
effectiveAssetId,
navigation,
selectedProvider?.id,
focusTrigger,
providers,
setSelectedProvider,
]);
const currency = userRegion?.country?.currency || 'USD';
const { currencyPrefix, currencySuffix } = useMemo(() => {
const formatted = formatCurrency(1, currency, {
currencyDisplay: 'narrowSymbol',
});
// Match: prefix (non-digit chars), digits/separators, suffix (non-digit chars)
const match = formatted.match(/^([^\d]*?)[\d.,]+\s*([^\d\s].*)?$/);
return {
currencyPrefix: match?.[1] ?? '',
currencySuffix: match?.[2]?.trim() ?? '',
};
}, [currency, formatCurrency]);
const quickAmounts = userRegion?.country?.quickAmounts ?? [50, 100, 200, 400];
const amountDisplayString = useMemo(
() => `${currencyPrefix}${amount}${currencySuffix}`,
[currencyPrefix, currencySuffix, amount],
);
const amountFontSize = getFontSizeForInputLength(amountDisplayString.length);
const amountLineHeight = amountFontSize + 10;
/*
* Tracks RAMPS_SCREEN_VIEWED
* @returns {void}
*/
const hasTrackedScreenViewRef = useRef(false);
useEffect(() => {
if (hasTrackedScreenViewRef.current) return;
if (rampRoutingDecision != null) {
hasTrackedScreenViewRef.current = true;
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_SCREEN_VIEWED)
.addProperties({
location: 'Amount Input',
ramp_type: 'UNIFIED_BUY_2',
ramp_routing: rampRoutingDecision,
})
.build(),
);
}
}, [rampRoutingDecision, trackEvent, createEventBuilder]);
/*
* Sets the default amount for the user's region.
*/
useEffect(() => {
if (!userHasEnteredAmount && userRegion?.country?.defaultAmount != null) {
const regionDefault = userRegion.country.defaultAmount;
setAmount(String(regionDefault));
setAmountAsNumber(regionDefault);
setUserHasEnteredAmount(true);
}
}, [userRegion?.country?.defaultAmount, userHasEnteredAmount]);
const getTokenNetworkInfo = useTokenNetworkInfo();
const walletAddress = useRampAccountAddress(
selectedToken?.chainId as CaipChainId,
);
const debouncedPollingAmount = useDebouncedValue(amountAsNumber, 500);
const hasAmount = amountAsNumber > 0;
const { amountLimitError } = useProviderLimits({
provider: selectedProvider,
fiatCurrency: userRegion?.country?.currency,
paymentMethodId: selectedPaymentMethod?.id,
amount: amountAsNumber,
currency,
});
const debouncedAmountLimitError = useDebouncedValue(amountLimitError);
const displayedAmountLimitError =
amountLimitError === debouncedAmountLimitError ? amountLimitError : null;
const hasSettledQuoteAmount = amountAsNumber === debouncedPollingAmount;
const quoteFetchEnabled = !!(
walletAddress &&
selectedPaymentMethod &&
selectedProvider &&
selectedToken?.assetId &&
tokenStateIsSettled &&
debouncedPollingAmount > 0 &&
!amountLimitError &&
!isTokenUnavailable
);
/*
* Creates the quote fetch parameters for the useRampsQuotes hook,
* Fetches only 1 quote for the selected provider and payment method.
*/
const quoteFetchParams = useMemo(
() =>
selectedToken?.assetId &&
walletAddress &&
selectedPaymentMethod &&
selectedProvider
? {
assetId: normalizeAssetIdForApi(selectedToken.assetId),
amount: debouncedPollingAmount,
walletAddress,
redirectUrl: getRampCallbackBaseUrl(),
paymentMethods: [selectedPaymentMethod.id],
providers: [selectedProvider.id],
}
: null,
[
selectedToken?.assetId,
debouncedPollingAmount,
walletAddress,
selectedPaymentMethod,
selectedProvider,
],
);
const {
data: quotesResponse,
loading: selectedQuoteLoading,
error: quoteFetchError,
} = useRampsQuotes(quoteFetchEnabled ? quoteFetchParams : null);
const hasQuoteFetchError = quoteFetchError !== null;
/*
* Tracks RAMPS_QUOTE_ERROR
*/
const lastTrackedQuoteErrorRef = useRef<unknown>(null);
useEffect(() => {
if (
hasQuoteFetchError &&
quoteFetchError !== lastTrackedQuoteErrorRef.current
) {
lastTrackedQuoteErrorRef.current = quoteFetchError;
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_QUOTE_ERROR)
.addProperties({
error_message: parseUserFacingError(
quoteFetchError,
strings('deposit.buildQuote.quoteFetchError'),
),
amount: amountAsNumber,
currency_source: currency,
currency_destination: selectedToken?.assetId,
payment_method_id: selectedPaymentMethod?.id,
chain_id: selectedToken?.chainId,
ramp_type: 'UNIFIED_BUY_2',
ramp_routing: rampRoutingDecision ?? undefined,
})
.build(),
);
}
if (!hasQuoteFetchError) {
lastTrackedQuoteErrorRef.current = null;
}
}, [
hasQuoteFetchError,
quoteFetchError,
amountAsNumber,
currency,
selectedToken?.assetId,
selectedToken?.chainId,
selectedPaymentMethod?.id,
rampRoutingDecision,
trackEvent,
createEventBuilder,
]);
const selectedQuote = useMemo(() => {
if (
!quotesResponse?.success ||
!selectedProvider ||
!selectedPaymentMethod
) {
return null;
}
const targetProvider = normalizeProviderCode(selectedProvider.id);
return (
quotesResponse.success.find(
(quote) => normalizeProviderCode(quote.provider) === targetProvider,
) ?? null
);
}, [quotesResponse, selectedProvider, selectedPaymentMethod]);
const networkInfo = useMemo(() => {
if (!selectedToken) return null;
return getTokenNetworkInfo(selectedToken.chainId as CaipChainId);
}, [selectedToken, getTokenNetworkInfo]);
const handleSettingsPress = useCallback(() => {
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_SETTINGS_CLICKED)
.addProperties({
location: 'Amount Input',
ramp_type: 'UNIFIED_BUY_2',
})
.build(),
);
navigation.navigate(...createSettingsModalNavDetails());
}, [trackEvent, createEventBuilder, navigation]);
const handleBackPress = useCallback(() => {
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_BACK_BUTTON_CLICKED)
.addProperties({
location: 'Amount Input',
ramp_type: 'UNIFIED_BUY_2',
})
.build(),
);
navigation.goBack();
}, [trackEvent, createEventBuilder, navigation]);
const updateAmount = useCallback(
(valueOrNumber: string | number, valueAsNumber?: number) => {
const { amount: nextAmount, amountAsNumber: nextAmountAsNumber } =
computeAmountUpdate(valueOrNumber, valueAsNumber);
setAmount(nextAmount);
setAmountAsNumber(nextAmountAsNumber);
setKeyboardIsDirty(true);
setUserHasEnteredAmount(true);
setRampsError(null);
},
[],
);
const handleKeypadChange = useCallback(
({ value, valueAsNumber, pressedKey }: KeypadChangeData) => {
if (pressedKey === Keys.Back && !keyboardIsDirty) {
updateAmount(0);
return;
}
updateAmount(value, valueAsNumber ?? 0);
},
[keyboardIsDirty, updateAmount],
);
const handleQuickAmountPress = useCallback(
(quickAmount: number) => {
updateAmount(quickAmount);
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_QUICK_AMOUNT_CLICKED)
.addProperties({
amount: quickAmount,
currency_source: currency,
location: 'Amount Input',
ramp_type: 'UNIFIED_BUY_2',
})
.build(),
);
},
[currency, trackEvent, createEventBuilder, updateAmount],
);
const handlePaymentPillPress = useCallback(() => {
trackEvent(
createEventBuilder(
MetaMetricsEvents.RAMPS_PAYMENT_METHOD_SELECTOR_CLICKED,
)
.addProperties({
current_payment_method: selectedPaymentMethod?.id,
location: 'Amount Input',
ramp_type: 'UNIFIED_BUY_2',
})
.build(),
);
navigation.navigate(
...createPaymentSelectionModalNavigationDetails({
amount: debouncedPollingAmount,
}),
);
}, [
debouncedPollingAmount,
navigation,
selectedPaymentMethod?.id,
trackEvent,
createEventBuilder,
]);
const handleContinuePress = useCallback(async () => {
if (!selectedQuote || !selectedProvider) return;
setRampsError(null);
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_CONTINUE_BUTTON_CLICKED)
.addProperties({
ramp_routing:
rampRoutingDecision ?? UnifiedRampRoutingType.AGGREGATOR,
ramp_type: 'UNIFIED_BUY_2',
amount_source: amountAsNumber,
payment_method_id: selectedPaymentMethod?.id ?? '',
provider_onramp: selectedProvider?.name,
region: userRegion?.regionCode ?? '',
chain_id: selectedToken?.chainId ?? '',
currency_destination: selectedToken?.assetId ?? '',
currency_destination_symbol: selectedToken?.symbol,
currency_source: currency,
})
.build(),
);
setIsContinueLoading(true);
try {
await continueWithQuote(selectedQuote, {
amount: amountAsNumber,
assetId: selectedToken?.assetId ?? '',
});
} catch (err) {
if (failSession(params?.headlessSessionId, err)) {
return;
}
setRampsError((err as Error).message);
} finally {
setIsContinueLoading(false);
}
}, [
selectedQuote,
selectedProvider,
selectedToken?.assetId,
selectedToken?.chainId,
selectedToken?.symbol,
amountAsNumber,
currency,
selectedPaymentMethod?.id,
rampRoutingDecision,
userRegion?.regionCode,
params?.headlessSessionId,
trackEvent,
createEventBuilder,
continueWithQuote,
]);
const canContinue =
hasAmount &&
!amountLimitError &&
!selectedQuoteLoading &&
selectedQuote !== null;
const hasNoQuotes =
hasAmount &&
hasSettledQuoteAmount &&
!selectedQuoteLoading &&
!hasQuoteFetchError &&
quotesResponse !== null &&
selectedQuote === null;
const providerQuoteError = useMemo(() => {
if (!hasNoQuotes || !quotesResponse?.error?.length) return undefined;
const firstError = quotesResponse.error[0];
return firstError?.error;
}, [hasNoQuotes, quotesResponse?.error]);
const inlineQuoteError =
displayedAmountLimitError ?? providerQuoteError ?? null;
const hasGenericNoQuotes = hasNoQuotes && !providerQuoteError;
const amountInputHasError = Boolean(
rampsError || quoteFetchError || inlineQuoteError || hasGenericNoQuotes,
);
const noQuotesErrorMessage = selectedProvider
? strings('fiat_on_ramp.no_quotes_error', {
provider: selectedProvider.name,
})
: strings('fiat_on_ramp.no_quotes_available');
const actionSectionMessage = (() => {
if (rampsError) {
return (
<TruncatedError
error={rampsError}
providerName={selectedProvider?.name}
providerSupportUrl={
selectedProvider?.links?.find(
(link) => link.name === PROVIDER_LINKS.SUPPORT,
)?.url
}
/>
);
}
if (inlineQuoteError) {
return (
<Text
variant={TextVariant.BodySm}
color={TextColor.ErrorDefault}
style={styles.centeredText}
>
{inlineQuoteError}
</Text>
);
}
if (hasGenericNoQuotes) {
return (
<TruncatedError
error={noQuotesErrorMessage}
showChangeProvider
amount={amountAsNumber}
/>
);
}
if (selectedProvider && !isTokenUnavailable && tokenStateIsSettled) {
return (
<Text variant={TextVariant.BodySm} style={styles.poweredByText}>
{strings('fiat_on_ramp.powered_by_provider', {
provider: selectedProvider.name,
})}
</Text>
);
}
return (
<Text
testID={BUILD_QUOTE_TEST_IDS.ACTION_MESSAGE_PLACEHOLDER}
variant={TextVariant.BodySm}
style={styles.poweredByText}
>
{''}
</Text>
);
})();
return (
<ScreenLayout>
<ScreenLayout.Body>
<HeaderCompactStandard
title={
selectedToken?.symbol
? strings('fiat_on_ramp.buy', { ticker: selectedToken.symbol })
: undefined
}
subtitle={
networkInfo?.networkName
? strings('fiat_on_ramp.on_network', {
networkName: networkInfo.networkName,
})
: undefined
}
onBack={handleBackPress}
backButtonProps={{ testID: BUILD_QUOTE_TEST_IDS.BACK_BUTTON }}
endButtonIconProps={[
{
iconName: IconName.Setting,
onPress: handleSettingsPress,
testID: BUILD_QUOTE_TEST_IDS.SETTINGS_BUTTON,
},
]}
includesTopInset
/>
<ScreenLayout.Content style={styles.content}>
<View style={styles.centerGroup}>
<View style={styles.amountContainer}>
<View style={styles.amountRow}>
<Text
testID={BuildQuoteSelectors.AMOUNT_INPUT}
variant={TextVariant.BodyMd}
fontWeight={FontWeight.Regular}
color={
amountInputHasError ? TextColor.ErrorDefault : undefined
}
twClassName={`text-[${amountFontSize}px] tracking-tight leading-[${amountLineHeight}px] font-normal text-center`}
numberOfLines={1}
>
{currencyPrefix}
{amount}
</Text>
<Animated.View
style={[
styles.cursor,
{
height: Math.max(amountLineHeight - 4, 16),
opacity: cursorOpacity,
},
]}
/>
{currencySuffix ? (
<Text
variant={TextVariant.BodyMd}
fontWeight={FontWeight.Regular}
color={
amountInputHasError ? TextColor.ErrorDefault : undefined
}
twClassName={`text-[${amountFontSize}px] tracking-tight leading-[${amountLineHeight}px] font-normal text-center`}
>
{currencySuffix}
</Text>
) : null}
</View>
<PaymentMethodPill
label={
selectedPaymentMethod?.name ||
strings('fiat_on_ramp.select_payment_method')
}
paymentMethod={selectedPaymentMethod}
isLoading={paymentMethodsLoading}
onPress={
isTokenUnavailable ? undefined : handlePaymentPillPress
}
testID="build-quote-payment-pill"
/>
</View>
</View>
{hasQuoteFetchError ? (
<BannerAlert
severity={BannerAlertSeverity.Error}
description={parseUserFacingError(
quoteFetchError,
strings('deposit.buildQuote.quoteFetchError'),
)}
/>
) : null}
<View style={styles.actionSection}>
{hasAmount ? (
<>
{actionSectionMessage}
<Button
variant={ButtonVariant.Primary}
size={ButtonSize.Lg}
onPress={handleContinuePress}
isFullWidth
isDisabled={!canContinue}
isLoading={
selectedQuoteLoading ||
isContinueLoading ||
isTokenUnavailable ||
!tokenStateIsSettled
}
testID={BuildQuoteSelectors.CONTINUE_BUTTON}
>
{strings('fiat_on_ramp.continue')}
</Button>
</>
) : (
quickAmounts.length > 0 && (
<QuickAmounts
amounts={quickAmounts}
currency={currency}
onAmountPress={handleQuickAmountPress}
/>
)
)}
</View>
<Keypad
currency={currency}
value={amount}
onChange={handleKeypadChange}
/>
</ScreenLayout.Content>
</ScreenLayout.Body>
</ScreenLayout>
);
}
export default BuildQuote;