Commit b722a20d authored by Jack Short's avatar Jack Short Committed by GitHub

fix: swap divide by zero (#6922)

* fix: swap divide by zero

* putting evaluation in memo
parent 9b5261aa
import { Price, WETH9 } from '@uniswap/sdk-core'
import { USDC_MAINNET } from 'constants/tokens'
import { fireEvent, render, screen } from 'test-utils/render'
import TradePrice from './TradePrice'
const price = new Price(WETH9[1], USDC_MAINNET, 100000000000, 5)
const zeroedNumeratorPrice = new Price(WETH9[1], USDC_MAINNET, 100000000000, 0)
const zeroedDenominatorPrice = new Price(WETH9[1], USDC_MAINNET, 0, 5)
describe('trade price', () => {
it('correctly renders the trade price', () => {
render(<TradePrice price={price} />)
const tradePriceToggle = screen.getByText('1 USDC = 0.02 WETH') as HTMLButtonElement
expect(tradePriceToggle).toBeInTheDocument()
fireEvent.click(tradePriceToggle)
expect(screen.getByText('1 WETH = 50.0 USDC')).toBeInTheDocument()
})
it('handles zeroed numerator', () => {
render(<TradePrice price={zeroedNumeratorPrice} />)
const tradePriceToggle = screen.getByText('1 USDC = 0 WETH') as HTMLButtonElement
expect(tradePriceToggle).toBeInTheDocument()
fireEvent.click(tradePriceToggle)
expect(screen.getByText('1 WETH = 0 USDC')).toBeInTheDocument()
})
it('handles zeroed denominator', () => {
render(<TradePrice price={zeroedDenominatorPrice} />)
const tradePriceToggle = screen.getByText('1 USDC = 0 WETH') as HTMLButtonElement
expect(tradePriceToggle).toBeInTheDocument()
fireEvent.click(tradePriceToggle)
expect(screen.getByText('1 WETH = 0 USDC')).toBeInTheDocument()
})
})
......@@ -3,7 +3,7 @@ import { formatNumber, formatPrice, NumberType } from '@uniswap/conedison/format
import { Currency, Price } from '@uniswap/sdk-core'
import { useUSDPrice } from 'hooks/useUSDPrice'
import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount'
import { useCallback, useState } from 'react'
import { useCallback, useMemo, useState } from 'react'
import styled from 'styled-components/macro'
import { ThemedText } from 'theme'
......@@ -33,7 +33,13 @@ export default function TradePrice({ price }: TradePriceProps) {
const { baseCurrency, quoteCurrency } = price
const { data: usdPrice } = useUSDPrice(tryParseCurrencyAmount('1', showInverted ? baseCurrency : quoteCurrency))
const formattedPrice = formatPrice(showInverted ? price : price.invert(), NumberType.TokenTx)
const formattedPrice = useMemo(() => {
try {
return formatPrice(showInverted ? price : price.invert(), NumberType.TokenTx)
} catch {
return '0'
}
}, [price, showInverted])
const label = showInverted ? `${price.quoteCurrency?.symbol}` : `${price.baseCurrency?.symbol} `
const labelInverted = showInverted ? `${price.baseCurrency?.symbol} ` : `${price.quoteCurrency?.symbol}`
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment