-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
601 lines (557 loc) · 18.8 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
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
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useEffect, useContext } from 'react'
import axios from 'axios'
import {
EuiInMemoryTable,
EuiToolTip,
EuiButtonIcon,
EuiBasicTableColumn,
EuiConfirmModal,
Pagination,
Search,
} from '@elastic/eui'
import { toDate, lightFormat, formatDistanceToNow } from 'date-fns'
import { toast } from 'react-toastify'
import { toHex } from 'web3-utils'
import ToastMessage from '../ToastMessage'
import {
useAllTransactions,
useActiveWeb3React,
useNetworkInfo,
useBridgeAddress,
useBridgeContract,
useAllNetworks,
} from 'hooks'
import { parseResponseToTransactions, setupNetwork } from 'utils'
import Transaction from 'type/Transaction'
import Network from 'type/Network'
import ClaimCountdown from './ClaimCountdown'
import {
TableWrap,
TableTitle,
StyledSpan,
Wrapper,
ExplorerLogo,
Link,
FakeLink,
CollapseWrap,
Row,
StyledClaimButton,
ConfirmMessage,
} from './styled'
import UnknownSVG from 'assets/images/unknown.svg'
import NetworkInfo from './NetworkInfo'
import { ConnectorNames, injected } from 'connectors'
import { connectorLocalStorageKey, NATIVE_TOKEN_ADDERSS } from '../../constants'
import BridgeAppContext from 'context/BridgeAppContext'
import { ethers, Contract } from 'ethers'
import BRIDGE_ABI from '../../constants/abi/GenericBridge.abi.json'
import { BigNumber } from '@ethersproject/bignumber'
import TransportWebUSB from '@ledgerhq/hw-transport-webusb'
import EthApp from '@ledgerhq/hw-app-eth'
function TransactionsTable(): JSX.Element {
const { sourceNetwork, ledgerAddress, ledgerApp, ledgerPath } = useContext(BridgeAppContext)
const { account: web3Account, chainId: web3ChainId, deactivate, activate } = useActiveWeb3React()
const account = ledgerAddress !== '' ? ledgerAddress : web3Account
const currentChainId = ledgerAddress !== '' ? sourceNetwork?.chainId : web3ChainId
const currentNetwork = useNetworkInfo(currentChainId)
const bridgeAddress = useBridgeAddress(currentChainId)
const bridgeContract = useBridgeContract(bridgeAddress)
const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState<any>({})
const [isDisabled, setIsDisabled] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [showNetworkModal, setShowNetworkModal] = useState(false)
const [claimTokenSymbol, setClaimTokenSymbol] = useState('')
const [toNetwork, setToNetwork] = useState<Network>()
const [transactions, setTranstractions] = useState<Transaction[]>([])
const { data: response, error: srwError } = useAllTransactions(account, currentChainId, 200)
const toggleDetails = (item: Transaction) => {
const itemIdToExpandedRowMapValues = { ...itemIdToExpandedRowMap }
if (itemIdToExpandedRowMapValues[item._id]) {
delete itemIdToExpandedRowMapValues[item._id]
} else {
itemIdToExpandedRowMapValues[item._id] = (
<CollapseWrap>
<Row>
<div>
<span>Transfer</span>
{item.originNetwork ? (
<>
{item.originToken === NATIVE_TOKEN_ADDERSS ? (
<span>{item.amountFormated}</span>
) : (
<Wrapper>
<a
href={`${item.originNetwork.explorer}/token/${item.originToken}`}
target="__blank"
rel="noopener noreferrer nofollow"
>
{item.amountFormated}
</a>
</Wrapper>
)}
</>
) : (
<span>{item.amountFormated}</span>
)}
</div>
<div>
<span>From</span>
<NetworkInfo network={item.fromNetwork} />
</div>
<div>
<span>To</span>
<NetworkInfo network={item.toNetwork} />
</div>
</Row>
{item.account !== item.txCreator && (
<Row>
{item.toNetwork?.notEVM ? 'Your recipient account hash:' : 'Your recipient account address:'}
<a href={`${item.accountUrl}`} target="__blank">
{item.account}
</a>
</Row>
)}
{item.originNetwork && item.originToken !== NATIVE_TOKEN_ADDERSS && (
<>
<Row>
This token was deployed on <NetworkInfo network={item.originNetwork} />
</Row>
{(item.fromNetwork?.notEVM || item.toNetwork?.notEVM) &&
item.account !== item.txCreator &&
item.contractHash && (
<Row>
Contrach hash on
<NetworkInfo network={item.fromNetwork?.notEVM ? item.fromNetwork : item.toNetwork} />
{` ${item.contractHash}`}
</Row>
)}
</>
)}
</CollapseWrap>
)
}
setItemIdToExpandedRowMap(itemIdToExpandedRowMapValues)
}
const columns: EuiBasicTableColumn<any>[] = [
{
field: 'requestTime',
name: 'Request Time',
sortable: true,
width: '20%',
render: function (time: number): JSX.Element {
return (
<EuiToolTip content={lightFormat(toDate(time * 1000), 'yyyy-MM-dd HH:mm:ss')}>
<StyledSpan>{formatDistanceToNow(time * 1000, { addSuffix: true })}</StyledSpan>
</EuiToolTip>
)
},
},
{
field: 'fromChainId',
name: 'From Chain Id',
},
{
field: 'requestHashLink',
name: 'Request Tx',
width: '22.5%',
render: function ({
networkName,
explorerLogo,
requestHash,
requestHashUrl,
}: {
networkName: string
explorerLogo: string
requestHash: string
requestHashUrl: string
}): JSX.Element {
return (
<EuiToolTip content={networkName}>
<Wrapper>
<ExplorerLogo src={explorerLogo ? explorerLogo : UnknownSVG} alt="explorer-logo" />
<Link href={requestHashUrl} target="__blank" rel="noopener nofollow noreferrer">
{requestHash}
</Link>
</Wrapper>
</EuiToolTip>
)
},
},
{
field: 'amountFormated',
name: 'Amount',
width: '20%',
sortable: true,
render: function (amountFormated: string): JSX.Element {
return <StyledSpan>{amountFormated}</StyledSpan>
},
},
{
field: 'claimHashLink',
name: 'Claim Tx',
width: '22.5%',
render: function ({
networkName,
explorerLogo,
claimHash,
claimHashUrl,
}: {
networkName: string
explorerLogo: string
claimHash: string
claimHashUrl: string
}): JSX.Element {
return (
<EuiToolTip content={networkName}>
<Wrapper>
{claimHash && <ExplorerLogo src={explorerLogo ? explorerLogo : UnknownSVG} alt="explorer-logo" />}
{claimHashUrl ? (
<Link href={claimHashUrl} target="__blank" rel="noopener nofollow noreferrer">
{claimHash}
</Link>
) : (
<FakeLink>{claimHash}</FakeLink>
)}
</Wrapper>
</EuiToolTip>
)
},
},
{
field: 'toChainId',
name: 'To Chain Id',
},
{
name: 'Action',
width: '15%',
actions: [
{
render: (item: Transaction) => {
return (
<>
{!item.claimed ? (
<>
{item.index ? (
<>
{item.toNetwork?.notEVM ? (
<>
<span>Processing</span>
</>
) : (
<>
<StyledClaimButton isDisabled={isDisabled} onClick={(e: any) => onClaimToken(e, item)}>
Claim Token
</StyledClaimButton>
</>
)}
</>
) : (
<>
{item.fromNetwork && (
<ClaimCountdown
transaction={item}
network={item.fromNetwork}
isDisabled={isDisabled}
onClick={(e: any) => onClaimToken(e, item)}
/>
)}
</>
)}
</>
) : (
<span style={{ opacity: 0.5 }}>Complete</span>
)}
</>
)
},
},
],
},
{
align: 'right',
width: '40px',
isExpander: true,
render: (item: Transaction) => (
<EuiButtonIcon
onClick={() => toggleDetails(item)}
aria-label={itemIdToExpandedRowMap[item._id] ? 'Collapse' : 'Expand'}
iconType={itemIdToExpandedRowMap[item._id] ? 'arrowUp' : 'arrowDown'}
/>
),
},
]
// pagination
const [pageIndex, setPageIndex] = useState(0)
const [pageSize, setPageSize] = useState(10)
const pagination = {
pageIndex,
pageSize,
totalItemCount: 5,
pageSizeOptions: [10, 15, 20],
} as Pagination
// Sorting
const [sortField, setSortField] = useState('requestTime')
const [sortDirection, setSortDirection] = useState('desc')
const sorting = {
sort: {
field: sortField,
direction: sortDirection,
},
}
// Search
const networks = useAllNetworks(currentNetwork?.isTestnet)
const search = {
box: {
incremental: true,
schema: true,
placeholder: 'Enter the transaction hash...',
},
filters: [
{
type: 'field_value_selection',
field: 'fromChainId',
name: 'From Network',
multiSelect: false,
options: networks.map((network: Network) => ({
value: network.chainId,
name: network.name,
view: <NetworkInfo network={network} />,
})),
},
{
type: 'field_value_selection',
field: 'toChainId',
name: 'To Network',
multiSelect: false,
options: networks.map((network: Network) => ({
value: network.chainId,
name: network.name,
view: <NetworkInfo network={network} />,
})),
},
],
} as Search
const onTableChange = ({ page = {}, sort = {} }) => {
// @ts-ignore
const { index: _pageIndex, size: _pageSize } = page
setPageIndex(_pageIndex)
setPageSize(_pageSize)
// @ts-ignore
const { field: _sortField, direction: _sortDirection } = sort
setSortField(_sortField)
setSortDirection(_sortDirection)
}
const onLoadTransactions = async () => {
try {
setIsLoading(true)
const _txns = await parseResponseToTransactions(response, currentChainId)
setTranstractions(_txns)
} catch (error) {
console.error(error)
} finally {
setIsLoading(false)
}
}
useEffect(() => {
const fetchTransactions = async () => {
onLoadTransactions()
}
fetchTransactions()
}, [account, currentChainId, response])
const changeButtonText = (button: HTMLElement, text: string) => {
const textTag = button.getElementsByClassName('euiButtonEmpty__text')[0]
textTag.textContent = text
}
const addLoadingState = (button: HTMLElement) => {
button.setAttribute('disabled', 'true')
const content = button.getElementsByClassName('euiButtonContent')[0]
const spinner = document.createElement('span')
changeButtonText(button, 'Please wait...')
spinner.classList.add('euiLoadingSpinner', 'euiLoadingSpinner--medium', 'euiButtonContent__spinner')
content.prepend(spinner)
}
const removeLoadingState = (button: HTMLElement) => {
button.removeAttribute('disabled')
const spinner = button.getElementsByClassName('euiLoadingSpinner')[0]
changeButtonText(button, 'Claim Token')
spinner.remove()
}
const onClaimToken = async (e: any, item: Transaction) => {
const button = e.currentTarget
addLoadingState(button)
try {
setIsDisabled(true)
setClaimTokenSymbol(item.originSymbol)
setToNetwork(item.toNetwork)
const { requestHash, originChainId, fromChainId, toChainId, index, originToken, amount } = item
// Ask user if the currentChainId is different than the toChainId
if (currentChainId !== toChainId) {
setShowNetworkModal(true)
} else {
const chainIdData = [originChainId, fromChainId, toChainId, index]
const _response = await axios.post(`${process.env.REACT_APP_API_URL}/request-withdraw`, {
requestHash,
fromChainId,
toChainId,
index: index,
})
if (_response.status === 200 && _response.data) {
const sign = _response.data
const { name, symbol, decimals, r, s, v } = sign
if (bridgeContract) {
changeButtonText(button, 'Confirming...')
let receipt
if (ledgerAddress != '') {
const provider = new ethers.providers.JsonRpcProvider(currentNetwork?.rpcURL)
const bridgeContractEth = new Contract(bridgeAddress, BRIDGE_ABI, provider)
const { data } = await bridgeContractEth.populateTransaction[
'claimToken(address,address,uint256,uint256[],bytes32,bytes32[],bytes32[],uint8[],string,string,uint8)'
](originToken, account, amount, chainIdData, requestHash, r, s, v, name, symbol, decimals)
const unsignedTx = {
to: bridgeAddress,
gasPrice: (await provider.getGasPrice())._hex,
gasLimit: ethers.utils.hexlify(500000),
value: BigNumber.from(0),
nonce: await provider.getTransactionCount(account ?? '', 'latest'),
chainId: item.toChainId,
data,
}
const transport = await TransportWebUSB.openConnected()
if (transport != null && ledgerApp && ledgerApp instanceof EthApp) {
const serializedTx = ethers.utils.serializeTransaction(unsignedTx).slice(2)
const _signature = await ledgerApp.signTransaction(ledgerPath, serializedTx)
const signature = {
r: '0x' + _signature.r,
s: '0x' + _signature.s,
v: parseInt('0x' + _signature.v),
from: account,
}
const signedTx = ethers.utils.serializeTransaction(unsignedTx, signature)
const { hash } = await provider.sendTransaction(signedTx)
receipt = {
transactionHash: hash,
}
}
} else {
receipt = await bridgeContract.methods
.claimToken(originToken, account, amount, chainIdData, requestHash, r, s, v, name, symbol, decimals)
.send({
chainId: toHex(item.toChainId),
from: account,
})
}
if (receipt && currentNetwork) {
toast.success(
<ToastMessage
color="success"
headerText="Success!"
link={`${currentNetwork.explorer}${currentNetwork.txUrl}${receipt.transactionHash}`}
linkText="View Transaction"
/>,
{
toastId: 'onClaimToken',
},
)
}
}
} else {
const signError = new Error('Could not sign the withdrawal request')
signError.name = 'SignError'
throw signError
}
}
} catch (error: any) {
// we only care if the error is something _other_ than the user rejected the tx
if (error?.code !== 4001) {
let message = `Could not claim ${item.originSymbol}`
if (error.name === 'SignError') {
// eslint-disable-next-line prefer-destructuring
message = error.message
}
toast.error(<ToastMessage color="danger" headerText="Error!" bodyText={message} />, {
toastId: 'claimToken',
})
}
console.error(error)
} finally {
removeLoadingState(button)
setIsDisabled(false)
}
}
const onSetupNetwork = async () => {
try {
let hasSetup = false
if (toNetwork) {
if (currentNetwork?.notEVM) {
window.localStorage.removeItem(connectorLocalStorageKey)
deactivate()
window.localStorage.setItem(connectorLocalStorageKey, ConnectorNames.Injected)
await activate(injected, async (error: Error) => {
console.error(error)
})
window.location.reload()
}
hasSetup = await setupNetwork(toNetwork)
if (!toNetwork || !hasSetup) {
console.error('Could not setup network')
}
}
} catch (error: any) {
// we only care if the error is something _other_ than the user rejected the tx
if (error?.code !== 4001) {
toast.error(<ToastMessage color="danger" headerText="Error!" bodyText="Could not setup network" />, {
toastId: 'setupNetwork',
})
console.error(error)
}
} finally {
setShowNetworkModal(false)
}
}
return (
<>
<TableWrap>
<TableTitle>Latest Transactions</TableTitle>
{srwError ? (
<span>Could not load data</span>
) : (
<EuiInMemoryTable
loading={isLoading}
itemId="_id"
items={transactions}
columns={columns}
isExpandable={true}
itemIdToExpandedRowMap={itemIdToExpandedRowMap}
hasActions={false}
tableLayout="fixed"
pagination={pagination}
// @ts-ignore
sorting={sorting}
search={search}
onTableChange={onTableChange}
/>
)}
</TableWrap>
{showNetworkModal && toNetwork && (
<EuiConfirmModal
title="Important!"
onCancel={() => setShowNetworkModal(false)}
onConfirm={onSetupNetwork}
cancelButtonText="Cancel"
confirmButtonText="Change network"
defaultFocusedButton="confirm"
>
<ConfirmMessage>
You’re connected to <NetworkInfo network={currentNetwork}></NetworkInfo>
</ConfirmMessage>
<ConfirmMessage>
Please change the network to <NetworkInfo network={toNetwork}></NetworkInfo> to claim {claimTokenSymbol}.
</ConfirmMessage>
</EuiConfirmModal>
)}
</>
)
}
export default TransactionsTable