-
Notifications
You must be signed in to change notification settings - Fork 819
/
send.tsx
574 lines (521 loc) · 18.9 KB
/
send.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
// Copyright (c) 2022 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at https://mozilla.org/MPL/2.0/.
import * as React from 'react'
import { useParams } from 'react-router'
import { useDispatch } from 'react-redux'
import { skipToken } from '@reduxjs/toolkit/query/react'
// Messages
import { ENSOffchainLookupMessage, FailedChecksumMessage } from '../send-ui-messages'
// Types
import { BraveWallet, SendOptionTypes, AddressMessageInfo } from '../../../../constants/types'
// Actions
import { WalletActions } from '../../../../common/actions'
// Selectors
import { WalletSelectors } from '../../../../common/selectors'
import { useUnsafeWalletSelector } from '../../../../common/hooks/use-safe-selector'
// Constants
import { allSupportedExtensions } from '../../../../common/constants/domain-extensions'
// Utils
import { getLocale } from '../../../../../common/locale'
import Amount from '../../../../utils/amount'
import { getBalance, formatTokenBalanceWithSymbol } from '../../../../utils/balance-utils'
import { computeFiatAmount } from '../../../../utils/pricing-utils'
import { endsWithAny } from '../../../../utils/string-utils'
// Hooks
import { usePreset, useBalanceUpdater, useSend } from '../../../../common/hooks'
import { useOnClickOutside } from '../../../../common/hooks/useOnClickOutside'
import { useGetNetworkQuery, useSetNetworkMutation } from '../../../../common/slices/api.slice'
// Styled Components
import {
SendContainer,
SectionBox,
AddressInput,
AmountInput,
Background,
DIVForWidth,
InputRow,
DomainLoadIcon
} from './send.style'
import { Column, Text, Row, HorizontalDivider } from '../shared.styles'
// Component
import { SelectSendOptionButton } from '../components/select-send-option-button/select-send-option-button'
import { StandardButton } from '../components/standard-button/standard-button'
import { SelectTokenButton } from '../components/select-token-button/select-token-button'
import { PresetButton } from '../components/preset-button/preset-button'
import { AccountSelector } from '../components/account-selector/account-selector'
import { AddressMessage } from '../components/address-message/address-message'
import { SelectTokenModal } from '../components/select-token-modal/select-token-modal'
import { CopyAddress } from '../components/copy-address/copy-address'
import { ChecksumInfoModal } from '../components/checksum-info-modal/checksum-info-modal'
interface Props {
onShowSelectTokenModal: () => void
onHideSelectTokenModal: () => void
selectedSendOption: SendOptionTypes
setSelectedSendOption: (sendOption: SendOptionTypes) => void
selectTokenModalRef: React.RefObject<HTMLDivElement>
showSelectTokenModal: boolean
}
export const Send = (props: Props) => {
const {
onShowSelectTokenModal,
setSelectedSendOption,
selectedSendOption,
onHideSelectTokenModal,
selectTokenModalRef,
showSelectTokenModal
} = props
// Wallet Selectors
const selectedAccount = useUnsafeWalletSelector(WalletSelectors.selectedAccount)
const spotPrices = useUnsafeWalletSelector(WalletSelectors.transactionSpotPrices)
const defaultCurrencies = useUnsafeWalletSelector(WalletSelectors.defaultCurrencies)
const accounts = useUnsafeWalletSelector(WalletSelectors.accounts)
// routing
const { chainId, accountAddress, contractAddress, tokenId } = useParams<{
chainId?: string
accountAddress?: string
contractAddress?: string
tokenId?: string
}>()
// Hooks
const dispatch = useDispatch()
useBalanceUpdater()
const {
toAddressOrUrl,
toAddress,
enableEnsOffchainLookup,
showEnsOffchainWarning,
setShowEnsOffchainWarning,
addressError,
addressWarning,
sendAmount,
selectedSendAsset,
sendAmountValidationError,
setSendAmount,
updateToAddressOrUrl,
submitSend,
selectSendAsset,
searchingForDomain,
processAddressOrUrl,
sendAssetOptions
} = useSend(true)
// Queries & Mutations
const { data: selectedTokensNetwork } = useGetNetworkQuery(
selectedSendAsset ?? skipToken
)
const [setNetwork] = useSetNetworkMutation()
// Refs
const ref = React.createRef<HTMLDivElement>()
const checksumInfoModalRef = React.useRef<HTMLDivElement>(null)
// State
const [backgroundHeight, setBackgroundHeight] = React.useState<number>(0)
const [backgroundOpacity, setBackgroundOpacity] = React.useState<number>(0.3)
const [domainPosition, setDomainPosition] = React.useState<number>(0)
const [showChecksumInfoModal, setShowChecksumInfoModal] = React.useState<boolean>(false)
const onSelectPresetAmount = usePreset(
{
onSetAmount: setSendAmount,
asset: selectedSendAsset
}
)
useOnClickOutside(
checksumInfoModalRef,
() => setShowChecksumInfoModal(false),
showChecksumInfoModal
)
// Methods
const handleInputAmountChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setSendAmount(event.target.value)
},
[]
)
const handleInputAddressChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
updateToAddressOrUrl(event.target.value)
},
[updateToAddressOrUrl]
)
const setPresetAmountValue = React.useCallback((percent: number) => {
onSelectPresetAmount(percent)
}, [onSelectPresetAmount])
const onSelectSendOption = React.useCallback((option: SendOptionTypes) => {
selectSendAsset(undefined)
setSelectedSendOption(option)
}, [selectedSendAsset])
const onClickReviewOrENSConsent = React.useCallback(() => {
if (showEnsOffchainWarning) {
enableEnsOffchainLookup()
setShowEnsOffchainWarning(false)
processAddressOrUrl(toAddressOrUrl)
return
}
submitSend()
}, [
showEnsOffchainWarning,
setShowEnsOffchainWarning,
submitSend,
enableEnsOffchainLookup,
processAddressOrUrl,
toAddressOrUrl
])
const updateLoadingIconPosition = React.useCallback((ref: HTMLDivElement | null) => {
const position = ref?.clientWidth
setDomainPosition(position ? position + 22 : 0)
}, [])
// Memos
const sendAssetBalance = React.useMemo(() => {
return getBalance(selectedAccount, selectedSendAsset)
}, [selectedAccount, selectedSendAsset])
const accountNameAndBalance = React.useMemo(() => {
if (!selectedSendAsset || sendAssetBalance === '') {
return ''
}
if (selectedSendOption === 'nft') {
return selectedAccount?.name
}
return `${selectedAccount?.name}: ${formatTokenBalanceWithSymbol(
sendAssetBalance,
selectedSendAsset.decimals,
selectedSendAsset.symbol,
4
)}`
}, [
selectedAccount?.name,
selectedSendAsset,
sendAssetBalance
])
const insufficientFundsError = React.useMemo((): boolean => {
if (!selectedSendAsset) {
return false
}
const amountWei = new Amount(sendAmount).multiplyByDecimals(
selectedSendAsset.decimals
)
if (amountWei.isZero()) {
return false
}
return amountWei.gt(sendAssetBalance)
}, [sendAssetBalance, sendAmount, selectedSendAsset])
const sendAmountFiatValue = React.useMemo(() => {
if (!selectedSendAsset || sendAssetBalance === '' || selectedSendOption === 'nft') {
return ''
}
return computeFiatAmount(spotPrices, {
decimals: selectedSendAsset.decimals,
symbol: selectedSendAsset.symbol,
value: new Amount(sendAmount !== '' ? sendAmount : '0')
.multiplyByDecimals(selectedSendAsset.decimals) // ETH → Wei conversion
.toHex(),
contractAddress: selectedSendAsset.contractAddress,
chainId: selectedSendAsset.chainId
}).formatAsFiat(defaultCurrencies.fiat)
}, [spotPrices, selectedSendAsset, sendAmount, defaultCurrencies.fiat, sendAssetBalance, selectedSendOption])
const reviewButtonText = React.useMemo(() => {
return showEnsOffchainWarning
? getLocale('braveWalletEnsOffChainButton')
: searchingForDomain
? getLocale('braveWalletSearchingForDomain')
: sendAmountValidationError
? getLocale('braveWalletDecimalPlacesError')
: insufficientFundsError
? getLocale('braveWalletNotEnoughFunds')
: (
addressError !== undefined &&
addressError !== '' &&
addressError !== getLocale('braveWalletNotValidChecksumAddressError')
)
? addressError
: (
addressWarning !== undefined &&
addressWarning !== '' &&
addressWarning !== getLocale('braveWalletAddressMissingChecksumInfoWarning')
)
? addressWarning
: getLocale('braveWalletReviewSend')
}, [insufficientFundsError, addressError, addressWarning, sendAmountValidationError, searchingForDomain, showEnsOffchainWarning])
const isReviewButtonDisabled = React.useMemo(() => {
// We only need to check if showEnsOffchainWarning is true here to return
// false early before any other checks are made. This is to allow the button
// to be pressed to enable offchain lookup.
return !showEnsOffchainWarning &&
(searchingForDomain ||
toAddressOrUrl === '' ||
parseFloat(sendAmount) === 0 ||
sendAmount === '' ||
insufficientFundsError ||
(addressError !== undefined && addressError !== '') ||
sendAmountValidationError !== undefined)
},
[
toAddressOrUrl,
sendAmount,
insufficientFundsError,
addressError,
sendAmountValidationError,
searchingForDomain,
showEnsOffchainWarning
]
)
const reviewButtonHasError = React.useMemo(() => {
return searchingForDomain
? false
: insufficientFundsError ||
(addressError !== undefined &&
addressError !== '' &&
addressError !== getLocale('braveWalletNotValidChecksumAddressError'))
}, [searchingForDomain, insufficientFundsError, addressError])
const hasAddressError = React.useMemo(() => {
return searchingForDomain
? false
: !!addressError
}, [searchingForDomain, addressError])
const addressMessageInformation: AddressMessageInfo | undefined = React.useMemo(() => {
if (showEnsOffchainWarning) {
return ENSOffchainLookupMessage
}
if (addressError === getLocale('braveWalletNotValidChecksumAddressError')) {
return { ...FailedChecksumMessage, type: 'error' }
}
if (addressWarning === getLocale('braveWalletAddressMissingChecksumInfoWarning')) {
return { ...FailedChecksumMessage, type: 'warning' }
}
return undefined
}, [showEnsOffchainWarning, addressError, addressWarning])
const showResolvedDomain = React.useMemo(() => {
return (addressError === undefined ||
addressError === '' ||
addressError === getLocale('braveWalletSameAddressError')) &&
toAddress &&
endsWithAny(allSupportedExtensions, toAddressOrUrl.toLowerCase())
}, [addressError, toAddress, toAddressOrUrl])
const showSearchingForDomainIcon = React.useMemo(() => {
return (endsWithAny(allSupportedExtensions, toAddressOrUrl.toLowerCase()) && searchingForDomain) ||
showEnsOffchainWarning
}, [toAddressOrUrl, searchingForDomain, showEnsOffchainWarning])
const selectedAssetFromParams = React.useMemo(() => {
if (!contractAddress) return
return sendAssetOptions.find((option) =>
tokenId
? option.contractAddress.toLowerCase() ===
contractAddress.toLowerCase() && option.tokenId === tokenId
: option.contractAddress.toLowerCase() === contractAddress.toLowerCase()
)
}, [sendAssetOptions, contractAddress, tokenId])
const accountFromParams = React.useMemo(() => {
return accounts.find(
(account) => account.address === accountAddress
)
}, [accountAddress, accounts])
// Effects
React.useEffect(() => {
// Keeps track of the Swap Containers Height to update
// the network backgrounds height.
setBackgroundHeight(ref?.current?.clientHeight ?? 0)
}, [ref?.current?.clientHeight])
React.useEffect(() => {
let subscribed = true
// Changes network background opacity to 0.6 after changing networks
setBackgroundOpacity(0.6)
// Changes network background opacity back to 0.3 after 1 second
setTimeout(() => {
if (subscribed) {
setBackgroundOpacity(0.3)
}
}, 1000)
// cleanup
return () => {
subscribed = false
}
}, [selectedTokensNetwork])
React.useEffect(() => {
// check if the user has selected an asset
if (!chainId || !selectedAssetFromParams || !accountFromParams || selectedSendAsset) return
dispatch(WalletActions.selectAccount(accountFromParams))
setNetwork({
chainId: chainId,
coin: selectedAssetFromParams.coin
})
.catch((e) => console.error(e))
setSelectedSendOption(tokenId ? 'nft' : 'token')
selectSendAsset(selectedAssetFromParams)
}, [
setSelectedSendOption,
selectSendAsset,
selectedSendAsset,
chainId,
selectedAssetFromParams,
accountFromParams
])
// render
return (
<>
<SendContainer ref={ref}>
<Row rowWidth='full' marginBottom={16}>
<SelectSendOptionButton
selectedSendOption={selectedSendOption}
onClick={onSelectSendOption}
/>
</Row>
<SectionBox
minHeight={150}
hasError={insufficientFundsError}
>
{selectedSendOption === 'token' &&
<Column
columnHeight='full'
columnWidth='full'
verticalAlign='space-between'
horizontalAlign='space-between'
>
<Row
rowWidth='full'
horizontalAlign='flex-end'>
<Text textSize='14px' textColor='text03' maintainHeight={true} isBold={true}>
{accountNameAndBalance}
</Text>
</Row>
<Row
rowWidth='full'
>
<Row>
<SelectTokenButton
onClick={onShowSelectTokenModal}
token={selectedSendAsset}
selectedSendOption={selectedSendOption} />
{selectedSendOption === 'token' && selectedSendAsset &&
<>
<HorizontalDivider
height={28}
marginLeft={8}
marginRight={8}
dividerTheme='lighter'
/>
<PresetButton buttonText={getLocale('braveWalletSendHalf')} onClick={() => setPresetAmountValue(0.5)} />
<PresetButton buttonText={getLocale('braveWalletSendMax')} onClick={() => setPresetAmountValue(1)} />
</>
}
</Row>
{selectedSendOption === 'token' &&
<AmountInput
placeholder='0.0'
hasError={insufficientFundsError}
value={sendAmount}
onChange={handleInputAmountChange}
/>
}
</Row>
<Row
rowWidth='full'
horizontalAlign='flex-end'>
<Text textSize='14px' textColor='text03' maintainHeight={true} isBold={false}>
{sendAmountFiatValue}
</Text>
</Row>
</Column>
}
{selectedSendOption === 'nft' &&
<Row
rowWidth='full'
rowHeight='full'
>
<Column
columnHeight='full'
verticalAlign='center'
>
<SelectTokenButton
onClick={onShowSelectTokenModal}
token={selectedSendAsset}
selectedSendOption={selectedSendOption} />
</Column>
<Column
columnHeight='full'
verticalAlign='flex-start'
horizontalAlign='flex-end'
>
<Text textSize='14px' textColor='text03' maintainHeight={true} isBold={true} textAlign='right'>
{accountNameAndBalance}
</Text>
</Column>
</Row>
}
</SectionBox>
<SectionBox
hasError={hasAddressError}
hasWarning={addressWarning !== undefined && addressWarning !== ''}
noPadding={true}
>
<InputRow
rowWidth='full'
verticalAlign='center'
paddingTop={16}
paddingBottom={showResolvedDomain ? 4 : 16}
horizontalPadding={16}
>
{showSearchingForDomainIcon &&
<DomainLoadIcon position={domainPosition} />
}
<DIVForWidth ref={(ref) => updateLoadingIconPosition(ref)}>{toAddressOrUrl}</DIVForWidth>
<AddressInput
placeholder={getLocale('braveWalletEnterRecipientAddress')}
hasError={hasAddressError}
value={toAddressOrUrl}
onChange={handleInputAddressChange}
spellCheck={false}
disabled={!selectedSendAsset}
/>
<AccountSelector disabled={!selectedSendAsset} onSelectAddress={updateToAddressOrUrl} />
</InputRow>
{showResolvedDomain &&
<CopyAddress address={toAddress} />
}
{addressMessageInformation &&
<AddressMessage
addressMessageInfo={addressMessageInformation}
onClickHowToSolve={
(addressError === getLocale('braveWalletNotValidChecksumAddressError') ||
addressWarning === getLocale('braveWalletAddressMissingChecksumInfoWarning'))
? () => setShowChecksumInfoModal(true)
: undefined
}
/>
}
</SectionBox>
<StandardButton
buttonText={reviewButtonText}
onClick={onClickReviewOrENSConsent}
buttonType='primary'
buttonWidth='full'
isLoading={searchingForDomain}
disabled={isReviewButtonDisabled}
hasError={reviewButtonHasError}
/>
</SendContainer>
<Background
backgroundOpacity={backgroundOpacity}
height={backgroundHeight}
network={
selectedTokensNetwork?.chainId === BraveWallet.LOCALHOST_CHAIN_ID
? `${selectedTokensNetwork?.chainId}${selectedTokensNetwork?.coin}`
: selectedTokensNetwork?.chainId ?? ''
}
/>
{showSelectTokenModal &&
<SelectTokenModal
onClose={onHideSelectTokenModal}
selectedSendOption={selectedSendOption}
ref={selectTokenModalRef}
selectSendAsset={selectSendAsset}
/>
}
{showChecksumInfoModal &&
<ChecksumInfoModal
onClose={() => setShowChecksumInfoModal(false)}
ref={checksumInfoModalRef}
/>
}
</>
)
}
export default Send