-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSwapWidgetRenderer.tsx
More file actions
1259 lines (1184 loc) · 40.5 KB
/
SwapWidgetRenderer.tsx
File metadata and controls
1259 lines (1184 loc) · 40.5 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 type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
import { useCallback, useContext, useEffect, useMemo, useState } from 'react'
import {
useCurrencyBalance,
useENSResolver,
useRelayClient,
useDebounceState,
useWalletAddress,
useDisconnected,
usePreviousValueChange,
useIsWalletCompatible,
useFallbackState,
useGasTopUpRequired,
useEOADetection
} from '../../hooks/index.js'
import type { Address, WalletClient } from 'viem'
import { formatUnits, parseUnits } from 'viem'
import { useAccount, useWalletClient } from 'wagmi'
import { useCapabilities } from 'wagmi/experimental'
import type { Token } from '../../types/index.js'
import { useQueryClient } from '@tanstack/react-query'
import type { ChainVM, Execute } from '@relayprotocol/relay-sdk'
import {
calculatePriceTimeEstimate,
calculateRelayerFeeProportionUsd,
extractQuoteId,
getCurrentStep,
getSwapEventData,
isHighRelayerServiceFeeUsd,
parseFees
} from '../../utils/quote.js'
import { useQuote, useTokenPrice } from '@relayprotocol/relay-kit-hooks'
import { EventNames } from '../../constants/events.js'
import { ProviderOptionsContext } from '../../providers/RelayKitProvider.js'
import type { DebouncedState } from 'usehooks-ts'
import type { AdaptedWallet } from '@relayprotocol/relay-sdk'
import type { LinkedWallet } from '../../types/index.js'
import {
addressWithFallback,
isValidAddress,
findSupportedWallet
} from '../../utils/address.js'
import { adaptViemWallet, getDeadAddress } from '@relayprotocol/relay-sdk'
import { errorToJSON } from '../../utils/errors.js'
import { useSwapButtonCta } from '../../hooks/widget/useSwapButtonCta.js'
import { sha256 } from '../../utils/hashing.js'
import { get15MinuteInterval } from '../../utils/time.js'
import type { FeeBreakdown } from '../../types/FeeBreakdown.js'
export type TradeType = 'EXACT_INPUT' | 'EXPECTED_OUTPUT'
type SwapWidgetRendererProps = {
transactionModalOpen: boolean
setTransactionModalOpen: React.Dispatch<React.SetStateAction<boolean>>
depositAddressModalOpen: boolean
children: (props: ChildrenProps) => ReactNode
fromToken?: Token
setFromToken?: (token?: Token) => void
toToken?: Token
setToToken?: (token?: Token) => void
defaultToAddress?: Address
defaultAmount?: string
defaultTradeType?: TradeType
slippageTolerance?: string
context: 'Swap' | 'Deposit' | 'Withdraw'
wallet?: AdaptedWallet
linkedWallets?: LinkedWallet[]
multiWalletSupportEnabled?: boolean
supportedWalletVMs: Omit<ChainVM, 'hypevm'>[]
onConnectWallet?: () => void
onAnalyticEvent?: (eventName: string, data?: any) => void
onSwapError?: (error: string, data?: Execute) => void
sponsoredTokens?: string[]
}
export type ChildrenProps = {
quote?: ReturnType<typeof useQuote>['data']
steps: Execute['steps'] | null
setSteps: Dispatch<React.SetStateAction<Execute['steps'] | null>>
swap: () => void
transactionModalOpen: boolean
details: null | Execute['details']
feeBreakdown: FeeBreakdown | null
fromToken?: Token
setFromToken: Dispatch<React.SetStateAction<Token | undefined>>
toToken?: Token
setToToken: Dispatch<React.SetStateAction<Token | undefined>>
swapError: Error | null
error: Error | null
toDisplayName?: string
address?: Address | string
recipient?: Address | string
customToAddress?: Address | string
setCustomToAddress: Dispatch<
React.SetStateAction<Address | string | undefined>
>
tradeType: TradeType
setTradeType: Dispatch<React.SetStateAction<TradeType>>
isSameCurrencySameRecipientSwap: boolean
amountInputValue: string
debouncedInputAmountValue: string
setAmountInputValue: (value: string) => void
debouncedAmountInputControls: DebouncedState<(value: string) => void>
amountOutputValue: string
debouncedOutputAmountValue: string
setAmountOutputValue: (value: string) => void
debouncedAmountOutputControls: DebouncedState<(value: string) => void>
toBalance?: bigint
toBalancePending?: boolean
fromBalance?: bigint
fromBalancePending?: boolean
isFetchingQuote: boolean
isLoadingToBalance: boolean
isLoadingFromBalance: boolean
highRelayerServiceFee: boolean
relayerFeeProportion: bigint
hasInsufficientBalance: boolean
isInsufficientLiquidityError?: boolean
isCapacityExceededError?: boolean
isCouldNotExecuteError?: boolean
ctaCopy: string
isFromNative: boolean
useExternalLiquidity: boolean
slippageTolerance?: string
supportsExternalLiquidity: boolean
timeEstimate?: { time: number; formattedTime: string }
canonicalTimeEstimate?: { time: number; formattedTime: string }
fetchingExternalLiquiditySupport: boolean
isSvmSwap: boolean
isBvmSwap: boolean
isValidFromAddress: boolean
isValidToAddress: boolean
supportedWalletVMs: Omit<ChainVM, 'hypevm'>[]
fromChainWalletVMSupported: boolean
toChainWalletVMSupported: boolean
isRecipientLinked?: boolean
recipientWalletSupportsChain?: boolean
gasTopUpEnabled: boolean
setGasTopUpEnabled: Dispatch<React.SetStateAction<boolean>>
gasTopUpBalance?: bigint
gasTopUpRequired: boolean
gasTopUpAmount?: bigint
gasTopUpAmountUsd?: string
quoteInProgress: null | Execute
setQuoteInProgress: Dispatch<React.SetStateAction<null | Execute>>
linkedWallet?: LinkedWallet
quoteParameters?: Parameters<typeof useQuote>['2']
invalidateBalanceQueries: () => void
invalidateQuoteQuery: () => void
setUseExternalLiquidity: Dispatch<React.SetStateAction<boolean>>
setDetails: Dispatch<React.SetStateAction<Execute['details'] | null>>
setSwapError: Dispatch<React.SetStateAction<Error | null>>
abortController: AbortController | null
fromTokenPriceData: ReturnType<typeof useTokenPrice>['data']
isLoadingFromTokenPrice: boolean
toTokenPriceData: ReturnType<typeof useTokenPrice>['data']
isLoadingToTokenPrice: boolean
sponsoredTokens?: string[]
}
// shared query options for useTokenPrice
const tokenPriceQueryOptions = {
staleTime: 60 * 1000, // 1 minute
refetchInterval: 30 * 1000, // 30 seconds
refetchOnWindowFocus: false
}
const SwapWidgetRenderer: FC<SwapWidgetRendererProps> = ({
transactionModalOpen,
setTransactionModalOpen,
depositAddressModalOpen,
fromToken: _fromToken,
setFromToken: _setFromToken,
toToken: _toToken,
setToToken: _setToToken,
defaultToAddress,
defaultAmount,
defaultTradeType,
slippageTolerance,
context,
wallet,
multiWalletSupportEnabled = false,
linkedWallets,
supportedWalletVMs,
sponsoredTokens,
children,
onAnalyticEvent,
onSwapError
}) => {
const [fromToken, setFromToken] = useFallbackState(
_setFromToken ? _fromToken : undefined,
_setFromToken
? [
_fromToken,
_setFromToken as Dispatch<SetStateAction<Token | undefined>>
]
: undefined
)
const [toToken, setToToken] = useFallbackState(
_setToToken ? _toToken : undefined,
_setToToken
? [_toToken, _setToToken as Dispatch<SetStateAction<Token | undefined>>]
: undefined
)
const providerOptionsContext = useContext(ProviderOptionsContext)
const connectorKeyOverrides = providerOptionsContext.vmConnectorKeyOverrides
const relayClient = useRelayClient()
const { connector } = useAccount()
const walletClient = useWalletClient()
const [customToAddress, setCustomToAddress] = useState<
Address | string | undefined
>(defaultToAddress)
const [useExternalLiquidity, setUseExternalLiquidity] =
useState<boolean>(false)
const address = useWalletAddress(wallet, linkedWallets)
const [tradeType, setTradeType] = useState<'EXACT_INPUT' | 'EXPECTED_OUTPUT'>(
defaultTradeType ?? 'EXACT_INPUT'
)
const queryClient = useQueryClient()
const [steps, setSteps] = useState<null | Execute['steps']>(null)
const [quoteInProgress, setQuoteInProgress] = useState<null | Execute>(null)
const [waitingForSteps, setWaitingForSteps] = useState(false)
const [details, setDetails] = useState<null | Execute['details']>(null)
const [gasTopUpEnabled, setGasTopUpEnabled] = useState(false)
const [abortController, setAbortController] =
useState<AbortController | null>(null)
const {
value: amountInputValue,
debouncedValue: debouncedInputAmountValue,
setValue: setAmountInputValue,
debouncedControls: debouncedAmountInputControls
} = useDebounceState<string>(
!defaultTradeType || defaultTradeType === 'EXACT_INPUT'
? (defaultAmount ?? '')
: '',
500
)
const {
value: amountOutputValue,
debouncedValue: debouncedOutputAmountValue,
setValue: setAmountOutputValue,
debouncedControls: debouncedAmountOutputControls
} = useDebounceState<string>(
defaultTradeType === 'EXPECTED_OUTPUT' ? (defaultAmount ?? '') : '',
500
)
const [swapError, setSwapError] = useState<Error | null>(null)
const tokenPairIsCanonical =
fromToken?.chainId !== undefined &&
toToken?.chainId !== undefined &&
fromToken.symbol === toToken.symbol
const toChain = relayClient?.chains.find(
(chain) => chain.id === toToken?.chainId
)
const fromChain = relayClient?.chains?.find(
(chain) => chain.id === fromToken?.chainId
)
const fromChainWalletVMSupported =
!fromChain?.vmType ||
supportedWalletVMs.includes(fromChain?.vmType) ||
fromChain?.id === 1337
const toChainWalletVMSupported =
!toChain?.vmType || supportedWalletVMs.includes(toChain?.vmType)
const defaultRecipient = useMemo(() => {
const _linkedWallet = linkedWallets?.find(
(linkedWallet) =>
address ===
(linkedWallet.vmType === 'evm'
? linkedWallet.address.toLowerCase()
: linkedWallet.address)
)
const _isValidToAddress = isValidAddress(
toChain?.vmType,
customToAddress ?? '',
toChain?.id,
!customToAddress && _linkedWallet?.address === address
? _linkedWallet?.connector
: undefined,
connectorKeyOverrides
)
if (
multiWalletSupportEnabled &&
toChain &&
linkedWallets &&
!_isValidToAddress
) {
const supportedAddress = findSupportedWallet(
toChain,
customToAddress,
linkedWallets,
connectorKeyOverrides
)
return supportedAddress
}
}, [
multiWalletSupportEnabled,
toChain,
customToAddress,
address,
linkedWallets,
setCustomToAddress
])
const recipient = customToAddress ?? defaultRecipient ?? address
const {
value: fromBalance,
queryKey: fromBalanceQueryKey,
isLoading: isLoadingFromBalance,
isError: fromBalanceErrorFetching,
isDuneBalance: fromBalanceIsDune,
hasPendingBalance: fromBalancePending
} = useCurrencyBalance({
chain: fromChain,
address: address,
currency: fromToken?.address ? (fromToken.address as Address) : undefined,
enabled: fromToken !== undefined,
refreshInterval: undefined,
wallet
})
const {
value: toBalance,
queryKey: toBalanceQueryKey,
isLoading: isLoadingToBalance,
isDuneBalance: toBalanceIsDune,
hasPendingBalance: toBalancePending
} = useCurrencyBalance({
chain: toChain,
address: recipient,
currency: toToken?.address ? (toToken.address as Address) : undefined,
enabled: toToken !== undefined,
refreshInterval: undefined,
wallet
})
const invalidateBalanceQueries = useCallback(() => {
const invalidatePeriodically = (invalidateFn: () => void) => {
let maxRefreshes = 4
let refreshCount = 0
const timer = setInterval(() => {
if (maxRefreshes === refreshCount) {
clearInterval(timer)
return
}
refreshCount++
invalidateFn()
}, 3000)
}
queryClient.invalidateQueries({ queryKey: ['useDuneBalances'] })
// Dune balances are sometimes stale, because of this we need to aggressively fetch them
// for a predetermined period to make sure we get back a fresh response
if (fromBalanceIsDune) {
invalidatePeriodically(() => {
queryClient.invalidateQueries({ queryKey: fromBalanceQueryKey })
})
} else {
queryClient.invalidateQueries({ queryKey: fromBalanceQueryKey })
}
if (toBalanceIsDune) {
invalidatePeriodically(() => {
queryClient.invalidateQueries({ queryKey: toBalanceQueryKey })
})
} else {
queryClient.invalidateQueries({ queryKey: toBalanceQueryKey })
}
}, [
queryClient,
fromBalanceQueryKey,
toBalanceQueryKey,
toBalanceIsDune,
fromBalanceIsDune,
address
])
const { data: capabilities } = useCapabilities({
query: {
enabled:
connector &&
(connector.id === 'coinbaseWalletSDK' || connector.id === 'coinbase')
}
})
const hasAuxiliaryFundsSupport = Boolean(
fromToken?.chainId
? capabilities?.[fromToken?.chainId]?.auxiliaryFunds?.supported
: false
)
const isSvmSwap = fromChain?.vmType === 'svm' || toChain?.vmType === 'svm'
const isBvmSwap = fromChain?.vmType === 'bvm' || toChain?.vmType === 'bvm'
const linkedWallet = linkedWallets?.find(
(linkedWallet) =>
address ===
(linkedWallet.vmType === 'evm'
? linkedWallet.address.toLowerCase()
: linkedWallet.address) || linkedWallet.address === address
)
const isRecipientLinked =
(recipient
? linkedWallets?.find((wallet) => wallet.address === recipient)
: undefined) !== undefined
const isValidFromAddress = isValidAddress(
fromChain?.vmType,
address ?? '',
fromChain?.id,
linkedWallet?.connector,
connectorKeyOverrides
)
const fromAddressWithFallback = addressWithFallback(
fromChain?.vmType,
address,
fromChain?.id,
linkedWallet?.connector,
connectorKeyOverrides
)
const isValidToAddress = isValidAddress(
toChain?.vmType,
recipient ?? '',
toChain?.id
)
const toAddressWithFallback = addressWithFallback(
toChain?.vmType,
recipient,
toChain?.id
)
const externalLiquiditySupport = useQuote(
relayClient ? relayClient : undefined,
wallet,
fromToken && toToken
? {
user: getDeadAddress(fromChain?.vmType, fromChain?.id),
originChainId: fromToken.chainId,
destinationChainId: toToken.chainId,
originCurrency: fromToken.address,
destinationCurrency: toToken.address,
recipient: getDeadAddress(toChain?.vmType, toChain?.id),
tradeType,
appFees: providerOptionsContext.appFees,
amount: '10000000000000000000000', //Hardcode an extremely high number
referrer: relayClient?.source ?? undefined,
useExternalLiquidity: true
}
: undefined,
undefined,
undefined,
{
refetchOnWindowFocus: false,
enabled:
fromToken !== undefined &&
toToken !== undefined &&
fromChain &&
toChain &&
(fromChain.id === toChain.baseChainId ||
toChain.id === fromChain.baseChainId)
}
)
const supportsExternalLiquidity =
tokenPairIsCanonical &&
externalLiquiditySupport.status === 'success' &&
fromChainWalletVMSupported
? true
: false
const { displayName: toDisplayName } = useENSResolver(recipient, {
enabled: toChain?.vmType === 'evm' && isValidToAddress
})
const [currentSlippageTolerance, setCurrentSlippageTolerance] = useState<
string | undefined
>(slippageTolerance)
useEffect(() => {
setCurrentSlippageTolerance(slippageTolerance)
}, [slippageTolerance])
const {
required: gasTopUpRequired,
amount: _gasTopUpAmount,
amountUsd: _gasTopUpAmountUsd,
balance: gasTopUpBalance
} = useGasTopUpRequired(toChain, fromChain, toToken, recipient)
// Retrieve the price of the `from` token
const { data: fromTokenPriceData, isLoading: isLoadingFromTokenPrice } =
useTokenPrice(
relayClient?.baseApiUrl,
{
address: fromToken?.address ?? '',
chainId: fromToken?.chainId ?? 0,
referrer: relayClient?.source
},
{
enabled: !!(fromToken?.address && fromToken.chainId),
...tokenPriceQueryOptions
}
)
// Retrieve the price of the `to` token
const { data: toTokenPriceData, isLoading: isLoadingToTokenPrice } =
useTokenPrice(
relayClient?.baseApiUrl,
{
address: toToken?.address ?? '',
chainId: toToken?.chainId ?? 0,
referrer: relayClient?.source
},
{
enabled: !!(toToken?.address && toToken.chainId),
...tokenPriceQueryOptions
}
)
const originChainSupportsProtocolv2 =
fromChain?.protocol?.v2?.depository !== undefined &&
toChain?.protocol?.v2?.chainId !== undefined
const quoteProtocol = useMemo(() => {
//Enabled only on certain chains
if (fromChain?.id && originChainSupportsProtocolv2) {
return 'preferV2'
} else {
return undefined
}
}, [originChainSupportsProtocolv2, fromChain?.id])
// Get native balance only when not swapping from native token
const isFromNative = fromToken?.address === fromChain?.currency?.address
const { value: nativeBalance } = useCurrencyBalance({
chain: fromChain,
address: address,
currency: fromChain?.currency?.address
? (fromChain.currency.address as string)
: undefined,
enabled: fromToken !== undefined && !isFromNative,
wallet
})
const effectiveNativeBalance = isFromNative ? fromBalance : nativeBalance
const hasZeroNativeBalance = effectiveNativeBalance === 0n
const eoaExplicitDeposit = useEOADetection(
wallet,
quoteProtocol,
fromToken?.chainId,
fromChain?.vmType
)
const explicitDeposit = hasZeroNativeBalance ? true : eoaExplicitDeposit
const normalizedSponsoredTokens = useMemo(() => {
const chainVms = relayClient?.chains.reduce(
(chains, chain) => {
chains[chain.id] = chain.vmType as ChainVM
return chains
},
{} as Record<number, ChainVM>
)
return sponsoredTokens?.map((token) => {
const [chainId, address] = token.match(/^([^:]*):?(.*)$/)?.slice(1) ?? []
const chainVm = chainVms?.[Number(chainId)]
const normalizedAddress =
chainVm && chainVm === 'evm' ? address.toLowerCase() : address
return `${chainId}:${normalizedAddress}`
})
}, [sponsoredTokens, relayClient?.chains])
const normalizedToToken =
toChain?.vmType === 'evm'
? `${toToken?.chainId}:${toToken?.address.toLowerCase()}`
: `${toToken?.chainId}:${toToken?.address}`
const normalizedFromToken =
fromChain?.vmType === 'evm'
? `${fromToken?.chainId}:${fromToken?.address.toLowerCase()}`
: `${fromToken?.chainId}:${fromToken?.address}`
const isGasSponsorshipEnabled =
normalizedSponsoredTokens &&
normalizedSponsoredTokens.length > 0 &&
toToken &&
fromToken &&
normalizedSponsoredTokens.includes(normalizedToToken) &&
normalizedSponsoredTokens.includes(normalizedFromToken)
const shouldSetQuoteParameters =
fromToken &&
toToken &&
(quoteProtocol !== 'preferV2' ||
fromChain?.vmType !== 'evm' ||
explicitDeposit !== undefined)
const quoteParameters: Parameters<typeof useQuote>['2'] =
shouldSetQuoteParameters
? {
user: fromAddressWithFallback,
originChainId: fromToken.chainId,
destinationChainId: toToken.chainId,
originCurrency: fromToken.address,
destinationCurrency: toToken.address,
recipient: toAddressWithFallback,
tradeType,
appFees: providerOptionsContext.appFees,
amount:
tradeType === 'EXACT_INPUT'
? parseUnits(
debouncedInputAmountValue,
fromToken.decimals
).toString()
: parseUnits(
debouncedOutputAmountValue,
toToken.decimals
).toString(),
referrer: relayClient?.source ?? undefined,
useExternalLiquidity,
useDepositAddress:
!fromChainWalletVMSupported || fromToken?.chainId === 1337,
refundTo: fromToken?.chainId === 1337 ? address : undefined,
slippageTolerance: slippageTolerance,
topupGas: gasTopUpEnabled && gasTopUpRequired,
protocolVersion: quoteProtocol,
...(quoteProtocol === 'preferV2' &&
explicitDeposit !== undefined && {
explicitDeposit: explicitDeposit
})
}
: undefined
const onQuoteRequested: Parameters<typeof useQuote>['3'] = (
options,
config
) => {
const interval = get15MinuteInterval()
const quoteRequestId = sha256({ ...options, interval })
onAnalyticEvent?.(EventNames.QUOTE_REQUESTED, {
parameters: options,
wallet_connector: linkedWallet?.connector,
chain_id_in: options?.originChainId,
chain_id_out: options?.destinationChainId,
http_config: config,
quote_request_id: quoteRequestId
})
}
const onQuoteReceived: Parameters<typeof useQuote>['4'] = (
{ details, steps },
options
) => {
const interval = get15MinuteInterval()
const quoteRequestId = sha256({ ...options, interval })
onAnalyticEvent?.(EventNames.QUOTE_RECEIVED, {
parameters: options,
wallet_connector: linkedWallet?.connector,
amount_in: details?.currencyIn?.amountFormatted,
amount_in_raw: details?.currencyIn?.amount,
currency_in: details?.currencyIn?.currency?.symbol,
chain_id_in: details?.currencyIn?.currency?.chainId,
amount_out: details?.currencyOut?.amountFormatted,
amount_out_raw: details?.currencyOut?.amount,
currency_out: details?.currencyOut?.currency?.symbol,
chain_id_out: details?.currencyOut?.currency?.chainId,
slippage_tolerance_destination_percentage:
details?.slippageTolerance?.destination?.percent,
slippage_tolerance_origin_percentage:
details?.slippageTolerance?.origin?.percent,
steps,
quote_request_id: quoteRequestId,
quote_id: steps ? extractQuoteId(steps) : undefined
})
}
const quoteFetchingEnabled = Boolean(
relayClient &&
((tradeType === 'EXACT_INPUT' &&
debouncedInputAmountValue &&
debouncedInputAmountValue.length > 0 &&
Number(debouncedInputAmountValue) !== 0) ||
(tradeType === 'EXPECTED_OUTPUT' &&
debouncedOutputAmountValue &&
debouncedOutputAmountValue.length > 0 &&
Number(debouncedOutputAmountValue) !== 0)) &&
fromToken !== undefined &&
toToken !== undefined &&
!transactionModalOpen &&
!depositAddressModalOpen
)
const {
data: _quoteData,
error: quoteError,
isFetching: isFetchingQuote,
executeQuote: executeSwap,
queryKey: quoteQueryKey
} = useQuote(
relayClient ? relayClient : undefined,
wallet,
quoteParameters,
onQuoteRequested,
onQuoteReceived,
{
refetchOnWindowFocus: false,
enabled: quoteFetchingEnabled && quoteParameters !== undefined,
refetchInterval:
!transactionModalOpen &&
!depositAddressModalOpen &&
debouncedInputAmountValue === amountInputValue &&
debouncedOutputAmountValue === amountOutputValue
? 12000
: undefined
},
(e: any) => {
const errorMessage = errorToJSON(
e?.response?.data?.message ? new Error(e?.response?.data?.message) : e
)
const interval = get15MinuteInterval()
const quoteRequestId = sha256({ ...quoteParameters, interval })
onAnalyticEvent?.(EventNames.QUOTE_ERROR, {
wallet_connector: linkedWallet?.connector,
error_message: errorMessage,
parameters: quoteParameters,
quote_request_id: quoteRequestId,
status_code: e.response.status ?? e.status ?? ''
})
},
undefined,
isGasSponsorshipEnabled ? providerOptionsContext?.secureBaseUrl : undefined
)
const invalidateQuoteQuery = useCallback(() => {
queryClient.invalidateQueries({ queryKey: quoteQueryKey })
}, [queryClient, quoteQueryKey])
let error =
_quoteData || (isFetchingQuote && quoteFetchingEnabled) ? null : quoteError
let quote = error ? undefined : _quoteData
const gasTopUpAmount = quote?.details?.currencyGasTopup?.amount
? BigInt(quote?.details?.currencyGasTopup?.amount)
: _gasTopUpAmount
const gasTopUpAmountUsd =
quote?.details?.currencyGasTopup?.amountUsd ?? _gasTopUpAmountUsd
useDisconnected(address, () => {
setCustomToAddress(undefined)
})
useEffect(() => {
if (tradeType === 'EXACT_INPUT') {
const amountOut = quote?.details?.currencyOut?.amount ?? ''
setAmountOutputValue(
amountOut !== ''
? formatUnits(
BigInt(amountOut),
Number(quote?.details?.currencyOut?.currency?.decimals ?? 18)
)
: ''
)
} else if (tradeType === 'EXPECTED_OUTPUT') {
const amountIn = quote?.details?.currencyIn?.amount ?? ''
setAmountInputValue(
amountIn !== ''
? formatUnits(
BigInt(amountIn),
Number(quote?.details?.currencyIn?.currency?.decimals ?? 18)
)
: ''
)
}
debouncedAmountInputControls.flush()
debouncedAmountOutputControls.flush()
}, [quote, tradeType])
useEffect(() => {
if (
useExternalLiquidity &&
!externalLiquiditySupport.isFetching &&
!supportsExternalLiquidity
) {
setUseExternalLiquidity(false)
}
}, [
supportsExternalLiquidity,
useExternalLiquidity,
externalLiquiditySupport.isFetching
])
const feeBreakdown = useMemo(() => {
const chains = relayClient?.chains
const fromChain = chains?.find((chain) => chain.id === fromToken?.chainId)
const toChain = chains?.find((chain) => chain.id === toToken?.chainId)
return fromToken && toToken && fromChain && toChain && quote
? parseFees(toChain, fromChain, quote)
: null
}, [quote, fromToken, toToken, relayClient])
const totalAmount = BigInt(quote?.details?.currencyIn?.amount ?? 0n)
const hasInsufficientBalance = Boolean(
!fromBalanceErrorFetching &&
totalAmount &&
address &&
(fromBalance ?? 0n) < totalAmount &&
!hasAuxiliaryFundsSupport &&
fromChainWalletVMSupported
)
const fetchQuoteErrorMessage = error
? error?.message
? (error?.message as string)
: 'Unknown Error'
: null
const fetchQuoteDataErrorMessage = error
? (error as any)?.response?.data?.message
? ((error as any)?.response?.data.message as string)
: 'Unknown Error'
: null
const isInsufficientLiquidityError = Boolean(
fetchQuoteErrorMessage?.includes('No quotes available')
)
const isCapacityExceededError =
fetchQuoteDataErrorMessage?.includes(
'Amount is higher than the available liquidity'
) || fetchQuoteDataErrorMessage?.includes('Insufficient relayer liquidity')
const isCouldNotExecuteError =
fetchQuoteDataErrorMessage?.includes('Could not execute')
const highRelayerServiceFee = isHighRelayerServiceFeeUsd(quote)
const relayerFeeProportion = calculateRelayerFeeProportionUsd(quote)
const timeEstimate = calculatePriceTimeEstimate(quote?.details)
const canonicalTimeEstimate = calculatePriceTimeEstimate(
externalLiquiditySupport.data?.details
)
const recipientWalletSupportsChain = useIsWalletCompatible(
toChain?.id,
recipient,
linkedWallets,
onAnalyticEvent
)
const isSameCurrencySameRecipientSwap =
fromToken?.address === toToken?.address &&
fromToken?.chainId === toToken?.chainId &&
address === recipient
const ctaCopy = useSwapButtonCta({
fromToken,
toToken,
multiWalletSupportEnabled,
isValidFromAddress,
fromChainWalletVMSupported,
isValidToAddress,
toChainWalletVMSupported,
fromChain,
toChain,
isSameCurrencySameRecipientSwap,
debouncedInputAmountValue,
debouncedOutputAmountValue,
hasInsufficientBalance,
isInsufficientLiquidityError,
quote,
operation: quote?.details?.operation
})
usePreviousValueChange(
isCapacityExceededError && supportsExternalLiquidity,
!isFetchingQuote && !externalLiquiditySupport.isFetching,
(capacityExceeded) => {
if (capacityExceeded) {
onAnalyticEvent?.(EventNames.CTA_MAX_CAPACITY_PROMPTED, {
inputAmount: debouncedInputAmountValue,
outputAmount: debouncedOutputAmountValue
})
}
}
)
const swap = useCallback(async () => {
let submittedEvents: string[] = []
const swapErrorHandler = (
error: any,
currentSteps?: Execute['steps'] | null
) => {
const errorMessage = errorToJSON(
error?.response?.data?.message
? new Error(error?.response?.data?.message)
: error
)
if (
error &&
((typeof error.message === 'string' &&
error.message.includes('rejected')) ||
(typeof error === 'string' && error.includes('rejected')) ||
(typeof error === 'string' && error.includes('Approval Denied')) ||
(typeof error === 'string' && error.includes('denied transaction')) ||
(typeof error.message === 'string' &&
error.message.includes('Approval Denied')) ||
(typeof error.message === 'string' &&
error.message.includes('Plugin Closed')) ||
(typeof error.message === 'string' &&
error.message.includes('denied transaction')) ||
(typeof error.message === 'string' &&
error.message.includes('Failed to initialize request') &&
fromChain?.id === 2741)) // Abstract @TODO: remove once privy improves handling rejected transactions
) {
// Close the transaction modal if the user rejects the tx
setTransactionModalOpen(false)
onAnalyticEvent?.(EventNames.USER_REJECTED_WALLET, {
error_message: errorMessage
})
return
}
const { step, stepItem } = getCurrentStep(currentSteps)
const swapEventData = {
...getSwapEventData(
quote?.details,
quote?.fees,
currentSteps ?? null,
linkedWallet?.connector,
quoteParameters
),
error_message: errorMessage
}
const isApproval = step?.id === 'approve'
const errorEvent = isApproval
? EventNames.APPROVAL_ERROR
: EventNames.DEPOSIT_ERROR
//Filter out receipt/deposit transaction errors, those are approval/deposit errors
const isTransactionConfirmationError =
(error &&
typeof error.message === 'string' &&
error.message.includes('TransactionConfirmationError')) ||
(error.name && error.name.includes('TransactionConfirmationError'))
if (
stepItem?.receipt &&
stepItem.check &&
!isTransactionConfirmationError &&
(typeof stepItem.receipt === 'object' && 'status' in stepItem.receipt
? stepItem.receipt.status !== 'reverted'
: true) &&
(!stepItem.checkStatus || stepItem.checkStatus !== 'unknown')
) {
//In some cases there's a race condition where an error is thrown before the steps get a chance to call
//the callback which triggers the success event. This is a workaround to ensure the success event is triggered when
//we have a receipt and require a fill check if we haven't already send the success event.
const successEvent = isApproval
? EventNames.APPROVAL_SUCCESS
: EventNames.DEPOSIT_SUCCESS
if (!submittedEvents.includes(successEvent)) {
onAnalyticEvent?.(successEvent, swapEventData)
submittedEvents.push(successEvent)
//To preserve the order of events we need to delay sending the fill error event but mark that we did send it to avoid duplicates
setTimeout(() => {
onAnalyticEvent?.(EventNames.FILL_ERROR, swapEventData)
}, 20)
} else {
onAnalyticEvent?.(EventNames.FILL_ERROR, swapEventData)
}
} else if (
!stepItem?.receipt ||
(typeof stepItem.receipt === 'object' &&
'status' in stepItem.receipt &&
stepItem.receipt.status === 'reverted')
) {
onAnalyticEvent?.(errorEvent, swapEventData)
} else {
onAnalyticEvent?.(EventNames.SWAP_ERROR, swapEventData)
}
setSwapError(errorMessage)
onSwapError?.(errorMessage, { ...quote, steps: currentSteps } as Execute)
}
try {
const swapEventData = getSwapEventData(
quote?.details,
quote?.fees,
quote?.steps ? (quote?.steps as Execute['steps']) : null,
linkedWallet?.connector,
quoteParameters
)
onAnalyticEvent?.(EventNames.SWAP_CTA_CLICKED, swapEventData)
setWaitingForSteps(true)
if (!executeSwap) {
throw 'Missing a quote'
}
if (!wallet && !walletClient.data) {
throw 'Missing a wallet'
}