-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCheckout.tsx
More file actions
340 lines (321 loc) · 11.4 KB
/
Checkout.tsx
File metadata and controls
340 lines (321 loc) · 11.4 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
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { parseUrl } from 'query-string';
import { WebView, WebViewNavigation } from '@metamask/react-native-webview';
import { useNavigation } from '@react-navigation/native';
import { useAnalytics } from '../../../../hooks/useAnalytics/useAnalytics';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import { callbackBaseUrl } from '../../Aggregator/sdk';
import { getRampRoutingDecision } from '../../../../../reducers/fiatOrders';
import { normalizeProviderCode } from '@metamask/ramps-controller';
import { FIAT_ORDER_PROVIDERS } from '../../../../../constants/on-ramp';
import { strings } from '../../../../../../locales/i18n';
import Routes from '../../../../../constants/navigation/Routes';
import {
createNavigationDetails,
useParams,
} from '../../../../../util/navigation/navUtils';
import ScreenLayout from '../../Aggregator/components/ScreenLayout';
import ErrorView from '../../Aggregator/components/ErrorView';
import Logger from '../../../../../util/Logger';
import { protectWalletModalVisible } from '../../../../../actions/user';
import { useRampsOrders } from '../../hooks/useRampsOrders';
import {
BottomSheet,
type BottomSheetRef,
} from '@metamask/design-system-react-native';
import HeaderCompactStandard from '../../../../../component-library/components-temp/HeaderCompactStandard';
import { useStyles } from '../../../../hooks/useStyles';
import styleSheet from './Checkout.styles';
import Device from '../../../../../util/device';
import { shouldStartLoadWithRequest } from '../../../../../util/browser';
import { CHECKOUT_TEST_IDS } from './Checkout.testIds';
interface CheckoutParams {
url: string;
providerName: string;
/** Optional provider-specific userAgent for the WebView (e.g. features.buy.userAgent). */
userAgent?: string;
/** V2 callback flow: provider code (e.g., "moonpay", "transak"). */
providerCode?: string;
/** V2: order ID from BuyWidget for polling. Prefer orderId; customOrderId kept for backward compatibility. */
orderId?: string | null;
/** @deprecated Use orderId instead. */
customOrderId?: string | null;
/** V2 callback flow: wallet address for this order. */
walletAddress?: string;
/** V2: network chain ID for the order. */
network?: string;
/** V2: fiat currency code (e.g., "USD"). Fallback when the callback order has no fiatCurrency yet. */
currency?: string;
/** V2: crypto currency symbol (e.g., "ETH"). Fallback when the callback order has no cryptoCurrency yet. */
cryptocurrency?: string;
/** V2: the Redux provider type for this order. Defaults to AGGREGATOR. */
providerType?: FIAT_ORDER_PROVIDERS;
/** Optional callback invoked on navigation state changes after URL de-duplication (e.g. redirect URLs). */
onNavigationStateChange?: (navState: { url: string }) => void;
}
export const createCheckoutNavDetails = createNavigationDetails<CheckoutParams>(
Routes.RAMP.CHECKOUT,
);
const Checkout = () => {
const sheetRef = useRef<BottomSheetRef>(null);
const previousUrlRef = useRef<string | null>(null);
const dispatch = useDispatch();
const [error, setError] = useState('');
const isRedirectionHandledRef = useRef(false);
const [key, setKey] = useState(0);
const navigation = useNavigation();
const params = useParams<CheckoutParams>();
const { styles } = useStyles(styleSheet, {});
const { addPrecreatedOrder } = useRampsOrders();
const { trackEvent, createEventBuilder } = useAnalytics();
const rampRoutingDecision = useSelector(getRampRoutingDecision);
const {
url: uri,
providerCode,
orderId: orderIdParam,
customOrderId,
walletAddress,
network,
userAgent,
onNavigationStateChange,
cryptocurrency,
} = params ?? {};
const effectiveOrderId = (orderIdParam ?? customOrderId)?.trim() || null;
const initialUriRef = useRef(uri);
const registeredOrderIdsRef = useRef<Set<string>>(new Set());
const hasCallbackFlow = Boolean(providerCode && walletAddress);
const hasTrackedScreenViewRef = useRef(false);
useEffect(() => {
if (uri && !hasTrackedScreenViewRef.current) {
hasTrackedScreenViewRef.current = true;
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_SCREEN_VIEWED)
.addProperties({
location: 'Checkout',
ramp_type: 'UNIFIED_BUY_2',
ramp_routing: rampRoutingDecision ?? undefined,
})
.build(),
);
}
}, [uri, createEventBuilder, trackEvent, rampRoutingDecision]);
useEffect(() => {
// For external-browser flows (e.g. PayPal), addPrecreatedOrder is called in
// BuildQuote; the user never reaches Checkout. For WebView flows,
// providerCode and walletAddress are passed, so hasCallbackFlow is true
// and we can register. hasCallbackFlow being false means we lack the data
// required for addPrecreatedOrder anyway.
// Note: network/chainId is optional in addPrecreatedOrder; do not require it
// in the guard, otherwise orders with unusual chain ID formats (e.g. empty
// string from chainId.split(':')[1]) would silently skip registration here
// while external-browser flows would still register (BuildQuote passes
// chainId: network || undefined without requiring network).
const canRegister =
hasCallbackFlow && effectiveOrderId && providerCode && walletAddress;
if (!canRegister) return;
if (registeredOrderIdsRef.current.has(effectiveOrderId)) return;
registeredOrderIdsRef.current.add(effectiveOrderId);
addPrecreatedOrder({
orderId: effectiveOrderId,
providerCode: normalizeProviderCode(providerCode),
walletAddress,
chainId: network || undefined,
});
}, [
hasCallbackFlow,
effectiveOrderId,
walletAddress,
network,
providerCode,
addPrecreatedOrder,
]);
const handleNavigationStateChange = useCallback(
async (navState: WebViewNavigation) => {
if (
!hasCallbackFlow ||
isRedirectionHandledRef.current ||
!navState.url.startsWith(callbackBaseUrl) ||
navState.loading !== false
) {
return;
}
isRedirectionHandledRef.current = true;
try {
const parsedUrl = parseUrl(navState.url);
if (Object.keys(parsedUrl.query).length === 0) {
// @ts-expect-error navigation prop mismatch
navigation.getParent()?.pop();
return;
}
if (!walletAddress || !providerCode) {
throw new Error('No wallet address or provider code available');
}
dispatch(protectWalletModalVisible());
// Unified buy stack only: leave the WebView immediately; OrderDetails
// resolves the order via callback params (same pattern as external-browser return).
navigation.reset({
index: 0,
routes: [
{
name: Routes.RAMP.RAMPS_ORDER_DETAILS,
params: {
callbackUrl: navState.url,
providerCode,
walletAddress,
showCloseButton: true,
...(cryptocurrency ? { cryptocurrency } : {}),
},
},
],
});
} catch (navError) {
Logger.error(navError as Error, {
message: 'UnifiedCheckout: error handling callback',
});
setError((navError as Error)?.message);
}
},
[
dispatch,
hasCallbackFlow,
providerCode,
walletAddress,
navigation,
cryptocurrency,
],
);
const handleCancelPress = useCallback(() => {
trackEvent(
createEventBuilder(MetaMetricsEvents.RAMPS_CLOSE_BUTTON_CLICKED)
.addProperties({
location: 'Checkout',
ramp_type: 'UNIFIED_BUY_2',
ramp_routing: rampRoutingDecision ?? undefined,
})
.build(),
);
}, [createEventBuilder, trackEvent, rampRoutingDecision]);
const handleClosePress = useCallback(() => {
handleCancelPress();
sheetRef.current?.onCloseBottomSheet();
}, [handleCancelPress]);
const handleNavigationStateChangeWithDedup = useCallback(
(navState: { url: string }) => {
if (navState.url !== previousUrlRef.current) {
previousUrlRef.current = navState.url;
onNavigationStateChange?.(navState);
}
},
[onNavigationStateChange],
);
const handleShouldStartLoadWithRequest = useCallback(
({ url }: { url: string }) => shouldStartLoadWithRequest(url, Logger),
[],
);
const sharedHeader = (
<HeaderCompactStandard
onClose={handleClosePress}
closeButtonProps={{
testID: CHECKOUT_TEST_IDS.CLOSE_BUTTON,
}}
style={styles.headerWithoutPadding}
/>
);
if (error) {
return (
<BottomSheet
ref={sheetRef}
goBack={navigation.goBack}
isFullscreen
keyboardAvoidingViewEnabled={false}
>
{sharedHeader}
<ScreenLayout>
<ScreenLayout.Body>
<ErrorView
description={error}
ctaOnPress={() => {
setKey((prevKey) => prevKey + 1);
setError('');
isRedirectionHandledRef.current = false;
}}
location="Provider Webview"
/>
</ScreenLayout.Body>
</ScreenLayout>
</BottomSheet>
);
}
if (uri) {
return (
<BottomSheet
ref={sheetRef}
goBack={navigation.goBack}
isFullscreen
isInteractable={!Device.isAndroid()}
keyboardAvoidingViewEnabled={false}
>
{sharedHeader}
<WebView
key={key}
style={styles.webview}
source={{ uri }}
userAgent={userAgent ?? undefined}
onHttpError={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
const errorUrl = nativeEvent.url;
if (
errorUrl === initialUriRef.current ||
errorUrl.startsWith(callbackBaseUrl)
) {
const webviewHttpError = strings(
'fiat_on_ramp_aggregator.webview_received_error',
{ code: nativeEvent.statusCode },
);
setError(webviewHttpError);
} else {
Logger.log(
`Checkout: HTTP error ${nativeEvent.statusCode} for auxiliary resource: ${errorUrl}`,
);
}
}}
allowsInlineMediaPlayback
enableApplePay
paymentRequestEnabled
mediaPlaybackRequiresUserAction={false}
onNavigationStateChange={
hasCallbackFlow
? handleNavigationStateChange
: onNavigationStateChange
? handleNavigationStateChangeWithDedup
: undefined
}
onShouldStartLoadWithRequest={handleShouldStartLoadWithRequest}
testID={CHECKOUT_TEST_IDS.WEBVIEW}
/>
</BottomSheet>
);
}
return (
<BottomSheet
ref={sheetRef}
goBack={navigation.goBack}
isFullscreen
keyboardAvoidingViewEnabled={false}
>
{sharedHeader}
<ScreenLayout>
<ScreenLayout.Body>
<ErrorView
description={strings(
'fiat_on_ramp_aggregator.webview_no_url_provided',
)}
location="Provider Webview"
/>
</ScreenLayout.Body>
</ScreenLayout>
</BottomSheet>
);
};
export default Checkout;