@ensofinance/checkout-widget 0.1.9 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/checkout-widget.es.js +25671 -24394
  2. package/dist/checkout-widget.es.js.map +1 -0
  3. package/dist/checkout-widget.umd.js +65 -59
  4. package/dist/checkout-widget.umd.js.map +1 -0
  5. package/dist/index.d.ts +3 -1
  6. package/package.json +2 -2
  7. package/src/assets/providers/alchemypay.svg +21 -0
  8. package/src/assets/providers/banxa.svg +21 -0
  9. package/src/assets/providers/binanceconnect.svg +14 -0
  10. package/src/assets/providers/kryptonim.svg +6 -0
  11. package/src/assets/providers/mercuryo.svg +21 -0
  12. package/src/assets/providers/moonpay.svg +14 -0
  13. package/src/assets/providers/stripe.svg +16 -0
  14. package/src/assets/providers/swapped.svg +1 -0
  15. package/src/assets/providers/topper.svg +14 -0
  16. package/src/assets/providers/transak.svg +21 -0
  17. package/src/assets/providers/unlimit.svg +21 -0
  18. package/src/components/AmountInput.tsx +41 -25
  19. package/src/components/ChakraProvider.tsx +36 -13
  20. package/src/components/Checkout.tsx +3 -0
  21. package/src/components/CurrencySwapDisplay.tsx +59 -22
  22. package/src/components/DepositProcessing.tsx +1 -1
  23. package/src/components/ExchangeConfirmSecurity.tsx +1 -1
  24. package/src/components/QuoteParameters.tsx +1 -1
  25. package/src/components/TransactionDetailRow.tsx +2 -2
  26. package/src/components/cards/ExchangeCard.tsx +1 -1
  27. package/src/components/cards/OptionCard.tsx +2 -1
  28. package/src/components/cards/WalletCard.tsx +1 -1
  29. package/src/components/modal.tsx +3 -3
  30. package/src/components/steps/CardBuyFlow/CardBuyFlow.tsx +420 -0
  31. package/src/components/steps/CardBuyFlow/ChooseAmountStep.tsx +343 -0
  32. package/src/components/steps/CardBuyFlow/OpenWidgetStep.tsx +189 -0
  33. package/src/components/steps/ExchangeFlow.tsx +237 -1410
  34. package/src/components/steps/FlowSelector.tsx +118 -61
  35. package/src/components/steps/SmartAccountFlow.tsx +372 -0
  36. package/src/components/steps/WalletFlow/WalletAmountStep.tsx +2 -2
  37. package/src/components/steps/WalletFlow/WalletConfirmStep.tsx +93 -52
  38. package/src/components/steps/WalletFlow/WalletFlow.tsx +17 -16
  39. package/src/components/steps/WalletFlow/WalletQuoteStep.tsx +2 -2
  40. package/src/components/steps/WalletFlow/WalletTokenStep.tsx +6 -4
  41. package/src/components/steps/shared/ChooseAmountStep.tsx +325 -0
  42. package/src/components/steps/shared/SignUserOpStep.tsx +117 -0
  43. package/src/components/steps/shared/TrackUserOpStep.tsx +650 -0
  44. package/src/components/steps/shared/exchangeIntegration.ts +19 -0
  45. package/src/components/steps/shared/types.ts +22 -0
  46. package/src/components/ui/index.tsx +23 -6
  47. package/src/components/ui/toaster.tsx +2 -1
  48. package/src/components/ui/transitions.tsx +16 -0
  49. package/src/enso-api/custom-instance.ts +5 -1
  50. package/src/enso-api/model/bridgeTransactionResponse.ts +37 -0
  51. package/src/enso-api/model/bridgeTransactionResponseStatus.ts +25 -0
  52. package/src/enso-api/model/ensoEvent.ts +30 -0
  53. package/src/enso-api/model/ensoMetadata.ts +23 -0
  54. package/src/enso-api/model/layerZeroControllerCheckBridgeTransactionParams.ts +21 -0
  55. package/src/enso-api/model/layerZeroMessageStatus.ts +39 -0
  56. package/src/enso-api/model/refundDetails.ts +21 -0
  57. package/src/types/index.ts +97 -0
  58. package/src/util/constants.tsx +27 -0
  59. package/src/util/enso-hooks.tsx +75 -61
  60. package/src/util/meld-hooks.tsx +494 -0
  61. package/src/assets/usdc.webp +0 -0
  62. package/src/assets/usdt.webp +0 -0
