-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.tsx
More file actions
282 lines (264 loc) · 8.84 KB
/
Copy pathindex.tsx
File metadata and controls
282 lines (264 loc) · 8.84 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
import { Dialog, type FlexProps, Portal } from '@chakra-ui/react'
import { type FC, useMemo, useState } from 'react'
import { type NumberFormatValues, NumericFormat } from 'react-number-format'
import { formatUnits } from 'viem'
import {
BigNumberInput,
type BigNumberInputProps,
type RenderInputProps,
} from '@/src/components/sharedComponents/BigNumberInput'
import {
Balance,
BalanceValue,
BottomRow,
CloseButton,
DropdownButton,
ErrorComponent,
EstimatedUSDValue,
Icon,
MaxButton,
SingleToken,
Textfield,
Title,
TopRow,
Wrapper,
} from '@/src/components/sharedComponents/TokenInput/Components'
import type { UseTokenInputReturnType } from '@/src/components/sharedComponents/TokenInput/useTokenInput'
import TokenLogo from '@/src/components/sharedComponents/TokenLogo'
import TokenSelect, { type TokenSelectProps } from '@/src/components/sharedComponents/TokenSelect'
import Spinner from '@/src/components/sharedComponents/ui/Spinner'
import { NO_PRICE_DATA_LABEL } from '@/src/constants/common'
import { useWeb3Status } from '@/src/hooks/useWeb3Status'
import { chains } from '@/src/lib/networks.config'
import type { Token } from '@/src/types/token'
import styles from './styles'
interface TokenInputProps extends Omit<TokenSelectProps, 'onTokenSelect'> {
singleToken?: boolean
thousandSeparator?: boolean
title?: string
tokenInput: UseTokenInputReturnType
}
/** @ignore */
type Props = FlexProps & TokenInputProps
/**
* TokenInput component allows users to input token amounts and select tokens from a list.
* It displays the token input field, token balance, and a dropdown list of available tokens.
*
* @param {TokenInputProps} props - TokenInput component props.
* @param {boolean} [props.thousandSeparator=true] - Optional flag to enable thousands separator. Default is true.
* @param {string} props.title - The title of the token input.
* @param {number} [props.currentNetworkId=mainnet.id] - The current network id. Default is mainnet's id.
* @param {function} props.onTokenSelect - Callback function to be called when a token is selected.
* @param {Networks} [props.networks] - Optional list of networks to display in the dropdown. The dropdown won't show up if undefined. Default is undefined.
* @param {string} [props.placeholder='Search by name or address'] - Optional placeholder text for the search input. Default is 'Search by name or address'.
* @param {number} [props.containerHeight=320] - Optional height of the virtualized tokens list. Default is 320.
* @param {number} [props.iconSize=32] - Optional size of the token icon in the list. Default is 32.
* @param {number} [props.itemHeight=64] - Optional height of each item in the list. Default is 64.
* @param {boolean} [props.showAddTokenButton=false] - Optional flag to allow adding a token. Default is false.
* @param {boolean} [props.showBalance=false] - Optional flag to show the token balance in the list. Default is false.
* @param {boolean} [props.showTopTokens=false] - Optional flag to show the top tokens in the list. Default is false.
*/
const TokenInput: FC<Props> = ({
containerHeight,
currentNetworkId,
css,
iconSize,
itemHeight,
networks,
placeholder,
showAddTokenButton,
showBalance,
showTopTokens,
singleToken,
thousandSeparator = true,
title,
tokenInput,
...restProps
}: Props) => {
const [isOpen, setIsOpen] = useState(false)
const {
amount,
amountError,
balance,
balanceError,
isLoadingBalance,
isLoadingPrice,
priceUSD,
selectedToken,
setAmount,
setAmountError,
setTokenSelected,
} = tokenInput
const max = useMemo(
() => (balance && selectedToken ? balance : BigInt(0)),
[balance, selectedToken],
)
const { appChainId, walletChainId } = useWeb3Status()
const activeChainId = selectedToken?.chainId ?? currentNetworkId ?? walletChainId ?? appChainId
const isTestnetChain = useMemo(
() => chains.find((c) => c.id === activeChainId)?.testnet === true,
[activeChainId],
)
const estimatedUSDValue = useMemo(() => {
if (isTestnetChain) return null
if (!selectedToken || !priceUSD || !balance) return 0
const tokenBalance = Number.parseFloat(formatUnits(balance, selectedToken.decimals ?? 0))
return Number.parseFloat(priceUSD) * tokenBalance
}, [isTestnetChain, selectedToken, priceUSD, balance])
const selectIconSize = 24
const decimals = selectedToken ? selectedToken.decimals : 2
const handleSelectedToken = (token: Token | undefined) => {
setAmount(BigInt(0))
setTokenSelected(token)
setIsOpen(false)
}
const handleSetMax = () => {
setAmountError(null)
setAmount(max)
}
const handleError: BigNumberInputProps['onError'] = (error) => {
setAmountError(error?.message)
}
const CurrentToken = () =>
selectedToken ? (
<>
<Icon $iconSize={selectIconSize}>
<TokenLogo
size={selectIconSize}
token={selectedToken}
/>
</Icon>
{selectedToken.symbol}
</>
) : (
'Select'
)
return singleToken && !selectedToken ? (
<div>When single token is true, a token is required.</div>
) : (
<Dialog.Root
open={isOpen}
onOpenChange={(state) => setIsOpen(state.open)}
>
<Wrapper
css={{ ...css, ...styles }}
{...restProps}
>
{title && <Title>{title}</Title>}
<TopRow>
<BigNumberInput
decimals={decimals}
max={max}
onChange={setAmount}
onError={handleError}
placeholder="0.00"
renderInput={(renderInputProps) => (
<TokenAmountField
amountError={amountError}
decimals={decimals}
renderInputProps={renderInputProps}
thousandSeparator={thousandSeparator}
/>
)}
value={amount}
/>
{singleToken ? (
<SingleToken>
<CurrentToken />
</SingleToken>
) : (
<Dialog.Trigger asChild>
<DropdownButton>
<CurrentToken />
</DropdownButton>
</Dialog.Trigger>
)}
</TopRow>
<BottomRow>
<EstimatedUSDValue>
{estimatedUSDValue === null ? (
NO_PRICE_DATA_LABEL
) : selectedToken && (isLoadingPrice || isLoadingBalance) ? (
<Spinner size="sm" />
) : (
`~$${estimatedUSDValue.toFixed(2)}`
)}
</EstimatedUSDValue>
<Balance>
<BalanceValue>
{balanceError && 'Error...'}
{isLoadingBalance ? (
<Spinner size="sm" />
) : (
`Balance: ${formatUnits(balance ?? 0n, selectedToken?.decimals ?? 0)}`
)}
</BalanceValue>
<MaxButton
disabled={isLoadingBalance || !!balanceError || balance === 0n}
onClick={handleSetMax}
>
Max
</MaxButton>
</Balance>
</BottomRow>
{amountError && <ErrorComponent>{amountError}</ErrorComponent>}
</Wrapper>
<Portal>
<Dialog.Backdrop />
<Dialog.Positioner>
<Dialog.Content>
<TokenSelect
containerHeight={containerHeight}
currentNetworkId={currentNetworkId}
iconSize={iconSize}
itemHeight={itemHeight}
networks={networks}
onTokenSelect={handleSelectedToken}
placeholder={placeholder}
showAddTokenButton={showAddTokenButton}
showBalance={showBalance}
showTopTokens={showTopTokens}
>
<CloseButton
aria-label="Close"
onClick={() => setIsOpen(false)}
/>
</TokenSelect>
</Dialog.Content>
</Dialog.Positioner>
</Portal>
</Dialog.Root>
)
}
function TokenAmountField({
amountError,
decimals,
renderInputProps,
thousandSeparator,
}: {
amountError?: string | null
decimals: number
renderInputProps: RenderInputProps
thousandSeparator: boolean
}) {
const { onChange, inputRef, ...restProps } = renderInputProps
const isAllowed = ({ value }: NumberFormatValues) => {
const [, inputDecimals] = value.toString().split('.')
if (!inputDecimals) {
return true
}
return decimals >= inputDecimals?.length
}
return (
<NumericFormat
$status={amountError ? 'error' : undefined}
customInput={Textfield}
isAllowed={isAllowed}
onValueChange={({ value }) => onChange?.(value)}
thousandSeparator={thousandSeparator}
// biome-ignore lint/suspicious/noExplicitAny: NumericFormat has defaultValue prop overwritten and is not compatible with the standard
{...(restProps as any)}
/>
)
}
export default TokenInput