Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -35,6 +35,8 @@ vi.mock('@/src/components/sharedComponents/TokenInput/useTokenInput', () => ({
balance: 0n,
balanceError: null,
isLoadingBalance: false,
isLoadingPrice: false,
priceUSD: undefined,
selectedToken: undefined,
setTokenSelected: vi.fn(),
})),
Expand Down
20 changes: 13 additions & 7 deletions src/components/sharedComponents/TokenInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ const TokenInput: FC<Props> = ({
balance,
balanceError,
isLoadingBalance,
isLoadingPrice,
priceUSD,
selectedToken,
setAmount,
setAmountError,
Expand All @@ -105,12 +107,10 @@ const TokenInput: FC<Props> = ({

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])
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
Expand Down Expand Up @@ -188,7 +188,13 @@ const TokenInput: FC<Props> = ({
</TopRow>
<BottomRow>
<EstimatedUSDValue>
{estimatedUSDValue === null ? NO_PRICE_DATA_LABEL : `~$${estimatedUSDValue.toFixed(2)}`}
{estimatedUSDValue === null ? (
NO_PRICE_DATA_LABEL
) : selectedToken && (isLoadingPrice || isLoadingBalance) ? (
<Spinner size="sm" />
) : (
`~$${estimatedUSDValue.toFixed(2)}`
)}
</EstimatedUSDValue>
<Balance>
<BalanceValue>
Expand Down
54 changes: 54 additions & 0 deletions src/components/sharedComponents/TokenInput/useTokenInput.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const walletAddress = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F' as const
const mockUseAccount = vi.fn()
const mockUsePublicClient = vi.fn()
const mockGetBalance = vi.fn()
const mockUseTokens = vi.fn()

vi.mock('wagmi', () => ({
useAccount: () => mockUseAccount(),
Expand All @@ -24,6 +25,10 @@ vi.mock('@/src/hooks/useErc20Balance', () => ({
useErc20Balance: () => ({ balance: undefined, balanceError: null, isLoadingBalance: false }),
}))

vi.mock('@/src/hooks/useTokens', () => ({
useTokens: (args: unknown) => mockUseTokens(args),
}))

vi.mock('@/src/env', () => ({
env: { PUBLIC_NATIVE_TOKEN_ADDRESS: zeroAddress.toLowerCase() },
}))
Expand Down Expand Up @@ -56,6 +61,7 @@ describe('useTokenInput', () => {
mockUseAccount.mockReturnValue({ address: walletAddress })
mockUsePublicClient.mockClear()
mockGetBalance.mockReset()
mockUseTokens.mockReturnValue({ tokensByChainId: {}, isLoadingBalances: false, tokens: [] })
})

it('rebinds the native public client to the selected token chain when the user switches chains', async () => {
Expand Down Expand Up @@ -98,4 +104,52 @@ describe('useTokenInput', () => {
expect(result.current.isLoadingBalance).toBe(false)
expect(mockGetBalance).not.toHaveBeenCalled()
})

it('exposes priceUSD for the selected token from useTokens', async () => {
mockUseTokens.mockReturnValue({
tokensByChainId: {
1: [{ ...mainnetUsdc, extensions: { priceUSD: '1.00' } }],
},
isLoadingBalances: false,
tokens: [],
})

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

await waitFor(() => expect(result.current.priceUSD).toBe('1.00'))
})

it('exposes isLoadingPrice as true while useTokens is loading', () => {
mockUseTokens.mockReturnValue({ tokensByChainId: {}, isLoadingBalances: true, tokens: [] })

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

expect(result.current.isLoadingPrice).toBe(true)
})

it('updates priceUSD when a different token is selected', async () => {
const mainnetEth: Token = {
address: zeroAddress,
chainId: 1,
decimals: 18,
name: 'Ether',
symbol: 'ETH',
}
mockUseTokens.mockReturnValue({
tokensByChainId: {
1: [{ ...mainnetEth, extensions: { priceUSD: '3000.00' } }],
},
isLoadingBalances: false,
tokens: [],
})
mockGetBalance.mockResolvedValue(1000000000000000000n)

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

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

await waitFor(() => expect(result.current.priceUSD).toBe('3000.00'))
})
})
13 changes: 13 additions & 0 deletions src/components/sharedComponents/TokenInput/useTokenInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'
import { getAddress } from 'viem'
import { useAccount, usePublicClient } from 'wagmi'
import { useErc20Balance } from '@/src/hooks/useErc20Balance'
import { useTokens } from '@/src/hooks/useTokens'
import type { Token } from '@/src/types/token'
import { isNativeToken } from '@/src/utils/address'

Expand Down Expand Up @@ -49,6 +50,16 @@ export function useTokenInput(token?: Token) {
}, [token])

const { address: userWallet } = useAccount()
const { tokensByChainId, isLoadingBalances: isLoadingPrice } = useTokens({
chainId: selectedToken?.chainId,
Comment thread
gabitoesmiapodo marked this conversation as resolved.
Outdated
withBalance: true,
})
const priceUSD = selectedToken
? (tokensByChainId[selectedToken.chainId]?.find(
(t) => t.address.toLowerCase() === selectedToken.address.toLowerCase(),
)?.extensions?.priceUSD as string | undefined)
Comment thread
gabitoesmiapodo marked this conversation as resolved.
: undefined

const { balance, balanceError, isLoadingBalance } = useErc20Balance({
address: userWallet ? getAddress(userWallet) : undefined,
token: selectedToken,
Expand All @@ -75,6 +86,8 @@ export function useTokenInput(token?: Token) {
balance: isNative ? nativeBalance : balance,
balanceError: isNative ? nativeBalanceError : balanceError,
isLoadingBalance: isNative ? isLoadingNativeBalance : isLoadingBalance,
isLoadingPrice,
priceUSD,
selectedToken,
setTokenSelected,
Comment thread
gabitoesmiapodo marked this conversation as resolved.
}
Expand Down
Loading