-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathuseContinueWithQuote.ts
More file actions
390 lines (364 loc) · 13.1 KB
/
Copy pathuseContinueWithQuote.ts
File metadata and controls
390 lines (364 loc) · 13.1 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
import { useCallback } from 'react';
import { Linking } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useSelector } from 'react-redux';
import InAppBrowser from 'react-native-inappbrowser-reborn';
import type { CaipChainId } from '@metamask/utils';
import { strings } from '../../../../../locales/i18n';
import { FIAT_ORDER_PROVIDERS } from '../../../../constants/on-ramp';
import { selectHasAgreedTransakNativePolicy } from '../../../../reducers/fiatOrders';
import Device from '../../../../util/device';
import {
buildQuoteWithRedirectUrl,
getCheckoutContext,
getWidgetRedirectConfig,
} from '../utils/buildQuoteWithRedirectUrl';
import { getNavigateAfterExternalBrowserRoutes } from '../utils/rampsNavigation';
import { reportRampsError } from '../utils/reportRampsError';
import {
type Quote,
isNativeProvider,
isCustomAction,
getQuoteProviderName,
getQuoteBuyUserAgent,
} from '../types';
import { createCheckoutNavDetails } from '../Views/Checkout';
import { createV2EnterEmailNavDetails } from '../Views/NativeFlow/EnterEmail';
import { createV2VerifyIdentityNavDetails } from '../Views/NativeFlow/VerifyIdentity';
import { useRampsController } from './useRampsController';
import { useTransakController } from './useTransakController';
import { useTransakRouting } from './useTransakRouting';
import useRampAccountAddress from './useRampAccountAddress';
export interface ContinueWithQuoteContext {
amount: number;
assetId: string;
/**
* Optional overrides for callers that don't seed the controller (e.g. the
* headless flow's Host screen). When omitted, each field falls back to the
* value derived from `useRampsController` selections — so BuildQuote
* keeps its existing behavior unchanged. When supplied, the override
* wins for the duration of this call only.
*/
chainId?: CaipChainId;
walletAddress?: string;
/** Fiat currency code, e.g. `'USD'`. */
currency?: string;
/** Crypto symbol used for Checkout WebView's display label. */
cryptoSymbol?: string;
/** Payment method id used for the native Transak quote fetch. */
paymentMethodId?: string;
/** Provider display name used for Checkout WebView's `providerName`. */
providerName?: string;
/**
* When set, the native (Transak) auth-loop screens (VerifyIdentity →
* EnterEmail → OtpCode) will carry this id and route post-auth resets
* back to `Routes.RAMP.HEADLESS_HOST` instead of BuildQuote. Ignored
* by the widget branch (no auth loop there).
*/
headlessSessionId?: string;
}
export interface UseContinueWithQuoteOptions {
/**
* Forwarded to the inner `useTransakRouting` instance. Lets the headless
* Host pin the stack base for post-auth resets onto
* `Routes.RAMP.HEADLESS_HOST` so the auth loop returns to the Host
* instead of BuildQuote (which a headless caller never opened).
*/
transakRouting?: {
baseRoute?: string;
baseRouteParams?: Record<string, unknown>;
};
}
export interface UseContinueWithQuoteResult {
/**
* Advances the buy flow for a given quote. Native (Transak) quotes check
* authentication and either route through the post-auth flow or navigate
* into EnterEmail / VerifyIdentity. Widget / aggregator quotes fetch the
* widget URL and either open it in-app (Checkout WebView) or delegate to
* an external browser.
*
* Error contract: on failure the hook calls `reportRampsError` (Logger +
* Sentry side effect) and throws an `Error` whose `message` is a
* user-facing string suitable for direct display. Callers should catch
* and surface that message in their own UI.
*
* The hook does not manage loading state or fire the
* RAMPS_CONTINUE_BUTTON_CLICKED analytics event — those stay with the
* caller.
*/
continueWithQuote: (
quote: Quote,
context: ContinueWithQuoteContext,
) => Promise<void>;
}
export function useContinueWithQuote(
options?: UseContinueWithQuoteOptions,
): UseContinueWithQuoteResult {
const navigation = useNavigation();
const {
selectedToken,
selectedProvider,
selectedPaymentMethod,
userRegion,
getBuyWidgetData,
addPrecreatedOrder,
} = useRampsController();
const {
checkExistingToken: transakCheckExistingToken,
getBuyQuote: transakGetBuyQuote,
} = useTransakController();
const { routeAfterAuthentication: transakRouteAfterAuth } = useTransakRouting(
options?.transakRouting,
);
const walletAddress = useRampAccountAddress(
selectedToken?.chainId as CaipChainId,
);
const hasAgreedTransakNativePolicy = useSelector(
selectHasAgreedTransakNativePolicy,
);
const currency = userRegion?.country?.currency || 'USD';
const navigateAfterExternalBrowser = useCallback(
(opts: Parameters<typeof getNavigateAfterExternalBrowserRoutes>[0]) => {
navigation.reset({
index: 0,
routes: getNavigateAfterExternalBrowserRoutes(opts),
});
},
[navigation],
);
// The aggregator-format `_quote` is used only by the caller to dispatch
// to this branch via `isNativeProvider`. The native (Transak) path fetches
// its own `TransakBuyQuote` via `transakGetBuyQuote` below.
const continueNative = useCallback(
async (_quote: Quote, ctx: ContinueWithQuoteContext) => {
const { amount, assetId } = ctx;
// Resolve every controller-coupled value through the override-first
// ladder so headless callers (Phase 5) can drive this hook without
// pre-seeding the RampsController.
const effectiveCurrency = ctx.currency ?? currency;
const effectiveChainId = ctx.chainId ?? selectedToken?.chainId ?? '';
const effectivePaymentMethodId =
ctx.paymentMethodId ?? selectedPaymentMethod?.id ?? '';
// The native Transak quote fetch requires a payment method. An empty
// value gets dropped from the request query and Transak rejects it with
// HTTP 400, so fail fast with a reported error instead of issuing a
// request that can never succeed.
//
// Gate on `ctx.headlessSessionId` so this guard is scoped to the
// headless buy flow. The shared UB2 path (BuildQuote ->
// continueWithQuote -> continueNative) never sets `headlessSessionId`,
// so its behavior is provably unchanged.
if (!effectivePaymentMethodId && ctx.headlessSessionId) {
throw new Error(
reportRampsError(
new Error('Native provider flow requires a payment method'),
{ message: 'Missing payment method for native provider flow' },
strings('deposit.buildQuote.unexpectedError'),
),
);
}
try {
const hasToken = await transakCheckExistingToken();
if (hasToken) {
const transakQuote = await transakGetBuyQuote(
effectiveCurrency,
assetId,
effectiveChainId,
effectivePaymentMethodId,
String(amount),
);
if (!transakQuote) {
throw new Error(strings('deposit.buildQuote.unexpectedError'));
}
await transakRouteAfterAuth(transakQuote, amount);
} else if (hasAgreedTransakNativePolicy) {
navigation.navigate(
...createV2EnterEmailNavDetails({
amount: String(amount),
currency: effectiveCurrency,
assetId,
headlessSessionId: ctx.headlessSessionId,
}),
);
} else {
navigation.navigate(
...createV2VerifyIdentityNavDetails({
amount: String(amount),
currency: effectiveCurrency,
assetId,
headlessSessionId: ctx.headlessSessionId,
}),
);
}
} catch (error) {
throw new Error(
reportRampsError(
error,
{ message: 'Failed to route native provider flow' },
strings('deposit.buildQuote.unexpectedError'),
),
);
}
},
[
currency,
selectedToken?.chainId,
selectedPaymentMethod?.id,
transakCheckExistingToken,
transakGetBuyQuote,
transakRouteAfterAuth,
navigation,
hasAgreedTransakNativePolicy,
],
);
const continueWidget = useCallback(
async (quote: Quote, ctx: ContinueWithQuoteContext) => {
// See `continueNative` — every controller-coupled value resolves
// through the override-first ladder so headless callers can drive the
// widget branch without touching the controller.
const effectiveCurrency = ctx.currency ?? currency;
const effectiveWalletAddress = ctx.walletAddress ?? walletAddress;
const effectiveCryptoSymbol =
ctx.cryptoSymbol ?? selectedToken?.symbol ?? '';
const effectiveChainId = ctx.chainId ?? selectedToken?.chainId;
const effectiveProviderName =
ctx.providerName ??
selectedProvider?.name ??
getQuoteProviderName(quote);
let providerCode: string;
let useExternalBrowser: boolean;
let redirectUrl: string;
let buyWidget: Awaited<ReturnType<typeof getBuyWidgetData>>;
try {
providerCode = quote.provider;
const isCustom = isCustomAction(quote);
const redirectConfig = getWidgetRedirectConfig(
quote,
providerCode,
isCustom,
);
useExternalBrowser = redirectConfig.useExternalBrowser;
redirectUrl = redirectConfig.redirectUrl;
const quoteForWidget = buildQuoteWithRedirectUrl(quote, redirectUrl);
buyWidget = await getBuyWidgetData(quoteForWidget);
} catch (error) {
throw new Error(
reportRampsError(
error,
{
provider: quote.provider,
message: 'Failed to fetch widget URL',
},
strings('deposit.buildQuote.unexpectedError'),
),
);
}
if (!buyWidget?.url) {
throw new Error(
reportRampsError(
new Error('No widget URL available for provider'),
{ provider: quote.provider },
strings('deposit.buildQuote.unexpectedError'),
),
);
}
try {
const { network, effectiveWallet, effectiveOrderId } =
getCheckoutContext(
{ chainId: effectiveChainId },
effectiveWalletAddress,
buyWidget.orderId,
);
if (useExternalBrowser) {
if (effectiveOrderId && effectiveWallet) {
addPrecreatedOrder({
orderId: effectiveOrderId,
providerCode,
walletAddress: effectiveWallet,
chainId: network || undefined,
});
}
const isAndroid = Device.isAndroid();
const inAppBrowserAvailable =
!isAndroid && (await InAppBrowser.isAvailable());
if (isAndroid || !inAppBrowserAvailable) {
await Linking.openURL(buyWidget.url);
navigateAfterExternalBrowser({ returnDestination: 'buildQuote' });
return;
}
try {
const result = await InAppBrowser.openAuth(
buyWidget.url,
redirectUrl,
);
if (result.type !== 'success' || !result.url) {
navigateAfterExternalBrowser({ returnDestination: 'buildQuote' });
return;
}
if (!effectiveWallet) {
navigateAfterExternalBrowser({ returnDestination: 'buildQuote' });
return;
}
navigateAfterExternalBrowser({
returnDestination: 'order',
callbackUrl: result.url,
providerCode,
walletAddress: effectiveWallet,
});
} finally {
InAppBrowser.closeAuth();
}
return;
}
navigation.navigate(
...createCheckoutNavDetails({
url: buyWidget.url,
providerName: effectiveProviderName,
userAgent: getQuoteBuyUserAgent(quote),
providerCode,
providerType: FIAT_ORDER_PROVIDERS.RAMPS_V2,
walletAddress: effectiveWallet || undefined,
network,
currency: effectiveCurrency,
cryptocurrency: effectiveCryptoSymbol,
orderId: buyWidget.orderId?.trim() || undefined,
headlessSessionId: ctx.headlessSessionId,
}),
);
} catch (error) {
throw new Error(
reportRampsError(
error,
{
provider: quote.provider,
message: 'Failed to open widget',
},
strings('deposit.buildQuote.unexpectedError'),
),
);
}
},
[
selectedProvider,
selectedToken,
walletAddress,
currency,
navigation,
getBuyWidgetData,
addPrecreatedOrder,
navigateAfterExternalBrowser,
],
);
const continueWithQuote = useCallback(
async (quote: Quote, context: ContinueWithQuoteContext) => {
if (isNativeProvider(quote)) {
await continueNative(quote, context);
return;
}
await continueWidget(quote, context);
},
[continueNative, continueWidget],
);
return { continueWithQuote };
}
export default useContinueWithQuote;