refactor the fiat values

This commit is contained in:
Moody Salem 2021-05-03 16:29:45 -05:00
parent 4c2cb5b0c1
commit ff12b7be10
No known key found for this signature in database
GPG Key ID: 8CB5CD10385138DB
4 changed files with 48 additions and 28 deletions

@ -1,10 +1,8 @@
import { Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import { Currency, CurrencyAmount } from '@uniswap/sdk-core' import { Currency, CurrencyAmount } from '@uniswap/sdk-core'
import React, { useState, useCallback, useMemo } from 'react' import React, { useState, useCallback } from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import { darken } from 'polished' import { darken } from 'polished'
import useUSDCPrice from '../../hooks/useUSDCPrice'
import { tryParseAmount } from '../../state/swap/hooks'
import { useCurrencyBalance } from '../../state/wallet/hooks' import { useCurrencyBalance } from '../../state/wallet/hooks'
import CurrencySearchModal from '../SearchModal/CurrencySearchModal' import CurrencySearchModal from '../SearchModal/CurrencySearchModal'
import CurrencyLogo from '../CurrencyLogo' import CurrencyLogo from '../CurrencyLogo'
@ -159,7 +157,7 @@ interface CurrencyInputPanelProps {
pair?: Pair | null pair?: Pair | null
hideInput?: boolean hideInput?: boolean
otherCurrency?: Currency | null otherCurrency?: Currency | null
showFiatValue?: boolean fiatValue?: CurrencyAmount
id: string id: string
showCommonBases?: boolean showCommonBases?: boolean
customBalanceText?: string customBalanceText?: string
@ -177,7 +175,7 @@ export default function CurrencyInputPanel({
id, id,
showCommonBases, showCommonBases,
customBalanceText, customBalanceText,
showFiatValue = false, fiatValue,
hideBalance = false, hideBalance = false,
pair = null, // used for double token logo pair = null, // used for double token logo
hideInput = false, hideInput = false,
@ -195,14 +193,6 @@ export default function CurrencyInputPanel({
setModalOpen(false) setModalOpen(false)
}, [setModalOpen]) }, [setModalOpen])
const price = useUSDCPrice(showFiatValue ? currency ?? undefined : undefined)
const fiatValueOfTypedAmount: CurrencyAmount | null = useMemo(() => {
if (!price) return null
const amount = tryParseAmount(value, currency ?? undefined)
return amount ? price.quote(amount) : null
}, [currency, price, value])
return ( return (
<InputPanel id={id} hideInput={hideInput} {...rest}> <InputPanel id={id} hideInput={hideInput} {...rest}>
{locked && ( {locked && (
@ -295,9 +285,8 @@ export default function CurrencyInputPanel({
</RowFixed> </RowFixed>
)} )}
<TYPE.body fontSize={14} color={fiatValueOfTypedAmount ? theme.text2 : theme.text4}> <TYPE.body fontSize={14} color={fiatValue ? theme.text2 : theme.text4}>
{fiatValueOfTypedAmount ? '~' : ''}$ {fiatValue ? '~' : ''}${fiatValue ? Number(fiatValue?.toSignificant(6)).toLocaleString('en') : '-'}
{fiatValueOfTypedAmount ? Number(fiatValueOfTypedAmount?.toSignificant(6)).toLocaleString('en') : '-'}
</TYPE.body> </TYPE.body>
</RowBetween> </RowBetween>
</FiatRow> </FiatRow>

@ -1,17 +1,31 @@
import { Percent } from '@uniswap/sdk-core'
import { Trade as V2Trade } from '@uniswap/v2-sdk' import { Trade as V2Trade } from '@uniswap/v2-sdk'
import { Trade as V3Trade } from '@uniswap/v3-sdk' import { Trade as V3Trade, FeeAmount } from '@uniswap/v3-sdk'
import React, { Fragment, memo, useContext } from 'react' import React, { Fragment, memo, useContext } from 'react'
import { ChevronRight } from 'react-feather' import { ChevronLeft, ChevronRight } from 'react-feather'
import { Flex } from 'rebass' import { Flex } from 'rebass'
import { ThemeContext } from 'styled-components' import { ThemeContext } from 'styled-components'
import { TYPE } from '../../theme' import { TYPE } from '../../theme'
import { unwrappedToken } from 'utils/wrappedCurrency' import { unwrappedToken } from 'utils/wrappedCurrency'
function LabeledArrow({ fee }: { fee: FeeAmount }) {
const theme = useContext(ThemeContext)
// todo: improve the rendering of this labeled arrow
return (
<>
<ChevronLeft size={12} color={theme.text2} />
<span style={{ fontSize: 12, marginTop: 2 }}>{new Percent(fee, 1_000_000).toSignificant()}%</span>
<ChevronRight size={12} color={theme.text2} />
</>
)
}
export default memo(function SwapRoute({ trade }: { trade: V2Trade | V3Trade }) { export default memo(function SwapRoute({ trade }: { trade: V2Trade | V3Trade }) {
const tokenPath = trade instanceof V2Trade ? trade.route.path : trade.route.tokenPath const tokenPath = trade instanceof V2Trade ? trade.route.path : trade.route.tokenPath
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
return ( return (
<Flex flexWrap="wrap" width="100%" justifyContent="flex-end" alignItems="center"> <Flex flexWrap="wrap" width="100%" justifyContent="flex-start" alignItems="center">
{tokenPath.map((token, i, path) => { {tokenPath.map((token, i, path) => {
const isLastItem: boolean = i === path.length - 1 const isLastItem: boolean = i === path.length - 1
const currency = unwrappedToken(token) const currency = unwrappedToken(token)
@ -22,7 +36,11 @@ export default memo(function SwapRoute({ trade }: { trade: V2Trade | V3Trade })
{currency.symbol} {currency.symbol}
</TYPE.black> </TYPE.black>
</Flex> </Flex>
{isLastItem ? null : <ChevronRight size={12} color={theme.text2} />} {isLastItem ? null : trade instanceof V2Trade ? (
<ChevronRight size={12} color={theme.text2} />
) : (
<LabeledArrow fee={trade.route.pools[i].fee} />
)}
</Fragment> </Fragment>
) )
})} })}

@ -1,4 +1,4 @@
import { ChainId, Currency, currencyEquals, Price, Token, WETH9 } from '@uniswap/sdk-core' import { ChainId, Currency, CurrencyAmount, currencyEquals, Price, Token, WETH9 } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import { JSBI } from '@uniswap/v2-sdk'
import { useMemo } from 'react' import { useMemo } from 'react'
import { USDC } from '../constants' import { USDC } from '../constants'
@ -75,3 +75,12 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined {
return undefined return undefined
}, [chainId, currency, ethPair, ethPairState, usdcEthPair, usdcEthPairState, usdcPair, usdcPairState, weth, wrapped]) }, [chainId, currency, ethPair, ethPairState, usdcEthPair, usdcEthPairState, usdcPair, usdcPairState, weth, wrapped])
} }
export function useUSDCValue(currencyAmount: CurrencyAmount | undefined | null) {
const price = useUSDCPrice(currencyAmount?.currency)
return useMemo(() => {
if (!price || !currencyAmount) return null
return price.quote(currencyAmount)
}, [currencyAmount, price])
}

@ -34,6 +34,7 @@ import { useERC20PermitFromTrade, UseERC20PermitState } from '../../hooks/useERC
import { useIsSwapUnsupported } from '../../hooks/useIsSwapUnsupported' import { useIsSwapUnsupported } from '../../hooks/useIsSwapUnsupported'
import { useSwapCallback } from '../../hooks/useSwapCallback' import { useSwapCallback } from '../../hooks/useSwapCallback'
import useToggledVersion, { Version } from '../../hooks/useToggledVersion' import useToggledVersion, { Version } from '../../hooks/useToggledVersion'
import { useUSDCValue } from '../../hooks/useUSDCPrice'
import useWrapCallback, { WrapType } from '../../hooks/useWrapCallback' import useWrapCallback, { WrapType } from '../../hooks/useWrapCallback'
import { useWalletModalToggle } from '../../state/application/hooks' import { useWalletModalToggle } from '../../state/application/hooks'
import { Field } from '../../state/swap/actions' import { Field } from '../../state/swap/actions'
@ -132,6 +133,9 @@ export default function Swap({ history }: RouteComponentProps) {
[allowedSlippage, independentField, parsedAmount, showWrap, trade] [allowedSlippage, independentField, parsedAmount, showWrap, trade]
) )
const fiatValueInput = useUSDCValue(parsedAmounts[Field.INPUT])
const fiatValueOutput = useUSDCValue(parsedAmounts[Field.OUTPUT])
const { onSwitchTokens, onCurrencySelection, onUserInput, onChangeRecipient } = useSwapActionHandlers() const { onSwitchTokens, onCurrencySelection, onUserInput, onChangeRecipient } = useSwapActionHandlers()
const isValid = !swapInputError const isValid = !swapInputError
const dependentField: Field = independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT const dependentField: Field = independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT
@ -216,15 +220,15 @@ export default function Swap({ history }: RouteComponentProps) {
signatureData signatureData
) )
const { priceImpactWithoutFee } = computeTradePriceBreakdown(trade) const { priceImpactWithoutFee: priceImpact } = computeTradePriceBreakdown(trade)
const [singleHopOnly] = useUserSingleHopOnly() const [singleHopOnly] = useUserSingleHopOnly()
const handleSwap = useCallback(() => { const handleSwap = useCallback(() => {
if (priceImpactWithoutFee && !confirmPriceImpactWithoutFee(priceImpactWithoutFee)) { if (!swapCallback) {
return return
} }
if (!swapCallback) { if (priceImpact && !confirmPriceImpactWithoutFee(priceImpact)) {
return return
} }
setSwapState({ attemptingTxn: true, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: undefined }) setSwapState({ attemptingTxn: true, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: undefined })
@ -258,7 +262,7 @@ export default function Swap({ history }: RouteComponentProps) {
}) })
}) })
}, [ }, [
priceImpactWithoutFee, priceImpact,
swapCallback, swapCallback,
tradeToConfirm, tradeToConfirm,
showConfirm, showConfirm,
@ -273,7 +277,7 @@ export default function Swap({ history }: RouteComponentProps) {
const [showInverted, setShowInverted] = useState<boolean>(false) const [showInverted, setShowInverted] = useState<boolean>(false)
// warnings on price impact // warnings on price impact
const priceImpactSeverity = warningSeverity(priceImpactWithoutFee) const priceImpactSeverity = warningSeverity(priceImpact)
// show approve flow when: no error on inputs, not approved or pending, or approved in current session // show approve flow when: no error on inputs, not approved or pending, or approved in current session
// never show if price impact is above threshold in non expert mode // never show if price impact is above threshold in non expert mode
@ -350,7 +354,7 @@ export default function Swap({ history }: RouteComponentProps) {
currency={currencies[Field.INPUT]} currency={currencies[Field.INPUT]}
onUserInput={handleTypeInput} onUserInput={handleTypeInput}
onMax={handleMaxInput} onMax={handleMaxInput}
showFiatValue fiatValue={fiatValueInput ?? undefined}
onCurrencySelect={handleInputSelect} onCurrencySelect={handleInputSelect}
otherCurrency={currencies[Field.OUTPUT]} otherCurrency={currencies[Field.OUTPUT]}
showCommonBases={true} showCommonBases={true}
@ -372,7 +376,7 @@ export default function Swap({ history }: RouteComponentProps) {
label={independentField === Field.INPUT && !showWrap ? 'To (at least)' : 'To'} label={independentField === Field.INPUT && !showWrap ? 'To (at least)' : 'To'}
showMaxButton={false} showMaxButton={false}
hideBalance={false} hideBalance={false}
showFiatValue fiatValue={fiatValueOutput ?? undefined}
currency={currencies[Field.OUTPUT]} currency={currencies[Field.OUTPUT]}
onCurrencySelect={handleOutputSelect} onCurrencySelect={handleOutputSelect}
otherCurrency={currencies[Field.INPUT]} otherCurrency={currencies[Field.INPUT]}