-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindex.tsx
566 lines (520 loc) · 18.7 KB
/
index.tsx
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
import { useAccount, useNetwork } from 'wagmi'
import { useSelector } from 'react-redux'
import { RootState } from '../../store/store'
import toast from 'react-hot-toast'
import { animated } from 'react-spring'
import { useRouter } from 'next/router'
import { segmentAnalyticsEvent } from '@/contexts/SegmentAnalyticsProvider'
import { useBridgeState } from '@/slices/bridge/hooks'
import { BridgeState } from '@/slices/bridge/reducer'
import {
updateFromValue,
setBridgeQuote,
setIsLoading,
setDestinationAddress,
} from '@/slices/bridge/reducer'
import {
setShowDestinationAddress,
setShowFromTokenListOverlay,
setShowSettingsSlideOver,
} from '@/slices/bridgeDisplaySlice'
import { EMPTY_BRIDGE_QUOTE_ZERO } from '@/constants/bridge'
import { useSynapseContext } from '@/utils/providers/SynapseProvider'
import { getErc20TokenAllowance } from '@/actions/getErc20TokenAllowance'
import { subtractSlippage } from '@/utils/slippage'
import { commify } from '@ethersproject/units'
import { formatBigIntToString, powBigInt } from '@/utils/bigint/format'
import { calculateExchangeRate } from '@/utils/calculateExchangeRate'
import { useEffect, useRef, useState, useMemo } from 'react'
import { Token } from '@/utils/types'
import { getWalletClient } from '@wagmi/core'
import { txErrorHandler } from '@/utils/txErrorHandler'
import { AcceptedChainId, CHAINS_ARR, CHAINS_BY_ID } from '@/constants/chains'
import { approveToken } from '@/utils/approveToken'
import { PageHeader } from '@/components/PageHeader'
import Card from '@/components/ui/tailwind/Card'
import BridgeExchangeRateInfo from '@/components/StateManagedBridge/BridgeExchangeRateInfo'
import { Transition } from '@headlessui/react'
import {
SECTION_TRANSITION_PROPS,
TRANSITION_PROPS,
} from '@/styles/transitions'
import { InputContainer } from '@/components/StateManagedBridge/InputContainer'
import { OutputContainer } from '@/components/StateManagedBridge/OutputContainer'
import SettingsSlideOver from '@/components/StateManagedBridge/SettingsSlideOver'
import Button from '@/components/ui/tailwind/Button'
import { SettingsIcon } from '@/components/icons/SettingsIcon'
import { DestinationAddressInput } from '@/components/StateManagedBridge/DestinationAddressInput'
import { isAddress } from '@ethersproject/address'
import { BridgeTransactionButton } from '@/components/StateManagedBridge/BridgeTransactionButton'
import ExplorerToastLink from '@/components/ExplorerToastLink'
import { Address, zeroAddress } from 'viem'
import { stringToBigInt } from '@/utils/bigint/format'
import { Warning } from '@/components/Warning'
import { useAppDispatch } from '@/store/hooks'
import { fetchAndStoreSingleNetworkPortfolioBalances } from '@/slices/portfolio/hooks'
import {
updatePendingBridgeTransaction,
addPendingBridgeTransaction,
removePendingBridgeTransaction,
} from '@/slices/transactions/actions'
import { getTimeMinutesFromNow } from '@/utils/time'
import { FromChainListOverlay } from '@/components/StateManagedBridge/FromChainListOverlay'
import { ToChainListOverlay } from '@/components/StateManagedBridge/ToChainListOverlay'
import { FromTokenListOverlay } from '@/components/StateManagedBridge/FromTokenListOverlay'
import { ToTokenListOverlay } from '@/components/StateManagedBridge/ToTokenListOverlay'
import { waitForTransaction } from '@wagmi/core'
const StateManagedBridge = () => {
const { address } = useAccount()
const { chain } = useNetwork()
const { synapseSDK } = useSynapseContext()
const bridgeDisplayRef = useRef(null)
const currentSDKRequestID = useRef(0)
const router = useRouter()
const { query, pathname } = router
const {
fromChainId,
toChainId,
fromToken,
toToken,
bridgeQuote,
debouncedFromValue,
destinationAddress,
}: BridgeState = useBridgeState()
const {
showSettingsSlideOver,
showDestinationAddress,
showFromChainListOverlay,
showToChainListOverlay,
showFromTokenListOverlay,
showToTokenListOverlay,
} = useSelector((state: RootState) => state.bridgeDisplay)
let pendingPopup
let successPopup
const [isApproved, setIsApproved] = useState(false)
const dispatch = useAppDispatch()
useEffect(() => {
segmentAnalyticsEvent(`[Bridge page] arrives`, {
fromChainId,
query,
pathname,
})
}, [query])
useEffect(() => {
if (
fromToken &&
toToken &&
fromToken?.decimals[fromChainId] &&
stringToBigInt(debouncedFromValue, fromToken?.decimals[fromChainId]) > 0n
) {
console.log('trying to set bridge quote')
getAndSetBridgeQuote()
} else {
dispatch(setBridgeQuote(EMPTY_BRIDGE_QUOTE_ZERO))
dispatch(setIsLoading(false))
}
}, [fromChainId, toChainId, fromToken, toToken, debouncedFromValue])
// don't like this, rewrite: could be custom hook
useEffect(() => {
if (fromToken && fromToken?.addresses[fromChainId] === zeroAddress) {
setIsApproved(true)
} else {
if (
fromToken &&
bridgeQuote?.allowance &&
stringToBigInt(debouncedFromValue, fromToken.decimals[fromChainId]) <=
bridgeQuote.allowance
) {
setIsApproved(true)
} else {
setIsApproved(false)
}
}
}, [bridgeQuote, fromToken, debouncedFromValue, fromChainId, toChainId])
let quoteToast
const getAndSetBridgeQuote = async () => {
currentSDKRequestID.current += 1
const thisRequestId = currentSDKRequestID.current
// will have to handle deadlineMinutes here at later time, gets passed as optional last arg in .bridgeQuote()
try {
dispatch(setIsLoading(true))
const allQuotes = await synapseSDK.allBridgeQuotes(
fromChainId,
toChainId,
fromToken.addresses[fromChainId],
toToken.addresses[toChainId],
stringToBigInt(debouncedFromValue, fromToken?.decimals[fromChainId])
)
if (allQuotes.length === 0) {
const msg = `No route found for bridging ${debouncedFromValue} ${fromToken?.symbol} on ${CHAINS_BY_ID[fromChainId]?.name} to ${toToken?.symbol} on ${CHAINS_BY_ID[toChainId]?.name}`
throw new Error(msg)
}
const rfqQuote = allQuotes.find(
(quote) => quote.bridgeModuleName === 'SynapseRFQ'
)
let quote
if (rfqQuote) {
quote = rfqQuote
} else {
/* allBridgeQuotes returns sorted quotes by maxAmountOut descending */
quote = allQuotes[0]
}
const {
feeAmount,
routerAddress,
maxAmountOut,
originQuery,
destQuery,
estimatedTime,
bridgeModuleName,
} = quote
// console.log(`[getAndSetQuote] fromChainId`, fromChainId)
// console.log(`[getAndSetQuote] toChainId`, toChainId)
// console.log(`[getAndSetQuote] fromToken.symbol`, fromToken.symbol)
// console.log(`[getAndSetQuote] toToken.symbol`, toToken.symbol)
// console.log(`[getAndSetQuote] fromValue`, fromValue)
// console.log('feeAmount', feeAmount)
// console.log(`[getAndSetQuote] maxAmountOut`, maxAmountOut)
if (!(originQuery && maxAmountOut && destQuery && feeAmount)) {
dispatch(setBridgeQuote(EMPTY_BRIDGE_QUOTE_ZERO))
dispatch(setIsLoading(false))
return
}
const toValueBigInt = BigInt(maxAmountOut.toString()) ?? 0n
// Bridge Lifecycle: originToken -> bridgeToken -> destToken
// debouncedFromValue is in originToken decimals
// originQuery.minAmountOut and feeAmount is in bridgeToken decimals
// Adjust feeAmount to be in originToken decimals
const adjustedFeeAmount =
(BigInt(feeAmount) *
stringToBigInt(
`${debouncedFromValue}`,
fromToken?.decimals[fromChainId]
)) /
BigInt(originQuery.minAmountOut)
const isUnsupported = AcceptedChainId[fromChainId] ? false : true
const allowance =
fromToken?.addresses[fromChainId] === zeroAddress ||
address === undefined ||
isUnsupported
? 0n
: await getErc20TokenAllowance({
address,
chainId: fromChainId,
tokenAddress: fromToken?.addresses[fromChainId] as Address,
spender: routerAddress,
})
const {
originQuery: originQueryWithSlippage,
destQuery: destQueryWithSlippage,
} = synapseSDK.applyBridgeSlippage(
bridgeModuleName,
originQuery,
destQuery
)
if (thisRequestId === currentSDKRequestID.current) {
dispatch(
setBridgeQuote({
outputAmount: toValueBigInt,
outputAmountString: commify(
formatBigIntToString(
toValueBigInt,
toToken.decimals[toChainId],
8
)
),
routerAddress,
allowance,
exchangeRate: calculateExchangeRate(
stringToBigInt(
debouncedFromValue,
fromToken?.decimals[fromChainId]
) - BigInt(adjustedFeeAmount),
fromToken?.decimals[fromChainId],
toValueBigInt,
toToken.decimals[toChainId]
),
feeAmount,
delta: BigInt(maxAmountOut.toString()),
quotes: {
originQuery: originQueryWithSlippage,
destQuery: destQueryWithSlippage,
},
estimatedTime: estimatedTime,
bridgeModuleName: bridgeModuleName,
})
)
if (quoteToast) {
toast.dismiss(quoteToast)
}
const message = `Route found for bridging ${debouncedFromValue} ${fromToken?.symbol} on ${CHAINS_BY_ID[fromChainId]?.name} to ${toToken.symbol} on ${CHAINS_BY_ID[toChainId]?.name}`
console.log(message)
quoteToast = toast(message, { duration: 3000 })
}
} catch (err) {
console.log(err)
if (thisRequestId === currentSDKRequestID.current) {
toast.dismiss(quoteToast)
let message
if (!fromChainId) {
message = 'Please select an origin chain'
} else if (!toChainId) {
message = 'Please select a destination chain'
} else if (!fromToken) {
message = 'Please select an origin token'
} else if (!toToken) {
message = 'Please select a destination token'
} else {
message = `No route found for bridging ${debouncedFromValue} ${fromToken?.symbol} on ${CHAINS_BY_ID[fromChainId]?.name} to ${toToken.symbol} on ${CHAINS_BY_ID[toChainId]?.name}`
}
console.log(message)
quoteToast = toast(message, { duration: 3000 })
dispatch(setBridgeQuote(EMPTY_BRIDGE_QUOTE_ZERO))
return
}
} finally {
if (thisRequestId === currentSDKRequestID.current) {
dispatch(setIsLoading(false))
}
}
}
const approveTxn = async () => {
try {
const tx = approveToken(
bridgeQuote?.routerAddress,
fromChainId,
fromToken?.addresses[fromChainId]
)
await tx
/** Re-fetch bridge quote to re-check approval state */
getAndSetBridgeQuote()
} catch (error) {
return txErrorHandler(error)
}
}
const executeBridge = async () => {
segmentAnalyticsEvent(
`[Bridge] initiates bridge`,
{
address,
originChainId: fromChainId,
destinationChainId: toChainId,
inputAmount: debouncedFromValue,
expectedReceivedAmount: bridgeQuote.outputAmountString,
slippage: bridgeQuote.exchangeRate,
},
true
)
const currentTimestamp: number = getTimeMinutesFromNow(0)
dispatch(
addPendingBridgeTransaction({
id: currentTimestamp,
originChain: CHAINS_BY_ID[fromChainId],
originToken: fromToken,
originValue: debouncedFromValue,
destinationChain: CHAINS_BY_ID[toChainId],
destinationToken: toToken,
transactionHash: undefined,
timestamp: undefined,
isSubmitted: false,
estimatedTime: bridgeQuote.estimatedTime,
bridgeModuleName: bridgeQuote.bridgeModuleName,
})
)
try {
const wallet = await getWalletClient({
chainId: fromChainId,
})
const toAddress =
destinationAddress && isAddress(destinationAddress)
? destinationAddress
: address
const data = await synapseSDK.bridge(
toAddress,
bridgeQuote.routerAddress,
fromChainId,
toChainId,
fromToken?.addresses[fromChainId as keyof Token['addresses']],
stringToBigInt(debouncedFromValue, fromToken?.decimals[fromChainId]),
bridgeQuote.quotes.originQuery,
bridgeQuote.quotes.destQuery
)
const payload =
fromToken?.addresses[fromChainId as keyof Token['addresses']] ===
zeroAddress ||
fromToken?.addresses[fromChainId as keyof Token['addresses']] === ''
? {
data: data.data,
to: data.to,
value: stringToBigInt(
debouncedFromValue,
fromToken?.decimals[fromChainId]
),
}
: data
const tx = await wallet.sendTransaction(payload)
const originChainName = CHAINS_BY_ID[fromChainId]?.name
const destinationChainName = CHAINS_BY_ID[toChainId]?.name
pendingPopup = toast(
`Bridging from ${fromToken?.symbol} on ${originChainName} to ${toToken.symbol} on ${destinationChainName}`,
{ id: 'bridge-in-progress-popup', duration: Infinity }
)
segmentAnalyticsEvent(`[Bridge] bridges successfully`, {
address,
originChainId: fromChainId,
destinationChainId: toChainId,
inputAmount: debouncedFromValue,
expectedReceivedAmount: bridgeQuote.outputAmountString,
slippage: bridgeQuote.exchangeRate,
})
dispatch(
updatePendingBridgeTransaction({
id: currentTimestamp,
timestamp: undefined,
transactionHash: tx,
isSubmitted: false,
})
)
dispatch(setBridgeQuote(EMPTY_BRIDGE_QUOTE_ZERO))
dispatch(setDestinationAddress(null))
dispatch(setShowDestinationAddress(false))
dispatch(updateFromValue(''))
const successToastContent = (
<div>
<div>
Successfully initiated bridge from {fromToken?.symbol} on{' '}
{originChainName} to {toToken.symbol} on {destinationChainName}
</div>
<ExplorerToastLink
transactionHash={tx ?? zeroAddress}
chainId={fromChainId}
/>
</div>
)
successPopup = toast.success(successToastContent, {
id: 'bridge-success-popup',
duration: 10000,
})
toast.dismiss(pendingPopup)
const transactionReceipt = await waitForTransaction({
hash: tx as Address,
timeout: 30_000,
})
console.log('Transaction Receipt: ', transactionReceipt)
/** Update Origin Chain token balances after resolved tx or timeout reached */
/** Assume tx has been actually resolved if above times out */
dispatch(
fetchAndStoreSingleNetworkPortfolioBalances({
address,
chainId: fromChainId,
})
)
return tx
} catch (error) {
segmentAnalyticsEvent(`[Bridge] error bridging`, {
address,
errorCode: error.code,
})
dispatch(removePendingBridgeTransaction(currentTimestamp))
console.log('Error executing bridge', error)
toast.dismiss(pendingPopup)
return txErrorHandler(error)
}
}
const springClass =
'-mt-4 fixed z-50 w-full h-full bg-opacity-50 bg-[#343036]'
return (
<div className="flex flex-col w-full max-w-lg mx-auto lg:mx-0">
<div className="flex flex-col">
<div className="flex items-center justify-between">
<PageHeader
title="Bridge"
subtitle="Send your assets across chains."
/>
<div>
<Button
className="flex items-center p-3 text-opacity-75 bg-bgLight hover:bg-bgLighter text-secondaryTextColor hover:text-white"
onClick={() => {
if (showSettingsSlideOver === true) {
dispatch(setShowSettingsSlideOver(false))
} else {
dispatch(setShowSettingsSlideOver(true))
}
}}
>
{!showSettingsSlideOver ? (
<>
<SettingsIcon className="w-5 h-5 mr-2" />
<span>Settings</span>
</>
) : (
<span>Close</span>
)}
</Button>
</div>
</div>
<Card
divider={false}
className={`
pb-3 mt-5 overflow-hidden
transition-all duration-100 transform rounded-md
bg-bgBase
`}
>
<div ref={bridgeDisplayRef}>
<Transition show={showSettingsSlideOver} {...TRANSITION_PROPS}>
<animated.div>
<SettingsSlideOver key="settings" />
</animated.div>
</Transition>
<Transition show={showFromChainListOverlay} {...TRANSITION_PROPS}>
<animated.div className={springClass}>
<FromChainListOverlay />
</animated.div>
</Transition>
<Transition show={showFromTokenListOverlay} {...TRANSITION_PROPS}>
<animated.div className={springClass}>
<FromTokenListOverlay />
</animated.div>
</Transition>
<Transition show={showToChainListOverlay} {...TRANSITION_PROPS}>
<animated.div className={springClass}>
<ToChainListOverlay />
</animated.div>
</Transition>
<Transition show={showToTokenListOverlay} {...TRANSITION_PROPS}>
<animated.div className={springClass}>
<ToTokenListOverlay />
</animated.div>
</Transition>
<InputContainer />
<OutputContainer />
<Warning />
<Transition
appear={true}
unmount={false}
show={true}
{...SECTION_TRANSITION_PROPS}
>
<BridgeExchangeRateInfo showGasDrop={true} />
</Transition>
{showDestinationAddress && (
<DestinationAddressInput
toChainId={toChainId}
destinationAddress={destinationAddress}
/>
)}
<div className="md:my-3">
<BridgeTransactionButton
isApproved={isApproved}
approveTxn={approveTxn}
executeBridge={executeBridge}
/>
</div>
</div>
</Card>
</div>
</div>
)
}
export default StateManagedBridge