Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
@@ -1,5 +1,6 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { screen } from '@testing-library/react'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { createMockWeb3Status, renderWithProviders } from '@/src/test-utils'
import tokenInput from './index'
Expand All @@ -20,6 +21,8 @@ vi.mock('@/src/hooks/useTokenLists', () => ({
vi.mock('@/src/hooks/useTokenSearch', () => ({
useTokenSearch: vi.fn(() => ({
searchResult: [],
searchTerm: '',
setSearchTerm: vi.fn(),
})),
}))

Expand All @@ -37,13 +40,51 @@ vi.mock('@/src/components/sharedComponents/TokenInput/useTokenInput', () => ({
})),
}))

// TokenSelect calls useTokens internally; return empty arrays per chain to avoid
// TopTokens receiving undefined and crashing on .find()
vi.mock('@/src/hooks/useTokens', () => ({
useTokens: vi.fn(() => ({
tokens: [],
tokensByChainId: { 1: [], 10: [], 42161: [], 137: [], 11155111: [] },
isLoadingBalances: false,
})),
}))

vi.mock('@/src/constants/common', () => ({
includeTestnets: true,
isDev: false,
NO_PRICE_DATA_LABEL: 'N/A',
}))

describe('TokenInput demo', () => {
it('renders the token input container', () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
renderWithProviders(
<QueryClientProvider client={queryClient}>{tokenInput.demo}</QueryClientProvider>,
)
// The mode dropdown should be visible
expect(screen.getByText('Single token')).toBeDefined()
expect(screen.getByText('Multi token')).toBeDefined()
})

it('shows Sepolia in the network selector when includeTestnets is true', async () => {
const user = userEvent.setup()
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })

renderWithProviders(
<QueryClientProvider client={queryClient}>{tokenInput.demo}</QueryClientProvider>,
)

// Open the TokenSelect dialog
await user.click(screen.getByText('Select'))

// There are two "Chevron down" SVGs: one in the DropdownButton trigger (pointer-events:none)
// and one in the NetworkButton inside the dialog. Click the last one (the network switcher).
const chevrons = await screen.findAllByTitle('Chevron down')
const networkChevron = chevrons[chevrons.length - 1]
const networkButton = networkChevron.closest('button')
expect(networkButton).not.toBeNull()
await user.click(networkButton as HTMLButtonElement)

// Sepolia should be listed as a network option
await waitFor(() => expect(screen.getByText('Sepolia')).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 @@ -27,6 +27,9 @@ 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 { chains } from '@/src/lib/networks.config'
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(
() => chains.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
101 changes: 101 additions & 0 deletions src/components/sharedComponents/TokenInput/useTokenInput.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
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 mockUseAccount = vi.fn()
const mockUsePublicClient = vi.fn()
const mockGetBalance = vi.fn()

vi.mock('wagmi', () => ({
useAccount: () => mockUseAccount(),
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(() => {
mockUseAccount.mockReturnValue({ address: walletAddress })
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))
})

it('does not fetch native balance when wallet is disconnected', () => {
mockUseAccount.mockReturnValue({ address: undefined })

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

expect(result.current.balance).toBeUndefined()
expect(result.current.balanceError).toBeNull()
expect(result.current.isLoadingBalance).toBe(false)
expect(mockGetBalance).not.toHaveBeenCalled()
})
})
4 changes: 2 additions & 2 deletions src/components/sharedComponents/TokenInput/useTokenInput.tsx
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 All @@ -64,7 +64,7 @@ export function useTokenInput(token?: Token) {
} = useQuery({
queryKey: ['nativeBalance', selectedToken?.address, selectedToken?.chainId, userWallet],
queryFn: () => publicClient?.getBalance({ address: getAddress(userWallet ?? '') }),
enabled: isNative,
enabled: isNative && !!userWallet,
})

return {
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