-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathWidget.tsx
More file actions
1510 lines (1385 loc) · 56.1 KB
/
Widget.tsx
File metadata and controls
1510 lines (1385 loc) · 56.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
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
import {
Box,
CircularProgress,
Fade,
Typography,
TextField,
IconButton,
Tooltip,
} from '@mui/material'
import React, { Fragment, useCallback, useEffect, useMemo, useState } from 'react'
import copyToClipboard from 'copy-to-clipboard'
import { QRCodeSVG } from 'qrcode.react'
import { Socket } from 'socket.io-client'
import { Theme, ThemeName, ThemeProvider, useTheme } from '../../themes'
import { NumericFormat } from 'react-number-format';
import { Button, animation } from '../Button/Button'
import BarChart from '../BarChart/BarChart'
import config from '../../paybutton-config.json'
import { DONATION_RATE_STORAGE_KEY } from '../../util/constants'
import {
getAddressBalance,
Currency,
isFiat,
Transaction,
openCashtabPayment,
initializeCashtabStatus,
DECIMALS,
MAX_AMOUNT,
CurrencyObject,
getCurrencyObject,
formatPrice,
encodeOpReturnProps,
isValidCashAddress,
isValidXecAddress,
getCurrencyTypeFromAddress,
CURRENCY_PREFIXES_MAP,
CRYPTO_CURRENCIES,
isPropsTrue,
setupChronikWebSocket,
setupAltpaymentSocket,
CryptoCurrency,
DEFAULT_DONATION_RATE,
DEFAULT_MINIMUM_DONATION_AMOUNT,
createPayment,
darkMode
} from '../../util';
import AltpaymentWidget from './AltpaymentWidget'
import {
AltpaymentPair,
AltpaymentShift,
AltpaymentError,
AltpaymentCoin,
MINIMUM_ALTPAYMENT_DOLLAR_AMOUNT,
MINIMUM_ALTPAYMENT_CAD_AMOUNT,
} from '../../altpayment'
import { WsEndpoint } from 'chronik-client'
export interface WidgetProps {
to: string
isChild?: boolean
amount?: number | null | string
setAmount?: Function
opReturn?: string
paymentId?: string
disablePaymentId?: boolean
text?: string
ButtonComponent?: React.ComponentType
success?: boolean
pendingFinalization?: boolean
successText?: string
theme?: ThemeName | Theme
foot?: React.ReactNode
disabled?: boolean
goalAmount?: number | string | null
currency?: Currency
animation?: animation
currencyObject?: CurrencyObject | undefined
setCurrencyObject?: Function
randomSatoshis?: boolean | number
price?: number | undefined
usdPrice?: number | undefined
editable?: boolean
setNewTxs?: Function
newTxs?: Transaction[]
wsBaseUrl?: string
apiBaseUrl?: string
loading?: boolean
hoverText?: string
disableAltpayment?: boolean
contributionOffset?: number
setAltpaymentShift?: Function
altpaymentShift?: AltpaymentShift | undefined
useAltpayment?: boolean
setUseAltpayment?: Function
txsSocket?: Socket
setTxsSocket?: Function
altpaymentSocket?: Socket
setAltpaymentSocket?: Function
shiftCompleted?: boolean
donationAddress?: string
donationRate?: number
setShiftCompleted?: Function;
setCoins?: Function;
coins?: AltpaymentCoin[];
setCoinPair?: Function;
coinPair?: AltpaymentPair;
setLoadingPair?: Function;
loadingPair?: boolean;
setLoadingShift?: Function;
loadingShift?: boolean;
setAltpaymentError?: Function;
altpaymentError?: AltpaymentError;
addressType?: Currency,
setAddressType?: Function,
newTxText?: string;
transactionText?: string;
convertedCurrencyObj?: CurrencyObject;
hideSendButton?: boolean;
setConvertedCurrencyObj?: Function;
setPaymentId?: Function;
}
interface StyleProps {
success: boolean
loading: boolean
theme: Theme
recentlyCopied: boolean
copied: boolean
}
function convertBip21ToDeeplink(bip21Url: string, apiBaseUrl?: string): string | undefined {
if (!apiBaseUrl) {
return undefined
}
// Parse BIP21 URL: ecash:address?amount=100&opreturnraw=xxx
const [addressPart, queryPart] = bip21Url.split('?')
const params = new URLSearchParams()
params.set('address', addressPart)
if (queryPart) {
const queryParams = new URLSearchParams(queryPart)
// Add all query parameters from the BIP21 string
queryParams.forEach((value, key) => {
params.set(key, value)
})
}
// Add b=1 to the deeplink URL to indicate that the payment app should move
// back to the browser after the payment is complete.
params.set('b', '1')
// Return absolute URL for the deeplink
return `${apiBaseUrl}/app?${params.toString()}`
}
export const Widget: React.FunctionComponent<WidgetProps> = props => {
const {
to,
foot,
success = false,
pendingFinalization = false,
paymentId,
successText = 'Thank you!',
disablePaymentId,
goalAmount,
ButtonComponent = Button,
currency = getCurrencyTypeFromAddress(to),
animation,
randomSatoshis = false,
editable = false,
newTxs,
setNewTxs,
apiBaseUrl,
usdPrice,
wsBaseUrl,
hoverText = 'Send Payment',
setAltpaymentShift,
altpaymentShift,
shiftCompleted,
setShiftCompleted,
disableAltpayment,
contributionOffset,
useAltpayment,
setUseAltpayment,
setTxsSocket,
txsSocket,
setAltpaymentSocket,
altpaymentSocket,
addressType,
setAddressType,
coins,
setCoins,
coinPair,
setCoinPair,
loadingPair,
setLoadingPair,
loadingShift,
setLoadingShift,
altpaymentError,
setAltpaymentError,
isChild,
convertedCurrencyObj,
donationAddress = config.donationAddress,
donationRate = DEFAULT_DONATION_RATE,
setConvertedCurrencyObj = () => {},
setPaymentId,
hideSendButton,
} = props;
const [loading, setLoading] = useState(true);
const [draftAmount, setDraftAmount] = useState<string>("")
const inputRef = React.useRef<HTMLInputElement>(null)
const lastEffectiveAmountRef = React.useRef<number | undefined | null>(undefined)
const [standalonePaymentPending, setStandalonePaymentPending] = useState(false)
const isWaitingForPaymentId =
!disablePaymentId && (
(isChild === true && paymentId === undefined) ||
(isChild !== true && standalonePaymentPending)
)
const qrLoading = loading || isWaitingForPaymentId
const showPaymentPendingSpinner = pendingFinalization && !success
// websockets if standalone
const [internalTxsSocket, setInternalTxsSocket] = useState<Socket | WsEndpoint | undefined>(undefined)
const thisTxsSocket = txsSocket ?? internalTxsSocket
const setThisTxsSocket =
(setTxsSocket as ((s: Socket | WsEndpoint | undefined) => void) | undefined) ?? setInternalTxsSocket
// Type guard to check if socket is a Chronik WsEndpoint
const isChronikWsEndpoint = (socket: Socket | WsEndpoint | undefined): socket is WsEndpoint => {
return socket instanceof WsEndpoint;
};
const [internalNewTxs, setInternalNewTxs] = useState<Transaction[] | undefined>()
const thisNewTxs = newTxs ?? internalNewTxs
const setThisNewTxs = useCallback(
(txs: Transaction[]) => {
const setterFn =
(setNewTxs as ((t: Transaction[]) => void) | undefined) ?? setInternalNewTxs
setterFn(txs)
},
[setNewTxs]
)
const [internalAltpaymentShift, setInternalAltpaymentShift] = useState<AltpaymentShift | undefined>(undefined)
const thisAltpaymentShift = altpaymentShift ?? internalAltpaymentShift
const setThisAltpaymentShift =
(setAltpaymentShift as ((s: AltpaymentShift | undefined) => void) | undefined) ??
setInternalAltpaymentShift
const [internalUseAltpayment, setInternalUseAltpayment] = useState<boolean>(false)
const thisUseAltpayment = useAltpayment ?? internalUseAltpayment
const setThisUseAltpayment =
(setUseAltpayment as ((b: boolean) => void) | undefined) ?? setInternalUseAltpayment
const [internalAltpaymentSocket, setInternalAltpaymentSocket] = useState<Socket | undefined>(undefined)
const thisAltpaymentSocket = altpaymentSocket ?? internalAltpaymentSocket
const setThisAltpaymentSocket =
(setAltpaymentSocket as ((s: Socket | undefined) => void) | undefined) ??
setInternalAltpaymentSocket
const [internalShiftCompleted, setInternalShiftCompleted] = useState<boolean>(false)
const thisShiftCompleted = shiftCompleted ?? internalShiftCompleted
const setThisShiftCompleted =
(setShiftCompleted as ((b: boolean) => void) | undefined) ?? setInternalShiftCompleted
const [internalCoins, setInternalCoins] = useState<AltpaymentCoin[]>([])
const thisCoins = coins ?? internalCoins
const setThisCoins = (setCoins as ((c: AltpaymentCoin[]) => void) | undefined) ?? setInternalCoins
const [internalCoinPair, setInternalCoinPair] = useState<AltpaymentPair | undefined>()
const thisCoinPair = coinPair ?? internalCoinPair
const setThisCoinPair =
(setCoinPair as ((p: AltpaymentPair | undefined) => void) | undefined) ?? setInternalCoinPair
const [internalLoadingPair, setInternalLoadingPair] = useState<boolean>(false)
const thisLoadingPair = loadingPair ?? internalLoadingPair
const setThisLoadingPair =
(setLoadingPair as ((b: boolean) => void) | undefined) ?? setInternalLoadingPair
const [internalLoadingShift, setInternalLoadingShift] = useState<boolean>(false)
const thisLoadingShift = loadingShift ?? internalLoadingShift
const setThisLoadingShift =
(setLoadingShift as ((b: boolean) => void) | undefined) ?? setInternalLoadingShift
const [internalAltpaymentError, setInternalAltpaymentError] = useState<AltpaymentError | undefined>()
const thisAltpaymentError = altpaymentError ?? internalAltpaymentError
const setThisAltpaymentError =
(setAltpaymentError as ((e: AltpaymentError | undefined) => void) | undefined) ??
setInternalAltpaymentError
const [internalAddressType, setInternalAddressType] = useState<CryptoCurrency>(getCurrencyTypeFromAddress(to))
const thisAddressType = addressType ?? internalAddressType
const setThisAddressType =
(setAddressType as ((c: CryptoCurrency) => void) | undefined) ?? setInternalAddressType
const [copied, setCopied] = useState(false)
const [recentlyCopied, setRecentlyCopied] = useState(false)
const [totalReceived, setTotalReceived] = useState<number | undefined>(undefined)
const [disabled, setDisabled] = useState(false)
const [errorMsg, setErrorMsg] = useState('')
const [goalText, setGoalText] = useState('')
const [goalPercent, setGoalPercent] = useState(0)
const [altpaymentEditable, setAltpaymentEditable] = useState<boolean>(false)
const price = props.price ?? 0
const [hasPrice, setHasPrice] = useState(props.price !== undefined && props.price > 0)
// Helper to clamp donation rate to valid range (1-99 if > 0, or 0)
const clampDonationRate = useCallback((value: number): number => {
if (value <= 0) return 0
return Math.max(1, Math.min(99, value))
}, [])
// Load donation rate from localStorage on mount
const getInitialDonationRate = useCallback(() => {
if (typeof window !== 'undefined' && window.localStorage) {
try {
const stored = localStorage.getItem(DONATION_RATE_STORAGE_KEY)
if (stored !== null) {
const parsed = parseFloat(stored)
if (!isNaN(parsed) && parsed >= 0) {
// Clamp to 1-99 range if > 0, or return 0
return clampDonationRate(parsed)
}
}
} catch (e) {
console.warn('Failed to load donation rate from localStorage:', e)
}
}
return 0
}, [clampDonationRate])
// Clamp the donationRate prop to ensure it's in valid range
const clampedDonationRateProp = useMemo(() => clampDonationRate(donationRate), [donationRate, clampDonationRate])
const initialDonationRate = useMemo(() => getInitialDonationRate(), [getInitialDonationRate])
const [userDonationRate, setUserDonationRate] = useState<number>(initialDonationRate)
const [donationEnabled, setDonationEnabled] = useState<boolean>(initialDonationRate > 0)
// Initialize previousDonationRate with clamped prop value so it's available when user first enables donation
const [previousDonationRate, setPreviousDonationRate] = useState<number>(
initialDonationRate > 0 ? initialDonationRate : clampedDonationRateProp
)
const [url, setUrl] = useState('')
const [userEditedAmount, setUserEditedAmount] = useState<CurrencyObject>()
const [text, setText] = useState(`Send any amount of ${thisAddressType}`)
const [widgetButtonText, setWidgetButtonText] = useState('Send Payment')
const [opReturn, setOpReturn] = useState<string | undefined>()
const [isCashtabAvailable, setIsCashtabAvailable] = useState<boolean>(false)
const [convertedCryptoAmount, setConvertedCryptoAmount] = useState<number | undefined>(undefined)
const updateConvertedCurrencyObj = useCallback((convertedObj: CurrencyObject | null) => {
setConvertedCurrencyObj(convertedObj);
if (!isChild && !disablePaymentId && setPaymentId !== undefined) {
setPaymentId(undefined);
}
}, [setConvertedCurrencyObj, setPaymentId]);
const [isAboveMinimumAltpaymentAmount, setIsAboveMinimumAltpaymentAmount] = useState<boolean | null>(null)
const theme = useTheme(props.theme, isValidXecAddress(to))
const isDarkMode = useMemo(() => darkMode(theme.palette.tertiary), [theme.palette.tertiary])
const [thisAmount, setThisAmount] = useState(props.amount)
const [thisCurrencyObject, setThisCurrencyObject] = useState(props.currencyObject)
const blurCSS = isPropsTrue(disabled) ? { filter: 'blur(5px)' } : {}
// inject keyframes once (replacement for @global in makeStyles)
useEffect(() => {
const id = 'paybutton-widget-keyframes'
if (document.getElementById(id)) return
const style = document.createElement('style')
style.id = id
style.textContent = `
@keyframes reveal-qr { from { clip-path: circle(0% at 50% 50%); transform: rotate(-10deg); } to { clip-path: circle(100% at 50% 50%); transform: rotate(0deg); } }
@keyframes fade-scale { from { opacity: 0; transform: scale(0.3); } 80% { opacity: 1; transform: scale(1.3); } to { opacity: 1; transform: scale(1); } }
@keyframes button-slide { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0px); } }
@keyframes button-slide-out { from { opacity: 1; transform: translateY(0px); } to { opacity: 0; transform: translateY(20px); } }
@keyframes fade-slide-up { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0px); } }
@keyframes copy-qr { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
@keyframes copy-svg { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }
@keyframes copy-icon { 0% { transform: scale(1); } 50% { transform: scale(0.7); } 100% { transform: scale(1); } }
@keyframes success-qr { 0% { transform: scale(1); } 50% { transform: scale(0.7); } 100% { transform: scale(1); } }
@keyframes success-icon { 0% { transform: rotate(0deg); } 20% { transform: rotate(-10deg); } 60% { transform: rotate(370deg); } 100% { transform: rotate(360deg); } }
`
document.head.appendChild(style)
}, [])
const classes = useMemo(() => {
const base: StyleProps = { success, loading: qrLoading, theme, recentlyCopied, copied }
return {
root: {
minWidth: '240px',
background: isDarkMode ? '#2a2a2a' : '#f5f5f7',
position: 'relative',
overflow: 'hidden',
},
qrCode: {
background: isDarkMode ? '#1a1a1a' : '#fff',
border: isDarkMode ? '1px solid #333' : '1px solid #eee',
borderRadius: '4px',
outline: 'none',
lineHeight: 0,
maxWidth: '28vh',
maxHeight: '28vh',
position: 'relative' as const,
padding: '1rem',
cursor: 'pointer',
userSelect: 'none',
'& path': {
opacity: base.loading ? 0 : base.success ? 0.35 : 1,
color: base.theme.palette.secondary,
},
'& image': { opacity: base.loading ? 0 : 1 },
},
copyTextContainer: {
display: base.loading ? 'none' : 'block',
background: isDarkMode ? '#1a1a1acc' : '#ffffffcc',
padding: '0 0.15rem 0.15rem 0',
},
copyText: {
lineHeight: '1.2em',
fontSize: '0.7em',
color: base.theme.palette.tertiary,
textShadow: isDarkMode
? '#000 -2px 0 1px, #000 0 -2px 1px, #000 0 2px 1px, #000 2px 0 1px'
: '#fff -2px 0 1px, #fff 0 -2px 1px, #fff 0 2px 1px, #fff 2px 0 1px',
'&:disabled span': {
filter: 'blur(2px)',
color: isDarkMode ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.5)',
},
},
text: {
fontSize: '0.9rem',
color: base.theme.palette.tertiary,
},
spinner: {
color: base.theme.palette.primary,
},
footer: {
fontSize: '0.6rem',
color: isDarkMode ? '#888888' : '#a8a8a8',
fontWeight: 'normal',
userSelect: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
animation: 'fade-slide-up 0.6s ease-out forwards',
animationDelay: '0.7s',
opacity: 0,
lineHeight: 2.5,
paddingTop: '14px',
},
footerSeparator: {
marginLeft: '7px',
marginRight: '4px'
},
sideShiftLink: {
fontSize: '14px',
cursor: 'pointer',
padding: '6px 12px',
marginTop: '20px',
background: isDarkMode ? '#444444' : '#e9e9e9',
color: isDarkMode ? '#ffffff' : 'inherit',
borderRadius: '5px',
transition: 'all ease-in-out 200ms',
opacity: 0,
'&:hover': {
background: base.theme.palette.primary,
color: base.theme.palette.secondary,
},
},
animate_sideshift: {
animation: base.success
? 'button-slide-out 0.4s ease-in-out forwards'
: 'button-slide 0.6s ease-in-out forwards',
animationDelay: base.success ? '0s' : '0.5s',
},
hide_sideshift: { display: 'none' },
editAmount: {
width: '100%',
margin: '12px auto 10px',
display: 'flex',
alignItems: 'center',
'& > div': { width: '100%' },
'& span': { marginLeft: '4px', fontSize: '16px' },
},
error: { fontSize: '0.9rem', color: '#EB3B3B' },
qrAnimations: {
animation: base.success
? 'success-qr 0.4s ease-in-out forwards'
: base.recentlyCopied
? 'copy-qr 0.3s ease-in-out forwards'
: !base.loading && !base.copied
? 'reveal-qr 0.8s ease-in-out forwards'
: 'none',
'& svg': {
animation: base.recentlyCopied ? 'copy-svg 0.3s ease-in-out forwards' : 'none',
},
'& image': {
animation: base.success
? 'success-icon 1s ease-in-out forwards'
: base.recentlyCopied
? 'copy-icon 0.3s ease-in-out forwards'
: !base.loading && !base.copied
? 'fade-scale 0.6s ease-in-out forwards'
: 'none',
transformOrigin: 'center center',
},
},
button_container: {
opacity: 0,
animation: 'button-slide 0.6s ease-in-out forwards',
animationDelay: '0.4s',
},
}
}, [success, qrLoading, theme, recentlyCopied, copied, isDarkMode])
const bchSvg = useMemo((): string => {
const color = theme.palette.logo ?? theme.palette.primary
return `data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg version='1.1' viewBox='0 0 34 34' xmlns='http://www.w3.org/2000/svg'%3E%3Cg transform='translate(1,1)'%3E%3Ccircle cx='16' cy='16' r='17' fill='%23fff' stroke-width='1.0625'/%3E%3C/g%3E%3Cg transform='translate(1,1)' fill-rule='evenodd'%3E%3Ccircle cx='16' cy='16' r='16' fill='${window.encodeURIComponent(
color,
)}'/%3E%3Cpath d='m21.207 10.534c-0.776-1.972-2.722-2.15-4.988-1.71l-0.807-2.813-1.712 0.491 0.786 2.74c-0.45 0.128-0.908 0.27-1.363 0.41l-0.79-2.758-1.711 0.49 0.805 2.813c-0.368 0.114-0.73 0.226-1.085 0.328l-3e-3 -0.01-2.362 0.677 0.525 1.83s1.258-0.388 1.243-0.358c0.694-0.199 1.035 0.139 1.2 0.468l0.92 3.204c0.047-0.013 0.11-0.029 0.184-0.04l-0.181 0.052 1.287 4.49c0.032 0.227 4e-3 0.612-0.48 0.752 0.027 0.013-1.246 0.356-1.246 0.356l0.247 2.143 2.228-0.64c0.415-0.117 0.825-0.227 1.226-0.34l0.817 2.845 1.71-0.49-0.807-2.815a65.74 65.74 0 0 0 1.372-0.38l0.802 2.803 1.713-0.491-0.814-2.84c2.831-0.991 4.638-2.294 4.113-5.07-0.422-2.234-1.724-2.912-3.471-2.836 0.848-0.79 1.213-1.858 0.642-3.3zm-0.65 6.77c0.61 2.127-3.1 2.929-4.26 3.263l-1.081-3.77c1.16-0.333 4.704-1.71 5.34 0.508zm-2.322-5.09c0.554 1.935-2.547 2.58-3.514 2.857l-0.98-3.419c0.966-0.277 3.915-1.455 4.494 0.563z' fill='%23fff' fill-rule='nonzero'/%3E%3C/g%3E%3C/svg%3E%0A`
}, [theme])
const xecSvg =
"data:image/svg+xml;charset=UTF-8,%3csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='576px' height='576px' viewBox='0 0 576 576' enable-background='new 0 0 576 576' xml:space='preserve'%3e%3cg transform='translate(1,1)'%3e%3ccircle fill='%23FFFFFF' cx='287' cy='287' r='288'/%3e%3c/g%3e%3cpath fill='%23FFFFFF' d='M325.089,228.325l-67.15,38.668c-1.734,0.995-2.794,2.85-2.773,4.849v32.443 c-0.019,1.954,1.05,3.757,2.773,4.681l28.122,16.22c1.635,1.039,3.723,1.039,5.359,0l116.046-66.833 c19.694-11.393,19.694-44.216,0-55.609l-104.294-60.057c-8.867-5.357-19.975-5.357-28.842,0l-104.294,60.078 c-9.056,5.074-14.637,14.671-14.569,25.052c0,40.235,0.17,80.28,0,120.325c-0.085,10.362,5.461,19.954,14.485,25.052l104.294,60.247 c8.914,5.188,19.928,5.188,28.843,0l104.378-60.247c9.017-5.085,14.521-14.702,14.337-25.052v-52.306l-124.136,71.83 c-5.537,3.283-12.423,3.283-17.959,0l-55.439-32.124c-5.612-3.147-9.056-9.11-8.979-15.545V255.96 c-0.028-6.327,3.322-12.188,8.788-15.374c18.487-10.716,37.122-21.409,55.609-32.125c5.542-3.262,12.416-3.262,17.958,0 l27.53,15.713c1.13,0.727,1.459,2.233,0.732,3.365C325.7,227.862,325.42,228.131,325.089,228.325z'/%3e%3cpath fill='%230074C2' d='M288.878,16.941C139.176,16.941,17.819,138.298,17.819,288c0,149.701,121.357,271.059,271.059,271.059 c149.701,0,271.059-121.357,271.059-271.059C559.937,138.298,438.579,16.941,288.878,16.941z M325.089,224.174l-27.529-15.713 c-5.541-3.262-12.415-3.262-17.957,0c-18.487,10.715-37.122,21.409-55.609,32.125c-5.466,3.186-8.816,9.047-8.788,15.374v64.037 c-0.078,6.435,3.366,12.397,8.979,15.545l55.418,32.124c5.536,3.283,12.422,3.283,17.957,0l124.138-71.83v52.306 c0.204,10.327-5.257,19.938-14.231,25.052L303.193,433.44c-8.915,5.188-19.928,5.188-28.843,0l-104.315-60.247 c-9.056-5.075-14.637-14.671-14.569-25.052c0.17-40.045,0-80.111,0-120.325c-0.085-10.363,5.461-19.956,14.485-25.052 l104.294-60.078c8.868-5.357,19.975-5.357,28.843,0l104.378,60.078c19.694,11.393,19.694,44.217,0,55.609L291.42,325.186 c-1.636,1.039-3.724,1.039-5.359,0l-28.122-16.22c-1.724-0.924-2.792-2.727-2.773-4.681v-32.443 c-0.021-1.999,1.04-3.854,2.773-4.849l67.15-38.668c1.146-0.705,1.506-2.204,0.802-3.35 C325.689,224.649,325.416,224.375,325.089,224.174z'/%3e%3c/svg%3e"
const checkSvg = useMemo((): string => {
const color = theme.palette.logo ?? theme.palette.primary
return `data:image/svg+xml,%3Csvg version='1.1' viewBox='1.65 1.65 20.65 20.65' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' fill='${window.encodeURIComponent(
color,
)}' stroke='%23fff' stroke-width='.6'/%3E%3Cpath d='m7.2979 14.697-2.6964-2.6966 0.89292-0.8934c0.49111-0.49137 0.90364-0.88958 0.91675-0.88491 0.013104 0.0047 0.71923 0.69866 1.5692 1.5422 0.84994 0.84354 1.6548 1.6397 1.7886 1.7692l0.24322 0.23547 7.5834-7.5832 1.8033 1.8033-9.4045 9.4045z' fill='%23fff' stroke-width='.033708'/%3E%3C/svg%3E%0A`
}, [theme])
useEffect(() => {
if (thisCurrencyObject?.string !== undefined) {
const raw = stripFormatting(thisCurrencyObject.string);
setDraftAmount(raw);
}
}, [thisCurrencyObject?.string]);
useEffect(() => {
if (!recentlyCopied) return
const timer = setTimeout(() => {
setRecentlyCopied(false)
}, 1000)
return () => clearTimeout(timer)
}, [recentlyCopied])
useEffect(() => {
setHasPrice(price !== undefined && price > 0)
}, [price])
useEffect(() => {
const initCashtab = async () => {
try {
const isAvailable = await initializeCashtabStatus()
setIsCashtabAvailable(isAvailable)
} catch {
setIsCashtabAvailable(false)
}
}
initCashtab()
}, [])
useEffect(() => {
(async () => {
if (isChild !== true) {
await setupChronikWebSocket({
address: to,
txsSocket: thisTxsSocket,
apiBaseUrl,
wsBaseUrl,
setTxsSocket: setThisTxsSocket,
setNewTxs: setThisNewTxs,
})
if (thisUseAltpayment) {
await setupAltpaymentSocket({
addressType: thisAddressType,
wsBaseUrl,
altpaymentSocket: thisAltpaymentSocket,
setAltpaymentSocket: setThisAltpaymentSocket,
setCoins: setThisCoins,
setCoinPair: setThisCoinPair,
setLoadingPair: setThisLoadingPair,
setAltpaymentShift: setThisAltpaymentShift,
setLoadingShift: setThisLoadingShift,
setAltpaymentError: setThisAltpaymentError,
})
}
}
})()
return () => {
if (thisAltpaymentSocket !== undefined) {
thisAltpaymentSocket.disconnect()
setThisAltpaymentSocket(undefined)
}
}
}, [to, thisUseAltpayment])
// Suspend/resume Chronik WebSocket based on page visibility
useEffect(() => {
if (typeof document === 'undefined' || isChild === true) {
return;
}
const handleVisibilityChange = async () => {
if (!thisTxsSocket) {
// Not initialized yet
return;
}
// Check if this is a Chronik WsEndpoint (has pause/resume methods)
// vs a socket.io Socket (doesn't have these methods)
if (!isChronikWsEndpoint(thisTxsSocket)) {
return;
}
if (document.hidden) {
// Page went to background - suspend WebSocket
try {
thisTxsSocket.pause();
} catch (error) {
console.error('Error pausing WebSocket:', error);
}
} else {
// Page came to foreground - resume WebSocket
try {
await thisTxsSocket.resume();
} catch (error) {
console.error('Error resuming WebSocket:', error);
}
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [isChild, thisTxsSocket])
const tradeWithAltpayment = () => {
setThisUseAltpayment(true)
}
useEffect(() => {
if (thisAmount === undefined || thisAmount === null || thisAmount === 0) {
setAltpaymentEditable(true)
}
if (isPropsTrue(editable)) {
setAltpaymentEditable(true)
}
}, [])
useEffect(() => {
;(async (): Promise<void> => {
if (thisNewTxs === undefined || thisNewTxs.length === 0) {
const balance = await getAddressBalance(to, apiBaseUrl)
setTotalReceived(balance)
}
setLoading(false)
})()
}, [thisNewTxs, to, apiBaseUrl])
useEffect(() => {
if (
isChild ||
disablePaymentId ||
setPaymentId === undefined ||
to === ''
) {
return;
}
// For fiat with defined amount, wait until we have a converted crypto amount
if (isFiat(currency) && convertedCryptoAmount === undefined && thisAmount !== undefined ) {
return;
}
const initializePaymentId = async () => {
try {
let effectiveAmount: number | null;
if (typeof convertedCryptoAmount === 'number') {
effectiveAmount = convertedCryptoAmount;
} else if (convertedCurrencyObj && typeof convertedCurrencyObj.float === 'number') {
effectiveAmount = convertedCurrencyObj.float;
} else if (
thisAmount !== undefined &&
thisAmount !== null &&
thisAmount !== ''
) {
const n = Number(thisAmount);
if (Number.isNaN(n)) {
return
}
effectiveAmount = n;
} else {
effectiveAmount = null
}
if (lastEffectiveAmountRef.current === effectiveAmount) {
return;
}
lastEffectiveAmountRef.current = effectiveAmount;
setStandalonePaymentPending(true)
const responsePaymentId = await createPayment(
effectiveAmount ?? undefined,
to,
apiBaseUrl,
);
setPaymentId(responsePaymentId);
} catch (error) {
console.error('Error creating payment ID:', error);
} finally {
setStandalonePaymentPending(false)
}
};
void initializePaymentId();
}, [
isChild,
disablePaymentId,
to,
currency,
convertedCryptoAmount,
convertedCurrencyObj,
thisAmount,
apiBaseUrl,
setPaymentId,
lastEffectiveAmountRef,
]);
useEffect(() => {
const invalidAmount = thisAmount !== undefined && thisAmount && isNaN(+thisAmount)
if (isValidCashAddress(to) || isValidXecAddress(to)) {
setDisabled(isPropsTrue(props.disabled))
setErrorMsg('')
} else if (invalidAmount) {
setDisabled(true)
setErrorMsg('Amount should be a number')
} else {
setDisabled(true)
setErrorMsg('Invalid Recipient')
}
if (usdPrice && thisAmount) {
const usdAmount = usdPrice * +thisAmount
setIsAboveMinimumAltpaymentAmount(usdAmount >= MINIMUM_ALTPAYMENT_DOLLAR_AMOUNT)
} else if (currency === 'USD') {
if (thisAmount && +thisAmount >= MINIMUM_ALTPAYMENT_DOLLAR_AMOUNT) {
setIsAboveMinimumAltpaymentAmount(true)
}
} else if (currency === 'CAD') {
if (thisAmount && +thisAmount >= MINIMUM_ALTPAYMENT_CAD_AMOUNT) {
setIsAboveMinimumAltpaymentAmount(true)
}
}
}, [to, thisAmount, usdPrice])
useEffect(() => {
const invalidAmount = thisAmount !== undefined && thisAmount && isNaN(+thisAmount)
const isNegativeNumber =
(typeof thisAmount === 'number' && thisAmount < 0) ||
(typeof thisAmount === 'string' && thisAmount.trim().startsWith('-'))
let cleanAmount: any
if (invalidAmount) {
setDisabled(true)
setErrorMsg('Amount should be a number')
} else if (isNegativeNumber) {
setDisabled(true)
setErrorMsg('Amount should be positive')
} else {
if (isValidCashAddress(to) || isValidXecAddress(to)) {
setErrorMsg('')
} else {
setErrorMsg('Invalid Recipient')
}
}
if (userEditedAmount !== undefined && thisAmount && thisAddressType) {
const obj = getCurrencyObject(+thisAmount, currency, false);
setThisCurrencyObject(obj);
if (props.setCurrencyObject) {
props.setCurrencyObject(obj);
}
const convertedAmount = obj.float / price
const convertedObj = price
? getCurrencyObject(
convertedAmount,
thisAddressType,
randomSatoshis,
)
: null;
updateConvertedCurrencyObj(convertedObj)
} else if (thisAmount && thisAddressType) {
cleanAmount = +thisAmount;
const obj = getCurrencyObject(cleanAmount, currency, randomSatoshis);
setThisCurrencyObject(obj);
if(!isFiat(currency)) {
updateConvertedCurrencyObj(obj);
}
if (props.setCurrencyObject) {
props.setCurrencyObject(obj);
}
}
}, [thisAmount, currency, userEditedAmount])
// Helper function to check if amount meets minimum for donation UI visibility
const shouldShowDonationUI = useCallback((amount: number, currencyType: string): boolean => {
// Normalize currency type to uppercase for comparison
const normalizedCurrency = currencyType.toUpperCase()
if (normalizedCurrency !== 'XEC' && normalizedCurrency !== 'BCH') {
return false
}
// Check if 1% of the amount is >= minimum donation amount
const onePercentOfAmount = amount * 0.01
const minimumDonationAmount = DEFAULT_MINIMUM_DONATION_AMOUNT[normalizedCurrency] || 0
return onePercentOfAmount >= minimumDonationAmount
}, [])
// Helper function to check if donation should be applied
const shouldApplyDonation = useCallback((amount: number, currencyType: string): boolean => {
if (!donationEnabled || !userDonationRate || userDonationRate <= 0) {
return false
}
return shouldShowDonationUI(amount, currencyType)
}, [donationEnabled, userDonationRate, shouldShowDonationUI])
useEffect(() => {
if (to === undefined) return
let nextUrl: string | undefined
setThisAddressType(thisAddressType)
if (thisAddressType === 'XEC' && isCashtabAvailable) {
setWidgetButtonText('Send with Cashtab')
} else {
setWidgetButtonText(`Send with ${thisAddressType} wallet`)
}
if (thisCurrencyObject && hasPrice) {
// Use convertedAmount prop if available, otherwise calculate locally
const convertedAmount = convertedCurrencyObj ? convertedCurrencyObj.float : thisCurrencyObject.float / price
const convertedObj = convertedCurrencyObj ? convertedCurrencyObj : price
? getCurrencyObject(
convertedAmount,
thisAddressType,
randomSatoshis,
)
: null;
if (convertedObj) {
// Store converted crypto amount for donation UI visibility check
setConvertedCryptoAmount(convertedObj.float)
let amountToDisplay = thisCurrencyObject.string;
let convertedAmountToDisplay = convertedObj.string
// Only apply donation if 1% of converted crypto amount is >= minimum donation amount
if (shouldApplyDonation(convertedObj.float, thisAddressType)) {
const thisDonationAmount = thisCurrencyObject.float * (userDonationRate / 100)
const amountWithDonation = thisCurrencyObject.float + thisDonationAmount
const amountWithDonationObj = getCurrencyObject(
amountWithDonation,
currency,
false,
)
amountToDisplay = amountWithDonationObj.string
const convertedDonationAmount = convertedObj.float * (userDonationRate / 100)
const convertedAmountWithDonation = convertedObj.float + convertedDonationAmount
const convertedAmountWithDonationObj = getCurrencyObject(
convertedAmountWithDonation,
thisAddressType,
randomSatoshis,
)
convertedAmountToDisplay = convertedAmountWithDonationObj.string
}
setText(
`Send ${amountToDisplay} ${thisCurrencyObject.currency} = ${convertedAmountToDisplay} ${thisAddressType}`,
)
const url = resolveUrl(thisAddressType, convertedObj.float)
setUrl(url ?? "")
}
} else {
// Clear converted amount when not in fiat conversion mode
setConvertedCryptoAmount(undefined)
const notZeroValue =
thisCurrencyObject?.float !== undefined && thisCurrencyObject.float > 0
if (!isFiat(currency) && thisCurrencyObject && notZeroValue) {
const cur: string = thisCurrencyObject.currency
const baseAmount = thisCurrencyObject.float // Base amount without donation
// Only apply donation if 1% of amount is >= minimum donation amount
let amountToDisplay = thisCurrencyObject.string
if (shouldApplyDonation(baseAmount, cur)) {
const donationAmountValue = baseAmount * (userDonationRate / 100)
const amountWithDonation = baseAmount + donationAmountValue
const amountWithDonationObj = getCurrencyObject(
amountWithDonation,
cur,
false,
)
amountToDisplay = amountWithDonationObj.string
}
setText(`Send ${amountToDisplay} ${cur}`)
// Pass base amount (without donation) to resolveUrl
nextUrl = resolveUrl(cur, baseAmount)
} else {
setText(`Send any amount of ${thisAddressType}`)
nextUrl = resolveUrl(thisAddressType)
}
setUrl(nextUrl ?? '')
}
}, [to, thisCurrencyObject, price, thisAmount, opReturn, hasPrice, isCashtabAvailable, userDonationRate, donationEnabled, disabled, donationAddress, currency, randomSatoshis, thisAddressType, shouldApplyDonation])
useEffect(() => {
try {
setOpReturn(
encodeOpReturnProps({
opReturn: props.opReturn,
paymentId,
disablePaymentId: disablePaymentId ?? false,
}),
)
} catch (err) {
console.error(err)
setErrorMsg((err as Error).message)
setDisabled(true)
}
}, [props.opReturn, paymentId, disablePaymentId])
useEffect(() => {
setThisAmount(props.amount)
}, [props.amount])
// Save donation rate to localStorage whenever it changes
useEffect(() => {
if (typeof window !== 'undefined' && window.localStorage) {
try {
localStorage.setItem(DONATION_RATE_STORAGE_KEY, userDonationRate.toString())
} catch (e) {
console.warn('Failed to save donation rate to localStorage:', e)
}
}
}, [userDonationRate])
// Don't sync with prop - we default to off (0) if no localStorage value
// This ensures user preference (stored in localStorage) always takes precedence
const handleDonationToggle = () => {
if (donationEnabled) {
// Turning off - save current rate (already clamped) and set to 0
setPreviousDonationRate(userDonationRate)
setUserDonationRate(0)
setDonationEnabled(false)
} else {
// Turning on - restore previous rate or use clamped prop/default
// Use same clamping logic as handleDonationRateChange to ensure 1-99 range
const rateToRestore = previousDonationRate > 0 ? previousDonationRate : clampedDonationRateProp
const clampedRate = clampDonationRate(rateToRestore)
setUserDonationRate(clampedRate)
setDonationEnabled(true)
// Update previousDonationRate to the clamped value
if (clampedRate > 0) {
setPreviousDonationRate(clampedRate)
}
}
}
const handleDonationRateChange = (value: number) => {
const clampedValue = clampDonationRate(value)
setUserDonationRate(clampedValue)
if (clampedValue >= 1) {
// Auto-enable donation if user enters a value >= 1
if (!donationEnabled) {
setDonationEnabled(true)
}
setPreviousDonationRate(clampedValue)
}
}
let cleanGoalAmount: any
if (goalAmount) {
cleanGoalAmount = +goalAmount
}
const shouldDisplayGoal: boolean = goalAmount !== undefined
useEffect(() => {
if (totalReceived !== undefined) {
const progress = getCurrencyObject(totalReceived, currency, false)
const goal = getCurrencyObject(cleanGoalAmount, currency, false)
if (!isFiat(currency)) {