Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('TokenInput demo', () => {
renderWithProviders(
<QueryClientProvider client={queryClient}>{tokenInput.demo}</QueryClientProvider>,
)
// The mode dropdown should be visible
expect(screen.getByText('Single token')).toBeDefined()
// The mode dropdown should be visible with the default mode selected
expect(screen.getByText('Multi token')).toBeDefined()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import {
NetworkEthereum,
NetworkOptimism,
NetworkPolygon,
NetworkSepolia,
} from '@web3icons/react'
import { useState } from 'react'
import { arbitrum, mainnet, optimism, polygon } from 'viem/chains'
import { arbitrum, mainnet, optimism, polygon, sepolia } from 'viem/chains'
import OptionsDropdown from '@/src/components/pageComponents/home/Examples/demos/OptionsDropdown'
import Icon from '@/src/components/pageComponents/home/Examples/demos/TokenInput/Icon'
import BaseTokenInput from '@/src/components/sharedComponents/TokenInput'
import { useTokenInput } from '@/src/components/sharedComponents/TokenInput/useTokenInput'
import type { Networks } from '@/src/components/sharedComponents/TokenSelect/types'
import { includeTestnets } from '@/src/constants/common'
import { useTokenLists } from '@/src/hooks/useTokenLists'
import { useTokenSearch } from '@/src/hooks/useTokenSearch'
import { useWeb3Status } from '@/src/hooks/useWeb3Status'
Expand Down Expand Up @@ -105,6 +107,21 @@ const TokenInputMode = withSuspenseAndRetry(
label: polygon.name,
onClick: () => setCurrentNetworkId(polygon.id),
},
...(includeTestnets
? [
{
icon: (
<NetworkSepolia
size={24}
variant="background"
/>
),
id: sepolia.id,
label: sepolia.name,
onClick: () => setCurrentNetworkId(sepolia.id),
},
]
: []),
Comment thread
gabitoesmiapodo marked this conversation as resolved.
]

return (
Expand All @@ -127,10 +144,10 @@ const TokenInputMode = withSuspenseAndRetry(
* token or multi token mode.
*/
const TokenInput = () => {
const [currentTokenInput, setCurrentTokenInput] = useState<Options>('single')
const [currentTokenInput, setCurrentTokenInput] = useState<Options>('multi')
const dropdownItems = [
{ label: 'Single token', onClick: () => setCurrentTokenInput('single') },
{ label: 'Multi token', onClick: () => setCurrentTokenInput('multi') },
{ label: 'Single token', onClick: () => setCurrentTokenInput('single') },
]

return (
Expand Down
7 changes: 4 additions & 3 deletions src/components/sharedComponents/TokenInput/Components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -277,9 +277,10 @@ export const CloseButton: FC<ButtonProps> = ({ children, ...restProps }) => (
border="none"
color="var(--title-color-default)"
cursor="pointer"
position="absolute"
right={0}
top={10}
marginLeft={'auto'}
marginRight={4}
marginBottom={4}
marginTop={0}
_active={{
opacity: 0.7,
}}
Expand Down
24 changes: 23 additions & 1 deletion src/components/sharedComponents/TokenInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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 * as viemChains from 'viem/chains'
import {
BigNumberInput,
type BigNumberInputProps,
Expand All @@ -27,6 +28,8 @@ import type { UseTokenInputReturnType } from '@/src/components/sharedComponents/
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 type { Token } from '@/src/types/token'
import styles from './styles'

Expand Down Expand Up @@ -92,6 +95,23 @@ const TokenInput: FC<Props> = ({
() => (balance && selectedToken ? balance : BigInt(0)),
[balance, selectedToken],
)

const { appChainId, walletChainId } = useWeb3Status()
const activeChainId = selectedToken?.chainId ?? currentNetworkId ?? walletChainId ?? appChainId
const isTestnetChain = useMemo(
() => Object.values(viemChains).find((c) => c.id === activeChainId)?.testnet === true,
[activeChainId],
)

const estimatedUSDValue = useMemo(() => {
if (isTestnetChain) return null
if (!selectedToken) return 0
const priceUSD = selectedToken.extensions?.priceUSD
if (priceUSD === undefined || priceUSD === null) return 0
const tokenAmount = Number.parseFloat(formatUnits(amount, selectedToken.decimals ?? 0))
return Number.parseFloat(priceUSD as string) * tokenAmount
}, [isTestnetChain, selectedToken, amount])

const selectIconSize = 24
const decimals = selectedToken ? selectedToken.decimals : 2

Expand Down Expand Up @@ -167,7 +187,9 @@ const TokenInput: FC<Props> = ({
)}
</TopRow>
<BottomRow>
<EstimatedUSDValue>~$0.00</EstimatedUSDValue>
<EstimatedUSDValue>
{estimatedUSDValue === null ? NO_PRICE_DATA_LABEL : `~$${estimatedUSDValue.toFixed(2)}`}
</EstimatedUSDValue>
<Balance>
<BalanceValue>
{balanceError && 'Error...'}
Expand Down
88 changes: 88 additions & 0 deletions src/components/sharedComponents/TokenInput/useTokenInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import { createElement, type ReactNode } from 'react'
import { zeroAddress } from 'viem'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Token } from '@/src/types/token'
import { useTokenInput } from './useTokenInput'

const walletAddress = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F' as const

const mockUsePublicClient = vi.fn()
const mockGetBalance = vi.fn()

vi.mock('wagmi', () => ({
useAccount: () => ({ address: walletAddress }),
usePublicClient: (args: { chainId?: number } = {}) => {
mockUsePublicClient(args)
return { getBalance: mockGetBalance }
},
}))

vi.mock('@/src/hooks/useErc20Balance', () => ({
useErc20Balance: () => ({ balance: undefined, balanceError: null, isLoadingBalance: false }),
}))

vi.mock('@/src/env', () => ({
env: { PUBLIC_NATIVE_TOKEN_ADDRESS: zeroAddress.toLowerCase() },
}))

const mainnetUsdc: Token = {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
chainId: 1,
decimals: 6,
name: 'USD Coin',
symbol: 'USDC',
}

const sepoliaEth: Token = {
address: zeroAddress,
chainId: 11155111,
decimals: 18,
name: 'Sepolia Ether',
symbol: 'ETH',
}

const wrapper = ({ children }: { children: ReactNode }) =>
createElement(
QueryClientProvider,
{ client: new QueryClient({ defaultOptions: { queries: { retry: false } } }) },
children,
)

describe('useTokenInput', () => {
beforeEach(() => {
mockUsePublicClient.mockClear()
mockGetBalance.mockReset()
})

it('rebinds the native public client to the selected token chain when the user switches chains', async () => {
mockGetBalance.mockResolvedValue(42n)

const { result } = renderHook(() => useTokenInput(mainnetUsdc), { wrapper })

act(() => {
result.current.setTokenSelected(sepoliaEth)
})

await waitFor(() =>
expect(mockUsePublicClient).toHaveBeenLastCalledWith({ chainId: sepoliaEth.chainId }),
)
await waitFor(() => expect(result.current.balance).toBe(42n))
})

it('binds the native public client to the selected token chain when no initial token is given', async () => {
mockGetBalance.mockResolvedValue(7n)

const { result } = renderHook(() => useTokenInput(), { wrapper })

act(() => {
result.current.setTokenSelected(sepoliaEth)
})

await waitFor(() =>
expect(mockUsePublicClient).toHaveBeenLastCalledWith({ chainId: sepoliaEth.chainId }),
)
await waitFor(() => expect(result.current.balance).toBe(7n))
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function useTokenInput(token?: Token) {
token: selectedToken,
})

const publicClient = usePublicClient({ chainId: token?.chainId })
const publicClient = usePublicClient({ chainId: selectedToken?.chainId })

const isNative = selectedToken?.address ? isNativeToken(selectedToken.address) : false
const {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Flex, type FlexProps, Skeleton } from '@chakra-ui/react'
import type { FC } from 'react'

/**
* Skeleton placeholder for token balance and USD value, shown while data is loading.
*/
const BalanceLoading: FC<FlexProps> = ({ ...restProps }) => (
<Flex
alignItems="flex-end"
display="flex"
flexDirection="column"
rowGap={1}
{...restProps}
>
<Skeleton
height="19px"
width="50px"
/>
<Skeleton
height="14px"
width="50px"
/>
</Flex>
)

export default BalanceLoading
22 changes: 2 additions & 20 deletions src/components/sharedComponents/TokenSelect/List/Row.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Box, Flex, type FlexProps, Skeleton } from '@chakra-ui/react'
import { Box, Flex, type FlexProps } from '@chakra-ui/react'
import type { FC } from 'react'
import TokenLogo from '@/src/components/sharedComponents/TokenLogo'
import AddERC20TokenButton from '@/src/components/sharedComponents/TokenSelect/List/AddERC20TokenButton'
import BalanceLoading from '@/src/components/sharedComponents/TokenSelect/List/BalanceLoading'
import TokenBalance from '@/src/components/sharedComponents/TokenSelect/List/TokenBalance'
import type { Token } from '@/src/types/token'

Expand All @@ -20,25 +21,6 @@ const Icon: FC<{ size: number } & FlexProps> = ({ size, children, ...restProps }
</Flex>
)

const BalanceLoading: FC<FlexProps> = ({ ...restProps }) => (
<Flex
alignItems="flex-end"
display="flex"
flexDirection="column"
rowGap={1}
{...restProps}
>
<Skeleton
height="19px"
width="50px"
/>
<Skeleton
height="14px"
width="50px"
/>
</Flex>
)

interface TokenSelectRowProps extends Omit<FlexProps, 'onClick'> {
iconSize: number
isLoadingBalances?: boolean
Expand Down
Loading
Loading