-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathTransactionStatus.tsx
More file actions
1120 lines (1032 loc) · 38.8 KB
/
TransactionStatus.tsx
File metadata and controls
1120 lines (1032 loc) · 38.8 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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import Image from "next/image";
import { useTheme } from "next-themes";
import { useEffect, useState, useRef } from "react";
import { AnimatePresence } from "framer-motion";
import { ImSpinner } from "react-icons/im";
import { Checkbox } from "@headlessui/react";
import {
AnimatedComponent,
scaleInOut,
secondaryBtnClasses,
fadeInOut,
slideInOut,
fadeUpAnimation,
primaryBtnClasses,
} from "../components";
import {
FarcasterIconDarkTheme,
FarcasterIconLightTheme,
QuotesBgIcon,
XIconDarkTheme,
XIconLightTheme,
YellowHeart,
} from "../components/ImageAssets";
import {
calculateDuration,
classNames,
formatCurrency,
formatNumberWithCommas,
getExplorerLink,
getInstitutionNameByCode,
} from "../utils";
import {
fetchOrderDetails,
updateTransactionDetails,
fetchSavedRecipients,
saveRecipient,
deleteSavedRecipient,
} from "../api/aggregator";
import { reindexSingleTransaction } from "../lib/reindex";
import {
STEPS,
type OrderDetailsData,
type TransactionStatusProps,
} from "../types";
import { toast } from "sonner";
import { trackEvent } from "../hooks/analytics/client";
import { PDFReceipt } from "../components/PDFReceipt";
import { pdf } from "@react-pdf/renderer";
import { CancelCircleIcon, CheckmarkCircle01Icon } from "hugeicons-react";
import { useBalance, useInjectedWallet, useNetwork } from "../context";
import { usePrivy } from "@privy-io/react-auth";
import { TransactionHelperText } from "../components/TransactionHelperText";
import { useConfetti } from "../hooks/useConfetti";
import { BlockFestCashbackComponent } from "../components/blockfest";
import { useBlockFestClaim } from "../context/BlockFestClaimContext";
import { useRocketStatus } from "../context/RocketStatusContext";
import { isBlockFestActive } from "../utils";
// Allowed tokens for BlockFest cashback
const ALLOWED_CASHBACK_TOKENS = new Set(["USDC", "USDT"]);
// Helper function to check BlockFest eligibility
const isBlockFestEligible = (
transactionStatus: string,
claimed: boolean | null,
orderDetails: any,
orderId: string | null,
) => {
const isCampaignActive = isBlockFestActive();
const isTransactionComplete = ["validated", "settling", "settled"].includes(
transactionStatus,
);
const isUserClaimed = claimed === true;
const isBaseNetwork = orderDetails?.network?.toLowerCase() === "base";
const hasValidOrder = Boolean(orderId && orderDetails?.token);
const isEligibleToken =
orderDetails?.token && ALLOWED_CASHBACK_TOKENS.has(orderDetails.token);
return (
isCampaignActive &&
isTransactionComplete &&
isUserClaimed &&
isBaseNetwork &&
hasValidOrder &&
isEligibleToken
);
};
/**
* Renders the transaction status component.
*
* @param transactionStatus - The status of the transaction.
* @param recipientName - The name of the recipient.
* @param errorMessage - The error message, if any.
* @param createdAt - The creation date of the transaction.
* @param clearForm - Function to clear the form.
* @param clearTransactionStatus - Function to clear the transaction status.
* @param setTransactionStatus - Function to set the transaction status.
* @param setCurrentStep - Function to set the current step.
* @param formMethods - The form methods.
*/
export function TransactionStatus({
transactionStatus,
orderId,
createdAt,
setTransactionStatus,
setCurrentStep,
clearTransactionStatus,
formMethods,
supportedInstitutions,
setOrderId,
}: TransactionStatusProps) {
const { claimed } = useBlockFestClaim();
const { resolvedTheme } = useTheme();
const { selectedNetwork } = useNetwork();
const { refreshBalance, smartWalletBalance, injectedWalletBalance } =
useBalance();
const { isInjectedWallet, injectedAddress } = useInjectedWallet();
const { user, getAccessToken } = usePrivy();
const { setRocketStatus } = useRocketStatus();
const embeddedWallet = user?.linkedAccounts.find(
(account) =>
account.type === "wallet" && account.connectorType === "embedded",
) as { address: string } | undefined;
const [orderDetails, setOrderDetails] = useState<OrderDetailsData>();
const [completedAt, setCompletedAt] = useState<string>("");
const [createdHash, setCreatedHash] = useState("");
const [isGettingReceipt, setIsGettingReceipt] = useState(false);
const [addToBeneficiaries, setAddToBeneficiaries] = useState(false);
const [isTracked, setIsTracked] = useState(false);
const [hasShownConfetti, setHasShownConfetti] = useState(false);
const [isSavingRecipient, setIsSavingRecipient] = useState(false);
const [showSaveSuccess, setShowSaveSuccess] = useState(false);
const [hasReindexed, setHasReindexed] = useState(false);
const reindexTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const latestRequestIdRef = useRef<number>(0);
const fireConfetti = useConfetti();
const { watch } = formMethods;
const token = watch("token") || "";
const currency = String(watch("currency")) || "USD";
const amount = watch("amountSent") || 0;
const fiat = Number(watch("amountReceived")) || 0;
const recipientName = String(watch("recipientName")) || "";
const accountIdentifier = watch("accountIdentifier") || "";
const institution = watch("institution") || "";
// Check if recipient is already saved in the database
const [isRecipientInBeneficiaries, setIsRecipientInBeneficiaries] =
useState(false);
// Check if recipient exists in saved beneficiaries
useEffect(() => {
const checkRecipientExists = async () => {
if (!accountIdentifier || !institution) {
setIsRecipientInBeneficiaries(false);
return;
}
try {
const accessToken = await getAccessToken();
if (!accessToken) {
setIsRecipientInBeneficiaries(false);
return;
}
const savedRecipients = await fetchSavedRecipients(accessToken);
const exists = savedRecipients.some(
(r) =>
r.accountIdentifier === accountIdentifier &&
r.institutionCode === institution,
);
setIsRecipientInBeneficiaries(exists);
} catch (error) {
console.error("Error checking if recipient exists:", error);
setIsRecipientInBeneficiaries(false);
}
};
checkRecipientExists();
}, [accountIdentifier, institution, getAccessToken]);
/**
* Updates transaction status in the backend
* Uses a request ID system to handle race conditions when multiple updates are triggered
* Only the latest update attempt will complete, older ones will be skipped
*/
const saveTransactionData = async () => {
if (!embeddedWallet?.address) return;
// Increment request ID to mark this as the latest request
const requestId = ++latestRequestIdRef.current;
try {
const accessToken = await getAccessToken();
if (!accessToken) {
throw new Error("No access token available");
}
// Get the stored transaction ID
const transactionId = localStorage.getItem("currentTransactionId");
if (!transactionId) {
console.error("No transaction ID found");
return;
}
// If this is no longer the latest request, skip saving
if (requestId !== latestRequestIdRef.current) {
return;
}
// Calculate time spent
const timeSpent = calculateDuration(createdAt, new Date().toISOString());
// Check again before making the API call
if (requestId !== latestRequestIdRef.current) {
return;
}
const refundReason =
transactionStatus === "refunded" && orderDetails?.cancellationReasons?.length
? orderDetails.cancellationReasons.join(", ")
: undefined;
const response = await updateTransactionDetails({
transactionId,
status: transactionStatus,
txHash:
transactionStatus !== "refunded" ? createdHash : orderDetails?.txHash,
timeSpent,
refundReason,
accessToken,
walletAddress: embeddedWallet.address,
});
if (!response.success) {
throw new Error("Failed to update transaction details");
}
} catch (error: unknown) {
// Only log if this is still the latest request
if (requestId === latestRequestIdRef.current) {
console.error("Error updating transaction:", error);
}
}
};
/**
* Polls the order details endpoint every 5 seconds to check transaction status
* Updates local state when status changes
* Saves transaction data when status is final (validated/settled/refunded)
*/
useEffect(
function pollOrderDetails() {
let intervalId: NodeJS.Timeout;
const getOrderDetails = async () => {
try {
const orderDetailsResponse = await fetchOrderDetails(
selectedNetwork.chain.id,
orderId,
);
setOrderDetails(orderDetailsResponse.data);
if (orderDetailsResponse.data.status !== "pending") {
const status = orderDetailsResponse.data.status;
// Update transaction status if changed
if (transactionStatus !== status) {
setTransactionStatus(
status as
| "fulfilling"
| "validated"
| "settling"
| "settled"
| "refunding"
| "refunded",
);
}
// Handle final statuses
if (["validated", "settling", "settled", "refunding", "refunded"].includes(status)) {
setCompletedAt(orderDetailsResponse.data.updatedAt);
if (["refunding", "refunded"].includes(status)) {
refreshBalance();
setRocketStatus("pending");
} else {
setRocketStatus("settled");
}
clearInterval(intervalId);
// Save transaction data only once on validation or refund
if (["validated", "refunded"].includes(transactionStatus)) {
saveTransactionData();
}
return; // No need to check further statuses
}
// Handle processing status
if (status === "fulfilling") {
const createdReceipt = orderDetailsResponse.data.txReceipts.find(
(txReceipt) => txReceipt.status === "pending",
);
if (createdReceipt) {
setCreatedHash(createdReceipt.txHash);
saveTransactionData();
}
setRocketStatus("processing");
return;
}
// Handle fulfilled status
if (status === "fulfilled") {
setRocketStatus("fulfilled");
return;
}
}
} catch (error) {
// fail silently
}
};
getOrderDetails();
intervalId = setInterval(getOrderDetails, 5000);
return () => {
if (intervalId) clearInterval(intervalId);
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[orderId, transactionStatus],
);
/**
* Tracks transaction events for analytics
* Only tracks once per transaction when status is final
*/
useEffect(
function trackTransactionEvents() {
// Only track if we haven't tracked yet and have all required data
if (!isTracked && transactionStatus && completedAt) {
const bankName = getInstitutionNameByCode(
String(formMethods.watch("institution")),
supportedInstitutions,
);
const balance = isInjectedWallet
? smartWalletBalance?.balances[token] || 0
: injectedWalletBalance?.balances[token] || 0;
const eventData = {
Amount: amount,
"Send token": token,
"Receive currency": currency,
"Recipient bank": bankName,
"Wallet balance": balance,
"Swap date": createdAt,
"Transaction duration": calculateDuration(createdAt, completedAt),
"Wallet type": isInjectedWallet ? "Injected" : "Smart wallet",
};
if (["validated", "settled"].includes(transactionStatus)) {
trackEvent("Swap completed", eventData);
setIsTracked(true);
} else if (transactionStatus === "refunded") {
const reason =
orderDetails?.cancellationReasons?.length &&
orderDetails.cancellationReasons[0]
? orderDetails.cancellationReasons[0]
: "Transaction failed and refunded";
trackEvent("Swap failed", {
...eventData,
"Reason for failure": reason,
});
setIsTracked(true);
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isTracked, transactionStatus, completedAt],
);
/**
* Shows confetti animation when transaction is successful
* Only shows once per transaction
*/
useEffect(
function fireConfettiOnSuccess() {
if (
["validated", "settling", "settled"].includes(transactionStatus) &&
!hasShownConfetti
) {
fireConfetti();
setHasShownConfetti(true);
}
},
[transactionStatus, fireConfetti, hasShownConfetti],
);
/**
* Reindexes transaction if it has been pending for more than 30 seconds
* Only calls reindex once per transaction
*/
useEffect(
function reindexPendingTransaction() {
// Only proceed if:
// 1. Transaction status is "pending"
// 2. We haven't already reindexed
// 3. We have order details with network
if (
transactionStatus !== "pending" ||
hasReindexed ||
!orderDetails ||
!orderDetails.network
) {
return;
}
// Get txHash from orderDetails.txHash or from txReceipts
let txHash = orderDetails.txHash;
if (
!txHash &&
orderDetails.txReceipts &&
orderDetails.txReceipts.length > 0
) {
// Try to find a pending receipt first, otherwise use the first one
const pendingReceipt = orderDetails.txReceipts.find(
(receipt) => receipt.status === "pending",
);
txHash = pendingReceipt?.txHash || orderDetails.txReceipts[0]?.txHash;
}
// If we still don't have a txHash, we can't reindex
if (!txHash) {
return;
}
// Reindex transaction to sync with blockchain state
const callReindex = async (): Promise<void> => {
try {
await reindexSingleTransaction(txHash, orderDetails.network);
setHasReindexed(true);
} catch (error) {
console.error("Error reindexing transaction:", error);
// Prevent infinite retry loops on persistent errors
setHasReindexed(true);
}
};
// Calculate time elapsed since transaction creation
const createdAtTime = new Date(createdAt).getTime();
const currentTime = Date.now();
const timeElapsed = currentTime - createdAtTime;
const thirtySecondsInMs = 30 * 1000;
// If 30 seconds haven't elapsed yet, schedule a check for when they will
if (timeElapsed <= thirtySecondsInMs) {
const remainingTime = thirtySecondsInMs - timeElapsed;
reindexTimeoutRef.current = setTimeout(() => {
callReindex();
}, remainingTime);
} else {
// 30 seconds have elapsed, call reindex immediately
callReindex();
}
// Cleanup function to clear timeout on unmount or dependency change
return () => {
if (reindexTimeoutRef.current) {
clearTimeout(reindexTimeoutRef.current);
reindexTimeoutRef.current = null;
}
};
},
[transactionStatus, hasReindexed, orderDetails, createdAt],
);
/**
* Renders the appropriate status indicator based on transaction status
* Shows checkmark for success, X for failure, or spinner for pending states
*/
const StatusIndicator = () => (
<AnimatePresence mode="wait">
{["validated", "settling", "settled"].includes(transactionStatus) ? (
<AnimatedComponent variant={scaleInOut} key="settled">
<CheckmarkCircle01Icon className="size-10" color="#39C65D" />
</AnimatedComponent>
) : ["refunding", "refunded"].includes(transactionStatus) ? (
<AnimatedComponent variant={scaleInOut} key="refunded">
<CancelCircleIcon className="size-10" color="#F53D6B" />
</AnimatedComponent>
) : (
<AnimatedComponent
variant={fadeInOut}
key="pending"
className={`flex items-center gap-1 rounded-full px-2 py-1 dark:bg-white/10 ${
transactionStatus === "pending"
? "bg-orange-50 text-orange-400"
: transactionStatus === "fulfilling"
? "bg-yellow-50 text-yellow-400"
: transactionStatus === "fulfilled"
? "bg-green-50 text-green-400"
: transactionStatus === "refunding"
? "bg-purple-50 text-purple-400"
: "bg-gray-50"
}`}
>
<ImSpinner className="animate-spin" />
<p>{transactionStatus === "fulfilling" ? "processing" : transactionStatus}</p>
</AnimatedComponent>
)}
</AnimatePresence>
);
/**
* Handles the back button click event.
* Clears the transaction status if it's refunded, otherwise clears the form and transaction status.
*/
const handleBackButtonClick = () => {
if (transactionStatus === "refunded") {
clearTransactionStatus();
setCurrentStep(STEPS.FORM);
} else {
window.location.reload();
}
};
const handleAddToBeneficiariesChange = async (checked: boolean) => {
setAddToBeneficiaries(checked);
if (checked) {
await addBeneficiary();
} else {
await removeRecipient();
}
};
const addBeneficiary = async () => {
setIsSavingRecipient(true);
const institutionCode = formMethods.watch("institution");
if (!institutionCode) {
setIsSavingRecipient(false);
return;
}
const institutionName = getInstitutionNameByCode(
String(institutionCode),
supportedInstitutions,
);
if (!institutionName) {
console.error("Institution name not found");
setIsSavingRecipient(false);
return;
}
const newRecipient = {
name: recipientName,
institution: institutionName,
institutionCode: String(institutionCode),
accountIdentifier: String(formMethods.watch("accountIdentifier") || ""),
type:
(formMethods.watch("accountType") as "bank" | "mobile_money") || "bank",
};
// Save recipient via API
const accessToken = await getAccessToken();
if (accessToken) {
try {
const success = await saveRecipient(newRecipient, accessToken);
if (success) {
// Show success state
setIsSavingRecipient(false);
setShowSaveSuccess(true);
// Hide after 2 seconds with fade out animation
setTimeout(() => {
setShowSaveSuccess(false);
// Add a small delay to allow fade out animation to complete
setTimeout(() => {
setIsRecipientInBeneficiaries(true);
}, 300);
}, 2000);
} else {
setIsSavingRecipient(false);
}
} catch (error) {
console.error("Error saving recipient:", error);
setIsSavingRecipient(false);
}
} else {
setIsSavingRecipient(false);
}
};
const removeRecipient = async () => {
const accountIdentifier = formMethods.watch("accountIdentifier");
const institutionCode = formMethods.watch("institution");
if (!accountIdentifier || !institutionCode) {
console.error("Missing account identifier or institution code");
return;
}
try {
const accessToken = await getAccessToken();
if (!accessToken) {
console.error("No access token available");
return;
}
// Fetch saved recipients to find the recipient ID
const savedRecipients = await fetchSavedRecipients(accessToken);
const recipientToDelete = savedRecipients.find(
(r) =>
r.accountIdentifier === accountIdentifier &&
r.institutionCode === institutionCode,
);
if (!recipientToDelete) {
console.error("Recipient not found in saved recipients");
return;
}
// Delete the recipient using its ID
const success = await deleteSavedRecipient(
recipientToDelete.id,
accessToken,
);
if (success) {
// Update state to show the checkbox again since recipient is now removed
setIsRecipientInBeneficiaries(false);
console.log("Recipient removed successfully");
}
} catch (error) {
console.error("Error removing recipient:", error);
}
};
const getPaymentMessage = () => {
const formattedRecipientName = recipientName
? recipientName
.toLowerCase()
.split(" ")
.map((name) => name.charAt(0).toUpperCase() + name.slice(1))
.join(" ")
: "";
if (transactionStatus === "refunded") {
const refundReason =
orderDetails?.cancellationReasons?.length &&
orderDetails.cancellationReasons[0]
? orderDetails.cancellationReasons[0]
: null;
return (
<>
Your transfer of{" "}
<span className="text-text-body dark:text-white">
{formatNumberWithCommas(amount)} {token} (
{formatCurrency(fiat ?? 0, currency, `en-${currency.slice(0, 2)}`)})
</span>{" "}
to {formattedRecipientName} was unsuccessful.
{refundReason && (
<>
<br />
<span className="text-text-secondary dark:text-white/70">
{refundReason}
</span>
</>
)}
<br />
<br />
The stablecoin has been refunded to your account.
</>
);
}
if (transactionStatus === "refunding") {
return (
<>
Refunding{" "}
<span className="text-text-body dark:text-white">
{formatNumberWithCommas(amount)} {token} (
{formatCurrency(fiat ?? 0, currency, `en-${currency.slice(0, 2)}`)})
</span>{" "}
to your account. Hang on, this will only take a few seconds.
</>
);
}
if (!["validated", "settling", "settled"].includes(transactionStatus)) {
return (
<>
Processing payment of{" "}
<span className="text-text-body dark:text-white">
{formatNumberWithCommas(amount)} {token} (
{formatCurrency(fiat ?? 0, currency, `en-${currency.slice(0, 2)}`)})
</span>{" "}
to {formattedRecipientName}. Hang on, this will only take a few
seconds
</>
);
}
return (
<>
Your transfer of{" "}
<span className="text-text-body dark:text-white">
{formatNumberWithCommas(amount)} {token} (
{formatCurrency(fiat ?? 0, currency, `en-${currency.slice(0, 2)}`)})
</span>{" "}
to {formattedRecipientName} has been completed successfully.
</>
);
};
const getImageSrc = () => {
const base = !["validated", "settled", "refunded"].includes(
transactionStatus,
)
? "/images/stepper"
: "/images/stepper-long";
const themeSuffix = resolvedTheme === "dark" ? "-dark.svg" : ".svg";
return base + themeSuffix;
};
const handleGetReceipt = async () => {
setIsGettingReceipt(true);
try {
if (orderDetails) {
const blob = await pdf(
<PDFReceipt
data={orderDetails as OrderDetailsData}
formData={{
recipientName,
accountIdentifier: formMethods.watch(
"accountIdentifier",
) as string,
institution: formMethods.watch("institution") as string,
memo: formMethods.watch("memo") as string,
amountReceived: formMethods.watch("amountReceived") as number,
currency: formMethods.watch("currency") as string,
}}
supportedInstitutions={supportedInstitutions}
/>,
).toBlob();
const pdfUrl = URL.createObjectURL(blob);
window.open(pdfUrl, "_blank");
}
} catch (error) {
toast.error("Error generating receipt. Please try again.");
console.error("Error generating receipt:", error);
} finally {
setIsGettingReceipt(false);
}
};
return (
<div className="flex w-full justify-center gap-[4.5rem]">
<div className="hidden flex-col gap-2 sm:flex">
<div className="flex w-fit flex-col items-end gap-2 text-neutral-900 dark:text-white/80">
<AnimatedComponent
variant={slideInOut}
delay={0.2}
className="flex items-center gap-1 rounded-full bg-gray-50 px-2 py-1 dark:bg-white/5"
>
{token && (
<Image
src={`/logos/${String(token)?.toLowerCase()}-logo.svg`}
alt={`${token} logo`}
width={14}
height={14}
/>
)}
<p className="whitespace-nowrap pr-4 font-medium">
{formatNumberWithCommas(amount)} {token}
</p>
</AnimatedComponent>
<Image
src={getImageSrc()}
alt="Progress"
width={200}
height={200}
className="w-auto"
/>
<AnimatedComponent
variant={slideInOut}
delay={0.4}
className="max-w-60 truncate whitespace-nowrap rounded-full bg-gray-50 px-3 py-1 capitalize dark:bg-white/5"
>
{(recipientName ?? "").toLowerCase().split(" ")[0]}
</AnimatedComponent>
</div>
</div>
<div className="flex flex-col items-start gap-4 sm:max-w-xs">
<StatusIndicator />
<AnimatedComponent
variant={slideInOut}
delay={0.2}
className="text-xl font-medium text-neutral-900 dark:text-white/80"
>
{["refunding", "refunded"].includes(transactionStatus)
? "Oops! Transaction failed"
: !["validated", "settling", "settled"].includes(transactionStatus)
? "Processing payment..."
: "Transaction successful"}
</AnimatedComponent>
<div className="flex w-full items-center gap-2 text-neutral-900 dark:text-white/80 sm:hidden">
<AnimatedComponent
variant={slideInOut}
delay={0.2}
className="flex items-center gap-2 rounded-full bg-gray-50 px-2 py-1 dark:bg-white/5"
>
{token && (
<Image
src={`/logos/${String(token)?.toLowerCase()}-logo.svg`}
alt={`${token} logo`}
width={14}
height={14}
/>
)}
<p className="whitespace-nowrap pr-0.5 font-medium">
{amount} {token}
</p>
</AnimatedComponent>
<Image
src={`/images/horizontal-stepper${resolvedTheme === "dark" ? "-dark" : ""}.svg`}
alt="Progress"
width={200}
height={200}
className="-mr-1.5 mt-1 size-auto"
/>
<AnimatedComponent
variant={slideInOut}
delay={0.4}
className="max-w-28 truncate rounded-full bg-gray-50 px-3 py-1 capitalize dark:bg-white/5"
>
{(recipientName ?? "").toLowerCase().split(" ")[0]}
</AnimatedComponent>
</div>
<hr className="w-full border-dashed border-border-light dark:border-white/10 sm:hidden" />
<AnimatedComponent
variant={slideInOut}
delay={0.4}
className="text-sm leading-normal text-gray-500 dark:text-white/50"
>
{getPaymentMessage()}
</AnimatedComponent>
{/* Helper text for long-running transactions */}
<TransactionHelperText
isVisible={["fulfilling", "fulfilled", "refunding"].includes(
transactionStatus,
)}
title="Taking longer than expected?"
message="Your transaction is still processing. You can safely
refresh or leave this page - your funds will either be
settled or automatically refunded if the transaction
fails."
showAfterMs={60000}
className="w-full space-y-4"
/>
<AnimatePresence>
{["validated", "settled", "refunded"].includes(transactionStatus) && (
<>
{/* BlockFest Cashback Component - only when validated/settled and claimed and on Base network */}
{isBlockFestEligible(
transactionStatus,
claimed,
orderDetails,
orderId,
) && (
<AnimatedComponent
variant={slideInOut}
delay={0.45}
className="flex justify-center"
>
<BlockFestCashbackComponent
transactionId={orderId}
cashbackPercentage="1%"
/>
</AnimatedComponent>
)}
<AnimatedComponent
variant={slideInOut}
delay={0.5}
className="flex w-full flex-wrap gap-3 max-sm:*:flex-1"
>
{["validated", "settled"].includes(transactionStatus) && (
<button
type="button"
onClick={handleGetReceipt}
className={`w-fit ${secondaryBtnClasses}`}
disabled={isGettingReceipt}
>
{isGettingReceipt ? "Generating..." : "Get receipt"}
</button>
)}
<button
type="button"
onClick={handleBackButtonClick}
className={`w-fit ${primaryBtnClasses}`}
>
{transactionStatus === "refunded"
? "Retry transaction"
: "New payment"}
</button>
</AnimatedComponent>
{["validated", "settled"].includes(transactionStatus) &&
!isRecipientInBeneficiaries && (
<AnimatePresence mode="wait">
{isSavingRecipient ? (
<AnimatedComponent
key="saving"
variant={fadeUpAnimation}
className="flex items-center gap-2"
>
<div className="mt-1 flex h-4 w-4 items-center justify-center">
<ImSpinner className="h-4 w-4 animate-spin text-text-body dark:text-white/80" />
</div>
<span className="text-text-body dark:text-white/80">
Saving to beneficiaries...
</span>
</AnimatedComponent>
) : showSaveSuccess ? (
<AnimatedComponent
key="success"
variant={slideInOut}
className="flex items-center gap-2"
>
<div className="mt-1 flex h-4 w-4 items-center justify-center">
<CheckmarkCircle01Icon className="h-4 w-4 text-green-500" />
</div>
<span className="text-green-600 dark:text-green-400">
Saved to beneficiaries!
</span>
</AnimatedComponent>
) : (
<AnimatedComponent
key="checkbox"
variant={fadeUpAnimation}
className="flex gap-2"
>
<Checkbox
checked={addToBeneficiaries}
onChange={handleAddToBeneficiariesChange}
className="group mt-1 block size-4 flex-shrink-0 cursor-pointer rounded border-2 border-gray-300 bg-transparent data-[checked]:border-lavender-500 data-[checked]:bg-lavender-500 dark:border-white/30 dark:data-[checked]:border-lavender-500"
>
<svg
className="stroke-white/50 opacity-0 group-data-[checked]:opacity-100 dark:stroke-neutral-800"
viewBox="0 0 14 14"
fill="none"
>
<title>
{addToBeneficiaries
? "Remove from beneficiaries"
: "Add to your beneficiaries"}
</title>
<path
d="M3 8L6 11L11 3.5"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</Checkbox>
<label className="text-text-body dark:text-white/80">
Add{" "}
{(recipientName ?? "")
.split(" ")[0]
.charAt(0)
.toUpperCase() +
(recipientName ?? "")
.toLowerCase()
.split(" ")[0]
.slice(1)}{" "}
to beneficiaries
</label>
</AnimatedComponent>
)}
</AnimatePresence>
)}
</>
)}
</AnimatePresence>