@@ -0,0 +1,494 @@
1
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2
+ import { useCallback, useState, useEffect, useMemo } from "react";
3
+ import { useReadContract } from "wagmi";
4
+ import { erc20Abi, formatUnits, isAddress, parseUnits } from "viem";
5
+ import type {
6
+ MeldQuote,
7
+ MeldQuotesResponse,
8
+ MeldSessionRequest,
9
+ MeldSessionResponse,
10
+ MeldSupportedCrypto,
11
+ MeldSupportedCryptoResponse,
12
+ MeldTransaction,
13
+ MeldTransactionStatus,
14
+ } from "@/types";
15
+ import { CHECKOUT_BFF_URL, USDC_ADDRESS_BY_CHAIN_ID } from "@/util/constants";
16
+ import transakIcon from "@/assets/providers/transak.svg";
17
+ import moonpayIcon from "@/assets/providers/moonpay.svg";
18
+ import banxaIcon from "@/assets/providers/banxa.svg";
19
+ import mercuryoIcon from "@/assets/providers/mercuryo.svg";
20
+ import kryptonimIcon from "@/assets/providers/kryptonim.svg";
21
+ import alchemypayIcon from "@/assets/providers/alchemypay.svg";
22
+ import unlimitIcon from "@/assets/providers/unlimit.svg";
23
+ import topperIcon from "@/assets/providers/topper.svg";
24
+ import stripeIcon from "@/assets/providers/stripe.svg";
25
+ import binanceconnectIcon from "@/assets/providers/binanceconnect.svg";
26
+
27
+ const MELD_BFF_URL = `${CHECKOUT_BFF_URL}/meld`;
28
+ const USDC_DECIMALS = 6;
29
+
30
+ function getMeldQuoteScore(quote: MeldQuote): number {
31
+ if (typeof quote.rampIntelligence?.rampScore === "number") {
32
+ return quote.rampIntelligence.rampScore;
33
+ }
34
+ if (typeof quote.customerScore === "number") {
35
+ return quote.customerScore;
36
+ }
37
+ return 0;
38
+ }
39
+
40
+ /**
41
+ * Fetch MELD-supported destination currencies for a given country.
42
+ */
43
+ export function useMeldSupportedCrypto(params?: {
44
+ countryCode?: string | null;
45
+ enabled?: boolean;
46
+ }) {
47
+ const { countryCode, enabled = true } = params ?? {};
48
+
49
+ return useQuery({
50
+ queryKey: ["meld-supported-crypto", countryCode],
51
+ queryFn: async (): Promise<MeldSupportedCrypto[]> => {
52
+ const searchParams = new URLSearchParams({
53
+ countryCode,
54
+ });
55
+
56
+ const res = await fetch(
57
+ `${MELD_BFF_URL}/supported-crypto?${searchParams.toString()}`,
58
+ );
59
+
60
+ if (!res.ok) {
61
+ const error = await res.json().catch(() => ({
62
+ error: "Failed to fetch supported crypto",
63
+ }));
64
+ throw new Error(
65
+ error.error ||
66
+ error.message ||
67
+ "Failed to fetch supported crypto",
68
+ );
69
+ }
70
+
71
+ const data:
72
+ | MeldSupportedCryptoResponse
73
+ | { currencies?: MeldSupportedCrypto[] }
74
+ | MeldSupportedCrypto[] = await res.json();
75
+
76
+ const rawCurrencies = Array.isArray(data)
77
+ ? data
78
+ : Array.isArray(data.currencies)
79
+ ? data.currencies
80
+ : [];
81
+
82
+ return rawCurrencies.filter((currency) => !!currency.currencyCode);
83
+ },
84
+ enabled,
85
+ staleTime: 5 * 60 * 1000,
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Resolve MELD destination currency code for symbol+chain from supported metadata.
91
+ */
92
+ export function getMeldDestinationCurrencyCode(params: {
93
+ symbol: string;
94
+ chainId: number;
95
+ supportedCryptos: MeldSupportedCrypto[];
96
+ }): string | null {
97
+ const { symbol, chainId, supportedCryptos } = params;
98
+
99
+ const symbolUpper = symbol.toUpperCase();
100
+ const targetContract = USDC_ADDRESS_BY_CHAIN_ID[chainId]?.toLowerCase();
101
+ if (!targetContract) return null;
102
+
103
+ const symbolMatches = supportedCryptos.filter((currency) =>
104
+ currency.currencyCode.toUpperCase().startsWith(`${symbolUpper}_`),
105
+ );
106
+ if (symbolMatches.length === 0) return null;
107
+
108
+ const byContract = symbolMatches.find(
109
+ (currency) =>
110
+ currency.contractAddress?.toLowerCase() === targetContract,
111
+ );
112
+ if (byContract) {
113
+ return byContract.currencyCode;
114
+ }
115
+
116
+ const byChainId = symbolMatches.find(
117
+ (currency) => currency.chainId === chainId,
118
+ );
119
+ if (byChainId) {
120
+ return byChainId.currencyCode;
121
+ }
122
+
123
+ return symbolMatches.length === 1 ? symbolMatches[0].currencyCode : null;
124
+ }
125
+
126
+ /**
127
+ * Card-buy (fixed USDC) support check.
128
+ */
129
+ export function isMeldCardBuySupportedChain(
130
+ chainId: number,
131
+ supportedCryptos: MeldSupportedCrypto[],
132
+ ): boolean {
133
+ return (
134
+ !!USDC_ADDRESS_BY_CHAIN_ID[chainId] &&
135
+ !!getMeldDestinationCurrencyCode({
136
+ symbol: "USDC",
137
+ chainId,
138
+ supportedCryptos,
139
+ })
140
+ );
141
+ }
142
+
143
+ /**
144
+ * Hook to fetch quotes from MELD
145
+ */
146
+ export function useMeldQuotes(params: {
147
+ sourceCurrency: string;
148
+ destinationCurrency: string; // Should be in format SYMBOL_CHAINCODE
149
+ amount: number;
150
+ countryCode: string;
151
+ walletAddress: string;
152
+ enabled?: boolean;
153
+ }) {
154
+ const {
155
+ sourceCurrency,
156
+ destinationCurrency,
157
+ amount,
158
+ countryCode,
159
+ walletAddress,
160
+ enabled = true,
161
+ } = params;
162
+
163
+ return useQuery({
164
+ queryKey: [
165
+ "meld-quotes",
166
+ sourceCurrency,
167
+ destinationCurrency,
168
+ amount,
169
+ countryCode,
170
+ walletAddress,
171
+ ],
172
+ queryFn: async (): Promise<MeldQuote[]> => {
173
+ const searchParams = new URLSearchParams({
174
+ sourceCurrencyCode: sourceCurrency,
175
+ destinationCurrencyCode: destinationCurrency,
176
+ sourceAmount: String(amount),
177
+ countryCode,
178
+ walletAddress,
179
+ paymentMethodType: "CREDIT_DEBIT_CARD",
180
+ });
181
+
182
+ const res = await fetch(
183
+ `${MELD_BFF_URL}/quotes?${searchParams.toString()}`,
184
+ );
185
+
186
+ if (!res.ok) {
187
+ const error = await res
188
+ .json()
189
+ .catch(() => ({ error: "Failed to fetch quotes" }));
190
+ throw new Error(
191
+ error.error || error.message || "Failed to fetch quotes",
192
+ );
193
+ }
194
+
195
+ const data: MeldQuotesResponse = await res.json();
196
+
197
+ if (data.error) {
198
+ throw new Error(data.error);
199
+ }
200
+
201
+ // Prefer modern MELD ramp score, fallback to legacy customerScore.
202
+ return (data.quotes || []).sort((a, b) => {
203
+ const scoreA = getMeldQuoteScore(a);
204
+ const scoreB = getMeldQuoteScore(b);
205
+ if (scoreB !== scoreA) return scoreB - scoreA;
206
+ return b.destinationAmount - a.destinationAmount;
207
+ });
208
+ },
209
+ enabled:
210
+ enabled &&
211
+ amount > 0 &&
212
+ !!destinationCurrency &&
213
+ !!countryCode &&
214
+ !!walletAddress,
215
+ staleTime: 30000, // 30 seconds
216
+ refetchInterval: 60000, // Refresh every minute
217
+ });
218
+ }
219
+
220
+ /**
221
+ * Hook to create a MELD session
222
+ */
223
+ export function useCreateMeldSession() {
224
+ const queryClient = useQueryClient();
225
+
226
+ return useMutation({
227
+ mutationFn: async (
228
+ params: MeldSessionRequest,
229
+ ): Promise<MeldSessionResponse> => {
230
+ const res = await fetch(`${MELD_BFF_URL}/session`, {
231
+ method: "POST",
232
+ headers: { "Content-Type": "application/json" },
233
+ body: JSON.stringify(params),
234
+ });
235
+
236
+ if (!res.ok) {
237
+ const error = await res
238
+ .json()
239
+ .catch(() => ({ error: "Failed to create session" }));
240
+ throw new Error(
241
+ error.error || error.message || "Failed to create session",
242
+ );
243
+ }
244
+
245
+ return res.json();
246
+ },
247
+ onSuccess: (data) => {
248
+ // Store session for tracking
249
+ if (data.sessionId) {
250
+ queryClient.setQueryData(
251
+ ["meld-session", data.sessionId],
252
+ data,
253
+ );
254
+ }
255
+ },
256
+ });
257
+ }
258
+
259
+ const TERMINAL_MELD_STATUSES = new Set<MeldTransactionStatus>([
260
+ "SETTLED",
261
+ "REFUNDED",
262
+ "DECLINED",
263
+ "CANCELLED",
264
+ "FAILED",
265
+ "ERROR",
266
+ "VOIDED",
267
+ "AUTHORIZATION_EXPIRED",
268
+ ]);
269
+
270
+ /**
271
+ * Terminal status check
272
+ */
273
+ export function isTerminalStatus(status: MeldTransactionStatus): boolean {
274
+ return TERMINAL_MELD_STATUSES.has(status);
275
+ }
276
+
277
+ /**
278
+ * Success status check
279
+ */
280
+ export function isSuccessStatus(status: MeldTransactionStatus): boolean {
281
+ return status === "SETTLED";
282
+ }
283
+
284
+ /**
285
+ * Check if MELD payment has been initiated (settling or settled)
286
+ */
287
+ export function isMeldPaymentInitiated(status: MeldTransactionStatus): boolean {
288
+ return status === "SETTLING" || status === "SETTLED";
289
+ }
290
+
291
+ /**
292
+ * Hook for detecting user's country code via BFF /geo endpoint.
293
+ */
294
+ export function useCountryCode() {
295
+ const { data, isLoading } = useQuery({
296
+ queryKey: ["geo-country"],
297
+ queryFn: async (): Promise<string | null> => {
298
+ try {
299
+ const res = await fetch(`${CHECKOUT_BFF_URL}/geo`, {
300
+ signal: AbortSignal.timeout(3000),
301
+ });
302
+ if (!res.ok) throw new Error("Failed to fetch country code");
303
+ const geo = (await res.json()) as { country?: string };
304
+ return geo.country || "PL";
305
+ } catch {
306
+ return "US";
307
+ }
308
+ },
309
+ retry: 0,
310
+ staleTime: 5 * 60 * 1000,
311
+ });
312
+
313
+ return {
314
+ countryCode: data ?? null,
315
+ isLoading,
316
+ };
317
+ }
318
+
319
+ export function useIncomingUsdcTransferDetector(params: {
320
+ chainId?: number;
321
+ walletAddress?: string;
322
+ enabled?: boolean;
323
+ thresholdUsdc?: string;
324
+ }) {
325
+ const {
326
+ chainId,
327
+ walletAddress,
328
+ enabled = true,
329
+ thresholdUsdc = "0.01",
330
+ } = params;
331
+
332
+ const usdcAddress = chainId ? USDC_ADDRESS_BY_CHAIN_ID[chainId] : undefined;
333
+ const shouldTrack =
334
+ !!enabled &&
335
+ !!chainId &&
336
+ !!usdcAddress &&
337
+ !!walletAddress &&
338
+ isAddress(walletAddress);
339
+ const threshold = useMemo(
340
+ () => parseUnits(thresholdUsdc, USDC_DECIMALS),
341
+ [thresholdUsdc],
342
+ );
343
+ const [baselineBalance, setBaselineBalance] = useState<bigint | null>(null);
344
+ const [detectedAmount, setDetectedAmount] = useState<string | null>(null);
345
+
346
+ const { data, refetch, isFetching, isLoading } = useReadContract({
347
+ chainId,
348
+ address: usdcAddress as `0x${string}` | undefined,
349
+ abi: erc20Abi,
350
+ functionName: "balanceOf",
351
+ args: walletAddress ? [walletAddress as `0x${string}`] : undefined,
352
+ query: {
353
+ enabled: shouldTrack,
354
+ refetchInterval: shouldTrack ? 4000 : false,
355
+ staleTime: 0,
356
+ },
357
+ });
358
+
359
+ useEffect(() => {
360
+ if (!shouldTrack) {
361
+ setBaselineBalance(null);
362
+ setDetectedAmount(null);
363
+ }
364
+ }, [shouldTrack]);
365
+
366
+ useEffect(() => {
367
+ if (!shouldTrack || typeof data !== "bigint" || detectedAmount) return;
368
+
369
+ if (baselineBalance === null) {
370
+ setBaselineBalance(data);
371
+ return;
372
+ }
373
+
374
+ if (data <= baselineBalance) return;
375
+
376
+ const delta = data - baselineBalance;
377
+ if (delta >= threshold) {
378
+ setDetectedAmount(formatUnits(delta, USDC_DECIMALS));
379
+ }
380
+ }, [
381
+ shouldTrack,
382
+ data,
383
+ baselineBalance,
384
+ detectedAmount,
385
+ threshold,
386
+ isFetching,
387
+ ]);
388
+
389
+ console.log(data, baselineBalance, detectedAmount);
390
+
391
+ const reset = useCallback(() => {
392
+ setBaselineBalance(null);
393
+ setDetectedAmount(null);
394
+ }, []);
395
+
396
+ return {
397
+ detectedAmount,
398
+ isDetected: detectedAmount !== null,
399
+ isTracking: shouldTrack,
400
+ isRefreshing: isFetching || isLoading,
401
+ currentBalance: typeof data === "bigint" ? data : null,
402
+ baselineBalance,
403
+ reset,
404
+ };
405
+ }
406
+
407
+ /**
408
+ * Hook to manage the full MELD card buy flow state
409
+ */
410
+ export function useMeldCardBuyFlow() {
411
+ const [sessionId, setSessionId] = useState<string | null>(null);
412
+ const [widgetUrl, setWidgetUrl] = useState<string | null>(null);
413
+ const [widgetOpen, setWidgetOpen] = useState(false);
414
+
415
+ const createSession = useCreateMeldSession();
416
+
417
+ const startSession = useCallback(
418
+ async (params: MeldSessionRequest) => {
419
+ const result = await createSession.mutateAsync(params);
420
+ setSessionId(result.sessionId);
421
+ setWidgetUrl(result.widgetUrl);
422
+ return result;
423
+ },
424
+ [createSession],
425
+ );
426
+
427
+ const openWidget = useCallback(() => {
428
+ if (widgetUrl) {
429
+ setWidgetOpen(true);
430
+ // Open in new window/tab
431
+ window.open(widgetUrl, "_blank", "width=500,height=700");
432
+ }
433
+ }, [widgetUrl]);
434
+
435
+ const reset = useCallback(() => {
436
+ setSessionId(null);
437
+ setWidgetUrl(null);
438
+ setWidgetOpen(false);
439
+ }, []);
440
+
441
+ return {
442
+ // Session management
443
+ sessionId,
444
+ widgetUrl,
445
+ widgetOpen,
446
+ startSession,
447
+ openWidget,
448
+ reset,
449
+
450
+ // Session creation state
451
+ isCreatingSession: createSession.isPending,
452
+ sessionError: createSession.error,
453
+ };
454
+ }
455
+
456
+ /**
457
+ * Format MELD provider name for display
458
+ */
459
+ export function formatProviderName(provider: string): string {
460
+ const names: Record<string, string> = {
461
+ TRANSAK: "Transak",
462
+ MOONPAY: "MoonPay",
463
+ BANXA: "Banxa",
464
+ RAMP: "Ramp",
465
+ SARDINE: "Sardine",
466
+ STRIPE: "Stripe",
467
+ MERCURYO: "Mercuryo",
468
+ ALCHEMY_PAY: "Alchemy Pay",
469
+ KRYPTONIM: "Kryptonim",
470
+ UNLIMIT: "Unlimit",
471
+ TOPPER: "Topper",
472
+ BINANCE_CONNECT: "Binance Connect",
473
+ };
474
+ return names[provider] || provider;
475
+ }
476
+
477
+ /**
478
+ * Get provider icon URL
479
+ */
480
+ export function getProviderIcon(provider: string): string {
481
+ const icons: Record<string, string> = {
482
+ TRANSAK: transakIcon,
483
+ MOONPAY: moonpayIcon,
484
+ BANXA: banxaIcon,
485
+ MERCURYO: mercuryoIcon,
486
+ KRYPTONIM: kryptonimIcon,
487
+ ALCHEMY_PAY: alchemypayIcon,
488
+ UNLIMIT: unlimitIcon,
489
+ TOPPER: topperIcon,
490
+ STRIPE: stripeIcon,
491
+ BINANCE_CONNECT: binanceconnectIcon,
492
+ };
493
+ return icons[provider] || "";
494
+ }
Binary file
Binary file