Commit 27960532 authored by Moody Salem's avatar Moody Salem Committed by GitHub

refactor: use new sdk version (#1472)

* do not construct tokens for wrapped token info

* some cleanup of the wrapped token info

* back to extends, bump sdk core version via v2/v3 sdk updates

* Revert "back to extends, bump sdk core version via v2/v3 sdk updates"

This reverts commit 92cc5073

* update the sdk version

* fix some more uses of instanceof

* finish the refactor

* mess with the currency list performance

* start replacing with the latest v3/v2 sdks

* raw -> quotient

* more cleanup

* finish the refactor

* clean up currency list refactor

* fix list rendering

* perf(token lists): improve app performance when there are large inactive token lists (#1510)

* improve inactive token lists performance

* cleanup before larger changes to combine inactive lists

* only do the search if the query does not match any active lists, limit the number of results

* more performance improvements

* search inactive lists more aggressively
parent 37a4e2f6
import { CurrencyAmount, Percent } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core'
import React, { useMemo } from 'react' import React, { useMemo } from 'react'
import useTheme from '../../hooks/useTheme' import useTheme from '../../hooks/useTheme'
import { TYPE } from '../../theme' import { TYPE } from '../../theme'
...@@ -9,7 +9,7 @@ export function FiatValue({ ...@@ -9,7 +9,7 @@ export function FiatValue({
fiatValue, fiatValue,
priceImpact, priceImpact,
}: { }: {
fiatValue: CurrencyAmount | null | undefined fiatValue: CurrencyAmount<Currency> | null | undefined
priceImpact?: Percent priceImpact?: Percent
}) { }) {
const theme = useTheme() const theme = useTheme()
......
import { Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Percent, Token } from '@uniswap/sdk-core'
import React, { useState, useCallback } 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'
...@@ -159,7 +159,7 @@ interface CurrencyInputPanelProps { ...@@ -159,7 +159,7 @@ interface CurrencyInputPanelProps {
pair?: Pair | null pair?: Pair | null
hideInput?: boolean hideInput?: boolean
otherCurrency?: Currency | null otherCurrency?: Currency | null
fiatValue?: CurrencyAmount | null fiatValue?: CurrencyAmount<Token> | null
priceImpact?: Percent priceImpact?: Percent
id: string id: string
showCommonBases?: boolean showCommonBases?: boolean
......
import { ChainId, Currency, ETHER, Token } from '@uniswap/sdk-core' import { ChainId, Currency } from '@uniswap/sdk-core'
import React, { useMemo } from 'react' import React, { useMemo } from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import EthereumLogo from '../../assets/images/ethereum-logo.png' import EthereumLogo from '../../assets/images/ethereum-logo.png'
import useHttpLocations from '../../hooks/useHttpLocations' import useHttpLocations from '../../hooks/useHttpLocations'
import { WrappedTokenInfo } from '../../state/lists/hooks' import { WrappedTokenInfo } from '../../state/lists/wrappedTokenInfo'
import Logo from '../Logo' import Logo from '../Logo'
export const getTokenLogoURL = (address: string) => export const getTokenLogoURL = (address: string) =>
...@@ -37,9 +37,9 @@ export default function CurrencyLogo({ ...@@ -37,9 +37,9 @@ export default function CurrencyLogo({
const uriLocations = useHttpLocations(currency instanceof WrappedTokenInfo ? currency.logoURI : undefined) const uriLocations = useHttpLocations(currency instanceof WrappedTokenInfo ? currency.logoURI : undefined)
const srcs: string[] = useMemo(() => { const srcs: string[] = useMemo(() => {
if (currency === ETHER) return [] if (!currency || currency.isEther) return []
if (currency instanceof Token) { if (currency.isToken) {
const defaultUrls = currency.chainId === ChainId.MAINNET ? [getTokenLogoURL(currency.address)] : [] const defaultUrls = currency.chainId === ChainId.MAINNET ? [getTokenLogoURL(currency.address)] : []
if (currency instanceof WrappedTokenInfo) { if (currency instanceof WrappedTokenInfo) {
return [...uriLocations, ...defaultUrls] return [...uriLocations, ...defaultUrls]
...@@ -49,7 +49,7 @@ export default function CurrencyLogo({ ...@@ -49,7 +49,7 @@ export default function CurrencyLogo({
return [] return []
}, [currency, uriLocations]) }, [currency, uriLocations])
if (currency === ETHER) { if (currency?.isEther) {
return <StyledEthereumLogo src={EthereumLogo} size={size} style={style} {...rest} /> return <StyledEthereumLogo src={EthereumLogo} size={size} style={style} {...rest} />
} }
......
import JSBI from 'jsbi'
import React from 'react' import React from 'react'
import { CurrencyAmount, Fraction } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Fraction } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk'
const CURRENCY_AMOUNT_MIN = new Fraction(JSBI.BigInt(1), JSBI.BigInt(1000000)) const CURRENCY_AMOUNT_MIN = new Fraction(JSBI.BigInt(1), JSBI.BigInt(1000000))
...@@ -8,7 +8,7 @@ export default function FormattedCurrencyAmount({ ...@@ -8,7 +8,7 @@ export default function FormattedCurrencyAmount({
currencyAmount, currencyAmount,
significantDigits = 4, significantDigits = 4,
}: { }: {
currencyAmount: CurrencyAmount currencyAmount: CurrencyAmount<Currency>
significantDigits?: number significantDigits?: number
}) { }) {
return ( return (
......
import { ChainId, TokenAmount } from '@uniswap/sdk-core' import { ChainId, CurrencyAmount, Token } from '@uniswap/sdk-core'
import React, { useMemo } from 'react' import React, { useMemo } from 'react'
import { X } from 'react-feather' import { X } from 'react-feather'
import styled from 'styled-components' import styled from 'styled-components'
...@@ -45,14 +45,14 @@ export default function UniBalanceContent({ setShowUniBalanceModal }: { setShowU ...@@ -45,14 +45,14 @@ export default function UniBalanceContent({ setShowUniBalanceModal }: { setShowU
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
const total = useAggregateUniBalance() const total = useAggregateUniBalance()
const uniBalance: TokenAmount | undefined = useTokenBalance(account ?? undefined, uni) const uniBalance: CurrencyAmount<Token> | undefined = useTokenBalance(account ?? undefined, uni)
const uniToClaim: TokenAmount | undefined = useTotalUniEarned() const uniToClaim: CurrencyAmount<Token> | undefined = useTotalUniEarned()
const totalSupply: TokenAmount | undefined = useTotalSupply(uni) const totalSupply: CurrencyAmount<Token> | undefined = useTotalSupply(uni)
const uniPrice = useUSDCPrice(uni) const uniPrice = useUSDCPrice(uni)
const blockTimestamp = useCurrentBlockTimestamp() const blockTimestamp = useCurrentBlockTimestamp()
const unclaimedUni = useTokenBalance(useMerkleDistributorContract()?.address, uni) const unclaimedUni = useTokenBalance(useMerkleDistributorContract()?.address, uni)
const circulation: TokenAmount | undefined = useMemo( const circulation: CurrencyAmount<Token> | undefined = useMemo(
() => () =>
blockTimestamp && uni && chainId === ChainId.MAINNET blockTimestamp && uni && chainId === ChainId.MAINNET
? computeUniCirculation(uni, blockTimestamp, unclaimedUni) ? computeUniCirculation(uni, blockTimestamp, unclaimedUni)
......
import { TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { X } from 'react-feather' import { X } from 'react-feather'
import styled, { keyframes } from 'styled-components' import styled, { keyframes } from 'styled-components'
...@@ -65,7 +65,7 @@ export default function ClaimPopup() { ...@@ -65,7 +65,7 @@ export default function ClaimPopup() {
// const userHasAvailableclaim = useUserHasAvailableClaim() // const userHasAvailableclaim = useUserHasAvailableClaim()
const userHasAvailableclaim: boolean = useUserHasAvailableClaim(account) const userHasAvailableclaim: boolean = useUserHasAvailableClaim(account)
const unclaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(account) const unclaimedAmount: CurrencyAmount<Token> | undefined = useUserUnclaimedAmount(account)
// listen for available claim and show popup if needed // listen for available claim and show popup if needed
useEffect(() => { useEffect(() => {
......
import JSBI from 'jsbi'
import React, { useState } from 'react' import React, { useState } from 'react'
import { Percent, TokenAmount } from '@uniswap/sdk-core' import { Percent, CurrencyAmount, Token } from '@uniswap/sdk-core'
import { JSBI, Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import { ChevronDown, ChevronUp } from 'react-feather' import { ChevronDown, ChevronUp } from 'react-feather'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { Text } from 'rebass' import { Text } from 'rebass'
...@@ -38,7 +39,7 @@ interface PositionCardProps { ...@@ -38,7 +39,7 @@ interface PositionCardProps {
pair: Pair pair: Pair
showUnwrapped?: boolean showUnwrapped?: boolean
border?: string border?: string
stakedBalance?: TokenAmount // optional balance to indicate that liquidity is deposited in mining pool stakedBalance?: CurrencyAmount<Token> // optional balance to indicate that liquidity is deposited in mining pool
} }
export default function V2PositionCard({ pair, border, stakedBalance }: PositionCardProps) { export default function V2PositionCard({ pair, border, stakedBalance }: PositionCardProps) {
...@@ -56,8 +57,10 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position ...@@ -56,8 +57,10 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position
const userPoolBalance = stakedBalance ? userDefaultPoolBalance?.add(stakedBalance) : userDefaultPoolBalance const userPoolBalance = stakedBalance ? userDefaultPoolBalance?.add(stakedBalance) : userDefaultPoolBalance
const poolTokenPercentage = const poolTokenPercentage =
!!userPoolBalance && !!totalPoolTokens && JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) !!userPoolBalance &&
? new Percent(userPoolBalance.raw, totalPoolTokens.raw) !!totalPoolTokens &&
JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? new Percent(userPoolBalance.quotient, totalPoolTokens.quotient)
: undefined : undefined
const [token0Deposited, token1Deposited] = const [token0Deposited, token1Deposited] =
...@@ -65,7 +68,7 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position ...@@ -65,7 +68,7 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position
!!totalPoolTokens && !!totalPoolTokens &&
!!userPoolBalance && !!userPoolBalance &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply // this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? [ ? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false),
...@@ -174,7 +177,7 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position ...@@ -174,7 +177,7 @@ export default function V2PositionCard({ pair, border, stakedBalance }: Position
</Text> </Text>
</FixedHeightRow> </FixedHeightRow>
{userDefaultPoolBalance && JSBI.greaterThan(userDefaultPoolBalance.raw, BIG_INT_ZERO) && ( {userDefaultPoolBalance && JSBI.greaterThan(userDefaultPoolBalance.quotient, BIG_INT_ZERO) && (
<RowBetween marginTop="10px"> <RowBetween marginTop="10px">
<ButtonPrimary <ButtonPrimary
padding="8px" padding="8px"
......
import { Percent, TokenAmount } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI, Pair } from '@uniswap/v2-sdk' import { Percent, CurrencyAmount, Token } from '@uniswap/sdk-core'
import { Pair } from '@uniswap/v2-sdk'
import { darken } from 'polished' import { darken } from 'polished'
import React, { useState } from 'react' import React, { useState } from 'react'
import { ChevronDown, ChevronUp } from 'react-feather' import { ChevronDown, ChevronUp } from 'react-feather'
...@@ -49,7 +50,7 @@ interface PositionCardProps { ...@@ -49,7 +50,7 @@ interface PositionCardProps {
pair: Pair pair: Pair
showUnwrapped?: boolean showUnwrapped?: boolean
border?: string border?: string
stakedBalance?: TokenAmount // optional balance to indicate that liquidity is deposited in mining pool stakedBalance?: CurrencyAmount<Token> // optional balance to indicate that liquidity is deposited in mining pool
} }
export function MinimalPositionCard({ pair, showUnwrapped = false, border }: PositionCardProps) { export function MinimalPositionCard({ pair, showUnwrapped = false, border }: PositionCardProps) {
...@@ -64,8 +65,10 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos ...@@ -64,8 +65,10 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos
const totalPoolTokens = useTotalSupply(pair.liquidityToken) const totalPoolTokens = useTotalSupply(pair.liquidityToken)
const poolTokenPercentage = const poolTokenPercentage =
!!userPoolBalance && !!totalPoolTokens && JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) !!userPoolBalance &&
? new Percent(userPoolBalance.raw, totalPoolTokens.raw) !!totalPoolTokens &&
JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? new Percent(userPoolBalance.quotient, totalPoolTokens.quotient)
: undefined : undefined
const [token0Deposited, token1Deposited] = const [token0Deposited, token1Deposited] =
...@@ -73,7 +76,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos ...@@ -73,7 +76,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos
!!totalPoolTokens && !!totalPoolTokens &&
!!userPoolBalance && !!userPoolBalance &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply // this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? [ ? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false),
...@@ -82,7 +85,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos ...@@ -82,7 +85,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos
return ( return (
<> <>
{userPoolBalance && JSBI.greaterThan(userPoolBalance.raw, JSBI.BigInt(0)) ? ( {userPoolBalance && JSBI.greaterThan(userPoolBalance.quotient, JSBI.BigInt(0)) ? (
<GreyCard border={border}> <GreyCard border={border}>
<AutoColumn gap="12px"> <AutoColumn gap="12px">
<FixedHeightRow> <FixedHeightRow>
...@@ -175,8 +178,10 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi ...@@ -175,8 +178,10 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
const userPoolBalance = stakedBalance ? userDefaultPoolBalance?.add(stakedBalance) : userDefaultPoolBalance const userPoolBalance = stakedBalance ? userDefaultPoolBalance?.add(stakedBalance) : userDefaultPoolBalance
const poolTokenPercentage = const poolTokenPercentage =
!!userPoolBalance && !!totalPoolTokens && JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) !!userPoolBalance &&
? new Percent(userPoolBalance.raw, totalPoolTokens.raw) !!totalPoolTokens &&
JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? new Percent(userPoolBalance.quotient, totalPoolTokens.quotient)
: undefined : undefined
const [token0Deposited, token1Deposited] = const [token0Deposited, token1Deposited] =
...@@ -184,7 +189,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi ...@@ -184,7 +189,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
!!totalPoolTokens && !!totalPoolTokens &&
!!userPoolBalance && !!userPoolBalance &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply // this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) JSBI.greaterThanOrEqual(totalPoolTokens.quotient, userPoolBalance.quotient)
? [ ? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false), pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false),
...@@ -296,7 +301,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi ...@@ -296,7 +301,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
View accrued fees and analytics<span style={{ fontSize: '11px' }}></span> View accrued fees and analytics<span style={{ fontSize: '11px' }}></span>
</ExternalLink> </ExternalLink>
</ButtonSecondary> </ButtonSecondary>
{userDefaultPoolBalance && JSBI.greaterThan(userDefaultPoolBalance.raw, BIG_INT_ZERO) && ( {userDefaultPoolBalance && JSBI.greaterThan(userDefaultPoolBalance.quotient, BIG_INT_ZERO) && (
<RowBetween marginTop="10px"> <RowBetween marginTop="10px">
<ButtonPrimary <ButtonPrimary
padding="8px" padding="8px"
...@@ -327,7 +332,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi ...@@ -327,7 +332,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
</ButtonPrimary> </ButtonPrimary>
</RowBetween> </RowBetween>
)} )}
{stakedBalance && JSBI.greaterThan(stakedBalance.raw, BIG_INT_ZERO) && ( {stakedBalance && JSBI.greaterThan(stakedBalance.quotient, BIG_INT_ZERO) && (
<ButtonPrimary <ButtonPrimary
padding="8px" padding="8px"
borderRadius="8px" borderRadius="8px"
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
// import { basisPointsToPercent } from 'utils' // import { basisPointsToPercent } from 'utils'
// import { DAI, WBTC } from '../../constants' // import { DAI, WBTC } from '../../constants'
// import Component, { PositionListProps } from './index' // import Component, { PositionListProps } from './index'
// import { TokenAmount } from '@uniswap/sdk-core' // import { CurrencyAmount } from '@uniswap/sdk-core'
// import JSBI from 'jsbi' // import JSBI from 'jsbi'
// const FEE_BIPS = { // const FEE_BIPS = {
...@@ -12,8 +12,8 @@ ...@@ -12,8 +12,8 @@
// THIRTY: basisPointsToPercent(30), // THIRTY: basisPointsToPercent(30),
// ONE_HUNDRED: basisPointsToPercent(100), // ONE_HUNDRED: basisPointsToPercent(100),
// } // }
// const daiAmount = new TokenAmount(DAI, JSBI.BigInt(500 * 10 ** 18)) // const daiAmount = CurrencyAmount.fromRawAmount(DAI, JSBI.BigInt(500 * 10 ** 18))
// const wbtcAmount = new TokenAmount(WBTC, JSBI.BigInt(10 ** 7)) // const wbtcAmount = CurrencyAmount.fromRawAmount(WBTC, JSBI.BigInt(10 ** 7))
// const positions = [ // const positions = [
// { // {
// feesEarned: { // feesEarned: {
......
...@@ -121,8 +121,8 @@ export interface PositionListItemProps { ...@@ -121,8 +121,8 @@ export interface PositionListItemProps {
export function getPriceOrderingFromPositionForUI( export function getPriceOrderingFromPositionForUI(
position?: Position position?: Position
): { ): {
priceLower?: Price priceLower?: Price<Token, Token>
priceUpper?: Price priceUpper?: Price<Token, Token>
quote?: Token quote?: Token
base?: Token base?: Token
} { } {
...@@ -130,8 +130,8 @@ export function getPriceOrderingFromPositionForUI( ...@@ -130,8 +130,8 @@ export function getPriceOrderingFromPositionForUI(
return {} return {}
} }
const token0 = position.amount0.token const token0 = position.amount0.currency
const token1 = position.amount1.token const token1 = position.amount1.currency
// if token0 is a dollar-stable asset, set it as the quote token // if token0 is a dollar-stable asset, set it as the quote token
const stables = [DAI, USDC, USDT] const stables = [DAI, USDC, USDT]
......
...@@ -13,7 +13,7 @@ import RateToggle from 'components/RateToggle' ...@@ -13,7 +13,7 @@ import RateToggle from 'components/RateToggle'
import DoubleCurrencyLogo from 'components/DoubleLogo' import DoubleCurrencyLogo from 'components/DoubleLogo'
import RangeBadge from 'components/Badge/RangeBadge' import RangeBadge from 'components/Badge/RangeBadge'
import { ThemeContext } from 'styled-components' import { ThemeContext } from 'styled-components'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
export const PositionPreview = ({ export const PositionPreview = ({
position, position,
......
import React from 'react' import React from 'react'
import { Currency, Price } from '@uniswap/sdk-core' import { Currency, Price, Token } from '@uniswap/sdk-core'
import StepCounter from 'components/InputStepCounter/InputStepCounter' import StepCounter from 'components/InputStepCounter/InputStepCounter'
import { RowBetween } from 'components/Row' import { RowBetween } from 'components/Row'
import { useActiveWeb3React } from 'hooks' import { useActiveWeb3React } from 'hooks'
...@@ -19,8 +19,8 @@ export default function RangeSelector({ ...@@ -19,8 +19,8 @@ export default function RangeSelector({
currencyB, currencyB,
feeAmount, feeAmount,
}: { }: {
priceLower?: Price priceLower?: Price<Token, Token>
priceUpper?: Price priceUpper?: Price<Token, Token>
getDecrementLower: () => string getDecrementLower: () => string
getIncrementLower: () => string getIncrementLower: () => string
getDecrementUpper: () => string getDecrementUpper: () => string
......
...@@ -49,7 +49,7 @@ export default function CommonBases({ ...@@ -49,7 +49,7 @@ export default function CommonBases({
onSelect(ETHER) onSelect(ETHER)
} }
}} }}
disable={selectedCurrency === ETHER} disable={selectedCurrency?.isEther}
> >
<CurrencyLogo currency={ETHER} style={{ marginRight: 8 }} /> <CurrencyLogo currency={ETHER} style={{ marginRight: 8 }} />
<Text fontWeight={500} fontSize={16}> <Text fontWeight={500} fontSize={16}>
...@@ -57,7 +57,7 @@ export default function CommonBases({ ...@@ -57,7 +57,7 @@ export default function CommonBases({
</Text> </Text>
</BaseWrapper> </BaseWrapper>
{(typeof chainId === 'number' ? SUGGESTED_BASES[chainId] ?? [] : []).map((token: Token) => { {(typeof chainId === 'number' ? SUGGESTED_BASES[chainId] ?? [] : []).map((token: Token) => {
const selected = selectedCurrency instanceof Token && selectedCurrency.address === token.address const selected = selectedCurrency?.isToken && selectedCurrency.address === token.address
return ( return (
<BaseWrapper onClick={() => !selected && onSelect(token)} disable={selected} key={token.address}> <BaseWrapper onClick={() => !selected && onSelect(token)} disable={selected} key={token.address}>
<CurrencyLogo currency={token} style={{ marginRight: 8 }} /> <CurrencyLogo currency={token} style={{ marginRight: 8 }} />
......
import { Currency, CurrencyAmount, currencyEquals, ETHER, Token } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, currencyEquals, ETHER, Token } from '@uniswap/sdk-core'
import { TokenList } from '@uniswap/token-lists/dist/types'
import React, { CSSProperties, MutableRefObject, useCallback, useMemo } from 'react' import React, { CSSProperties, MutableRefObject, useCallback, useMemo } from 'react'
import { FixedSizeList } from 'react-window' import { FixedSizeList } from 'react-window'
import { Text } from 'rebass' import { Text } from 'rebass'
import styled from 'styled-components' import styled from 'styled-components'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { WrappedTokenInfo, useCombinedActiveList } from '../../state/lists/hooks' import { useCombinedActiveList } from '../../state/lists/hooks'
import { WrappedTokenInfo } from '../../state/lists/wrappedTokenInfo'
import { useCurrencyBalance } from '../../state/wallet/hooks' import { useCurrencyBalance } from '../../state/wallet/hooks'
import { TYPE } from '../../theme' import { TYPE } from '../../theme'
import { useIsUserAddedToken, useAllInactiveTokens } from '../../hooks/Tokens' import { useIsUserAddedToken } from '../../hooks/Tokens'
import Column from '../Column' import Column from '../Column'
import { RowFixed, RowBetween } from '../Row' import { RowFixed, RowBetween } from '../Row'
import CurrencyLogo from '../CurrencyLogo' import CurrencyLogo from '../CurrencyLogo'
...@@ -23,7 +25,7 @@ import QuestionHelper from 'components/QuestionHelper' ...@@ -23,7 +25,7 @@ import QuestionHelper from 'components/QuestionHelper'
import useTheme from 'hooks/useTheme' import useTheme from 'hooks/useTheme'
function currencyKey(currency: Currency): string { function currencyKey(currency: Currency): string {
return currency instanceof Token ? currency.address : currency === ETHER ? 'ETHER' : '' return currency.isToken ? currency.address : 'ETHER'
} }
const StyledBalanceText = styled(Text)` const StyledBalanceText = styled(Text)`
...@@ -55,7 +57,7 @@ const FixedContentRow = styled.div` ...@@ -55,7 +57,7 @@ const FixedContentRow = styled.div`
align-items: center; align-items: center;
` `
function Balance({ balance }: { balance: CurrencyAmount }) { function Balance({ balance }: { balance: CurrencyAmount<Currency> }) {
return <StyledBalanceText title={balance.toExact()}>{balance.toSignificant(4)}</StyledBalanceText> return <StyledBalanceText title={balance.toExact()}>{balance.toSignificant(4)}</StyledBalanceText>
} }
...@@ -143,84 +145,84 @@ function CurrencyRow({ ...@@ -143,84 +145,84 @@ function CurrencyRow({
) )
} }
const BREAK_LINE = 'BREAK'
type BreakLine = typeof BREAK_LINE
function isBreakLine(x: unknown): x is BreakLine {
return x === BREAK_LINE
}
function BreakLineComponent({ style }: { style: CSSProperties }) {
const theme = useTheme()
return (
<FixedContentRow style={style}>
<LightGreyCard padding="8px 12px" borderRadius="8px">
<RowBetween>
<RowFixed>
<TokenListLogoWrapper src={TokenListLogo} />
<TYPE.main ml="6px" fontSize="12px" color={theme.text1}>
Expanded results from inactive Token Lists
</TYPE.main>
</RowFixed>
<QuestionHelper text="Tokens from inactive lists. Import specific tokens below or click 'Manage' to activate more lists." />
</RowBetween>
</LightGreyCard>
</FixedContentRow>
)
}
export default function CurrencyList({ export default function CurrencyList({
height, height,
currencies, currencies,
otherListTokens,
selectedCurrency, selectedCurrency,
onCurrencySelect, onCurrencySelect,
otherCurrency, otherCurrency,
fixedListRef, fixedListRef,
showETH,
showImportView, showImportView,
setImportToken, setImportToken,
breakIndex,
}: { }: {
height: number height: number
currencies: Currency[] currencies: Currency[]
otherListTokens?: WrappedTokenInfo[]
selectedCurrency?: Currency | null selectedCurrency?: Currency | null
onCurrencySelect: (currency: Currency) => void onCurrencySelect: (currency: Currency) => void
otherCurrency?: Currency | null otherCurrency?: Currency | null
fixedListRef?: MutableRefObject<FixedSizeList | undefined> fixedListRef?: MutableRefObject<FixedSizeList | undefined>
showETH: boolean
showImportView: () => void showImportView: () => void
setImportToken: (token: Token) => void setImportToken: (token: Token) => void
breakIndex: number | undefined
}) { }) {
const itemData: (Currency | undefined)[] = useMemo(() => { const itemData: (Currency | BreakLine)[] = useMemo(() => {
let formatted: (Currency | undefined)[] = showETH ? [Currency.ETHER, ...currencies] : currencies if (otherListTokens && otherListTokens?.length > 0) {
if (breakIndex !== undefined) { return [...currencies, BREAK_LINE, ...otherListTokens]
formatted = [...formatted.slice(0, breakIndex), undefined, ...formatted.slice(breakIndex, formatted.length)]
} }
return formatted return currencies
}, [breakIndex, currencies, showETH]) }, [currencies, otherListTokens])
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const theme = useTheme()
const inactiveTokens: {
[address: string]: Token
} = useAllInactiveTokens()
const Row = useCallback( const Row = useCallback(
({ data, index, style }) => { function TokenRow({ data, index, style }) {
const currency: Currency = data[index] const row: Currency | BreakLine = data[index]
const isSelected = Boolean(selectedCurrency && currencyEquals(selectedCurrency, currency))
const otherSelected = Boolean(otherCurrency && currencyEquals(otherCurrency, currency))
const handleSelect = () => onCurrencySelect(currency)
const token = wrappedCurrency(currency, chainId) if (isBreakLine(row)) {
return <BreakLineComponent style={style} />
}
const showImport = inactiveTokens && token && Object.keys(inactiveTokens).includes(token.address) const currency = row
if (index === breakIndex || !data) { const isSelected = Boolean(currency && selectedCurrency && currencyEquals(selectedCurrency, currency))
return ( const otherSelected = Boolean(currency && otherCurrency && currencyEquals(otherCurrency, currency))
<FixedContentRow style={style}> const handleSelect = () => currency && onCurrencySelect(currency)
<LightGreyCard padding="8px 12px" borderRadius="8px">
<RowBetween> const token = wrappedCurrency(currency, chainId)
<RowFixed>
<TokenListLogoWrapper src={TokenListLogo} /> const showImport = index > currencies.length
<TYPE.main ml="6px" fontSize="12px" color={theme.text1}>
Expanded results from inactive Token Lists
</TYPE.main>
</RowFixed>
<QuestionHelper text="Tokens from inactive lists. Import specific tokens below or click 'Manage' to activate more lists." />
</RowBetween>
</LightGreyCard>
</FixedContentRow>
)
}
if (showImport && token) { if (showImport && token) {
return ( return (
<ImportRow <ImportRow style={style} token={token} showImportView={showImportView} setImportToken={setImportToken} dim />
style={style}
token={token}
showImportView={showImportView}
setImportToken={setImportToken}
dim={true}
/>
) )
} else { } else if (currency) {
return ( return (
<CurrencyRow <CurrencyRow
style={style} style={style}
...@@ -230,22 +232,18 @@ export default function CurrencyList({ ...@@ -230,22 +232,18 @@ export default function CurrencyList({
otherSelected={otherSelected} otherSelected={otherSelected}
/> />
) )
} else {
return null
} }
}, },
[ [chainId, currencies.length, onCurrencySelect, otherCurrency, selectedCurrency, setImportToken, showImportView]
chainId,
inactiveTokens,
onCurrencySelect,
otherCurrency,
selectedCurrency,
setImportToken,
showImportView,
breakIndex,
theme.text1,
]
) )
const itemKey = useCallback((index: number, data: any) => currencyKey(data[index]), []) const itemKey = useCallback((index: number, data: typeof itemData) => {
const currency = data[index]
if (isBreakLine(currency)) return BREAK_LINE
return currencyKey(currency)
}, [])
return ( return (
<FixedSizeList <FixedSizeList
......
...@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next' ...@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next'
import { FixedSizeList } from 'react-window' import { FixedSizeList } from 'react-window'
import { Text } from 'rebass' import { Text } from 'rebass'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { useAllTokens, useToken, useIsUserAddedToken, useFoundOnInactiveList } from '../../hooks/Tokens' import { useAllTokens, useToken, useIsUserAddedToken, useSearchInactiveTokenLists } from '../../hooks/Tokens'
import { CloseIcon, TYPE, ButtonText, IconWrapper } from '../../theme' import { CloseIcon, TYPE, ButtonText, IconWrapper } from '../../theme'
import { isAddress } from '../../utils' import { isAddress } from '../../utils'
import Column from '../Column' import Column from '../Column'
...@@ -94,11 +94,6 @@ export function CurrencySearch({ ...@@ -94,11 +94,6 @@ export function CurrencySearch({
} }
}, [isAddressSearch]) }, [isAddressSearch])
const showETH: boolean = useMemo(() => {
const s = debouncedQuery.toLowerCase().trim()
return s === '' || s === 'e' || s === 'et' || s === 'eth'
}, [debouncedQuery])
const tokenComparator = useTokenComparator(invertSearchOrder) const tokenComparator = useTokenComparator(invertSearchOrder)
const filteredTokens: Token[] = useMemo(() => { const filteredTokens: Token[] = useMemo(() => {
...@@ -111,6 +106,14 @@ export function CurrencySearch({ ...@@ -111,6 +106,14 @@ export function CurrencySearch({
const filteredSortedTokens = useSortedTokensByQuery(sortedTokens, debouncedQuery) const filteredSortedTokens = useSortedTokensByQuery(sortedTokens, debouncedQuery)
const filteredSortedTokensWithETH: Currency[] = useMemo(() => {
const s = debouncedQuery.toLowerCase().trim()
if (s === '' || s === 'e' || s === 'et' || s === 'eth') {
return [ETHER, ...filteredSortedTokens]
}
return filteredSortedTokens
}, [debouncedQuery, filteredSortedTokens])
const handleCurrencySelect = useCallback( const handleCurrencySelect = useCallback(
(currency: Currency) => { (currency: Currency) => {
onCurrencySelect(currency) onCurrencySelect(currency)
...@@ -139,17 +142,17 @@ export function CurrencySearch({ ...@@ -139,17 +142,17 @@ export function CurrencySearch({
const s = debouncedQuery.toLowerCase().trim() const s = debouncedQuery.toLowerCase().trim()
if (s === 'eth') { if (s === 'eth') {
handleCurrencySelect(ETHER) handleCurrencySelect(ETHER)
} else if (filteredSortedTokens.length > 0) { } else if (filteredSortedTokensWithETH.length > 0) {
if ( if (
filteredSortedTokens[0].symbol?.toLowerCase() === debouncedQuery.trim().toLowerCase() || filteredSortedTokensWithETH[0].symbol?.toLowerCase() === debouncedQuery.trim().toLowerCase() ||
filteredSortedTokens.length === 1 filteredSortedTokensWithETH.length === 1
) { ) {
handleCurrencySelect(filteredSortedTokens[0]) handleCurrencySelect(filteredSortedTokensWithETH[0])
} }
} }
} }
}, },
[filteredSortedTokens, handleCurrencySelect, debouncedQuery] [filteredSortedTokensWithETH, handleCurrencySelect, debouncedQuery]
) )
// menu ui // menu ui
...@@ -158,8 +161,9 @@ export function CurrencySearch({ ...@@ -158,8 +161,9 @@ export function CurrencySearch({
useOnClickOutside(node, open ? toggle : undefined) useOnClickOutside(node, open ? toggle : undefined)
// if no results on main list, show option to expand into inactive // if no results on main list, show option to expand into inactive
const inactiveTokens = useFoundOnInactiveList(debouncedQuery) const filteredInactiveTokens = useSearchInactiveTokenLists(
const filteredInactiveTokens: Token[] = useSortedTokensByQuery(inactiveTokens, debouncedQuery) filteredTokens.length === 0 || (debouncedQuery.length > 2 && !isAddressSearch) ? debouncedQuery : undefined
)
return ( return (
<ContentWrapper> <ContentWrapper>
...@@ -197,11 +201,8 @@ export function CurrencySearch({ ...@@ -197,11 +201,8 @@ export function CurrencySearch({
{({ height }) => ( {({ height }) => (
<CurrencyList <CurrencyList
height={height} height={height}
showETH={showETH} currencies={filteredSortedTokensWithETH}
currencies={ otherListTokens={filteredInactiveTokens}
filteredInactiveTokens ? filteredSortedTokens.concat(filteredInactiveTokens) : filteredSortedTokens
}
breakIndex={inactiveTokens && filteredSortedTokens ? filteredSortedTokens.length : undefined}
onCurrencySelect={handleCurrencySelect} onCurrencySelect={handleCurrencySelect}
otherCurrency={otherSelectedCurrency} otherCurrency={otherSelectedCurrency}
selectedCurrency={selectedCurrency} selectedCurrency={selectedCurrency}
......
import { TokenList } from '@uniswap/token-lists/dist/types'
import React, { CSSProperties } from 'react' import React, { CSSProperties } from 'react'
import { Token } from '@uniswap/sdk-core' import { Token } from '@uniswap/sdk-core'
import { AutoRow, RowFixed } from 'components/Row' import { AutoRow, RowFixed } from 'components/Row'
...@@ -5,8 +6,6 @@ import { AutoColumn } from 'components/Column' ...@@ -5,8 +6,6 @@ import { AutoColumn } from 'components/Column'
import CurrencyLogo from 'components/CurrencyLogo' import CurrencyLogo from 'components/CurrencyLogo'
import { TYPE } from 'theme' import { TYPE } from 'theme'
import ListLogo from 'components/ListLogo' import ListLogo from 'components/ListLogo'
import { useActiveWeb3React } from 'hooks'
import { useCombinedInactiveList } from 'state/lists/hooks'
import useTheme from 'hooks/useTheme' import useTheme from 'hooks/useTheme'
import { ButtonPrimary } from 'components/Button' import { ButtonPrimary } from 'components/Button'
import styled from 'styled-components' import styled from 'styled-components'
...@@ -44,23 +43,19 @@ export default function ImportRow({ ...@@ -44,23 +43,19 @@ export default function ImportRow({
token, token,
style, style,
dim, dim,
list,
showImportView, showImportView,
setImportToken, setImportToken,
}: { }: {
token: Token token: Token
style?: CSSProperties style?: CSSProperties
dim?: boolean dim?: boolean
list?: TokenList
showImportView: () => void showImportView: () => void
setImportToken: (token: Token) => void setImportToken: (token: Token) => void
}) { }) {
// gloabls
const { chainId } = useActiveWeb3React()
const theme = useTheme() const theme = useTheme()
// check if token comes from list
const inactiveTokenList = useCombinedInactiveList()
const list = chainId && inactiveTokenList?.[chainId]?.[token.address]?.list
// check if already active on list or local storage tokens // check if already active on list or local storage tokens
const isAdded = useIsUserAddedToken(token) const isAdded = useIsUserAddedToken(token)
const isActive = useIsTokenActive(token) const isActive = useIsTokenActive(token)
......
import { TokenList } from '@uniswap/token-lists/dist/types'
import React from 'react' import React from 'react'
import { Token, Currency } from '@uniswap/sdk-core' import { Token, Currency } from '@uniswap/sdk-core'
import styled from 'styled-components' import styled from 'styled-components'
...@@ -15,7 +16,6 @@ import { useAddUserToken } from 'state/user/hooks' ...@@ -15,7 +16,6 @@ import { useAddUserToken } from 'state/user/hooks'
import { getEtherscanLink } from 'utils' import { getEtherscanLink } from 'utils'
import { useActiveWeb3React } from 'hooks' import { useActiveWeb3React } from 'hooks'
import { ExternalLink } from '../../theme/components' import { ExternalLink } from '../../theme/components'
import { useCombinedInactiveList } from 'state/lists/hooks'
import ListLogo from 'components/ListLogo' import ListLogo from 'components/ListLogo'
import { PaddedColumn } from './styleds' import { PaddedColumn } from './styleds'
...@@ -41,28 +41,26 @@ const AddressText = styled(TYPE.blue)` ...@@ -41,28 +41,26 @@ const AddressText = styled(TYPE.blue)`
interface ImportProps { interface ImportProps {
tokens: Token[] tokens: Token[]
list?: TokenList
onBack?: () => void onBack?: () => void
onDismiss?: () => void onDismiss?: () => void
handleCurrencySelect?: (currency: Currency) => void handleCurrencySelect?: (currency: Currency) => void
} }
export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }: ImportProps) { export function ImportToken({ tokens, list, onBack, onDismiss, handleCurrencySelect }: ImportProps) {
const theme = useTheme() const theme = useTheme()
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const addToken = useAddUserToken() const addToken = useAddUserToken()
// use for showing import source on inactive tokens
const inactiveTokenList = useCombinedInactiveList()
return ( return (
<Wrapper> <Wrapper>
<PaddedColumn gap="14px" style={{ width: '100%', flex: '1 1' }}> <PaddedColumn gap="14px" style={{ width: '100%', flex: '1 1' }}>
<RowBetween> <RowBetween>
{onBack ? <ArrowLeft style={{ cursor: 'pointer' }} onClick={onBack} /> : <div></div>} {onBack ? <ArrowLeft style={{ cursor: 'pointer' }} onClick={onBack} /> : <div />}
<TYPE.mediumHeader>Import {tokens.length > 1 ? 'Tokens' : 'Token'}</TYPE.mediumHeader> <TYPE.mediumHeader>Import {tokens.length > 1 ? 'Tokens' : 'Token'}</TYPE.mediumHeader>
{onDismiss ? <CloseIcon onClick={onDismiss} /> : <div></div>} {onDismiss ? <CloseIcon onClick={onDismiss} /> : <div />}
</RowBetween> </RowBetween>
</PaddedColumn> </PaddedColumn>
<SectionBreak /> <SectionBreak />
...@@ -76,7 +74,6 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }: ...@@ -76,7 +74,6 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }:
</TYPE.body> </TYPE.body>
</AutoColumn> </AutoColumn>
{tokens.map((token) => { {tokens.map((token) => {
const list = chainId && inactiveTokenList?.[chainId]?.[token.address]?.list
return ( return (
<Card <Card
backgroundColor={theme.bg2} backgroundColor={theme.bg2}
......
import { TokenInfo } from '@uniswap/token-lists'
import { useMemo } from 'react' import { useMemo } from 'react'
import { isAddress } from '../../utils' import { isAddress } from '../../utils'
import { Token } from '@uniswap/sdk-core' import { Token } from '@uniswap/sdk-core'
export function filterTokens(tokens: Token[], search: string): Token[] { export function filterTokens<T extends Token | TokenInfo>(tokens: T[], search: string): T[] {
if (search.length === 0) return tokens if (search.length === 0) return tokens
const searchingAddress = isAddress(search) const searchingAddress = isAddress(search)
......
import { Token, TokenAmount } from '@uniswap/sdk-core' import { Token, CurrencyAmount, Currency } from '@uniswap/sdk-core'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useAllTokenBalances } from '../../state/wallet/hooks' import { useAllTokenBalances } from '../../state/wallet/hooks'
// compare two token amounts with highest one coming first // compare two token amounts with highest one coming first
function balanceComparator(balanceA?: TokenAmount, balanceB?: TokenAmount) { function balanceComparator(balanceA?: CurrencyAmount<Currency>, balanceB?: CurrencyAmount<Currency>) {
if (balanceA && balanceB) { if (balanceA && balanceB) {
return balanceA.greaterThan(balanceB) ? -1 : balanceA.equalTo(balanceB) ? 0 : 1 return balanceA.greaterThan(balanceB) ? -1 : balanceA.equalTo(balanceB) ? 0 : 1
} else if (balanceA && balanceA.greaterThan('0')) { } else if (balanceA && balanceA.greaterThan('0')) {
...@@ -15,7 +15,7 @@ function balanceComparator(balanceA?: TokenAmount, balanceB?: TokenAmount) { ...@@ -15,7 +15,7 @@ function balanceComparator(balanceA?: TokenAmount, balanceB?: TokenAmount) {
} }
function getTokenComparator(balances: { function getTokenComparator(balances: {
[tokenAddress: string]: TokenAmount | undefined [tokenAddress: string]: CurrencyAmount<Currency> | undefined
}): (tokenA: Token, tokenB: Token) => number { }): (tokenA: Token, tokenB: Token) => number {
return function sortTokens(tokenA: Token, tokenB: Token): number { return function sortTokens(tokenA: Token, tokenB: Token): number {
// -1 = a is first // -1 = a is first
......
...@@ -17,7 +17,7 @@ import { isAddress } from 'ethers/lib/utils' ...@@ -17,7 +17,7 @@ import { isAddress } from 'ethers/lib/utils'
import Confetti from '../Confetti' import Confetti from '../Confetti'
import { CardNoise, CardBGImage, CardBGImageSmaller } from '../earn/styled' import { CardNoise, CardBGImage, CardBGImageSmaller } from '../earn/styled'
import { useIsTransactionPending } from '../../state/transactions/hooks' import { useIsTransactionPending } from '../../state/transactions/hooks'
import { TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import { getEtherscanLink, shortenAddress } from '../../utils' import { getEtherscanLink, shortenAddress } from '../../utils'
const ContentWrapper = styled(AutoColumn)` const ContentWrapper = styled(AutoColumn)`
...@@ -59,7 +59,7 @@ export default function AddressClaimModal({ isOpen, onDismiss }: { isOpen: boole ...@@ -59,7 +59,7 @@ export default function AddressClaimModal({ isOpen, onDismiss }: { isOpen: boole
// monitor the status of the claim from contracts and txns // monitor the status of the claim from contracts and txns
const { claimCallback } = useClaimCallback(parsedAddress) const { claimCallback } = useClaimCallback(parsedAddress)
const unclaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(parsedAddress) const unclaimedAmount: CurrencyAmount<Token> | undefined = useUserUnclaimedAmount(parsedAddress)
// check if the user has something available // check if the user has something available
const hasAvailableClaim = useUserHasAvailableClaim(parsedAddress) const hasAvailableClaim = useUserHasAvailableClaim(parsedAddress)
......
import { TokenAmount } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI } from '@uniswap/v2-sdk' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import { isAddress } from 'ethers/lib/utils' import { isAddress } from 'ethers/lib/utils'
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { Text } from 'rebass' import { Text } from 'rebass'
...@@ -60,7 +60,7 @@ export default function ClaimModal() { ...@@ -60,7 +60,7 @@ export default function ClaimModal() {
// monitor the status of the claim from contracts and txns // monitor the status of the claim from contracts and txns
const { claimCallback } = useClaimCallback(account) const { claimCallback } = useClaimCallback(account)
const unclaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(account) const unclaimedAmount: CurrencyAmount<Token> | undefined = useUserUnclaimedAmount(account)
const { claimSubmitted, claimTxn } = useUserHasSubmittedClaim(account ?? undefined) const { claimSubmitted, claimTxn } = useUserHasSubmittedClaim(account ?? undefined)
const claimConfirmed = Boolean(claimTxn?.receipt) const claimConfirmed = Boolean(claimTxn?.receipt)
...@@ -116,12 +116,12 @@ export default function ClaimModal() { ...@@ -116,12 +116,12 @@ export default function ClaimModal() {
)} )}
{userClaimData?.flags?.isLP && {userClaimData?.flags?.isLP &&
unclaimedAmount && unclaimedAmount &&
JSBI.greaterThanOrEqual(unclaimedAmount.raw, nonLPAmount) && ( JSBI.greaterThanOrEqual(unclaimedAmount.quotient, nonLPAmount) && (
<RowBetween> <RowBetween>
<TYPE.subHeader color="white">Liquidity</TYPE.subHeader> <TYPE.subHeader color="white">Liquidity</TYPE.subHeader>
<TYPE.subHeader color="white"> <TYPE.subHeader color="white">
{unclaimedAmount {unclaimedAmount
.subtract(new TokenAmount(unclaimedAmount.token, nonLPAmount)) .subtract(CurrencyAmount.fromRawAmount(unclaimedAmount.currency, nonLPAmount))
.toFixed(0, { groupSeparator: ',' })}{' '} .toFixed(0, { groupSeparator: ',' })}{' '}
UNI UNI
</TYPE.subHeader> </TYPE.subHeader>
......
...@@ -4,8 +4,8 @@ import { RowBetween } from '../Row' ...@@ -4,8 +4,8 @@ import { RowBetween } from '../Row'
import styled from 'styled-components' import styled from 'styled-components'
import { TYPE, StyledInternalLink } from '../../theme' import { TYPE, StyledInternalLink } from '../../theme'
import DoubleCurrencyLogo from '../DoubleLogo' import DoubleCurrencyLogo from '../DoubleLogo'
import { ETHER, TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { ButtonPrimary } from '../Button' import { ButtonPrimary } from '../Button'
import { StakingInfo } from '../../state/stake/hooks' import { StakingInfo } from '../../state/stake/hooks'
import { useColor } from '../../hooks/useColor' import { useColor } from '../../hooks/useColor'
...@@ -79,25 +79,27 @@ export default function PoolCard({ stakingInfo }: { stakingInfo: StakingInfo }) ...@@ -79,25 +79,27 @@ export default function PoolCard({ stakingInfo }: { stakingInfo: StakingInfo })
const isStaking = Boolean(stakingInfo.stakedAmount.greaterThan('0')) const isStaking = Boolean(stakingInfo.stakedAmount.greaterThan('0'))
// get the color of the token // get the color of the token
const token = currency0 === ETHER ? token1 : token0 const token = currency0.isEther ? token1 : token0
const WETH = currency0 === ETHER ? token0 : token1 const WETH = currency0.isEther ? token0 : token1
const backgroundColor = useColor(token) const backgroundColor = useColor(token)
const totalSupplyOfStakingToken = useTotalSupply(stakingInfo.stakedAmount.token) const totalSupplyOfStakingToken = useTotalSupply(
stakingInfo.stakedAmount.currency.isToken ? stakingInfo.stakedAmount.currency : undefined
)
const [, stakingTokenPair] = useV2Pair(...stakingInfo.tokens) const [, stakingTokenPair] = useV2Pair(...stakingInfo.tokens)
// let returnOverMonth: Percent = new Percent('0') // let returnOverMonth: Percent = new Percent('0')
let valueOfTotalStakedAmountInWETH: TokenAmount | undefined let valueOfTotalStakedAmountInWETH: CurrencyAmount<Token> | undefined
if (totalSupplyOfStakingToken && stakingTokenPair) { if (totalSupplyOfStakingToken && stakingTokenPair) {
// take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens // take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens
valueOfTotalStakedAmountInWETH = new TokenAmount( valueOfTotalStakedAmountInWETH = CurrencyAmount.fromRawAmount(
WETH, WETH,
JSBI.divide( JSBI.divide(
JSBI.multiply( JSBI.multiply(
JSBI.multiply(stakingInfo.totalStakedAmount.raw, stakingTokenPair.reserveOf(WETH).raw), JSBI.multiply(stakingInfo.totalStakedAmount.quotient, stakingTokenPair.reserveOf(WETH).quotient),
JSBI.BigInt(2) // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to JSBI.BigInt(2) // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to
), ),
totalSupplyOfStakingToken.raw totalSupplyOfStakingToken.quotient
) )
) )
} }
......
...@@ -11,7 +11,7 @@ import { ButtonConfirmed, ButtonError } from '../Button' ...@@ -11,7 +11,7 @@ import { ButtonConfirmed, ButtonError } from '../Button'
import ProgressCircles from '../ProgressSteps' import ProgressCircles from '../ProgressSteps'
import CurrencyInputPanel from '../CurrencyInputPanel' import CurrencyInputPanel from '../CurrencyInputPanel'
import { Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import { TokenAmount } from '@uniswap/sdk-core' import { Token, CurrencyAmount } from '@uniswap/sdk-core'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { maxAmountSpend } from '../../utils/maxAmountSpend' import { maxAmountSpend } from '../../utils/maxAmountSpend'
import { usePairContract, useStakingContract } from '../../hooks/useContract' import { usePairContract, useStakingContract } from '../../hooks/useContract'
...@@ -40,7 +40,7 @@ interface StakingModalProps { ...@@ -40,7 +40,7 @@ interface StakingModalProps {
isOpen: boolean isOpen: boolean
onDismiss: () => void onDismiss: () => void
stakingInfo: StakingInfo stakingInfo: StakingInfo
userLiquidityUnstaked: TokenAmount | undefined userLiquidityUnstaked: CurrencyAmount<Token> | undefined
} }
export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiquidityUnstaked }: StakingModalProps) { export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiquidityUnstaked }: StakingModalProps) {
...@@ -48,10 +48,14 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui ...@@ -48,10 +48,14 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
// track and parse user input // track and parse user input
const [typedValue, setTypedValue] = useState('') const [typedValue, setTypedValue] = useState('')
const { parsedAmount, error } = useDerivedStakeInfo(typedValue, stakingInfo.stakedAmount.token, userLiquidityUnstaked) const { parsedAmount, error } = useDerivedStakeInfo(
typedValue,
stakingInfo.stakedAmount.currency.isToken ? stakingInfo.stakedAmount.currency : undefined,
userLiquidityUnstaked
)
const parsedAmountWrapped = wrappedCurrencyAmount(parsedAmount, chainId) const parsedAmountWrapped = wrappedCurrencyAmount(parsedAmount, chainId)
let hypotheticalRewardRate: TokenAmount = new TokenAmount(stakingInfo.rewardRate.token, '0') let hypotheticalRewardRate: CurrencyAmount<Token> = CurrencyAmount.fromRawAmount(stakingInfo.rewardRate.currency, '0')
if (parsedAmountWrapped?.greaterThan('0')) { if (parsedAmountWrapped?.greaterThan('0')) {
hypotheticalRewardRate = stakingInfo.getHypotheticalRewardRate( hypotheticalRewardRate = stakingInfo.getHypotheticalRewardRate(
stakingInfo.stakedAmount.add(parsedAmountWrapped), stakingInfo.stakedAmount.add(parsedAmountWrapped),
...@@ -71,7 +75,10 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui ...@@ -71,7 +75,10 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
}, [onDismiss]) }, [onDismiss])
// pair contract for this token to be staked // pair contract for this token to be staked
const dummyPair = new Pair(new TokenAmount(stakingInfo.tokens[0], '0'), new TokenAmount(stakingInfo.tokens[1], '0')) const dummyPair = new Pair(
CurrencyAmount.fromRawAmount(stakingInfo.tokens[0], '0'),
CurrencyAmount.fromRawAmount(stakingInfo.tokens[1], '0')
)
const pairContract = usePairContract(dummyPair.liquidityToken.address) const pairContract = usePairContract(dummyPair.liquidityToken.address)
// approval data for stake // approval data for stake
...@@ -84,11 +91,11 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui ...@@ -84,11 +91,11 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
setAttempting(true) setAttempting(true)
if (stakingContract && parsedAmount && deadline) { if (stakingContract && parsedAmount && deadline) {
if (approval === ApprovalState.APPROVED) { if (approval === ApprovalState.APPROVED) {
await stakingContract.stake(`0x${parsedAmount.raw.toString(16)}`, { gasLimit: 350000 }) await stakingContract.stake(`0x${parsedAmount.quotient.toString(16)}`, { gasLimit: 350000 })
} else if (signatureData) { } else if (signatureData) {
stakingContract stakingContract
.stakeWithPermit( .stakeWithPermit(
`0x${parsedAmount.raw.toString(16)}`, `0x${parsedAmount.quotient.toString(16)}`,
signatureData.deadline, signatureData.deadline,
signatureData.v, signatureData.v,
signatureData.r, signatureData.r,
...@@ -155,7 +162,7 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui ...@@ -155,7 +162,7 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
onUserInput={onUserInput} onUserInput={onUserInput}
onMax={handleMax} onMax={handleMax}
showMaxButton={!atMaxAmount} showMaxButton={!atMaxAmount}
currency={stakingInfo.stakedAmount.token} currency={stakingInfo.stakedAmount.currency}
pair={dummyPair} pair={dummyPair}
label={''} label={''}
customBalanceText={'Available to deposit: '} customBalanceText={'Available to deposit: '}
......
import { Percent } from '@uniswap/sdk-core' import { Percent, Currency, TradeType } 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 } from '@uniswap/v3-sdk'
import React, { useContext } from 'react' import React, { useContext } from 'react'
...@@ -12,7 +12,7 @@ import FormattedPriceImpact from './FormattedPriceImpact' ...@@ -12,7 +12,7 @@ import FormattedPriceImpact from './FormattedPriceImpact'
import SwapRoute from './SwapRoute' import SwapRoute from './SwapRoute'
export interface AdvancedSwapDetailsProps { export interface AdvancedSwapDetailsProps {
trade?: V2Trade | V3Trade trade?: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
allowedSlippage: Percent allowedSlippage: Percent
} }
......
import { currencyEquals, Percent } from '@uniswap/sdk-core' import { Currency, currencyEquals, Percent, TradeType } 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 } from '@uniswap/v3-sdk'
import React, { useCallback, useMemo } from 'react' import React, { useCallback, useMemo } from 'react'
...@@ -13,7 +13,11 @@ import SwapModalHeader from './SwapModalHeader' ...@@ -13,7 +13,11 @@ import SwapModalHeader from './SwapModalHeader'
* Returns true if the trade requires a confirmation of details before we can submit it * Returns true if the trade requires a confirmation of details before we can submit it
* @param args either a pair of V2 trades or a pair of V3 trades * @param args either a pair of V2 trades or a pair of V3 trades
*/ */
function tradeMeaningfullyDiffers(...args: [V2Trade, V2Trade] | [V3Trade, V3Trade]): boolean { function tradeMeaningfullyDiffers(
...args:
| [V2Trade<Currency, Currency, TradeType>, V2Trade<Currency, Currency, TradeType>]
| [V3Trade<Currency, Currency, TradeType>, V3Trade<Currency, Currency, TradeType>]
): boolean {
const [tradeA, tradeB] = args const [tradeA, tradeB] = args
return ( return (
tradeA.tradeType !== tradeB.tradeType || tradeA.tradeType !== tradeB.tradeType ||
...@@ -38,8 +42,8 @@ export default function ConfirmSwapModal({ ...@@ -38,8 +42,8 @@ export default function ConfirmSwapModal({
txHash, txHash,
}: { }: {
isOpen: boolean isOpen: boolean
trade: V2Trade | V3Trade | undefined trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined
originalTrade: V2Trade | V3Trade | undefined originalTrade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined
attemptingTxn: boolean attemptingTxn: boolean
txHash: string | undefined txHash: string | undefined
recipient: string | null recipient: string | null
......
import { Currency, TradeType } 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 } from '@uniswap/v3-sdk'
...@@ -12,7 +13,7 @@ export default function SwapModalFooter({ ...@@ -12,7 +13,7 @@ export default function SwapModalFooter({
swapErrorMessage, swapErrorMessage,
disabledConfirm, disabledConfirm,
}: { }: {
trade: V2Trade | V3Trade trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
onConfirm: () => void onConfirm: () => void
swapErrorMessage: string | undefined swapErrorMessage: string | undefined
disabledConfirm: boolean disabledConfirm: boolean
......
import { Percent, TradeType } from '@uniswap/sdk-core' import { Currency, Percent, TradeType } 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 } from '@uniswap/v3-sdk'
import React, { useContext, useState } from 'react' import React, { useContext, useState } from 'react'
...@@ -47,7 +47,7 @@ export default function SwapModalHeader({ ...@@ -47,7 +47,7 @@ export default function SwapModalHeader({
showAcceptChanges, showAcceptChanges,
onAcceptChanges, onAcceptChanges,
}: { }: {
trade: V2Trade | V3Trade trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
allowedSlippage: Percent allowedSlippage: Percent
recipient: string | null recipient: string | null
showAcceptChanges: boolean showAcceptChanges: boolean
......
import { Currency, TradeType } from '@uniswap/sdk-core'
import { Trade as V2Trade } from '@uniswap/v2-sdk' import { Trade as V2Trade } from '@uniswap/v2-sdk'
import { Trade as V3Trade, FeeAmount } 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'
...@@ -14,7 +15,11 @@ function LabeledArrow({}: { fee: FeeAmount }) { ...@@ -14,7 +15,11 @@ function LabeledArrow({}: { fee: FeeAmount }) {
return <ChevronRight size={14} color={theme.text2} /> return <ChevronRight size={14} color={theme.text2} />
} }
export default memo(function SwapRoute({ trade }: { trade: V2Trade | V3Trade }) { export default memo(function SwapRoute({
trade,
}: {
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
}) {
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 (
......
import React, { useCallback } from 'react' import React, { useCallback } from 'react'
import { Price } from '@uniswap/sdk-core' import { Price, Currency } from '@uniswap/sdk-core'
import { useContext } from 'react' import { useContext } from 'react'
import { Text } from 'rebass' import { Text } from 'rebass'
import styled, { ThemeContext } from 'styled-components' import styled, { ThemeContext } from 'styled-components'
interface TradePriceProps { interface TradePriceProps {
price: Price price: Price<Currency, Currency>
showInverted: boolean showInverted: boolean
setShowInverted: (showInverted: boolean) => void setShowInverted: (showInverted: boolean) => void
} }
......
...@@ -12,7 +12,7 @@ import Circle from '../../assets/images/blue-loader.svg' ...@@ -12,7 +12,7 @@ import Circle from '../../assets/images/blue-loader.svg'
import { useVoteCallback, useUserVotes } from '../../state/governance/hooks' import { useVoteCallback, useUserVotes } from '../../state/governance/hooks'
import { getEtherscanLink } from '../../utils' import { getEtherscanLink } from '../../utils'
import { ExternalLink } from '../../theme/components' import { ExternalLink } from '../../theme/components'
import { TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
const ContentWrapper = styled(AutoColumn)` const ContentWrapper = styled(AutoColumn)`
width: 100%; width: 100%;
...@@ -48,7 +48,7 @@ export default function VoteModal({ isOpen, onDismiss, proposalId, support }: Vo ...@@ -48,7 +48,7 @@ export default function VoteModal({ isOpen, onDismiss, proposalId, support }: Vo
}: { }: {
voteCallback: (proposalId: string | undefined, support: boolean) => Promise<string> | undefined voteCallback: (proposalId: string | undefined, support: boolean) => Promise<string> | undefined
} = useVoteCallback() } = useVoteCallback()
const availableVotes: TokenAmount | undefined = useUserVotes() const availableVotes: CurrencyAmount<Token> | undefined = useUserVotes()
// monitor call to help UI loading state // monitor call to help UI loading state
const [hash, setHash] = useState<string | undefined>() const [hash, setHash] = useState<string | undefined>()
......
import { TokenAddressMap, useUnsupportedTokenList } from './../state/lists/hooks'
import { parseBytes32String } from '@ethersproject/strings' import { parseBytes32String } from '@ethersproject/strings'
import { Currency, ETHER, Token, currencyEquals } from '@uniswap/sdk-core' import { Currency, currencyEquals, ETHER, Token } from '@uniswap/sdk-core'
import { TokenList } from '@uniswap/token-lists/dist/types'
import { arrayify } from 'ethers/lib/utils'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useCombinedActiveList, useCombinedInactiveList } from '../state/lists/hooks' import { filterTokens } from '../components/SearchModal/filtering'
import { useAllLists, useCombinedActiveList, useInactiveListUrls } from '../state/lists/hooks'
import { WrappedTokenInfo } from '../state/lists/wrappedTokenInfo'
import { NEVER_RELOAD, useSingleCallResult } from '../state/multicall/hooks' import { NEVER_RELOAD, useSingleCallResult } from '../state/multicall/hooks'
import { useUserAddedTokens } from '../state/user/hooks' import { useUserAddedTokens } from '../state/user/hooks'
import { isAddress } from '../utils' import { isAddress } from '../utils'
import { TokenAddressMap, useUnsupportedTokenList } from './../state/lists/hooks'
import { useActiveWeb3React } from './index' import { useActiveWeb3React } from './index'
import { useBytes32TokenContract, useTokenContract } from './useContract' import { useBytes32TokenContract, useTokenContract } from './useContract'
import { filterTokens } from '../components/SearchModal/filtering'
import { arrayify } from 'ethers/lib/utils'
// reduce token map into standard address <-> Token mapping, optionally include user added tokens // reduce token map into standard address <-> Token mapping, optionally include user added tokens
function useTokensFromMap(tokenMap: TokenAddressMap, includeUserAdded: boolean): { [address: string]: Token } { function useTokensFromMap(tokenMap: TokenAddressMap, includeUserAdded: boolean): { [address: string]: Token } {
...@@ -51,30 +53,32 @@ export function useAllTokens(): { [address: string]: Token } { ...@@ -51,30 +53,32 @@ export function useAllTokens(): { [address: string]: Token } {
return useTokensFromMap(allTokens, true) return useTokensFromMap(allTokens, true)
} }
export function useAllInactiveTokens(): { [address: string]: Token } {
// get inactive tokens
const inactiveTokensMap = useCombinedInactiveList()
const inactiveTokens = useTokensFromMap(inactiveTokensMap, false)
// filter out any token that are on active list
const activeTokensAddresses = Object.keys(useAllTokens())
const filteredInactive = activeTokensAddresses
? Object.keys(inactiveTokens).reduce<{ [address: string]: Token }>((newMap, address) => {
if (!activeTokensAddresses.includes(address)) {
newMap[address] = inactiveTokens[address]
}
return newMap
}, {})
: inactiveTokens
return filteredInactive
}
export function useUnsupportedTokens(): { [address: string]: Token } { export function useUnsupportedTokens(): { [address: string]: Token } {
const unsupportedTokensMap = useUnsupportedTokenList() const unsupportedTokensMap = useUnsupportedTokenList()
return useTokensFromMap(unsupportedTokensMap, false) return useTokensFromMap(unsupportedTokensMap, false)
} }
export function useSearchInactiveTokenLists(search: string | undefined, minResults = 10): WrappedTokenInfo[] {
const lists = useAllLists()
const inactiveUrls = useInactiveListUrls()
const { chainId } = useActiveWeb3React()
return useMemo(() => {
if (!search || search.trim().length === 0) return []
let result: WrappedTokenInfo[] = []
for (const url of inactiveUrls) {
const list = lists[url].current
if (!list) continue
const matching = filterTokens(
list.tokens.filter((token) => token.chainId === chainId),
search
)
result = [...result, ...matching.map((tokenInfo) => new WrappedTokenInfo(tokenInfo, list))]
if (result.length >= minResults) return result
}
return result
}, [chainId, inactiveUrls, lists, minResults, search])
}
export function useIsTokenActive(token: Token | undefined | null): boolean { export function useIsTokenActive(token: Token | undefined | null): boolean {
const activeTokens = useAllTokens() const activeTokens = useAllTokens()
...@@ -85,21 +89,6 @@ export function useIsTokenActive(token: Token | undefined | null): boolean { ...@@ -85,21 +89,6 @@ export function useIsTokenActive(token: Token | undefined | null): boolean {
return !!activeTokens[token.address] return !!activeTokens[token.address]
} }
// used to detect extra search results
export function useFoundOnInactiveList(searchQuery: string): Token[] | undefined {
const { chainId } = useActiveWeb3React()
const inactiveTokens = useAllInactiveTokens()
return useMemo(() => {
if (!chainId || searchQuery === '') {
return undefined
} else {
const tokens = filterTokens(Object.values(inactiveTokens), searchQuery)
return tokens
}
}, [chainId, inactiveTokens, searchQuery])
}
// Check if currency is included in custom list from user storage // Check if currency is included in custom list from user storage
export function useIsUserAddedToken(currency: Currency | undefined | null): boolean { export function useIsUserAddedToken(currency: Currency | undefined | null): boolean {
const userAddedTokens = useUserAddedTokens() const userAddedTokens = useUserAddedTokens()
......
...@@ -12,16 +12,13 @@ function computeAllRoutes( ...@@ -12,16 +12,13 @@ function computeAllRoutes(
pools: Pool[], pools: Pool[],
chainId: ChainId, chainId: ChainId,
currentPath: Pool[] = [], currentPath: Pool[] = [],
allPaths: Route[] = [], allPaths: Route<Currency, Currency>[] = [],
startCurrencyIn: Currency = currencyIn, startCurrencyIn: Currency = currencyIn,
maxHops = 2 maxHops = 2
): Route[] { ): Route<Currency, Currency>[] {
const tokenIn = wrappedCurrency(currencyIn, chainId) const tokenIn = wrappedCurrency(currencyIn, chainId)
const tokenOut = wrappedCurrency(currencyOut, chainId) const tokenOut = wrappedCurrency(currencyOut, chainId)
if (!tokenIn || !tokenOut) throw new Error('Missing tokenIn/tokenOut')
if (!tokenIn || !tokenOut) {
throw new Error('Could not wrap currencies')
}
for (const pool of pools) { for (const pool of pools) {
if (currentPath.indexOf(pool) !== -1 || !pool.involvesToken(tokenIn)) continue if (currentPath.indexOf(pool) !== -1 || !pool.involvesToken(tokenIn)) continue
...@@ -51,7 +48,10 @@ function computeAllRoutes( ...@@ -51,7 +48,10 @@ function computeAllRoutes(
* @param currencyIn the input currency * @param currencyIn the input currency
* @param currencyOut the output currency * @param currencyOut the output currency
*/ */
export function useAllV3Routes(currencyIn?: Currency, currencyOut?: Currency): { loading: boolean; routes: Route[] } { export function useAllV3Routes(
currencyIn?: Currency,
currencyOut?: Currency
): { loading: boolean; routes: Route<Currency, Currency>[] } {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const { pools, loading: poolsLoading } = useV3SwapPools(currencyIn, currencyOut) const { pools, loading: poolsLoading } = useV3SwapPools(currencyIn, currencyOut)
......
import { MaxUint256 } from '@ethersproject/constants' import { MaxUint256 } from '@ethersproject/constants'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { TokenAmount, CurrencyAmount, ETHER, ChainId, Percent } from '@uniswap/sdk-core' import { CurrencyAmount, ChainId, Percent, Currency, TradeType } 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 } from '@uniswap/v3-sdk'
import { useCallback, useMemo } from 'react' import { useCallback, useMemo } from 'react'
...@@ -21,18 +21,18 @@ export enum ApprovalState { ...@@ -21,18 +21,18 @@ export enum ApprovalState {
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns // returns a variable indicating the state of the approval and a function which approves if necessary or early returns
export function useApproveCallback( export function useApproveCallback(
amountToApprove?: CurrencyAmount, amountToApprove?: CurrencyAmount<Currency>,
spender?: string spender?: string
): [ApprovalState, () => Promise<void>] { ): [ApprovalState, () => Promise<void>] {
const { account } = useActiveWeb3React() const { account } = useActiveWeb3React()
const token = amountToApprove instanceof TokenAmount ? amountToApprove.token : undefined const token = amountToApprove?.currency?.isToken ? amountToApprove.currency : undefined
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender) const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender) const pendingApproval = useHasPendingApproval(token?.address, spender)
// check the current approval status // check the current approval status
const approvalState: ApprovalState = useMemo(() => { const approvalState: ApprovalState = useMemo(() => {
if (!amountToApprove || !spender) return ApprovalState.UNKNOWN if (!amountToApprove || !spender) return ApprovalState.UNKNOWN
if (amountToApprove.currency === ETHER) return ApprovalState.APPROVED if (amountToApprove.currency.isEther) return ApprovalState.APPROVED
// we might not have enough data to know whether or not we need to approve // we might not have enough data to know whether or not we need to approve
if (!currentAllowance) return ApprovalState.UNKNOWN if (!currentAllowance) return ApprovalState.UNKNOWN
...@@ -76,11 +76,11 @@ export function useApproveCallback( ...@@ -76,11 +76,11 @@ export function useApproveCallback(
const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => { const estimatedGas = await tokenContract.estimateGas.approve(spender, MaxUint256).catch(() => {
// general fallback for tokens who restrict approval amounts // general fallback for tokens who restrict approval amounts
useExact = true useExact = true
return tokenContract.estimateGas.approve(spender, amountToApprove.raw.toString()) return tokenContract.estimateGas.approve(spender, amountToApprove.quotient.toString())
}) })
return tokenContract return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, { .approve(spender, useExact ? amountToApprove.quotient.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas), gasLimit: calculateGasMargin(estimatedGas),
}) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
...@@ -99,13 +99,16 @@ export function useApproveCallback( ...@@ -99,13 +99,16 @@ export function useApproveCallback(
} }
// wraps useApproveCallback in the context of a swap // wraps useApproveCallback in the context of a swap
export function useApproveCallbackFromTrade(trade: V2Trade | V3Trade | undefined, allowedSlippage: Percent) { export function useApproveCallbackFromTrade(
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined,
allowedSlippage: Percent
) {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const swapRouterAddress = SWAP_ROUTER_ADDRESSES[chainId as ChainId] const swapRouterAddress = SWAP_ROUTER_ADDRESSES[chainId as ChainId]
const amountToApprove = useMemo(() => (trade ? trade.maximumAmountIn(allowedSlippage) : undefined), [ const amountToApprove = useMemo(
trade, () => (trade && trade.inputAmount.currency.isToken ? trade.maximumAmountIn(allowedSlippage) : undefined),
allowedSlippage, [trade, allowedSlippage]
]) )
return useApproveCallback( return useApproveCallback(
amountToApprove, amountToApprove,
trade instanceof V2Trade ? V2_ROUTER_ADDRESS : trade instanceof V3Trade ? swapRouterAddress : undefined trade instanceof V2Trade ? V2_ROUTER_ADDRESS : trade instanceof V3Trade ? swapRouterAddress : undefined
......
import { Token, Currency, CurrencyAmount, TokenAmount, TradeType } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, TradeType } from '@uniswap/sdk-core'
import { encodeRouteToPath, Route, Trade } from '@uniswap/v3-sdk' import { encodeRouteToPath, Route, Trade } from '@uniswap/v3-sdk'
import { BigNumber } from 'ethers' import { BigNumber } from 'ethers'
import { useMemo } from 'react' import { useMemo } from 'react'
...@@ -20,16 +20,16 @@ export enum V3TradeState { ...@@ -20,16 +20,16 @@ export enum V3TradeState {
* @param currencyOut the desired output currency * @param currencyOut the desired output currency
*/ */
export function useBestV3TradeExactIn( export function useBestV3TradeExactIn(
amountIn?: CurrencyAmount, amountIn?: CurrencyAmount<Currency>,
currencyOut?: Currency currencyOut?: Currency
): { state: V3TradeState; trade: Trade | null } { ): { state: V3TradeState; trade: Trade<Currency, Currency, TradeType.EXACT_INPUT> | null } {
const quoter = useV3Quoter() const quoter = useV3Quoter()
const { routes, loading: routesLoading } = useAllV3Routes(amountIn?.currency, currencyOut) const { routes, loading: routesLoading } = useAllV3Routes(amountIn?.currency, currencyOut)
const quoteExactInInputs = useMemo(() => { const quoteExactInInputs = useMemo(() => {
return routes.map((route) => [ return routes.map((route) => [
encodeRouteToPath(route, false), encodeRouteToPath(route, false),
amountIn ? `0x${amountIn.raw.toString(16)}` : undefined, amountIn ? `0x${amountIn.quotient.toString(16)}` : undefined,
]) ])
}, [amountIn, routes]) }, [amountIn, routes])
...@@ -51,7 +51,7 @@ export function useBestV3TradeExactIn( ...@@ -51,7 +51,7 @@ export function useBestV3TradeExactIn(
} }
const { bestRoute, amountOut } = quotesResults.reduce( const { bestRoute, amountOut } = quotesResults.reduce(
(currentBest: { bestRoute: Route | null; amountOut: BigNumber | null }, { result }, i) => { (currentBest: { bestRoute: Route<Currency, Currency> | null; amountOut: BigNumber | null }, { result }, i) => {
if (!result) return currentBest if (!result) return currentBest
if (currentBest.amountOut === null) { if (currentBest.amountOut === null) {
...@@ -89,10 +89,9 @@ export function useBestV3TradeExactIn( ...@@ -89,10 +89,9 @@ export function useBestV3TradeExactIn(
route: bestRoute, route: bestRoute,
tradeType: TradeType.EXACT_INPUT, tradeType: TradeType.EXACT_INPUT,
inputAmount: amountIn, inputAmount: amountIn,
outputAmount: outputAmount: currencyOut.isToken
currencyOut instanceof Token ? CurrencyAmount.fromRawAmount(currencyOut, amountOut.toString())
? new TokenAmount(currencyOut, amountOut.toString()) : CurrencyAmount.ether(amountOut.toString()),
: CurrencyAmount.ether(amountOut.toString()),
}), }),
} }
}, [amountIn, currencyOut, quotesResults, routes, routesLoading]) }, [amountIn, currencyOut, quotesResults, routes, routesLoading])
...@@ -105,15 +104,15 @@ export function useBestV3TradeExactIn( ...@@ -105,15 +104,15 @@ export function useBestV3TradeExactIn(
*/ */
export function useBestV3TradeExactOut( export function useBestV3TradeExactOut(
currencyIn?: Currency, currencyIn?: Currency,
amountOut?: CurrencyAmount amountOut?: CurrencyAmount<Currency>
): { state: V3TradeState; trade: Trade | null } { ): { state: V3TradeState; trade: Trade<Currency, Currency, TradeType.EXACT_OUTPUT> | null } {
const quoter = useV3Quoter() const quoter = useV3Quoter()
const { routes, loading: routesLoading } = useAllV3Routes(currencyIn, amountOut?.currency) const { routes, loading: routesLoading } = useAllV3Routes(currencyIn, amountOut?.currency)
const quoteExactOutInputs = useMemo(() => { const quoteExactOutInputs = useMemo(() => {
return routes.map((route) => [ return routes.map((route) => [
encodeRouteToPath(route, true), encodeRouteToPath(route, true),
amountOut ? `0x${amountOut.raw.toString(16)}` : undefined, amountOut ? `0x${amountOut.quotient.toString(16)}` : undefined,
]) ])
}, [amountOut, routes]) }, [amountOut, routes])
...@@ -135,7 +134,7 @@ export function useBestV3TradeExactOut( ...@@ -135,7 +134,7 @@ export function useBestV3TradeExactOut(
} }
const { bestRoute, amountIn } = quotesResults.reduce( const { bestRoute, amountIn } = quotesResults.reduce(
(currentBest: { bestRoute: Route | null; amountIn: BigNumber | null }, { result }, i) => { (currentBest: { bestRoute: Route<Currency, Currency> | null; amountIn: BigNumber | null }, { result }, i) => {
if (!result) return currentBest if (!result) return currentBest
if (currentBest.amountIn === null) { if (currentBest.amountIn === null) {
...@@ -172,10 +171,7 @@ export function useBestV3TradeExactOut( ...@@ -172,10 +171,7 @@ export function useBestV3TradeExactOut(
trade: Trade.createUncheckedTrade({ trade: Trade.createUncheckedTrade({
route: bestRoute, route: bestRoute,
tradeType: TradeType.EXACT_OUTPUT, tradeType: TradeType.EXACT_OUTPUT,
inputAmount: inputAmount: CurrencyAmount.fromRawAmount(currencyIn, amountIn.toString()),
currencyIn instanceof Token
? new TokenAmount(currencyIn, amountIn.toString())
: CurrencyAmount.ether(amountIn.toString()),
outputAmount: amountOut, outputAmount: amountOut,
}), }),
} }
......
import JSBI from 'jsbi' import JSBI from 'jsbi'
import { ChainId, CurrencyAmount, Percent, TokenAmount } from '@uniswap/sdk-core' import { ChainId, Percent, CurrencyAmount, Currency, TradeType, Token } 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 } from '@uniswap/v3-sdk'
import { splitSignature } from 'ethers/lib/utils' import { splitSignature } from 'ethers/lib/utils'
...@@ -115,7 +115,7 @@ const PERMIT_ALLOWED_TYPE = [ ...@@ -115,7 +115,7 @@ const PERMIT_ALLOWED_TYPE = [
] ]
export function useERC20Permit( export function useERC20Permit(
currencyAmount: CurrencyAmount | null | undefined, currencyAmount: CurrencyAmount<Currency> | null | undefined,
spender: string | null | undefined, spender: string | null | undefined,
overridePermitInfo: PermitInfo | undefined | null overridePermitInfo: PermitInfo | undefined | null
): { ): {
...@@ -125,7 +125,7 @@ export function useERC20Permit( ...@@ -125,7 +125,7 @@ export function useERC20Permit(
} { } {
const { account, chainId, library } = useActiveWeb3React() const { account, chainId, library } = useActiveWeb3React()
const transactionDeadline = useTransactionDeadline() const transactionDeadline = useTransactionDeadline()
const tokenAddress = currencyAmount instanceof TokenAmount ? currencyAmount.token.address : undefined const tokenAddress = currencyAmount?.currency?.isToken ? currencyAmount.currency.address : undefined
const eip2612Contract = useEIP2612Contract(tokenAddress) const eip2612Contract = useEIP2612Contract(tokenAddress)
const isArgentWallet = useIsArgentWallet() const isArgentWallet = useIsArgentWallet()
const nonceInputs = useMemo(() => [account ?? undefined], [account]) const nonceInputs = useMemo(() => [account ?? undefined], [account])
...@@ -172,7 +172,7 @@ export function useERC20Permit( ...@@ -172,7 +172,7 @@ export function useERC20Permit(
signatureData.tokenAddress === tokenAddress && signatureData.tokenAddress === tokenAddress &&
signatureData.nonce === nonceNumber && signatureData.nonce === nonceNumber &&
signatureData.spender === spender && signatureData.spender === spender &&
('allowed' in signatureData || JSBI.equal(JSBI.BigInt(signatureData.amount), currencyAmount.raw)) ('allowed' in signatureData || JSBI.equal(JSBI.BigInt(signatureData.amount), currencyAmount.quotient))
return { return {
state: isSignatureDataValid ? UseERC20PermitState.SIGNED : UseERC20PermitState.NOT_SIGNED, state: isSignatureDataValid ? UseERC20PermitState.SIGNED : UseERC20PermitState.NOT_SIGNED,
...@@ -180,7 +180,7 @@ export function useERC20Permit( ...@@ -180,7 +180,7 @@ export function useERC20Permit(
gatherPermitSignature: async function gatherPermitSignature() { gatherPermitSignature: async function gatherPermitSignature() {
const allowed = permitInfo.type === PermitType.ALLOWED const allowed = permitInfo.type === PermitType.ALLOWED
const signatureDeadline = transactionDeadline.toNumber() + PERMIT_VALIDITY_BUFFER const signatureDeadline = transactionDeadline.toNumber() + PERMIT_VALIDITY_BUFFER
const value = currencyAmount.raw.toString() const value = currencyAmount.quotient.toString()
const message = allowed const message = allowed
? { ? {
...@@ -264,13 +264,16 @@ const REMOVE_V2_LIQUIDITY_PERMIT_INFO: PermitInfo = { ...@@ -264,13 +264,16 @@ const REMOVE_V2_LIQUIDITY_PERMIT_INFO: PermitInfo = {
} }
export function useV2LiquidityTokenPermit( export function useV2LiquidityTokenPermit(
liquidityAmount: TokenAmount | null | undefined, liquidityAmount: CurrencyAmount<Token> | null | undefined,
spender: string | null | undefined spender: string | null | undefined
) { ) {
return useERC20Permit(liquidityAmount, spender, REMOVE_V2_LIQUIDITY_PERMIT_INFO) return useERC20Permit(liquidityAmount, spender, REMOVE_V2_LIQUIDITY_PERMIT_INFO)
} }
export function useERC20PermitFromTrade(trade: V2Trade | V3Trade | undefined, allowedSlippage: Percent) { export function useERC20PermitFromTrade(
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined,
allowedSlippage: Percent
) {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const swapRouterAddress = SWAP_ROUTER_ADDRESSES[chainId as ChainId] const swapRouterAddress = SWAP_ROUTER_ADDRESSES[chainId as ChainId]
const amountToApprove = useMemo(() => (trade ? trade.maximumAmountIn(allowedSlippage) : undefined), [ const amountToApprove = useMemo(() => (trade ? trade.maximumAmountIn(allowedSlippage) : undefined), [
......
...@@ -14,8 +14,8 @@ export function useIsSwapUnsupported(currencyIn?: Currency, currencyOut?: Curren ...@@ -14,8 +14,8 @@ export function useIsSwapUnsupported(currencyIn?: Currency, currencyOut?: Curren
// if unsupported list loaded & either token on list, mark as unsupported // if unsupported list loaded & either token on list, mark as unsupported
return Boolean( return Boolean(
unsupportedTokens && unsupportedTokens &&
((currencyIn && currencyIn instanceof Token && unsupportedTokens[currencyIn.address]) || ((currencyIn && currencyIn.isToken && unsupportedTokens[currencyIn.address]) ||
(currencyOut && currencyOut instanceof Token && unsupportedTokens[currencyOut.address])) (currencyOut && currencyOut.isToken && unsupportedTokens[currencyOut.address]))
) )
}, [currencyIn, currencyOut, unsupportedTokens]) }, [currencyIn, currencyOut, unsupportedTokens])
} }
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { useMemo } from 'react' import { useMemo } from 'react'
import { NEVER_RELOAD, useSingleCallResult } from '../state/multicall/hooks' import { NEVER_RELOAD, useSingleCallResult } from '../state/multicall/hooks'
import { useActiveWeb3React } from './index' import { useActiveWeb3React } from './index'
......
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { Router, Trade as V2Trade } from '@uniswap/v2-sdk' import { Router, Trade as V2Trade } from '@uniswap/v2-sdk'
import { SwapRouter, Trade as V3Trade } from '@uniswap/v3-sdk' import { SwapRouter, Trade as V3Trade } from '@uniswap/v3-sdk'
import { ChainId, Percent, TradeType } from '@uniswap/sdk-core' import { ChainId, Currency, Percent, TradeType } from '@uniswap/sdk-core'
import { useMemo } from 'react' import { useMemo } from 'react'
import { SWAP_ROUTER_ADDRESSES } from '../constants/v3' import { SWAP_ROUTER_ADDRESSES } from '../constants/v3'
import { getTradeVersion } from '../utils/getTradeVersion' import { getTradeVersion } from '../utils/getTradeVersion'
...@@ -49,7 +49,7 @@ interface FailedCall extends SwapCallEstimate { ...@@ -49,7 +49,7 @@ interface FailedCall extends SwapCallEstimate {
* @param signatureData the signature data of the permit of the input token amount, if available * @param signatureData the signature data of the permit of the input token amount, if available
*/ */
function useSwapCallArguments( function useSwapCallArguments(
trade: V2Trade | V3Trade | undefined, // trade to execute, required trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined, // trade to execute, required
allowedSlippage: Percent, // in bips allowedSlippage: Percent, // in bips
recipientAddressOrName: string | null, // the ENS name or address of the recipient of the trade, or null if swap should be returned to sender recipientAddressOrName: string | null, // the ENS name or address of the recipient of the trade, or null if swap should be returned to sender
signatureData: SignatureData | null | undefined signatureData: SignatureData | null | undefined
...@@ -136,7 +136,7 @@ function useSwapCallArguments( ...@@ -136,7 +136,7 @@ function useSwapCallArguments(
// returns a function that will execute a swap, if the parameters are all valid // returns a function that will execute a swap, if the parameters are all valid
// and the user has approved the slippage adjusted input amount for the trade // and the user has approved the slippage adjusted input amount for the trade
export function useSwapCallback( export function useSwapCallback(
trade: V2Trade | V3Trade | undefined, // trade to execute, required trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined, // trade to execute, required
allowedSlippage: Percent, // in bips allowedSlippage: Percent, // in bips
recipientAddressOrName: string | null, // the ENS name or address of the recipient of the trade, or null if swap should be returned to sender recipientAddressOrName: string | null, // the ENS name or address of the recipient of the trade, or null if swap should be returned to sender
signatureData: SignatureData | undefined | null signatureData: SignatureData | undefined | null
......
import { Percent } from '@uniswap/sdk-core' import { Currency, Percent, TradeType } from '@uniswap/sdk-core'
import { Trade as V3Trade } from '@uniswap/v3-sdk' import { Trade as V3Trade } from '@uniswap/v3-sdk'
import { Trade as V2Trade } from '@uniswap/v2-sdk' import { Trade as V2Trade } from '@uniswap/v2-sdk'
import { useMemo } from 'react' import { useMemo } from 'react'
...@@ -8,7 +8,9 @@ const V2_SWAP_DEFAULT_SLIPPAGE = new Percent(50, 10_000) // .50% ...@@ -8,7 +8,9 @@ const V2_SWAP_DEFAULT_SLIPPAGE = new Percent(50, 10_000) // .50%
const V3_SWAP_DEFAULT_SLIPPAGE = new Percent(50, 10_000) // .50% const V3_SWAP_DEFAULT_SLIPPAGE = new Percent(50, 10_000) // .50%
const ONE_TENTHS_PERCENT = new Percent(10, 10_000) // .10% const ONE_TENTHS_PERCENT = new Percent(10, 10_000) // .10%
export default function useSwapSlippageTolerance(trade: V2Trade | V3Trade | undefined): Percent { export default function useSwapSlippageTolerance(
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined
): Percent {
const defaultSlippageTolerance = useMemo(() => { const defaultSlippageTolerance = useMemo(() => {
if (!trade) return ONE_TENTHS_PERCENT if (!trade) return ONE_TENTHS_PERCENT
if (trade instanceof V2Trade) return V2_SWAP_DEFAULT_SLIPPAGE if (trade instanceof V2Trade) return V2_SWAP_DEFAULT_SLIPPAGE
......
...@@ -5,7 +5,7 @@ export function getTickToPrice( ...@@ -5,7 +5,7 @@ export function getTickToPrice(
baseToken: Token | undefined, baseToken: Token | undefined,
quoteToken: Token | undefined, quoteToken: Token | undefined,
tick: number | undefined tick: number | undefined
): Price | undefined { ): Price<Token, Token> | undefined {
if (!baseToken || !quoteToken || !tick) { if (!baseToken || !quoteToken || !tick) {
return undefined return undefined
} }
......
import { Token, TokenAmount } from '@uniswap/sdk-core' import { Token, CurrencyAmount } from '@uniswap/sdk-core'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useSingleCallResult } from '../state/multicall/hooks' import { useSingleCallResult } from '../state/multicall/hooks'
import { useTokenContract } from './useContract' import { useTokenContract } from './useContract'
export function useTokenAllowance(token?: Token, owner?: string, spender?: string): TokenAmount | undefined { export function useTokenAllowance(token?: Token, owner?: string, spender?: string): CurrencyAmount<Token> | undefined {
const contract = useTokenContract(token?.address, false) const contract = useTokenContract(token?.address, false)
const inputs = useMemo(() => [owner, spender], [owner, spender]) const inputs = useMemo(() => [owner, spender], [owner, spender])
const allowance = useSingleCallResult(contract, 'allowance', inputs).result const allowance = useSingleCallResult(contract, 'allowance', inputs).result
return useMemo(() => (token && allowance ? new TokenAmount(token, allowance.toString()) : undefined), [ return useMemo(() => (token && allowance ? CurrencyAmount.fromRawAmount(token, allowance.toString()) : undefined), [
token, token,
allowance, allowance,
]) ])
......
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { Token, TokenAmount } from '@uniswap/sdk-core' import { Token, CurrencyAmount, Currency } from '@uniswap/sdk-core'
import { useTokenContract } from './useContract' import { useTokenContract } from './useContract'
import { useSingleCallResult } from '../state/multicall/hooks' import { useSingleCallResult } from '../state/multicall/hooks'
// returns undefined if input token is undefined, or fails to get token contract, // returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched // or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined { export function useTotalSupply(token?: Currency): CurrencyAmount<Token> | undefined {
const contract = useTokenContract(token?.address, false) const contract = useTokenContract(token?.isToken ? token.address : undefined, false)
const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0] const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]
return token && totalSupply ? new TokenAmount(token, totalSupply.toString()) : undefined return token?.isToken && totalSupply ? CurrencyAmount.fromRawAmount(token, totalSupply.toString()) : undefined
} }
import { ChainId, Currency, CurrencyAmount, 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 'jsbi'
import { useMemo } from 'react' import { useMemo } from 'react'
import { USDC } from '../constants' import { USDC } from '../constants'
import { PairState, useV2Pairs } from './useV2Pairs' import { PairState, useV2Pairs } from './useV2Pairs'
...@@ -10,7 +10,7 @@ import { wrappedCurrency } from '../utils/wrappedCurrency' ...@@ -10,7 +10,7 @@ import { wrappedCurrency } from '../utils/wrappedCurrency'
* Returns the price in USDC of the input currency * Returns the price in USDC of the input currency
* @param currency currency to compute the USDC price of * @param currency currency to compute the USDC price of
*/ */
export default function useUSDCPrice(currency?: Currency): Price | undefined { export default function useUSDCPrice(currency?: Currency): Price<Currency, Token> | undefined {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const wrapped = wrappedCurrency(currency, chainId) const wrapped = wrappedCurrency(currency, chainId)
const weth = WETH9[chainId as ChainId] const weth = WETH9[chainId as ChainId]
...@@ -56,7 +56,7 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined { ...@@ -56,7 +56,7 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined {
const ethPairETHAmount = ethPair?.reserveOf(weth) const ethPairETHAmount = ethPair?.reserveOf(weth)
const ethPairETHUSDCValue: JSBI = const ethPairETHUSDCValue: JSBI =
ethPairETHAmount && usdcEthPair ? usdcEthPair.priceOf(weth).quote(ethPairETHAmount).raw : JSBI.BigInt(0) ethPairETHAmount && usdcEthPair ? usdcEthPair.priceOf(weth).quote(ethPairETHAmount).quotient : JSBI.BigInt(0)
// all other tokens // all other tokens
// first try the usdc pair // first try the usdc pair
...@@ -76,7 +76,7 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined { ...@@ -76,7 +76,7 @@ export default function useUSDCPrice(currency?: Currency): Price | 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) { export function useUSDCValue(currencyAmount: CurrencyAmount<Currency> | undefined | null) {
const price = useUSDCPrice(currencyAmount?.currency) const price = useUSDCPrice(currencyAmount?.currency)
return useMemo(() => { return useMemo(() => {
......
...@@ -5,7 +5,7 @@ import { Interface } from '@ethersproject/abi' ...@@ -5,7 +5,7 @@ import { Interface } from '@ethersproject/abi'
import { useActiveWeb3React } from './index' import { useActiveWeb3React } from './index'
import { useMultipleContractSingleData } from '../state/multicall/hooks' import { useMultipleContractSingleData } from '../state/multicall/hooks'
import { wrappedCurrency } from '../utils/wrappedCurrency' import { wrappedCurrency } from '../utils/wrappedCurrency'
import { Currency, TokenAmount } from '@uniswap/sdk-core' import { Currency, CurrencyAmount } from '@uniswap/sdk-core'
const PAIR_INTERFACE = new Interface(IUniswapV2PairABI) const PAIR_INTERFACE = new Interface(IUniswapV2PairABI)
...@@ -51,7 +51,10 @@ export function useV2Pairs(currencies: [Currency | undefined, Currency | undefin ...@@ -51,7 +51,10 @@ export function useV2Pairs(currencies: [Currency | undefined, Currency | undefin
const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA] const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]
return [ return [
PairState.EXISTS, PairState.EXISTS,
new Pair(new TokenAmount(token0, reserve0.toString()), new TokenAmount(token1, reserve1.toString())), new Pair(
CurrencyAmount.fromRawAmount(token0, reserve0.toString()),
CurrencyAmount.fromRawAmount(token1, reserve1.toString())
),
] ]
}) })
}, [results, tokens]) }, [results, tokens])
......
import { Currency, CurrencyAmount } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, TradeType } from '@uniswap/sdk-core'
import { Pair, Trade } from '@uniswap/v2-sdk' import { Pair, Trade } from '@uniswap/v2-sdk'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useUserSingleHopOnly } from 'state/user/hooks' import { useUserSingleHopOnly } from 'state/user/hooks'
...@@ -34,7 +34,10 @@ const MAX_HOPS = 3 ...@@ -34,7 +34,10 @@ const MAX_HOPS = 3
/** /**
* Returns the best trade for the exact amount of tokens in to the given token out * Returns the best trade for the exact amount of tokens in to the given token out
*/ */
export function useV2TradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut?: Currency): Trade | null { export function useV2TradeExactIn(
currencyAmountIn?: CurrencyAmount<Currency>,
currencyOut?: Currency
): Trade<Currency, Currency, TradeType.EXACT_INPUT> | null {
const allowedPairs = useAllCommonPairs(currencyAmountIn?.currency, currencyOut) const allowedPairs = useAllCommonPairs(currencyAmountIn?.currency, currencyOut)
const [singleHopOnly] = useUserSingleHopOnly() const [singleHopOnly] = useUserSingleHopOnly()
...@@ -48,9 +51,9 @@ export function useV2TradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut ...@@ -48,9 +51,9 @@ export function useV2TradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut
) )
} }
// search through trades with varying hops, find best trade out of them // search through trades with varying hops, find best trade out of them
let bestTradeSoFar: Trade | null = null let bestTradeSoFar: Trade<Currency, Currency, TradeType.EXACT_INPUT> | null = null
for (let i = 1; i <= MAX_HOPS; i++) { for (let i = 1; i <= MAX_HOPS; i++) {
const currentTrade: Trade | null = const currentTrade: Trade<Currency, Currency, TradeType.EXACT_INPUT> | null =
Trade.bestTradeExactIn(allowedPairs, currencyAmountIn, currencyOut, { maxHops: i, maxNumResults: 1 })[0] ?? Trade.bestTradeExactIn(allowedPairs, currencyAmountIn, currencyOut, { maxHops: i, maxNumResults: 1 })[0] ??
null null
// if current trade is best yet, save it // if current trade is best yet, save it
...@@ -68,7 +71,10 @@ export function useV2TradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut ...@@ -68,7 +71,10 @@ export function useV2TradeExactIn(currencyAmountIn?: CurrencyAmount, currencyOut
/** /**
* Returns the best trade for the token in to the exact amount of token out * Returns the best trade for the token in to the exact amount of token out
*/ */
export function useV2TradeExactOut(currencyIn?: Currency, currencyAmountOut?: CurrencyAmount): Trade | null { export function useV2TradeExactOut(
currencyIn?: Currency,
currencyAmountOut?: CurrencyAmount<Currency>
): Trade<Currency, Currency, TradeType.EXACT_OUTPUT> | null {
const allowedPairs = useAllCommonPairs(currencyIn, currencyAmountOut?.currency) const allowedPairs = useAllCommonPairs(currencyIn, currencyAmountOut?.currency)
const [singleHopOnly] = useUserSingleHopOnly() const [singleHopOnly] = useUserSingleHopOnly()
...@@ -82,7 +88,7 @@ export function useV2TradeExactOut(currencyIn?: Currency, currencyAmountOut?: Cu ...@@ -82,7 +88,7 @@ export function useV2TradeExactOut(currencyIn?: Currency, currencyAmountOut?: Cu
) )
} }
// search through trades with varying hops, find best trade out of them // search through trades with varying hops, find best trade out of them
let bestTradeSoFar: Trade | null = null let bestTradeSoFar: Trade<Currency, Currency, TradeType.EXACT_OUTPUT> | null = null
for (let i = 1; i <= MAX_HOPS; i++) { for (let i = 1; i <= MAX_HOPS; i++) {
const currentTrade = const currentTrade =
Trade.bestTradeExactOut(allowedPairs, currencyIn, currencyAmountOut, { maxHops: i, maxNumResults: 1 })[0] ?? Trade.bestTradeExactOut(allowedPairs, currencyIn, currencyAmountOut, { maxHops: i, maxNumResults: 1 })[0] ??
......
...@@ -4,7 +4,7 @@ import { PositionDetails } from 'types/position' ...@@ -4,7 +4,7 @@ import { PositionDetails } from 'types/position'
import { useV3NFTPositionManagerContract } from './useContract' import { useV3NFTPositionManagerContract } from './useContract'
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { Pool } from '@uniswap/v3-sdk' import { Pool } from '@uniswap/v3-sdk'
import { TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import { useBlockNumber } from 'state/application/hooks' import { useBlockNumber } from 'state/application/hooks'
const MAX_UINT128 = BigNumber.from(2).pow(128).sub(1) const MAX_UINT128 = BigNumber.from(2).pow(128).sub(1)
...@@ -13,7 +13,7 @@ const MAX_UINT128 = BigNumber.from(2).pow(128).sub(1) ...@@ -13,7 +13,7 @@ const MAX_UINT128 = BigNumber.from(2).pow(128).sub(1)
export function useV3PositionFees( export function useV3PositionFees(
pool?: Pool, pool?: Pool,
positionDetails?: PositionDetails positionDetails?: PositionDetails
): [TokenAmount, TokenAmount] | [undefined, undefined] { ): [CurrencyAmount<Token>, CurrencyAmount<Token>] | [undefined, undefined] {
const positionManager = useV3NFTPositionManagerContract(false) const positionManager = useV3NFTPositionManagerContract(false)
const owner = useSingleCallResult(positionDetails?.tokenId ? positionManager : null, 'ownerOf', [ const owner = useSingleCallResult(positionDetails?.tokenId ? positionManager : null, 'ownerOf', [
positionDetails?.tokenId, positionDetails?.tokenId,
...@@ -46,8 +46,8 @@ export function useV3PositionFees( ...@@ -46,8 +46,8 @@ export function useV3PositionFees(
if (pool && positionDetails && amounts) { if (pool && positionDetails && amounts) {
return [ return [
new TokenAmount(pool.token0, positionDetails.tokensOwed0.add(amounts[0]).toString()), CurrencyAmount.fromRawAmount(pool.token0, positionDetails.tokensOwed0.add(amounts[0]).toString()),
new TokenAmount(pool.token1, positionDetails.tokensOwed1.add(amounts[1]).toString()), CurrencyAmount.fromRawAmount(pool.token1, positionDetails.tokensOwed1.add(amounts[1]).toString()),
] ]
} else { } else {
return [undefined, undefined] return [undefined, undefined]
......
import { Currency, currencyEquals, ETHER, WETH9 } from '@uniswap/sdk-core' import { Currency, currencyEquals, WETH9 } from '@uniswap/sdk-core'
import { useMemo } from 'react' import { useMemo } from 'react'
import { tryParseAmount } from '../state/swap/hooks' import { tryParseAmount } from '../state/swap/hooks'
import { useTransactionAdder } from '../state/transactions/hooks' import { useTransactionAdder } from '../state/transactions/hooks'
...@@ -37,14 +37,14 @@ export default function useWrapCallback( ...@@ -37,14 +37,14 @@ export default function useWrapCallback(
const hasInputAmount = Boolean(inputAmount?.greaterThan('0')) const hasInputAmount = Boolean(inputAmount?.greaterThan('0'))
const sufficientBalance = inputAmount && balance && !balance.lessThan(inputAmount) const sufficientBalance = inputAmount && balance && !balance.lessThan(inputAmount)
if (inputCurrency === ETHER && currencyEquals(WETH9[chainId], outputCurrency)) { if (inputCurrency.isEther && currencyEquals(WETH9[chainId], outputCurrency)) {
return { return {
wrapType: WrapType.WRAP, wrapType: WrapType.WRAP,
execute: execute:
sufficientBalance && inputAmount sufficientBalance && inputAmount
? async () => { ? async () => {
try { try {
const txReceipt = await wethContract.deposit({ value: `0x${inputAmount.raw.toString(16)}` }) const txReceipt = await wethContract.deposit({ value: `0x${inputAmount.quotient.toString(16)}` })
addTransaction(txReceipt, { summary: `Wrap ${inputAmount.toSignificant(6)} ETH to WETH` }) addTransaction(txReceipt, { summary: `Wrap ${inputAmount.toSignificant(6)} ETH to WETH` })
} catch (error) { } catch (error) {
console.error('Could not deposit', error) console.error('Could not deposit', error)
...@@ -53,14 +53,14 @@ export default function useWrapCallback( ...@@ -53,14 +53,14 @@ export default function useWrapCallback(
: undefined, : undefined,
inputError: sufficientBalance ? undefined : hasInputAmount ? 'Insufficient ETH balance' : 'Enter ETH amount', inputError: sufficientBalance ? undefined : hasInputAmount ? 'Insufficient ETH balance' : 'Enter ETH amount',
} }
} else if (currencyEquals(WETH9[chainId], inputCurrency) && outputCurrency === ETHER) { } else if (currencyEquals(WETH9[chainId], inputCurrency) && outputCurrency.isEther) {
return { return {
wrapType: WrapType.UNWRAP, wrapType: WrapType.UNWRAP,
execute: execute:
sufficientBalance && inputAmount sufficientBalance && inputAmount
? async () => { ? async () => {
try { try {
const txReceipt = await wethContract.withdraw(`0x${inputAmount.raw.toString(16)}`) const txReceipt = await wethContract.withdraw(`0x${inputAmount.quotient.toString(16)}`)
addTransaction(txReceipt, { summary: `Unwrap ${inputAmount.toSignificant(6)} WETH to ETH` }) addTransaction(txReceipt, { summary: `Unwrap ${inputAmount.toSignificant(6)} WETH to ETH` })
} catch (error) { } catch (error) {
console.error('Could not withdraw', error) console.error('Could not withdraw', error)
......
...@@ -17,7 +17,7 @@ export function PoolPriceBar({ ...@@ -17,7 +17,7 @@ export function PoolPriceBar({
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
noLiquidity?: boolean noLiquidity?: boolean
poolTokenPercentage?: Percent poolTokenPercentage?: Percent
price?: Price price?: Price<Currency, Currency>
}) { }) {
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
return ( return (
......
...@@ -3,7 +3,7 @@ import { Field } from '../../state/mint/v3/actions' ...@@ -3,7 +3,7 @@ import { Field } from '../../state/mint/v3/actions'
import { AutoColumn } from 'components/Column' import { AutoColumn } from 'components/Column'
import Card from 'components/Card' import Card from 'components/Card'
import styled from 'styled-components' import styled from 'styled-components'
import { CurrencyAmount, Price } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Price } from '@uniswap/sdk-core'
import { Position } from '@uniswap/v3-sdk' import { Position } from '@uniswap/v3-sdk'
import { PositionPreview } from 'components/PositionPreview' import { PositionPreview } from 'components/PositionPreview'
...@@ -26,9 +26,9 @@ export function Review({ ...@@ -26,9 +26,9 @@ export function Review({
}: { }: {
position?: Position position?: Position
existingPosition?: Position existingPosition?: Position
parsedAmounts: { [field in Field]?: CurrencyAmount } parsedAmounts: { [field in Field]?: CurrencyAmount<Currency> }
priceLower?: Price priceLower?: Price<Currency, Currency>
priceUpper?: Price priceUpper?: Price<Currency, Currency>
outOfRange: boolean outOfRange: boolean
}) { }) {
return ( return (
......
import React, { useCallback, useContext, useMemo, useState, useEffect } from 'react' import React, { useCallback, useContext, useMemo, useState, useEffect } from 'react'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { Currency, TokenAmount, ETHER, currencyEquals, Percent } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, currencyEquals, Percent } from '@uniswap/sdk-core'
import { WETH9 } from '@uniswap/sdk-core' import { WETH9 } from '@uniswap/sdk-core'
import { AlertTriangle, AlertCircle } from 'react-feather' import { AlertTriangle, AlertCircle } from 'react-feather'
import ReactGA from 'react-ga' import ReactGA from 'react-ga'
...@@ -167,7 +167,7 @@ export default function AddLiquidity({ ...@@ -167,7 +167,7 @@ export default function AddLiquidity({
} }
// get the max amounts user can add // get the max amounts user can add
const maxAmounts: { [field in Field]?: TokenAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( const maxAmounts: { [field in Field]?: CurrencyAmount<Currency> } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce(
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
...@@ -177,7 +177,7 @@ export default function AddLiquidity({ ...@@ -177,7 +177,7 @@ export default function AddLiquidity({
{} {}
) )
const atMaxAmounts: { [field in Field]?: TokenAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( const atMaxAmounts: { [field in Field]?: CurrencyAmount<Currency> } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce(
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
...@@ -215,13 +215,13 @@ export default function AddLiquidity({ ...@@ -215,13 +215,13 @@ export default function AddLiquidity({
tokenId, tokenId,
slippageTolerance: allowedSlippage, slippageTolerance: allowedSlippage,
deadline: deadline.toString(), deadline: deadline.toString(),
useEther: currencyA === ETHER || currencyB === ETHER, useEther: currencyA.isEther || currencyB.isEther,
}) })
: NonfungiblePositionManager.addCallParameters(position, { : NonfungiblePositionManager.addCallParameters(position, {
slippageTolerance: allowedSlippage, slippageTolerance: allowedSlippage,
recipient: account, recipient: account,
deadline: deadline.toString(), deadline: deadline.toString(),
useEther: currencyA === ETHER || currencyB === ETHER, useEther: currencyA.isEther || currencyB.isEther,
createPool: noLiquidity, createPool: noLiquidity,
}) })
......
...@@ -18,7 +18,7 @@ export function ConfirmAddModalBottom({ ...@@ -18,7 +18,7 @@ export function ConfirmAddModalBottom({
noLiquidity?: boolean noLiquidity?: boolean
price?: Fraction price?: Fraction
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
parsedAmounts: { [field in Field]?: CurrencyAmount } parsedAmounts: { [field in Field]?: CurrencyAmount<Currency> }
poolTokenPercentage?: Percent poolTokenPercentage?: Percent
onAdd: () => void onAdd: () => void
}) { }) {
......
...@@ -17,7 +17,7 @@ export function PoolPriceBar({ ...@@ -17,7 +17,7 @@ export function PoolPriceBar({
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
noLiquidity?: boolean noLiquidity?: boolean
poolTokenPercentage?: Percent poolTokenPercentage?: Percent
price?: Price price?: Price<Currency, Currency>
}) { }) {
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
return ( return (
......
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { Currency, currencyEquals, ETHER, Percent, TokenAmount, WETH9 } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, currencyEquals, Percent, WETH9 } from '@uniswap/sdk-core'
import React, { useCallback, useContext, useState } from 'react' import React, { useCallback, useContext, useState } from 'react'
import { Plus } from 'react-feather' import { Plus } from 'react-feather'
import ReactGA from 'react-ga' import ReactGA from 'react-ga'
...@@ -102,7 +102,7 @@ export default function AddLiquidity({ ...@@ -102,7 +102,7 @@ export default function AddLiquidity({
} }
// get the max amounts user can add // get the max amounts user can add
const maxAmounts: { [field in Field]?: TokenAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( const maxAmounts: { [field in Field]?: CurrencyAmount<Currency> } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce(
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
...@@ -112,7 +112,7 @@ export default function AddLiquidity({ ...@@ -112,7 +112,7 @@ export default function AddLiquidity({
{} {}
) )
const atMaxAmounts: { [field in Field]?: TokenAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( const atMaxAmounts: { [field in Field]?: CurrencyAmount<Currency> } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce(
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
...@@ -147,27 +147,27 @@ export default function AddLiquidity({ ...@@ -147,27 +147,27 @@ export default function AddLiquidity({
method: (...args: any) => Promise<TransactionResponse>, method: (...args: any) => Promise<TransactionResponse>,
args: Array<string | string[] | number>, args: Array<string | string[] | number>,
value: BigNumber | null value: BigNumber | null
if (currencyA === ETHER || currencyB === ETHER) { if (currencyA.isEther || currencyB.isEther) {
const tokenBIsETH = currencyB === ETHER const tokenBIsETH = currencyB.isEther
estimate = router.estimateGas.addLiquidityETH estimate = router.estimateGas.addLiquidityETH
method = router.addLiquidityETH method = router.addLiquidityETH
args = [ args = [
wrappedCurrency(tokenBIsETH ? currencyA : currencyB, chainId)?.address ?? '', // token wrappedCurrency(tokenBIsETH ? currencyA : currencyB, chainId)?.address ?? '', // token
(tokenBIsETH ? parsedAmountA : parsedAmountB).raw.toString(), // token desired (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired
amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min
amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min
account, account,
deadline.toHexString(), deadline.toHexString(),
] ]
value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).raw.toString()) value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString())
} else { } else {
estimate = router.estimateGas.addLiquidity estimate = router.estimateGas.addLiquidity
method = router.addLiquidity method = router.addLiquidity
args = [ args = [
wrappedCurrency(currencyA, chainId)?.address ?? '', wrappedCurrency(currencyA, chainId)?.address ?? '',
wrappedCurrency(currencyB, chainId)?.address ?? '', wrappedCurrency(currencyB, chainId)?.address ?? '',
parsedAmountA.raw.toString(), parsedAmountA.quotient.toString(),
parsedAmountB.raw.toString(), parsedAmountB.quotient.toString(),
amountsMin[Field.CURRENCY_A].toString(), amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(), amountsMin[Field.CURRENCY_B].toString(),
account, account,
......
...@@ -2,9 +2,8 @@ import React, { useCallback, useState } from 'react' ...@@ -2,9 +2,8 @@ import React, { useCallback, useState } from 'react'
import { AutoColumn } from '../../components/Column' import { AutoColumn } from '../../components/Column'
import styled from 'styled-components' import styled from 'styled-components'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import JSBI from 'jsbi'
import { TokenAmount, ETHER } from '@uniswap/sdk-core' import { Token, CurrencyAmount } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk'
import { RouteComponentProps } from 'react-router-dom' import { RouteComponentProps } from 'react-router-dom'
import DoubleCurrencyLogo from '../../components/DoubleLogo' import DoubleCurrencyLogo from '../../components/DoubleLogo'
import { useCurrency } from '../../hooks/Tokens' import { useCurrency } from '../../hooks/Tokens'
...@@ -104,7 +103,7 @@ export default function Manage({ ...@@ -104,7 +103,7 @@ export default function Manage({
const stakingInfo = useStakingInfo(stakingTokenPair)?.[0] const stakingInfo = useStakingInfo(stakingTokenPair)?.[0]
// detect existing unstaked LP position to show add button if none found // detect existing unstaked LP position to show add button if none found
const userLiquidityUnstaked = useTokenBalance(account ?? undefined, stakingInfo?.stakedAmount?.token) const userLiquidityUnstaked = useTokenBalance(account ?? undefined, stakingInfo?.stakedAmount?.currency)
const showAddLiquidityButton = Boolean(stakingInfo?.stakedAmount?.equalTo('0') && userLiquidityUnstaked?.equalTo('0')) const showAddLiquidityButton = Boolean(stakingInfo?.stakedAmount?.equalTo('0') && userLiquidityUnstaked?.equalTo('0'))
// toggle for staking modal and unstaking modal // toggle for staking modal and unstaking modal
...@@ -115,23 +114,23 @@ export default function Manage({ ...@@ -115,23 +114,23 @@ export default function Manage({
// fade cards if nothing staked or nothing earned yet // fade cards if nothing staked or nothing earned yet
const disableTop = !stakingInfo?.stakedAmount || stakingInfo.stakedAmount.equalTo(JSBI.BigInt(0)) const disableTop = !stakingInfo?.stakedAmount || stakingInfo.stakedAmount.equalTo(JSBI.BigInt(0))
const token = currencyA === ETHER ? tokenB : tokenA const token = currencyA?.isEther ? tokenB : tokenA
const WETH = currencyA === ETHER ? tokenA : tokenB const WETH = currencyA?.isEther ? tokenA : tokenB
const backgroundColor = useColor(token) const backgroundColor = useColor(token)
// get WETH value of staked LP tokens // get WETH value of staked LP tokens
const totalSupplyOfStakingToken = useTotalSupply(stakingInfo?.stakedAmount?.token) const totalSupplyOfStakingToken = useTotalSupply(stakingInfo?.stakedAmount?.currency)
let valueOfTotalStakedAmountInWETH: TokenAmount | undefined let valueOfTotalStakedAmountInWETH: CurrencyAmount<Token> | undefined
if (totalSupplyOfStakingToken && stakingTokenPair && stakingInfo && WETH) { if (totalSupplyOfStakingToken && stakingTokenPair && stakingInfo && WETH) {
// take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens // take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens
valueOfTotalStakedAmountInWETH = new TokenAmount( valueOfTotalStakedAmountInWETH = CurrencyAmount.fromRawAmount(
WETH, WETH,
JSBI.divide( JSBI.divide(
JSBI.multiply( JSBI.multiply(
JSBI.multiply(stakingInfo.totalStakedAmount.raw, stakingTokenPair.reserveOf(WETH).raw), JSBI.multiply(stakingInfo.totalStakedAmount.quotient, stakingTokenPair.reserveOf(WETH).quotient),
JSBI.BigInt(2) // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to JSBI.BigInt(2) // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to
), ),
totalSupplyOfStakingToken.raw totalSupplyOfStakingToken.quotient
) )
) )
} }
...@@ -269,7 +268,7 @@ export default function Manage({ ...@@ -269,7 +268,7 @@ export default function Manage({
<div> <div>
<TYPE.black>Your unclaimed UNI</TYPE.black> <TYPE.black>Your unclaimed UNI</TYPE.black>
</div> </div>
{stakingInfo?.earnedAmount && JSBI.notEqual(BIG_INT_ZERO, stakingInfo?.earnedAmount?.raw) && ( {stakingInfo?.earnedAmount && JSBI.notEqual(BIG_INT_ZERO, stakingInfo?.earnedAmount?.quotient) && (
<ButtonEmpty <ButtonEmpty
padding="8px" padding="8px"
borderRadius="8px" borderRadius="8px"
......
import JSBI from 'jsbi'
import React from 'react' import React from 'react'
import { AutoColumn } from '../../components/Column' import { AutoColumn } from '../../components/Column'
import styled from 'styled-components' import styled from 'styled-components'
...@@ -9,7 +10,6 @@ import { CardSection, DataCard, CardNoise, CardBGImage } from '../../components/ ...@@ -9,7 +10,6 @@ import { CardSection, DataCard, CardNoise, CardBGImage } from '../../components/
import { Countdown } from './Countdown' import { Countdown } from './Countdown'
import Loader from '../../components/Loader' import Loader from '../../components/Loader'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { JSBI } from '@uniswap/v2-sdk'
import { BIG_INT_ZERO } from '../../constants' import { BIG_INT_ZERO } from '../../constants'
import { OutlineCard } from '../../components/Card' import { OutlineCard } from '../../components/Card'
...@@ -48,7 +48,7 @@ export default function Earn() { ...@@ -48,7 +48,7 @@ export default function Earn() {
* only show staking cards with balance * only show staking cards with balance
* @todo only account for this if rewards are inactive * @todo only account for this if rewards are inactive
*/ */
const stakingInfosWithBalance = stakingInfos?.filter((s) => JSBI.greaterThan(s.stakedAmount.raw, BIG_INT_ZERO)) const stakingInfosWithBalance = stakingInfos?.filter((s) => JSBI.greaterThan(s.stakedAmount.quotient, BIG_INT_ZERO))
// toggle copy if rewards are inactive // toggle copy if rewards are inactive
const stakingRewardsExist = Boolean(typeof chainId === 'number' && (STAKING_REWARDS_INFO[chainId]?.length ?? 0) > 0) const stakingRewardsExist = Boolean(typeof chainId === 'number' && (STAKING_REWARDS_INFO[chainId]?.length ?? 0) > 0)
......
import JSBI from 'jsbi'
import React, { useCallback, useMemo, useState, useEffect } from 'react' import React, { useCallback, useMemo, useState, useEffect } from 'react'
import { Fraction, Percent, Price, Token, TokenAmount, WETH9 } from '@uniswap/sdk-core' import { Fraction, Percent, Price, Token, CurrencyAmount, WETH9 } from '@uniswap/sdk-core'
import { FACTORY_ADDRESS, JSBI } from '@uniswap/v2-sdk' import { FACTORY_ADDRESS } from '@uniswap/v2-sdk'
import { Redirect, RouteComponentProps } from 'react-router' import { Redirect, RouteComponentProps } from 'react-router'
import { Text } from 'rebass' import { Text } from 'rebass'
import { AutoColumn } from '../../components/Column' import { AutoColumn } from '../../components/Column'
...@@ -59,9 +60,15 @@ function EmptyState({ message }: { message: string }) { ...@@ -59,9 +60,15 @@ function EmptyState({ message }: { message: string }) {
) )
} }
function LiquidityInfo({ token0Amount, token1Amount }: { token0Amount: TokenAmount; token1Amount: TokenAmount }) { function LiquidityInfo({
const currency0 = unwrappedToken(token0Amount.token) token0Amount,
const currency1 = unwrappedToken(token1Amount.token) token1Amount,
}: {
token0Amount: CurrencyAmount<Token>
token1Amount: CurrencyAmount<Token>
}) {
const currency0 = unwrappedToken(token0Amount.currency)
const currency1 = unwrappedToken(token1Amount.currency)
return ( return (
<AutoColumn gap="8px"> <AutoColumn gap="8px">
...@@ -105,10 +112,10 @@ function V2PairMigration({ ...@@ -105,10 +112,10 @@ function V2PairMigration({
token1, token1,
}: { }: {
pair: Contract pair: Contract
pairBalance: TokenAmount pairBalance: CurrencyAmount<Token>
totalSupply: TokenAmount totalSupply: CurrencyAmount<Token>
reserve0: TokenAmount reserve0: CurrencyAmount<Token>
reserve1: TokenAmount reserve1: CurrencyAmount<Token>
token0: Token token0: Token
token1: Token token1: Token
}) { }) {
...@@ -128,11 +135,19 @@ function V2PairMigration({ ...@@ -128,11 +135,19 @@ function V2PairMigration({
// this is just getLiquidityValue with the fee off, but for the passed pair // this is just getLiquidityValue with the fee off, but for the passed pair
const token0Value = useMemo( const token0Value = useMemo(
() => new TokenAmount(token0, JSBI.divide(JSBI.multiply(pairBalance.raw, reserve0.raw), totalSupply.raw)), () =>
CurrencyAmount.fromRawAmount(
token0,
JSBI.divide(JSBI.multiply(pairBalance.quotient, reserve0.quotient), totalSupply.quotient)
),
[token0, pairBalance, reserve0, totalSupply] [token0, pairBalance, reserve0, totalSupply]
) )
const token1Value = useMemo( const token1Value = useMemo(
() => new TokenAmount(token1, JSBI.divide(JSBI.multiply(pairBalance.raw, reserve1.raw), totalSupply.raw)), () =>
CurrencyAmount.fromRawAmount(
token1,
JSBI.divide(JSBI.multiply(pairBalance.quotient, reserve1.quotient), totalSupply.quotient)
),
[token1, pairBalance, reserve1, totalSupply] [token1, pairBalance, reserve1, totalSupply]
) )
...@@ -142,7 +157,7 @@ function V2PairMigration({ ...@@ -142,7 +157,7 @@ function V2PairMigration({
const noLiquidity = poolState === PoolState.NOT_EXISTS const noLiquidity = poolState === PoolState.NOT_EXISTS
// get spot prices + price difference // get spot prices + price difference
const v2SpotPrice = useMemo(() => new Price(token0, token1, reserve0.raw, reserve1.raw), [ const v2SpotPrice = useMemo(() => new Price(token0, token1, reserve0.quotient, reserve1.quotient), [
token0, token0,
token1, token1,
reserve0, reserve0,
...@@ -191,18 +206,18 @@ function V2PairMigration({ ...@@ -191,18 +206,18 @@ function V2PairMigration({
pool: pool ?? new Pool(token0, token1, feeAmount, sqrtPrice, 0, tick, []), pool: pool ?? new Pool(token0, token1, feeAmount, sqrtPrice, 0, tick, []),
tickLower, tickLower,
tickUpper, tickUpper,
amount0: token0Value.raw, amount0: token0Value.quotient,
amount1: token1Value.raw, amount1: token1Value.quotient,
}) })
: undefined : undefined
const v3Amount0Min = useMemo( const v3Amount0Min = useMemo(
() => () =>
position && position &&
new TokenAmount( CurrencyAmount.fromRawAmount(
token0, token0,
JSBI.divide( JSBI.divide(
JSBI.multiply(position.amount0.raw, JSBI.BigInt(10000 - JSBI.toNumber(allowedSlippage.numerator))), JSBI.multiply(position.amount0.quotient, JSBI.BigInt(10000 - JSBI.toNumber(allowedSlippage.numerator))),
JSBI.BigInt(10000) JSBI.BigInt(10000)
) )
), ),
...@@ -211,10 +226,10 @@ function V2PairMigration({ ...@@ -211,10 +226,10 @@ function V2PairMigration({
const v3Amount1Min = useMemo( const v3Amount1Min = useMemo(
() => () =>
position && position &&
new TokenAmount( CurrencyAmount.fromRawAmount(
token1, token1,
JSBI.divide( JSBI.divide(
JSBI.multiply(position.amount1.raw, JSBI.BigInt(10000 - JSBI.toNumber(allowedSlippage.numerator))), JSBI.multiply(position.amount1.quotient, JSBI.BigInt(10000 - JSBI.toNumber(allowedSlippage.numerator))),
JSBI.BigInt(10000) JSBI.BigInt(10000)
) )
), ),
...@@ -222,11 +237,13 @@ function V2PairMigration({ ...@@ -222,11 +237,13 @@ function V2PairMigration({
) )
const refund0 = useMemo( const refund0 = useMemo(
() => position && new TokenAmount(token0, JSBI.subtract(token0Value.raw, position.amount0.raw)), () =>
position && CurrencyAmount.fromRawAmount(token0, JSBI.subtract(token0Value.quotient, position.amount0.quotient)),
[token0Value, position, token0] [token0Value, position, token0]
) )
const refund1 = useMemo( const refund1 = useMemo(
() => position && new TokenAmount(token1, JSBI.subtract(token1Value.raw, position.amount1.raw)), () =>
position && CurrencyAmount.fromRawAmount(token1, JSBI.subtract(token1Value.quotient, position.amount1.quotient)),
[token1Value, position, token1] [token1Value, position, token1]
) )
...@@ -283,7 +300,7 @@ function V2PairMigration({ ...@@ -283,7 +300,7 @@ function V2PairMigration({
data.push( data.push(
migrator.interface.encodeFunctionData('selfPermit', [ migrator.interface.encodeFunctionData('selfPermit', [
pair.address, pair.address,
`0x${pairBalance.raw.toString(16)}`, `0x${pairBalance.quotient.toString(16)}`,
deadlineToUse, deadlineToUse,
signatureData.v, signatureData.v,
signatureData.r, signatureData.r,
...@@ -309,15 +326,15 @@ function V2PairMigration({ ...@@ -309,15 +326,15 @@ function V2PairMigration({
migrator.interface.encodeFunctionData('migrate', [ migrator.interface.encodeFunctionData('migrate', [
{ {
pair: pair.address, pair: pair.address,
liquidityToMigrate: `0x${pairBalance.raw.toString(16)}`, liquidityToMigrate: `0x${pairBalance.quotient.toString(16)}`,
percentageToMigrate, percentageToMigrate,
token0: token0.address, token0: token0.address,
token1: token1.address, token1: token1.address,
fee: feeAmount, fee: feeAmount,
tickLower, tickLower,
tickUpper, tickUpper,
amount0Min: `0x${v3Amount0Min.raw.toString(16)}`, amount0Min: `0x${v3Amount0Min.quotient.toString(16)}`,
amount1Min: `0x${v3Amount1Min.raw.toString(16)}`, amount1Min: `0x${v3Amount1Min.quotient.toString(16)}`,
recipient: account, recipient: account,
deadline: deadlineToUse, deadline: deadlineToUse,
refundAsETH: true, // hard-code this for now refundAsETH: true, // hard-code this for now
...@@ -371,7 +388,7 @@ function V2PairMigration({ ...@@ -371,7 +388,7 @@ function V2PairMigration({
currency1, currency1,
]) ])
const isSuccessfullyMigrated = !!pendingMigrationHash && JSBI.equal(pairBalance.raw, ZERO) const isSuccessfullyMigrated = !!pendingMigrationHash && JSBI.equal(pairBalance.quotient, ZERO)
return ( return (
<AutoColumn gap="20px"> <AutoColumn gap="20px">
...@@ -646,14 +663,14 @@ export default function MigrateV2Pair({ ...@@ -646,14 +663,14 @@ export default function MigrateV2Pair({
const pairBalance = useTokenBalance(account ?? undefined, liquidityToken) const pairBalance = useTokenBalance(account ?? undefined, liquidityToken)
const totalSupply = useTotalSupply(liquidityToken) const totalSupply = useTotalSupply(liquidityToken)
const [reserve0Raw, reserve1Raw] = useSingleCallResult(pair, 'getReserves')?.result ?? [] const [reserve0Raw, reserve1Raw] = useSingleCallResult(pair, 'getReserves')?.result ?? []
const reserve0 = useMemo(() => (token0 && reserve0Raw ? new TokenAmount(token0, reserve0Raw) : undefined), [ const reserve0 = useMemo(
token0, () => (token0 && reserve0Raw ? CurrencyAmount.fromRawAmount(token0, reserve0Raw) : undefined),
reserve0Raw, [token0, reserve0Raw]
]) )
const reserve1 = useMemo(() => (token1 && reserve1Raw ? new TokenAmount(token1, reserve1Raw) : undefined), [ const reserve1 = useMemo(
token1, () => (token1 && reserve1Raw ? CurrencyAmount.fromRawAmount(token1, reserve1Raw) : undefined),
reserve1Raw, [token1, reserve1Raw]
]) )
// redirect for invalid url params // redirect for invalid url params
if ( if (
......
...@@ -23,7 +23,7 @@ import { currencyId } from 'utils/currencyId' ...@@ -23,7 +23,7 @@ import { currencyId } from 'utils/currencyId'
import { formatTokenAmount } from 'utils/formatTokenAmount' import { formatTokenAmount } from 'utils/formatTokenAmount'
import { useV3PositionFees } from 'hooks/useV3PositionFees' import { useV3PositionFees } from 'hooks/useV3PositionFees'
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { WETH9, Currency, CurrencyAmount, Percent, Fraction, Price } from '@uniswap/sdk-core' import { Token, WETH9, Currency, CurrencyAmount, Percent, Fraction, Price, currencyEquals } from '@uniswap/sdk-core'
import { useActiveWeb3React } from 'hooks' import { useActiveWeb3React } from 'hooks'
import { useV3NFTPositionManagerContract } from 'hooks/useContract' import { useV3NFTPositionManagerContract } from 'hooks/useContract'
import { useIsTransactionPending, useTransactionAdder } from 'state/transactions/hooks' import { useIsTransactionPending, useTransactionAdder } from 'state/transactions/hooks'
...@@ -155,7 +155,11 @@ function CurrentPriceCard({ ...@@ -155,7 +155,11 @@ function CurrentPriceCard({
) )
} }
function getRatio(lower: Price, current: Price, upper: Price) { function getRatio(
lower: Price<Currency, Currency>,
current: Price<Currency, Currency>,
upper: Price<Currency, Currency>
) {
try { try {
if (!current.greaterThan(lower)) { if (!current.greaterThan(lower)) {
return 100 return 100
...@@ -255,8 +259,12 @@ export function PositionPage({ ...@@ -255,8 +259,12 @@ export function PositionPage({
const { calldata, value } = NonfungiblePositionManager.collectCallParameters({ const { calldata, value } = NonfungiblePositionManager.collectCallParameters({
tokenId: tokenId.toString(), tokenId: tokenId.toString(),
expectedCurrencyOwed0: feeValue0.token.equals(WETH9[chainId]) ? CurrencyAmount.ether(feeValue0.raw) : feeValue0, expectedCurrencyOwed0: currencyEquals(feeValue0.currency, WETH9[chainId])
expectedCurrencyOwed1: feeValue1.token.equals(WETH9[chainId]) ? CurrencyAmount.ether(feeValue1.raw) : feeValue1, ? CurrencyAmount.ether(feeValue0.quotient)
: feeValue0,
expectedCurrencyOwed1: currencyEquals(feeValue1.currency, WETH9[chainId])
? CurrencyAmount.ether(feeValue1.quotient)
: feeValue1,
recipient: account, recipient: account,
}) })
...@@ -285,11 +293,11 @@ export function PositionPage({ ...@@ -285,11 +293,11 @@ export function PositionPage({
ReactGA.event({ ReactGA.event({
category: 'Liquidity', category: 'Liquidity',
action: 'CollectV3', action: 'CollectV3',
label: [feeValue0.token.symbol, feeValue1.token.symbol].join('/'), label: [feeValue0.currency.symbol, feeValue1.currency.symbol].join('/'),
}) })
addTransaction(response, { addTransaction(response, {
summary: `Collect ${feeValue0.token.symbol}/${feeValue1.token.symbol} fees`, summary: `Collect ${feeValue0.currency.symbol}/${feeValue1.currency.symbol} fees`,
}) })
}) })
}) })
...@@ -305,14 +313,14 @@ export function PositionPage({ ...@@ -305,14 +313,14 @@ export function PositionPage({
const price0 = useUSDCPrice(token0 ?? undefined) const price0 = useUSDCPrice(token0 ?? undefined)
const price1 = useUSDCPrice(token1 ?? undefined) const price1 = useUSDCPrice(token1 ?? undefined)
const fiatValueOfFees: CurrencyAmount | null = useMemo(() => { const fiatValueOfFees: CurrencyAmount<Token> | null = useMemo(() => {
if (!price0 || !price1 || !feeValue0 || !feeValue1) return null if (!price0 || !price1 || !feeValue0 || !feeValue1) return null
const amount0 = price0.quote(feeValue0) const amount0 = price0.quote(feeValue0)
const amount1 = price1.quote(feeValue1) const amount1 = price1.quote(feeValue1)
return amount0.add(amount1) return amount0.add(amount1)
}, [price0, price1, feeValue0, feeValue1]) }, [price0, price1, feeValue0, feeValue1])
const fiatValueOfLiquidity: CurrencyAmount | null = useMemo(() => { const fiatValueOfLiquidity: CurrencyAmount<Token> | null = useMemo(() => {
if (!price0 || !price1 || !position) return null if (!price0 || !price1 || !position) return null
const amount0 = price0.quote(position.amount0) const amount0 = price0.quote(position.amount0)
const amount1 = price1.quote(position.amount1) const amount1 = price1.quote(position.amount1)
......
...@@ -110,7 +110,9 @@ export default function Pool() { ...@@ -110,7 +110,9 @@ export default function Pool() {
// show liquidity even if its deposited in rewards contract // show liquidity even if its deposited in rewards contract
const stakingInfo = useStakingInfo() const stakingInfo = useStakingInfo()
const stakingInfosWithBalance = stakingInfo?.filter((pool) => JSBI.greaterThan(pool.stakedAmount.raw, BIG_INT_ZERO)) const stakingInfosWithBalance = stakingInfo?.filter((pool) =>
JSBI.greaterThan(pool.stakedAmount.quotient, BIG_INT_ZERO)
)
const stakingPairs = useV2Pairs(stakingInfosWithBalance?.map((stakingInfo) => stakingInfo.tokens)) const stakingPairs = useV2Pairs(stakingInfosWithBalance?.map((stakingInfo) => stakingInfo.tokens))
// remove any pairs that also are included in pairs with stake in mining pool // remove any pairs that also are included in pairs with stake in mining pool
......
import { Currency, ETHER, TokenAmount } from '@uniswap/sdk-core' import { Currency, ETHER, CurrencyAmount, Token } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import React, { useCallback, useEffect, useState } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { Plus } from 'react-feather' import { Plus } from 'react-feather'
import { Text } from 'rebass' import { Text } from 'rebass'
...@@ -56,12 +56,12 @@ export default function PoolFinder() { ...@@ -56,12 +56,12 @@ export default function PoolFinder() {
Boolean( Boolean(
pairState === PairState.EXISTS && pairState === PairState.EXISTS &&
pair && pair &&
JSBI.equal(pair.reserve0.raw, JSBI.BigInt(0)) && JSBI.equal(pair.reserve0.quotient, JSBI.BigInt(0)) &&
JSBI.equal(pair.reserve1.raw, JSBI.BigInt(0)) JSBI.equal(pair.reserve1.quotient, JSBI.BigInt(0))
) )
const position: TokenAmount | undefined = useTokenBalance(account ?? undefined, pair?.liquidityToken) const position: CurrencyAmount<Token> | undefined = useTokenBalance(account ?? undefined, pair?.liquidityToken)
const hasPosition = Boolean(position && JSBI.greaterThan(position.raw, JSBI.BigInt(0))) const hasPosition = Boolean(position && JSBI.greaterThan(position.quotient, JSBI.BigInt(0)))
const handleCurrencySelect = useCallback( const handleCurrencySelect = useCallback(
(currency: Currency) => { (currency: Currency) => {
......
...@@ -21,7 +21,7 @@ import ReactGA from 'react-ga' ...@@ -21,7 +21,7 @@ import ReactGA from 'react-ga'
import { useActiveWeb3React } from 'hooks' import { useActiveWeb3React } from 'hooks'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { useTransactionAdder } from 'state/transactions/hooks' import { useTransactionAdder } from 'state/transactions/hooks'
import { WETH9, CurrencyAmount, Percent } from '@uniswap/sdk-core' import { WETH9, CurrencyAmount, currencyEquals, Percent } from '@uniswap/sdk-core'
import { TYPE } from 'theme' import { TYPE } from 'theme'
import { Wrapper, SmallMaxButton, ResponsiveHeaderText } from './styled' import { Wrapper, SmallMaxButton, ResponsiveHeaderText } from './styled'
import Loader from 'components/Loader' import Loader from 'components/Loader'
...@@ -122,11 +122,11 @@ function Remove({ tokenId }: { tokenId: BigNumber }) { ...@@ -122,11 +122,11 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
slippageTolerance: allowedSlippage, slippageTolerance: allowedSlippage,
deadline: deadline.toString(), deadline: deadline.toString(),
collectOptions: { collectOptions: {
expectedCurrencyOwed0: liquidityValue0.token.equals(WETH9[chainId]) expectedCurrencyOwed0: currencyEquals(liquidityValue0.currency, WETH9[chainId])
? CurrencyAmount.ether(feeValue0.raw) ? CurrencyAmount.ether(feeValue0.quotient)
: feeValue0, : feeValue0,
expectedCurrencyOwed1: liquidityValue1.token.equals(WETH9[chainId]) expectedCurrencyOwed1: currencyEquals(liquidityValue1.currency, WETH9[chainId])
? CurrencyAmount.ether(feeValue1.raw) ? CurrencyAmount.ether(feeValue1.quotient)
: feeValue1, : feeValue1,
recipient: account, recipient: account,
}, },
...@@ -154,12 +154,12 @@ function Remove({ tokenId }: { tokenId: BigNumber }) { ...@@ -154,12 +154,12 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
ReactGA.event({ ReactGA.event({
category: 'Liquidity', category: 'Liquidity',
action: 'RemoveV3', action: 'RemoveV3',
label: [liquidityValue0.token.symbol, liquidityValue1.token.symbol].join('/'), label: [liquidityValue0.currency.symbol, liquidityValue1.currency.symbol].join('/'),
}) })
setTxnHash(response.hash) setTxnHash(response.hash)
setAttemptingTxn(false) setAttemptingTxn(false)
addTransaction(response, { addTransaction(response, {
summary: `Remove ${liquidityValue0.token.symbol}/${liquidityValue1.token.symbol} V3 liquidity`, summary: `Remove ${liquidityValue0.currency.symbol}/${liquidityValue1.currency.symbol} V3 liquidity`,
}) })
}) })
}) })
......
import { Contract } from '@ethersproject/contracts' import { Contract } from '@ethersproject/contracts'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { Currency, currencyEquals, ETHER, Percent, WETH9 } from '@uniswap/sdk-core' import { Currency, currencyEquals, Percent, WETH9 } from '@uniswap/sdk-core'
import React, { useCallback, useContext, useMemo, useState } from 'react' import React, { useCallback, useContext, useMemo, useState } from 'react'
import { ArrowDown, Plus } from 'react-feather' import { ArrowDown, Plus } from 'react-feather'
import ReactGA from 'react-ga' import ReactGA from 'react-ga'
...@@ -163,8 +163,8 @@ export default function RemoveLiquidity({ ...@@ -163,8 +163,8 @@ export default function RemoveLiquidity({
const liquidityAmount = parsedAmounts[Field.LIQUIDITY] const liquidityAmount = parsedAmounts[Field.LIQUIDITY]
if (!liquidityAmount) throw new Error('missing liquidity amount') if (!liquidityAmount) throw new Error('missing liquidity amount')
const currencyBIsETH = currencyB === ETHER const currencyBIsETH = currencyB.isEther
const oneCurrencyIsETH = currencyA === ETHER || currencyBIsETH const oneCurrencyIsETH = currencyA.isEther || currencyBIsETH
if (!tokenA || !tokenB) throw new Error('could not wrap') if (!tokenA || !tokenB) throw new Error('could not wrap')
...@@ -176,7 +176,7 @@ export default function RemoveLiquidity({ ...@@ -176,7 +176,7 @@ export default function RemoveLiquidity({
methodNames = ['removeLiquidityETH', 'removeLiquidityETHSupportingFeeOnTransferTokens'] methodNames = ['removeLiquidityETH', 'removeLiquidityETHSupportingFeeOnTransferTokens']
args = [ args = [
currencyBIsETH ? tokenA.address : tokenB.address, currencyBIsETH ? tokenA.address : tokenB.address,
liquidityAmount.raw.toString(), liquidityAmount.quotient.toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(),
account, account,
...@@ -189,7 +189,7 @@ export default function RemoveLiquidity({ ...@@ -189,7 +189,7 @@ export default function RemoveLiquidity({
args = [ args = [
tokenA.address, tokenA.address,
tokenB.address, tokenB.address,
liquidityAmount.raw.toString(), liquidityAmount.quotient.toString(),
amountsMin[Field.CURRENCY_A].toString(), amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(), amountsMin[Field.CURRENCY_B].toString(),
account, account,
...@@ -204,7 +204,7 @@ export default function RemoveLiquidity({ ...@@ -204,7 +204,7 @@ export default function RemoveLiquidity({
methodNames = ['removeLiquidityETHWithPermit', 'removeLiquidityETHWithPermitSupportingFeeOnTransferTokens'] methodNames = ['removeLiquidityETHWithPermit', 'removeLiquidityETHWithPermitSupportingFeeOnTransferTokens']
args = [ args = [
currencyBIsETH ? tokenA.address : tokenB.address, currencyBIsETH ? tokenA.address : tokenB.address,
liquidityAmount.raw.toString(), liquidityAmount.quotient.toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(),
account, account,
...@@ -221,7 +221,7 @@ export default function RemoveLiquidity({ ...@@ -221,7 +221,7 @@ export default function RemoveLiquidity({
args = [ args = [
tokenA.address, tokenA.address,
tokenB.address, tokenB.address,
liquidityAmount.raw.toString(), liquidityAmount.quotient.toString(),
amountsMin[Field.CURRENCY_A].toString(), amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(), amountsMin[Field.CURRENCY_B].toString(),
account, account,
...@@ -383,7 +383,7 @@ export default function RemoveLiquidity({ ...@@ -383,7 +383,7 @@ export default function RemoveLiquidity({
[onUserInput] [onUserInput]
) )
const oneCurrencyIsETH = currencyA === ETHER || currencyB === ETHER const oneCurrencyIsETH = currencyA?.isEther || currencyB?.isEther
const oneCurrencyIsWETH = Boolean( const oneCurrencyIsWETH = Boolean(
chainId && chainId &&
((currencyA && currencyEquals(WETH9[chainId], currencyA)) || ((currencyA && currencyEquals(WETH9[chainId], currencyA)) ||
...@@ -526,8 +526,8 @@ export default function RemoveLiquidity({ ...@@ -526,8 +526,8 @@ export default function RemoveLiquidity({
<RowBetween style={{ justifyContent: 'flex-end' }}> <RowBetween style={{ justifyContent: 'flex-end' }}>
{oneCurrencyIsETH ? ( {oneCurrencyIsETH ? (
<StyledInternalLink <StyledInternalLink
to={`/remove/v2/${currencyA === ETHER ? WETH9[chainId].address : currencyIdA}/${ to={`/remove/v2/${currencyA?.isEther ? WETH9[chainId].address : currencyIdA}/${
currencyB === ETHER ? WETH9[chainId].address : currencyIdB currencyB?.isEther ? WETH9[chainId].address : currencyIdB
}`} }`}
> >
Receive WETH Receive WETH
......
import { CurrencyAmount, Token } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Token, TradeType } 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 } from '@uniswap/v3-sdk'
import { AdvancedSwapDetails } from 'components/swap/AdvancedSwapDetails' import { AdvancedSwapDetails } from 'components/swap/AdvancedSwapDetails'
...@@ -76,7 +76,7 @@ export default function Swap({ history }: RouteComponentProps) { ...@@ -76,7 +76,7 @@ export default function Swap({ history }: RouteComponentProps) {
] ]
const [dismissTokenWarning, setDismissTokenWarning] = useState<boolean>(false) const [dismissTokenWarning, setDismissTokenWarning] = useState<boolean>(false)
const urlLoadedTokens: Token[] = useMemo( const urlLoadedTokens: Token[] = useMemo(
() => [loadedInputCurrency, loadedOutputCurrency]?.filter((c): c is Token => c instanceof Token) ?? [], () => [loadedInputCurrency, loadedOutputCurrency]?.filter((c): c is Token => c?.isToken ?? false) ?? [],
[loadedInputCurrency, loadedOutputCurrency] [loadedInputCurrency, loadedOutputCurrency]
) )
const handleConfirmTokenWarning = useCallback(() => { const handleConfirmTokenWarning = useCallback(() => {
...@@ -168,7 +168,7 @@ export default function Swap({ history }: RouteComponentProps) { ...@@ -168,7 +168,7 @@ export default function Swap({ history }: RouteComponentProps) {
// modal and loading // modal and loading
const [{ showConfirm, tradeToConfirm, swapErrorMessage, attemptingTxn, txHash }, setSwapState] = useState<{ const [{ showConfirm, tradeToConfirm, swapErrorMessage, attemptingTxn, txHash }, setSwapState] = useState<{
showConfirm: boolean showConfirm: boolean
tradeToConfirm: V2Trade | V3Trade | undefined tradeToConfirm: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined
attemptingTxn: boolean attemptingTxn: boolean
swapErrorMessage: string | undefined swapErrorMessage: string | undefined
txHash: string | undefined txHash: string | undefined
...@@ -225,7 +225,7 @@ export default function Swap({ history }: RouteComponentProps) { ...@@ -225,7 +225,7 @@ export default function Swap({ history }: RouteComponentProps) {
} }
}, [approvalState, approvalSubmitted]) }, [approvalState, approvalSubmitted])
const maxInputAmount: CurrencyAmount | undefined = maxAmountSpend(currencyBalances[Field.INPUT]) const maxInputAmount: CurrencyAmount<Currency> | undefined = maxAmountSpend(currencyBalances[Field.INPUT])
const showMaxButton = Boolean(maxInputAmount?.greaterThan(0) && !parsedAmounts[Field.INPUT]?.equalTo(maxInputAmount)) const showMaxButton = Boolean(maxInputAmount?.greaterThan(0) && !parsedAmounts[Field.INPUT]?.equalTo(maxInputAmount))
// the callback to execute the swap // the callback to execute the swap
......
...@@ -19,8 +19,8 @@ import { ...@@ -19,8 +19,8 @@ import {
import { DateTime } from 'luxon' import { DateTime } from 'luxon'
import ReactMarkdown from 'react-markdown' import ReactMarkdown from 'react-markdown'
import VoteModal from '../../components/vote/VoteModal' import VoteModal from '../../components/vote/VoteModal'
import { TokenAmount } from '@uniswap/sdk-core' import { Token, CurrencyAmount } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { AVERAGE_BLOCK_TIME_IN_SECS, COMMON_CONTRACT_NAMES, UNI, ZERO_ADDRESS } from '../../constants' import { AVERAGE_BLOCK_TIME_IN_SECS, COMMON_CONTRACT_NAMES, UNI, ZERO_ADDRESS } from '../../constants'
import { getEtherscanLink, isAddress } from '../../utils' import { getEtherscanLink, isAddress } from '../../utils'
...@@ -152,21 +152,24 @@ export default function VotePage({ ...@@ -152,21 +152,24 @@ export default function VotePage({
proposalData && totalVotes ? ((proposalData.againstCount * 100) / totalVotes).toFixed(0) + '%' : '0%' proposalData && totalVotes ? ((proposalData.againstCount * 100) / totalVotes).toFixed(0) + '%' : '0%'
// only count available votes as of the proposal start block // only count available votes as of the proposal start block
const availableVotes: TokenAmount | undefined = useUserVotesAsOfBlock(proposalData?.startBlock ?? undefined) const availableVotes: CurrencyAmount<Token> | undefined = useUserVotesAsOfBlock(proposalData?.startBlock ?? undefined)
// only show voting if user has > 0 votes at proposal start block and proposal is active, // only show voting if user has > 0 votes at proposal start block and proposal is active,
const showVotingButtons = const showVotingButtons =
availableVotes && availableVotes &&
JSBI.greaterThan(availableVotes.raw, JSBI.BigInt(0)) && JSBI.greaterThan(availableVotes.quotient, JSBI.BigInt(0)) &&
proposalData && proposalData &&
proposalData.status === ProposalState.Active proposalData.status === ProposalState.Active
const uniBalance: TokenAmount | undefined = useTokenBalance(account ?? undefined, chainId ? UNI[chainId] : undefined) const uniBalance: CurrencyAmount<Token> | undefined = useTokenBalance(
account ?? undefined,
chainId ? UNI[chainId] : undefined
)
const userDelegatee: string | undefined = useUserDelegatee() const userDelegatee: string | undefined = useUserDelegatee()
// in blurb link to home page if they are able to unlock // in blurb link to home page if they are able to unlock
const showLinkForUnlock = Boolean( const showLinkForUnlock = Boolean(
uniBalance && JSBI.notEqual(uniBalance.raw, JSBI.BigInt(0)) && userDelegatee === ZERO_ADDRESS uniBalance && JSBI.notEqual(uniBalance.quotient, JSBI.BigInt(0)) && userDelegatee === ZERO_ADDRESS
) )
// show links in propsoal details if content is an address // show links in propsoal details if content is an address
......
...@@ -20,8 +20,8 @@ import DelegateModal from '../../components/vote/DelegateModal' ...@@ -20,8 +20,8 @@ import DelegateModal from '../../components/vote/DelegateModal'
import { useTokenBalance } from '../../state/wallet/hooks' import { useTokenBalance } from '../../state/wallet/hooks'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { UNI, ZERO_ADDRESS } from '../../constants' import { UNI, ZERO_ADDRESS } from '../../constants'
import { TokenAmount, ChainId } from '@uniswap/sdk-core' import { Token, CurrencyAmount, ChainId } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { shortenAddress, getEtherscanLink } from '../../utils' import { shortenAddress, getEtherscanLink } from '../../utils'
import Loader from '../../components/Loader' import Loader from '../../components/Loader'
import FormattedCurrencyAmount from '../../components/FormattedCurrencyAmount' import FormattedCurrencyAmount from '../../components/FormattedCurrencyAmount'
...@@ -119,13 +119,16 @@ export default function Vote() { ...@@ -119,13 +119,16 @@ export default function Vote() {
const allProposals: ProposalData[] = useAllProposalData() const allProposals: ProposalData[] = useAllProposalData()
// user data // user data
const availableVotes: TokenAmount | undefined = useUserVotes() const availableVotes: CurrencyAmount<Token> | undefined = useUserVotes()
const uniBalance: TokenAmount | undefined = useTokenBalance(account ?? undefined, chainId ? UNI[chainId] : undefined) const uniBalance: CurrencyAmount<Token> | undefined = useTokenBalance(
account ?? undefined,
chainId ? UNI[chainId] : undefined
)
const userDelegatee: string | undefined = useUserDelegatee() const userDelegatee: string | undefined = useUserDelegatee()
// show delegation option if they have have a balance, but have not delegated // show delegation option if they have have a balance, but have not delegated
const showUnlockVoting = Boolean( const showUnlockVoting = Boolean(
uniBalance && JSBI.notEqual(uniBalance.raw, JSBI.BigInt(0)) && userDelegatee === ZERO_ADDRESS uniBalance && JSBI.notEqual(uniBalance.quotient, JSBI.BigInt(0)) && userDelegatee === ZERO_ADDRESS
) )
return ( return (
...@@ -176,14 +179,14 @@ export default function Vote() { ...@@ -176,14 +179,14 @@ export default function Vote() {
> >
Unlock Voting Unlock Voting
</ButtonPrimary> </ButtonPrimary>
) : availableVotes && JSBI.notEqual(JSBI.BigInt(0), availableVotes?.raw) ? ( ) : availableVotes && JSBI.notEqual(JSBI.BigInt(0), availableVotes?.quotient) ? (
<TYPE.body fontWeight={500} mr="6px"> <TYPE.body fontWeight={500} mr="6px">
<FormattedCurrencyAmount currencyAmount={availableVotes} /> Votes <FormattedCurrencyAmount currencyAmount={availableVotes} /> Votes
</TYPE.body> </TYPE.body>
) : uniBalance && ) : uniBalance &&
userDelegatee && userDelegatee &&
userDelegatee !== ZERO_ADDRESS && userDelegatee !== ZERO_ADDRESS &&
JSBI.notEqual(JSBI.BigInt(0), uniBalance?.raw) ? ( JSBI.notEqual(JSBI.BigInt(0), uniBalance?.quotient) ? (
<TYPE.body fontWeight={500} mr="6px"> <TYPE.body fontWeight={500} mr="6px">
<FormattedCurrencyAmount currencyAmount={uniBalance} /> Votes <FormattedCurrencyAmount currencyAmount={uniBalance} /> Votes
</TYPE.body> </TYPE.body>
......
import { Currency, CurrencyAmount, Percent, TokenAmount } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI, Pair } from '@uniswap/v2-sdk' import { Token, Currency, Percent, CurrencyAmount } from '@uniswap/sdk-core'
import { Pair } from '@uniswap/v2-sdk'
import { useCallback } from 'react' import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
import { useV2Pair } from '../../hooks/useV2Pairs' import { useV2Pair } from '../../hooks/useV2Pairs'
...@@ -23,9 +24,9 @@ export function useDerivedBurnInfo( ...@@ -23,9 +24,9 @@ export function useDerivedBurnInfo(
pair?: Pair | null pair?: Pair | null
parsedAmounts: { parsedAmounts: {
[Field.LIQUIDITY_PERCENT]: Percent [Field.LIQUIDITY_PERCENT]: Percent
[Field.LIQUIDITY]?: TokenAmount [Field.LIQUIDITY]?: CurrencyAmount<Token>
[Field.CURRENCY_A]?: CurrencyAmount [Field.CURRENCY_A]?: CurrencyAmount<Currency>
[Field.CURRENCY_B]?: CurrencyAmount [Field.CURRENCY_B]?: CurrencyAmount<Currency>
} }
error?: string error?: string
} { } {
...@@ -38,7 +39,7 @@ export function useDerivedBurnInfo( ...@@ -38,7 +39,7 @@ export function useDerivedBurnInfo(
// balances // balances
const relevantTokenBalances = useTokenBalances(account ?? undefined, [pair?.liquidityToken]) const relevantTokenBalances = useTokenBalances(account ?? undefined, [pair?.liquidityToken])
const userLiquidity: undefined | TokenAmount = relevantTokenBalances?.[pair?.liquidityToken?.address ?? ''] const userLiquidity: undefined | CurrencyAmount<Token> = relevantTokenBalances?.[pair?.liquidityToken?.address ?? '']
const [tokenA, tokenB] = [wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId)] const [tokenA, tokenB] = [wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId)]
const tokens = { const tokens = {
...@@ -55,8 +56,8 @@ export function useDerivedBurnInfo( ...@@ -55,8 +56,8 @@ export function useDerivedBurnInfo(
userLiquidity && userLiquidity &&
tokenA && tokenA &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply // this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalSupply.raw, userLiquidity.raw) JSBI.greaterThanOrEqual(totalSupply.quotient, userLiquidity.quotient)
? new TokenAmount(tokenA, pair.getLiquidityValue(tokenA, totalSupply, userLiquidity, false).raw) ? CurrencyAmount.fromRawAmount(tokenA, pair.getLiquidityValue(tokenA, totalSupply, userLiquidity, false).quotient)
: undefined : undefined
const liquidityValueB = const liquidityValueB =
pair && pair &&
...@@ -64,10 +65,10 @@ export function useDerivedBurnInfo( ...@@ -64,10 +65,10 @@ export function useDerivedBurnInfo(
userLiquidity && userLiquidity &&
tokenB && tokenB &&
// this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply // this condition is a short-circuit in the case where useTokenBalance updates sooner than useTotalSupply
JSBI.greaterThanOrEqual(totalSupply.raw, userLiquidity.raw) JSBI.greaterThanOrEqual(totalSupply.quotient, userLiquidity.quotient)
? new TokenAmount(tokenB, pair.getLiquidityValue(tokenB, totalSupply, userLiquidity, false).raw) ? CurrencyAmount.fromRawAmount(tokenB, pair.getLiquidityValue(tokenB, totalSupply, userLiquidity, false).quotient)
: undefined : undefined
const liquidityValues: { [Field.CURRENCY_A]?: TokenAmount; [Field.CURRENCY_B]?: TokenAmount } = { const liquidityValues: { [Field.CURRENCY_A]?: CurrencyAmount<Token>; [Field.CURRENCY_B]?: CurrencyAmount<Token> } = {
[Field.CURRENCY_A]: liquidityValueA, [Field.CURRENCY_A]: liquidityValueA,
[Field.CURRENCY_B]: liquidityValueB, [Field.CURRENCY_B]: liquidityValueB,
} }
...@@ -82,7 +83,7 @@ export function useDerivedBurnInfo( ...@@ -82,7 +83,7 @@ export function useDerivedBurnInfo(
if (pair?.liquidityToken) { if (pair?.liquidityToken) {
const independentAmount = tryParseAmount(typedValue, pair.liquidityToken) const independentAmount = tryParseAmount(typedValue, pair.liquidityToken)
if (independentAmount && userLiquidity && !independentAmount.greaterThan(userLiquidity)) { if (independentAmount && userLiquidity && !independentAmount.greaterThan(userLiquidity)) {
percentToRemove = new Percent(independentAmount.raw, userLiquidity.raw) percentToRemove = new Percent(independentAmount.quotient, userLiquidity.quotient)
} }
} }
} }
...@@ -92,29 +93,32 @@ export function useDerivedBurnInfo( ...@@ -92,29 +93,32 @@ export function useDerivedBurnInfo(
const independentAmount = tryParseAmount(typedValue, tokens[independentField]) const independentAmount = tryParseAmount(typedValue, tokens[independentField])
const liquidityValue = liquidityValues[independentField] const liquidityValue = liquidityValues[independentField]
if (independentAmount && liquidityValue && !independentAmount.greaterThan(liquidityValue)) { if (independentAmount && liquidityValue && !independentAmount.greaterThan(liquidityValue)) {
percentToRemove = new Percent(independentAmount.raw, liquidityValue.raw) percentToRemove = new Percent(independentAmount.quotient, liquidityValue.quotient)
} }
} }
} }
const parsedAmounts: { const parsedAmounts: {
[Field.LIQUIDITY_PERCENT]: Percent [Field.LIQUIDITY_PERCENT]: Percent
[Field.LIQUIDITY]?: TokenAmount [Field.LIQUIDITY]?: CurrencyAmount<Token>
[Field.CURRENCY_A]?: TokenAmount [Field.CURRENCY_A]?: CurrencyAmount<Currency>
[Field.CURRENCY_B]?: TokenAmount [Field.CURRENCY_B]?: CurrencyAmount<Currency>
} = { } = {
[Field.LIQUIDITY_PERCENT]: percentToRemove, [Field.LIQUIDITY_PERCENT]: percentToRemove,
[Field.LIQUIDITY]: [Field.LIQUIDITY]:
userLiquidity && percentToRemove && percentToRemove.greaterThan('0') userLiquidity && percentToRemove && percentToRemove.greaterThan('0')
? new TokenAmount(userLiquidity.token, percentToRemove.multiply(userLiquidity.raw).quotient) ? CurrencyAmount.fromRawAmount(
userLiquidity.currency,
percentToRemove.multiply(userLiquidity.quotient).quotient
)
: undefined, : undefined,
[Field.CURRENCY_A]: [Field.CURRENCY_A]:
tokenA && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueA tokenA && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueA
? new TokenAmount(tokenA, percentToRemove.multiply(liquidityValueA.raw).quotient) ? CurrencyAmount.fromRawAmount(tokenA, percentToRemove.multiply(liquidityValueA.quotient).quotient)
: undefined, : undefined,
[Field.CURRENCY_B]: [Field.CURRENCY_B]:
tokenB && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueB tokenB && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueB
? new TokenAmount(tokenB, percentToRemove.multiply(liquidityValueB.raw).quotient) ? CurrencyAmount.fromRawAmount(tokenB, percentToRemove.multiply(liquidityValueB.quotient).quotient)
: undefined, : undefined,
} }
......
import { TokenAmount, Percent } from '@uniswap/sdk-core' import { Token, CurrencyAmount, Percent } from '@uniswap/sdk-core'
import { Position } from '@uniswap/v3-sdk' import { Position } from '@uniswap/v3-sdk'
import { usePool } from 'hooks/usePools' import { usePool } from 'hooks/usePools'
import { useActiveWeb3React } from 'hooks' import { useActiveWeb3React } from 'hooks'
...@@ -20,10 +20,10 @@ export function useDerivedV3BurnInfo( ...@@ -20,10 +20,10 @@ export function useDerivedV3BurnInfo(
): { ): {
position?: Position position?: Position
liquidityPercentage?: Percent liquidityPercentage?: Percent
liquidityValue0?: TokenAmount liquidityValue0?: CurrencyAmount<Token>
liquidityValue1?: TokenAmount liquidityValue1?: CurrencyAmount<Token>
feeValue0?: TokenAmount feeValue0?: CurrencyAmount<Token>
feeValue1?: TokenAmount feeValue1?: CurrencyAmount<Token>
outOfRange: boolean outOfRange: boolean
error?: string error?: string
} { } {
...@@ -52,10 +52,16 @@ export function useDerivedV3BurnInfo( ...@@ -52,10 +52,16 @@ export function useDerivedV3BurnInfo(
const liquidityValue0 = const liquidityValue0 =
positionSDK && positionSDK &&
new TokenAmount(positionSDK.amount0.token, liquidityPercentage.multiply(positionSDK.amount0.raw).quotient) CurrencyAmount.fromRawAmount(
positionSDK.amount0.currency,
liquidityPercentage.multiply(positionSDK.amount0.quotient).quotient
)
const liquidityValue1 = const liquidityValue1 =
positionSDK && positionSDK &&
new TokenAmount(positionSDK.amount1.token, liquidityPercentage.multiply(positionSDK.amount1.raw).quotient) CurrencyAmount.fromRawAmount(
positionSDK.amount1.currency,
liquidityPercentage.multiply(positionSDK.amount1.quotient).quotient
)
const [feeValue0, feeValue1] = useV3PositionFees(pool ?? undefined, position) const [feeValue0, feeValue1] = useV3PositionFees(pool ?? undefined, position)
......
import { UNI } from './../../constants/index' import { UNI } from './../../constants/index'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { TokenAmount, ChainId } from '@uniswap/sdk-core' import { CurrencyAmount, ChainId, Token } from '@uniswap/sdk-core'
import { TransactionResponse } from '@ethersproject/providers' import { TransactionResponse } from '@ethersproject/providers'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
...@@ -74,7 +74,7 @@ export function useUserHasAvailableClaim(account: string | null | undefined): bo ...@@ -74,7 +74,7 @@ export function useUserHasAvailableClaim(account: string | null | undefined): bo
return Boolean(userClaimData && !isClaimedResult.loading && isClaimedResult.result?.[0] === false) return Boolean(userClaimData && !isClaimedResult.loading && isClaimedResult.result?.[0] === false)
} }
export function useUserUnclaimedAmount(account: string | null | undefined): TokenAmount | undefined { export function useUserUnclaimedAmount(account: string | null | undefined): CurrencyAmount<Token> | undefined {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const userClaimData = useUserClaimData(account) const userClaimData = useUserClaimData(account)
const canClaim = useUserHasAvailableClaim(account) const canClaim = useUserHasAvailableClaim(account)
...@@ -82,9 +82,9 @@ export function useUserUnclaimedAmount(account: string | null | undefined): Toke ...@@ -82,9 +82,9 @@ export function useUserUnclaimedAmount(account: string | null | undefined): Toke
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
if (!uni) return undefined if (!uni) return undefined
if (!canClaim || !userClaimData) { if (!canClaim || !userClaimData) {
return new TokenAmount(uni, JSBI.BigInt(0)) return CurrencyAmount.fromRawAmount(uni, JSBI.BigInt(0))
} }
return new TokenAmount(uni, JSBI.BigInt(userClaimData.amount)) return CurrencyAmount.fromRawAmount(uni, JSBI.BigInt(userClaimData.amount))
} }
export function useClaimCallback( export function useClaimCallback(
...@@ -97,7 +97,7 @@ export function useClaimCallback( ...@@ -97,7 +97,7 @@ export function useClaimCallback(
const claimData = useUserClaimData(account) const claimData = useUserClaimData(account)
// used for popup summary // used for popup summary
const unclaimedAmount: TokenAmount | undefined = useUserUnclaimedAmount(account) const unclaimedAmount: CurrencyAmount<Token> | undefined = useUserUnclaimedAmount(account)
const addTransaction = useTransactionAdder() const addTransaction = useTransactionAdder()
const distributorContract = useMerkleDistributorContract() const distributorContract = useMerkleDistributorContract()
......
import { UNI, PRELOADED_PROPOSALS } from './../../constants/index' import { UNI, PRELOADED_PROPOSALS } from './../../constants/index'
import { TokenAmount } from '@uniswap/sdk-core' import { CurrencyAmount, Token } from '@uniswap/sdk-core'
import { isAddress } from 'ethers/lib/utils' import { isAddress } from 'ethers/lib/utils'
import { useGovernanceContract, useUniContract } from '../../hooks/useContract' import { useGovernanceContract, useUniContract } from '../../hooks/useContract'
import { useSingleCallResult, useSingleContractMultipleData } from '../multicall/hooks' import { useSingleCallResult, useSingleContractMultipleData } from '../multicall/hooks'
...@@ -164,18 +164,18 @@ export function useUserDelegatee(): string { ...@@ -164,18 +164,18 @@ export function useUserDelegatee(): string {
} }
// gets the users current votes // gets the users current votes
export function useUserVotes(): TokenAmount | undefined { export function useUserVotes(): CurrencyAmount<Token> | undefined {
const { account, chainId } = useActiveWeb3React() const { account, chainId } = useActiveWeb3React()
const uniContract = useUniContract() const uniContract = useUniContract()
// check for available votes // check for available votes
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
const votes = useSingleCallResult(uniContract, 'getCurrentVotes', [account ?? undefined])?.result?.[0] const votes = useSingleCallResult(uniContract, 'getCurrentVotes', [account ?? undefined])?.result?.[0]
return votes && uni ? new TokenAmount(uni, votes) : undefined return votes && uni ? CurrencyAmount.fromRawAmount(uni, votes) : undefined
} }
// fetch available votes as of block (usually proposal start block) // fetch available votes as of block (usually proposal start block)
export function useUserVotesAsOfBlock(block: number | undefined): TokenAmount | undefined { export function useUserVotesAsOfBlock(block: number | undefined): CurrencyAmount<Token> | undefined {
const { account, chainId } = useActiveWeb3React() const { account, chainId } = useActiveWeb3React()
const uniContract = useUniContract() const uniContract = useUniContract()
...@@ -183,7 +183,7 @@ export function useUserVotesAsOfBlock(block: number | undefined): TokenAmount | ...@@ -183,7 +183,7 @@ export function useUserVotesAsOfBlock(block: number | undefined): TokenAmount |
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
const votes = useSingleCallResult(uniContract, 'getPriorVotes', [account ?? undefined, block ?? undefined]) const votes = useSingleCallResult(uniContract, 'getPriorVotes', [account ?? undefined, block ?? undefined])
?.result?.[0] ?.result?.[0]
return votes && uni ? new TokenAmount(uni, votes) : undefined return votes && uni ? CurrencyAmount.fromRawAmount(uni, votes) : undefined
} }
export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> { export function useDelegateCallback(): (delegatee: string | undefined) => undefined | Promise<string> {
......
import { UNSUPPORTED_LIST_URLS } from './../../constants/lists'
import DEFAULT_TOKEN_LIST from '@uniswap/default-token-list' import DEFAULT_TOKEN_LIST from '@uniswap/default-token-list'
import { ChainId, Token } from '@uniswap/sdk-core' import { ChainId } from '@uniswap/sdk-core'
import { Tags, TokenInfo, TokenList } from '@uniswap/token-lists' import { TokenList } from '@uniswap/token-lists'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { AppState } from '../index'
import sortByListPriority from 'utils/listSort' import sortByListPriority from 'utils/listSort'
import UNSUPPORTED_TOKEN_LIST from '../../constants/tokenLists/uniswap-v2-unsupported.tokenlist.json' import UNSUPPORTED_TOKEN_LIST from '../../constants/tokenLists/uniswap-v2-unsupported.tokenlist.json'
import { AppState } from '../index'
type TagDetails = Tags[keyof Tags] import { UNSUPPORTED_LIST_URLS } from './../../constants/lists'
export interface TagInfo extends TagDetails { import { WrappedTokenInfo } from './wrappedTokenInfo'
id: string
}
/**
* Token instances created from token info.
*/
export class WrappedTokenInfo extends Token {
public readonly tokenInfo: TokenInfo
public readonly tags: TagInfo[]
constructor(tokenInfo: TokenInfo, tags: TagInfo[]) {
super(tokenInfo.chainId, tokenInfo.address, tokenInfo.decimals, tokenInfo.symbol, tokenInfo.name)
this.tokenInfo = tokenInfo
this.tags = tags
}
public get logoURI(): string | undefined {
return this.tokenInfo.logoURI
}
}
export type TokenAddressMap = Readonly< export type TokenAddressMap = Readonly<
{ [chainId in ChainId | number]: Readonly<{ [tokenAddress: string]: { token: WrappedTokenInfo; list: TokenList } }> } { [chainId in ChainId | number]: Readonly<{ [tokenAddress: string]: { token: WrappedTokenInfo; list: TokenList } }> }
...@@ -53,14 +33,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap { ...@@ -53,14 +33,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
const map = list.tokens.reduce<TokenAddressMap>( const map = list.tokens.reduce<TokenAddressMap>(
(tokenMap, tokenInfo) => { (tokenMap, tokenInfo) => {
const tags: TagInfo[] = const token = new WrappedTokenInfo(tokenInfo, list)
tokenInfo.tags
?.map((tagId) => {
if (!list.tags?.[tagId]) return undefined
return { ...list.tags[tagId], id: tagId }
})
?.filter((x): x is TagInfo => Boolean(x)) ?? []
const token = new WrappedTokenInfo(tokenInfo, tags)
if (tokenMap[token.chainId][token.address] !== undefined) { if (tokenMap[token.chainId][token.address] !== undefined) {
console.error(new Error(`Duplicate token! ${token.address}`)) console.error(new Error(`Duplicate token! ${token.address}`))
return tokenMap return tokenMap
...@@ -71,7 +44,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap { ...@@ -71,7 +44,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
...tokenMap[token.chainId as ChainId], ...tokenMap[token.chainId as ChainId],
[token.address]: { [token.address]: {
token, token,
list: list, list,
}, },
}, },
} }
...@@ -84,14 +57,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap { ...@@ -84,14 +57,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
const TRANSFORMED_DEFAULT_TOKEN_LIST = listToTokenMap(DEFAULT_TOKEN_LIST) const TRANSFORMED_DEFAULT_TOKEN_LIST = listToTokenMap(DEFAULT_TOKEN_LIST)
export function useAllLists(): { export function useAllLists(): AppState['lists']['byUrl'] {
readonly [url: string]: {
readonly current: TokenList | null
readonly pendingUpdate: TokenList | null
readonly loadingRequestId: string | null
readonly error: string | null
}
} {
return useSelector<AppState, AppState['lists']['byUrl']>((state) => state.lists.byUrl) return useSelector<AppState, AppState['lists']['byUrl']>((state) => state.lists.byUrl)
} }
...@@ -119,8 +85,7 @@ function useCombinedTokenMapFromUrls(urls: string[] | undefined): TokenAddressMa ...@@ -119,8 +85,7 @@ function useCombinedTokenMapFromUrls(urls: string[] | undefined): TokenAddressMa
const current = lists[currentUrl]?.current const current = lists[currentUrl]?.current
if (!current) return allTokens if (!current) return allTokens
try { try {
const newTokens = Object.assign(listToTokenMap(current)) return combineMaps(allTokens, listToTokenMap(current))
return combineMaps(allTokens, newTokens)
} catch (error) { } catch (error) {
console.error('Could not show token list due to error', error) console.error('Could not show token list due to error', error)
return allTokens return allTokens
...@@ -150,12 +115,6 @@ export function useCombinedActiveList(): TokenAddressMap { ...@@ -150,12 +115,6 @@ export function useCombinedActiveList(): TokenAddressMap {
return combineMaps(activeTokens, TRANSFORMED_DEFAULT_TOKEN_LIST) return combineMaps(activeTokens, TRANSFORMED_DEFAULT_TOKEN_LIST)
} }
// all tokens from inactive lists
export function useCombinedInactiveList(): TokenAddressMap {
const allInactiveListUrls: string[] = useInactiveListUrls()
return useCombinedTokenMapFromUrls(allInactiveListUrls)
}
// list of tokens not supported on interface, used to show warnings and prevent swaps and adds // list of tokens not supported on interface, used to show warnings and prevent swaps and adds
export function useUnsupportedTokenList(): TokenAddressMap { export function useUnsupportedTokenList(): TokenAddressMap {
// get hard coded unsupported tokens // get hard coded unsupported tokens
...@@ -165,7 +124,10 @@ export function useUnsupportedTokenList(): TokenAddressMap { ...@@ -165,7 +124,10 @@ export function useUnsupportedTokenList(): TokenAddressMap {
const loadedUnsupportedListMap = useCombinedTokenMapFromUrls(UNSUPPORTED_LIST_URLS) const loadedUnsupportedListMap = useCombinedTokenMapFromUrls(UNSUPPORTED_LIST_URLS)
// format into one token address map // format into one token address map
return combineMaps(localUnsupportedListMap, loadedUnsupportedListMap) return useMemo(() => combineMaps(localUnsupportedListMap, loadedUnsupportedListMap), [
localUnsupportedListMap,
loadedUnsupportedListMap,
])
} }
export function useIsListActive(url: string): boolean { export function useIsListActive(url: string): boolean {
......
...@@ -9,7 +9,6 @@ import useIsWindowVisible from '../../hooks/useIsWindowVisible' ...@@ -9,7 +9,6 @@ import useIsWindowVisible from '../../hooks/useIsWindowVisible'
import { AppDispatch } from '../index' import { AppDispatch } from '../index'
import { acceptListUpdate } from './actions' import { acceptListUpdate } from './actions'
import { useActiveListUrls } from './hooks' import { useActiveListUrls } from './hooks'
import { useAllInactiveTokens } from 'hooks/Tokens'
import { UNSUPPORTED_LIST_URLS } from 'constants/lists' import { UNSUPPORTED_LIST_URLS } from 'constants/lists'
export default function Updater(): null { export default function Updater(): null {
...@@ -21,9 +20,6 @@ export default function Updater(): null { ...@@ -21,9 +20,6 @@ export default function Updater(): null {
const lists = useAllLists() const lists = useAllLists()
const activeListUrls = useActiveListUrls() const activeListUrls = useActiveListUrls()
// initiate loading
useAllInactiveTokens()
const fetchList = useFetchListCallback() const fetchList = useFetchListCallback()
const fetchAllListsCallback = useCallback(() => { const fetchAllListsCallback = useCallback(() => {
if (!isWindowVisible) return if (!isWindowVisible) return
......
import { ChainId, Token } from '@uniswap/sdk-core'
import { Tags, TokenInfo } from '@uniswap/token-lists'
import { TokenList } from '@uniswap/token-lists/dist/types'
import { isAddress } from '../../utils'
type TagDetails = Tags[keyof Tags]
export interface TagInfo extends TagDetails {
id: string
}
/**
* Token instances created from token info on a token list.
*/
export class WrappedTokenInfo implements Token {
public readonly isEther: false = false
public readonly isToken: true = true
public readonly list: TokenList
public readonly tokenInfo: TokenInfo
constructor(tokenInfo: TokenInfo, list: TokenList) {
this.tokenInfo = tokenInfo
this.list = list
}
private _checksummedAddress: string | null = null
public get address(): string {
if (this._checksummedAddress) return this._checksummedAddress
const checksummedAddress = isAddress(this.tokenInfo.address)
if (!checksummedAddress) throw new Error(`Invalid token address: ${this.tokenInfo.address}`)
return (this._checksummedAddress = checksummedAddress)
}
public get chainId(): ChainId | number {
return this.tokenInfo.chainId
}
public get decimals(): number {
return this.tokenInfo.decimals
}
public get name(): string {
return this.tokenInfo.name
}
public get symbol(): string {
return this.tokenInfo.symbol
}
public get logoURI(): string | undefined {
return this.tokenInfo.logoURI
}
private _tags: TagInfo[] | null = null
public get tags(): TagInfo[] {
if (this._tags !== null) return this._tags
if (!this.tokenInfo.tags) return (this._tags = [])
const listTags = this.list.tags
if (!listTags) return (this._tags = [])
return (this._tags = this.tokenInfo.tags.map((tagId) => {
return {
...listTags[tagId],
id: tagId,
}
}))
}
equals(other: Token): boolean {
return other.chainId === this.chainId && other.address.toLowerCase() === this.address.toLowerCase()
}
sortsBefore(other: Token): boolean {
if (this.equals(other)) throw new Error('Addresses should not be equal')
return this.address.toLowerCase() < other.address.toLowerCase()
}
}
...@@ -3,7 +3,7 @@ import { useDispatch, useSelector } from 'react-redux' ...@@ -3,7 +3,7 @@ import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch, AppState } from '../index' import { AppDispatch, AppState } from '../index'
import { Field, typeInput } from './actions' import { Field, typeInput } from './actions'
import { Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import { Currency, CurrencyAmount, ETHER, Percent, Price, TokenAmount } from '@uniswap/sdk-core' import { Currency, Token, Percent, Price, CurrencyAmount } from '@uniswap/sdk-core'
import JSBI from 'jsbi' import JSBI from 'jsbi'
import { PairState, useV2Pair } from '../../hooks/useV2Pairs' import { PairState, useV2Pair } from '../../hooks/useV2Pairs'
import { useTotalSupply } from '../../hooks/useTotalSupply' import { useTotalSupply } from '../../hooks/useTotalSupply'
...@@ -55,11 +55,11 @@ export function useDerivedMintInfo( ...@@ -55,11 +55,11 @@ export function useDerivedMintInfo(
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
pair?: Pair | null pair?: Pair | null
pairState: PairState pairState: PairState
currencyBalances: { [field in Field]?: CurrencyAmount } currencyBalances: { [field in Field]?: CurrencyAmount<Currency> }
parsedAmounts: { [field in Field]?: CurrencyAmount } parsedAmounts: { [field in Field]?: CurrencyAmount<Currency> }
price?: Price price?: Price<Currency, Currency>
noLiquidity?: boolean noLiquidity?: boolean
liquidityMinted?: TokenAmount liquidityMinted?: CurrencyAmount<Token>
poolTokenPercentage?: Percent poolTokenPercentage?: Percent
error?: string error?: string
} { } {
...@@ -83,21 +83,24 @@ export function useDerivedMintInfo( ...@@ -83,21 +83,24 @@ export function useDerivedMintInfo(
const totalSupply = useTotalSupply(pair?.liquidityToken) const totalSupply = useTotalSupply(pair?.liquidityToken)
const noLiquidity: boolean = const noLiquidity: boolean =
pairState === PairState.NOT_EXISTS || Boolean(totalSupply && JSBI.equal(totalSupply.raw, ZERO)) pairState === PairState.NOT_EXISTS || Boolean(totalSupply && JSBI.equal(totalSupply.quotient, ZERO))
// balances // balances
const balances = useCurrencyBalances(account ?? undefined, [ const balances = useCurrencyBalances(account ?? undefined, [
currencies[Field.CURRENCY_A], currencies[Field.CURRENCY_A],
currencies[Field.CURRENCY_B], currencies[Field.CURRENCY_B],
]) ])
const currencyBalances: { [field in Field]?: CurrencyAmount } = { const currencyBalances: { [field in Field]?: CurrencyAmount<Currency> } = {
[Field.CURRENCY_A]: balances[0], [Field.CURRENCY_A]: balances[0],
[Field.CURRENCY_B]: balances[1], [Field.CURRENCY_B]: balances[1],
} }
// amounts // amounts
const independentAmount: CurrencyAmount | undefined = tryParseAmount(typedValue, currencies[independentField]) const independentAmount: CurrencyAmount<Currency> | undefined = tryParseAmount(
const dependentAmount: CurrencyAmount | undefined = useMemo(() => { typedValue,
currencies[independentField]
)
const dependentAmount: CurrencyAmount<Currency> | undefined = useMemo(() => {
if (noLiquidity) { if (noLiquidity) {
if (otherTypedValue && currencies[dependentField]) { if (otherTypedValue && currencies[dependentField]) {
return tryParseAmount(otherTypedValue, currencies[dependentField]) return tryParseAmount(otherTypedValue, currencies[dependentField])
...@@ -113,7 +116,7 @@ export function useDerivedMintInfo( ...@@ -113,7 +116,7 @@ export function useDerivedMintInfo(
dependentField === Field.CURRENCY_B dependentField === Field.CURRENCY_B
? pair.priceOf(tokenA).quote(wrappedIndependentAmount) ? pair.priceOf(tokenA).quote(wrappedIndependentAmount)
: pair.priceOf(tokenB).quote(wrappedIndependentAmount) : pair.priceOf(tokenB).quote(wrappedIndependentAmount)
return dependentCurrency === ETHER ? CurrencyAmount.ether(dependentTokenAmount.raw) : dependentTokenAmount return dependentCurrency?.isEther ? CurrencyAmount.ether(dependentTokenAmount.quotient) : dependentTokenAmount
} }
return undefined return undefined
} else { } else {
...@@ -121,7 +124,7 @@ export function useDerivedMintInfo( ...@@ -121,7 +124,7 @@ export function useDerivedMintInfo(
} }
}, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, chainId, currencyB, pair]) }, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, chainId, currencyB, pair])
const parsedAmounts: { [field in Field]: CurrencyAmount | undefined } = useMemo(() => { const parsedAmounts: { [field in Field]: CurrencyAmount<Currency> | undefined } = useMemo(() => {
return { return {
[Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount, [Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount,
[Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount, [Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount,
...@@ -132,7 +135,12 @@ export function useDerivedMintInfo( ...@@ -132,7 +135,12 @@ export function useDerivedMintInfo(
if (noLiquidity) { if (noLiquidity) {
const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts
if (currencyAAmount && currencyBAmount) { if (currencyAAmount && currencyBAmount) {
return new Price(currencyAAmount.currency, currencyBAmount.currency, currencyAAmount.raw, currencyBAmount.raw) return new Price(
currencyAAmount.currency,
currencyBAmount.currency,
currencyAAmount.quotient,
currencyBAmount.quotient
)
} }
return undefined return undefined
} else { } else {
...@@ -157,7 +165,7 @@ export function useDerivedMintInfo( ...@@ -157,7 +165,7 @@ export function useDerivedMintInfo(
const poolTokenPercentage = useMemo(() => { const poolTokenPercentage = useMemo(() => {
if (liquidityMinted && totalSupply) { if (liquidityMinted && totalSupply) {
return new Percent(liquidityMinted.raw, totalSupply.add(liquidityMinted).raw) return new Percent(liquidityMinted.quotient, totalSupply.add(liquidityMinted).quotient)
} else { } else {
return undefined return undefined
} }
......
...@@ -12,7 +12,7 @@ import { ...@@ -12,7 +12,7 @@ import {
TICK_SPACINGS, TICK_SPACINGS,
encodeSqrtRatioX96, encodeSqrtRatioX96,
} from '@uniswap/v3-sdk/dist/' } from '@uniswap/v3-sdk/dist/'
import { Currency, CurrencyAmount, ETHER, Price, Rounding } from '@uniswap/sdk-core' import { Currency, Token, CurrencyAmount, currencyEquals, Price, Rounding } from '@uniswap/sdk-core'
import { useCallback, useMemo } from 'react' import { useCallback, useMemo } from 'react'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
import { useActiveWeb3React } from '../../../hooks' import { useActiveWeb3React } from '../../../hooks'
...@@ -94,14 +94,14 @@ export function useV3DerivedMintInfo( ...@@ -94,14 +94,14 @@ export function useV3DerivedMintInfo(
pool?: Pool | null pool?: Pool | null
poolState: PoolState poolState: PoolState
ticks: { [bound in Bound]?: number | undefined } ticks: { [bound in Bound]?: number | undefined }
price?: Price price?: Price<Token, Token>
pricesAtTicks: { pricesAtTicks: {
[bound in Bound]?: Price | undefined [bound in Bound]?: Price<Token, Token> | undefined
} }
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
currencyBalances: { [field in Field]?: CurrencyAmount } currencyBalances: { [field in Field]?: CurrencyAmount<Currency> }
dependentField: Field dependentField: Field
parsedAmounts: { [field in Field]?: CurrencyAmount } parsedAmounts: { [field in Field]?: CurrencyAmount<Currency> }
position: Position | undefined position: Position | undefined
noLiquidity?: boolean noLiquidity?: boolean
errorMessage?: string errorMessage?: string
...@@ -154,7 +154,7 @@ export function useV3DerivedMintInfo( ...@@ -154,7 +154,7 @@ export function useV3DerivedMintInfo(
currencies[Field.CURRENCY_A], currencies[Field.CURRENCY_A],
currencies[Field.CURRENCY_B], currencies[Field.CURRENCY_B],
]) ])
const currencyBalances: { [field in Field]?: CurrencyAmount } = { const currencyBalances: { [field in Field]?: CurrencyAmount<Currency> } = {
[Field.CURRENCY_A]: balances[0], [Field.CURRENCY_A]: balances[0],
[Field.CURRENCY_B]: balances[1], [Field.CURRENCY_B]: balances[1],
} }
...@@ -167,7 +167,7 @@ export function useV3DerivedMintInfo( ...@@ -167,7 +167,7 @@ export function useV3DerivedMintInfo(
const invertPrice = Boolean(baseToken && token0 && !baseToken.equals(token0)) const invertPrice = Boolean(baseToken && token0 && !baseToken.equals(token0))
// always returns the price with 0 as base token // always returns the price with 0 as base token
const price = useMemo(() => { const price: Price<Token, Token> | undefined = useMemo(() => {
// if no liquidity use typed value // if no liquidity use typed value
if (noLiquidity) { if (noLiquidity) {
const parsedQuoteAmount = tryParseAmount(startPriceTypedValue, invertPrice ? token0 : token1) const parsedQuoteAmount = tryParseAmount(startPriceTypedValue, invertPrice ? token0 : token1)
...@@ -175,7 +175,12 @@ export function useV3DerivedMintInfo( ...@@ -175,7 +175,12 @@ export function useV3DerivedMintInfo(
const baseAmount = tryParseAmount('1', invertPrice ? token1 : token0) const baseAmount = tryParseAmount('1', invertPrice ? token1 : token0)
const price = const price =
baseAmount && parsedQuoteAmount baseAmount && parsedQuoteAmount
? new Price(baseAmount.currency, parsedQuoteAmount.currency, baseAmount.raw, parsedQuoteAmount.raw) ? new Price(
baseAmount.currency,
parsedQuoteAmount.currency,
baseAmount.quotient,
parsedQuoteAmount.quotient
)
: undefined : undefined
return (invertPrice ? price?.invert() : price) ?? undefined return (invertPrice ? price?.invert() : price) ?? undefined
} }
...@@ -188,7 +193,7 @@ export function useV3DerivedMintInfo( ...@@ -188,7 +193,7 @@ export function useV3DerivedMintInfo(
// check for invalid price input (converts to invalid ratio) // check for invalid price input (converts to invalid ratio)
const invalidPrice = useMemo(() => { const invalidPrice = useMemo(() => {
const sqrtRatioX96 = price ? encodeSqrtRatioX96(price.raw.numerator, price.raw.denominator) : undefined const sqrtRatioX96 = price ? encodeSqrtRatioX96(price.numerator, price.denominator) : undefined
const invalid = const invalid =
price && price &&
sqrtRatioX96 && sqrtRatioX96 &&
...@@ -254,9 +259,12 @@ export function useV3DerivedMintInfo( ...@@ -254,9 +259,12 @@ export function useV3DerivedMintInfo(
) )
// amounts // amounts
const independentAmount: CurrencyAmount | undefined = tryParseAmount(typedValue, currencies[independentField]) const independentAmount: CurrencyAmount<Currency> | undefined = tryParseAmount(
typedValue,
currencies[independentField]
)
const dependentAmount: CurrencyAmount | undefined = useMemo(() => { const dependentAmount: CurrencyAmount<Currency> | undefined = useMemo(() => {
// we wrap the currencies just to get the price in terms of the other token // we wrap the currencies just to get the price in terms of the other token
const wrappedIndependentAmount = wrappedCurrencyAmount(independentAmount, chainId) const wrappedIndependentAmount = wrappedCurrencyAmount(independentAmount, chainId)
const dependentCurrency = dependentField === Field.CURRENCY_B ? currencyB : currencyA const dependentCurrency = dependentField === Field.CURRENCY_B ? currencyB : currencyA
...@@ -272,24 +280,24 @@ export function useV3DerivedMintInfo( ...@@ -272,24 +280,24 @@ export function useV3DerivedMintInfo(
return undefined return undefined
} }
const position: Position | undefined = wrappedIndependentAmount.token.equals(poolForPosition.token0) const position: Position | undefined = currencyEquals(wrappedIndependentAmount.currency, poolForPosition.token0)
? Position.fromAmount0({ ? Position.fromAmount0({
pool: poolForPosition, pool: poolForPosition,
tickLower, tickLower,
tickUpper, tickUpper,
amount0: independentAmount.raw, amount0: independentAmount.quotient,
}) })
: Position.fromAmount1({ : Position.fromAmount1({
pool: poolForPosition, pool: poolForPosition,
tickLower, tickLower,
tickUpper, tickUpper,
amount1: independentAmount.raw, amount1: independentAmount.quotient,
}) })
const dependentTokenAmount = wrappedIndependentAmount.token.equals(poolForPosition.token0) const dependentTokenAmount = currencyEquals(wrappedIndependentAmount.currency, poolForPosition.token0)
? position.amount1 ? position.amount1
: position.amount0 : position.amount0
return dependentCurrency === ETHER ? CurrencyAmount.ether(dependentTokenAmount.raw) : dependentTokenAmount return dependentCurrency?.isEther ? CurrencyAmount.ether(dependentTokenAmount.quotient) : dependentTokenAmount
} }
return undefined return undefined
...@@ -306,7 +314,7 @@ export function useV3DerivedMintInfo( ...@@ -306,7 +314,7 @@ export function useV3DerivedMintInfo(
invalidRange, invalidRange,
]) ])
const parsedAmounts: { [field in Field]: CurrencyAmount | undefined } = useMemo(() => { const parsedAmounts: { [field in Field]: CurrencyAmount<Currency> | undefined } = useMemo(() => {
return { return {
[Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount, [Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount,
[Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount, [Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount,
...@@ -350,10 +358,10 @@ export function useV3DerivedMintInfo( ...@@ -350,10 +358,10 @@ export function useV3DerivedMintInfo(
// mark as 0 if disbaled because out of range // mark as 0 if disbaled because out of range
const amount0 = !deposit0Disabled const amount0 = !deposit0Disabled
? parsedAmounts?.[tokenA.equals(poolForPosition.token0) ? Field.CURRENCY_A : Field.CURRENCY_B]?.raw ? parsedAmounts?.[tokenA.equals(poolForPosition.token0) ? Field.CURRENCY_A : Field.CURRENCY_B]?.quotient
: BIG_INT_ZERO : BIG_INT_ZERO
const amount1 = !deposit1Disabled const amount1 = !deposit1Disabled
? parsedAmounts?.[tokenA.equals(poolForPosition.token0) ? Field.CURRENCY_B : Field.CURRENCY_A]?.raw ? parsedAmounts?.[tokenA.equals(poolForPosition.token0) ? Field.CURRENCY_B : Field.CURRENCY_A]?.quotient
: BIG_INT_ZERO : BIG_INT_ZERO
if (amount0 !== undefined && amount1 !== undefined) { if (amount0 !== undefined && amount1 !== undefined) {
......
...@@ -19,7 +19,7 @@ export function tryParseTick( ...@@ -19,7 +19,7 @@ export function tryParseTick(
if (!amount || !amountOne) return undefined if (!amount || !amountOne) return undefined
// parse the typed value into a price // parse the typed value into a price
const price = new Price(baseToken, quoteToken, amountOne.raw, amount.raw) const price = new Price(baseToken, quoteToken, amountOne.quotient, amount.quotient)
// this function is agnostic to the base, will always return the correct tick // this function is agnostic to the base, will always return the correct tick
const tick = priceToClosestTick(price) const tick = priceToClosestTick(price)
......
import { ChainId, CurrencyAmount, Token, TokenAmount, WETH9 } from '@uniswap/sdk-core' import { ChainId, Token, CurrencyAmount, WETH9 } from '@uniswap/sdk-core'
import { Pair } from '@uniswap/v2-sdk' import { Pair } from '@uniswap/v2-sdk'
import JSBI from 'jsbi' import JSBI from 'jsbi'
import { useMemo } from 'react' import { useMemo } from 'react'
...@@ -45,26 +45,26 @@ export interface StakingInfo { ...@@ -45,26 +45,26 @@ export interface StakingInfo {
// the tokens involved in this pair // the tokens involved in this pair
tokens: [Token, Token] tokens: [Token, Token]
// the amount of token currently staked, or undefined if no account // the amount of token currently staked, or undefined if no account
stakedAmount: TokenAmount stakedAmount: CurrencyAmount<Token>
// the amount of reward token earned by the active account, or undefined if no account // the amount of reward token earned by the active account, or undefined if no account
earnedAmount: TokenAmount earnedAmount: CurrencyAmount<Token>
// the total amount of token staked in the contract // the total amount of token staked in the contract
totalStakedAmount: TokenAmount totalStakedAmount: CurrencyAmount<Token>
// the amount of token distributed per second to all LPs, constant // the amount of token distributed per second to all LPs, constant
totalRewardRate: TokenAmount totalRewardRate: CurrencyAmount<Token>
// the current amount of token distributed to the active account per second. // the current amount of token distributed to the active account per second.
// equivalent to percent of total supply * reward rate // equivalent to percent of total supply * reward rate
rewardRate: TokenAmount rewardRate: CurrencyAmount<Token>
// when the period ends // when the period ends
periodFinish: Date | undefined periodFinish: Date | undefined
// if pool is active // if pool is active
active: boolean active: boolean
// calculates a hypothetical amount of token distributed to the active account per second. // calculates a hypothetical amount of token distributed to the active account per second.
getHypotheticalRewardRate: ( getHypotheticalRewardRate: (
stakedAmount: TokenAmount, stakedAmount: CurrencyAmount<Token>,
totalStakedAmount: TokenAmount, totalStakedAmount: CurrencyAmount<Token>,
totalRewardRate: TokenAmount totalRewardRate: CurrencyAmount<Token>
) => TokenAmount ) => CurrencyAmount<Token>
} }
// gets the staking info from the network for the active chain id // gets the staking info from the network for the active chain id
...@@ -154,23 +154,32 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -154,23 +154,32 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
// get the LP token // get the LP token
const tokens = info[index].tokens const tokens = info[index].tokens
const dummyPair = new Pair(new TokenAmount(tokens[0], '0'), new TokenAmount(tokens[1], '0')) const dummyPair = new Pair(
CurrencyAmount.fromRawAmount(tokens[0], '0'),
CurrencyAmount.fromRawAmount(tokens[1], '0')
)
// check for account, if no account set to 0 // check for account, if no account set to 0
const stakedAmount = new TokenAmount(dummyPair.liquidityToken, JSBI.BigInt(balanceState?.result?.[0] ?? 0)) const stakedAmount = CurrencyAmount.fromRawAmount(
const totalStakedAmount = new TokenAmount(dummyPair.liquidityToken, JSBI.BigInt(totalSupplyState.result?.[0])) dummyPair.liquidityToken,
const totalRewardRate = new TokenAmount(uni, JSBI.BigInt(rewardRateState.result?.[0])) JSBI.BigInt(balanceState?.result?.[0] ?? 0)
)
const totalStakedAmount = CurrencyAmount.fromRawAmount(
dummyPair.liquidityToken,
JSBI.BigInt(totalSupplyState.result?.[0])
)
const totalRewardRate = CurrencyAmount.fromRawAmount(uni, JSBI.BigInt(rewardRateState.result?.[0]))
const getHypotheticalRewardRate = ( const getHypotheticalRewardRate = (
stakedAmount: TokenAmount, stakedAmount: CurrencyAmount<Token>,
totalStakedAmount: TokenAmount, totalStakedAmount: CurrencyAmount<Token>,
totalRewardRate: TokenAmount totalRewardRate: CurrencyAmount<Token>
): TokenAmount => { ): CurrencyAmount<Token> => {
return new TokenAmount( return CurrencyAmount.fromRawAmount(
uni, uni,
JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0)) JSBI.greaterThan(totalStakedAmount.quotient, JSBI.BigInt(0))
? JSBI.divide(JSBI.multiply(totalRewardRate.raw, stakedAmount.raw), totalStakedAmount.raw) ? JSBI.divide(JSBI.multiply(totalRewardRate.quotient, stakedAmount.quotient), totalStakedAmount.quotient)
: JSBI.BigInt(0) : JSBI.BigInt(0)
) )
} }
...@@ -188,7 +197,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -188,7 +197,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
stakingRewardAddress: rewardsAddress, stakingRewardAddress: rewardsAddress,
tokens: info[index].tokens, tokens: info[index].tokens,
periodFinish: periodFinishMs > 0 ? new Date(periodFinishMs) : undefined, periodFinish: periodFinishMs > 0 ? new Date(periodFinishMs) : undefined,
earnedAmount: new TokenAmount(uni, JSBI.BigInt(earnedAmountState?.result?.[0] ?? 0)), earnedAmount: CurrencyAmount.fromRawAmount(uni, JSBI.BigInt(earnedAmountState?.result?.[0] ?? 0)),
rewardRate: individualRewardRate, rewardRate: individualRewardRate,
totalRewardRate: totalRewardRate, totalRewardRate: totalRewardRate,
stakedAmount: stakedAmount, stakedAmount: stakedAmount,
...@@ -213,7 +222,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -213,7 +222,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
]) ])
} }
export function useTotalUniEarned(): TokenAmount | undefined { export function useTotalUniEarned(): CurrencyAmount<Token> | undefined {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
const stakingInfos = useStakingInfo() const stakingInfos = useStakingInfo()
...@@ -223,8 +232,8 @@ export function useTotalUniEarned(): TokenAmount | undefined { ...@@ -223,8 +232,8 @@ export function useTotalUniEarned(): TokenAmount | undefined {
return ( return (
stakingInfos?.reduce( stakingInfos?.reduce(
(accumulator, stakingInfo) => accumulator.add(stakingInfo.earnedAmount), (accumulator, stakingInfo) => accumulator.add(stakingInfo.earnedAmount),
new TokenAmount(uni, '0') CurrencyAmount.fromRawAmount(uni, '0')
) ?? new TokenAmount(uni, '0') ) ?? CurrencyAmount.fromRawAmount(uni, '0')
) )
}, [stakingInfos, uni]) }, [stakingInfos, uni])
} }
...@@ -232,18 +241,18 @@ export function useTotalUniEarned(): TokenAmount | undefined { ...@@ -232,18 +241,18 @@ export function useTotalUniEarned(): TokenAmount | undefined {
// based on typed value // based on typed value
export function useDerivedStakeInfo( export function useDerivedStakeInfo(
typedValue: string, typedValue: string,
stakingToken: Token, stakingToken: Token | undefined,
userLiquidityUnstaked: TokenAmount | undefined userLiquidityUnstaked: CurrencyAmount<Token> | undefined
): { ): {
parsedAmount?: CurrencyAmount parsedAmount?: CurrencyAmount<Token>
error?: string error?: string
} { } {
const { account } = useActiveWeb3React() const { account } = useActiveWeb3React()
const parsedInput: CurrencyAmount | undefined = tryParseAmount(typedValue, stakingToken) const parsedInput: CurrencyAmount<Token> | undefined = tryParseAmount(typedValue, stakingToken)
const parsedAmount = const parsedAmount =
parsedInput && userLiquidityUnstaked && JSBI.lessThanOrEqual(parsedInput.raw, userLiquidityUnstaked.raw) parsedInput && userLiquidityUnstaked && JSBI.lessThanOrEqual(parsedInput.quotient, userLiquidityUnstaked.quotient)
? parsedInput ? parsedInput
: undefined : undefined
...@@ -264,16 +273,17 @@ export function useDerivedStakeInfo( ...@@ -264,16 +273,17 @@ export function useDerivedStakeInfo(
// based on typed value // based on typed value
export function useDerivedUnstakeInfo( export function useDerivedUnstakeInfo(
typedValue: string, typedValue: string,
stakingAmount: TokenAmount stakingAmount: CurrencyAmount<Token>
): { ): {
parsedAmount?: CurrencyAmount parsedAmount?: CurrencyAmount<Token>
error?: string error?: string
} { } {
const { account } = useActiveWeb3React() const { account } = useActiveWeb3React()
const parsedInput: CurrencyAmount | undefined = tryParseAmount(typedValue, stakingAmount.token) const parsedInput: CurrencyAmount<Token> | undefined = tryParseAmount(typedValue, stakingAmount.currency)
const parsedAmount = parsedInput && JSBI.lessThanOrEqual(parsedInput.raw, stakingAmount.raw) ? parsedInput : undefined const parsedAmount =
parsedInput && JSBI.lessThanOrEqual(parsedInput.quotient, stakingAmount.quotient) ? parsedInput : undefined
let error: string | undefined let error: string | undefined
if (!account) { if (!account) {
......
import JSBI from 'jsbi'
import { Trade as V3Trade } from '@uniswap/v3-sdk' import { Trade as V3Trade } from '@uniswap/v3-sdk'
import { useBestV3TradeExactIn, useBestV3TradeExactOut, V3TradeState } from '../../hooks/useBestV3Trade' import { useBestV3TradeExactIn, useBestV3TradeExactOut, V3TradeState } from '../../hooks/useBestV3Trade'
import useENS from '../../hooks/useENS' import useENS from '../../hooks/useENS'
import { parseUnits } from '@ethersproject/units' import { parseUnits } from '@ethersproject/units'
import { Currency, CurrencyAmount, ETHER, Token, TokenAmount, Percent } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Percent, TradeType } from '@uniswap/sdk-core'
import { JSBI, Trade as V2Trade } from '@uniswap/v2-sdk' import { Trade as V2Trade } from '@uniswap/v2-sdk'
import { ParsedQs } from 'qs' import { ParsedQs } from 'qs'
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
...@@ -35,7 +36,7 @@ export function useSwapActionHandlers(): { ...@@ -35,7 +36,7 @@ export function useSwapActionHandlers(): {
dispatch( dispatch(
selectCurrency({ selectCurrency({
field, field,
currencyId: currency instanceof Token ? currency.address : currency === ETHER ? 'ETH' : '', currencyId: currency.isToken ? currency.address : currency.isEther ? 'ETH' : '',
}) })
) )
}, },
...@@ -69,16 +70,14 @@ export function useSwapActionHandlers(): { ...@@ -69,16 +70,14 @@ export function useSwapActionHandlers(): {
} }
// try to parse a user entered amount for a given token // try to parse a user entered amount for a given token
export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmount | undefined { export function tryParseAmount<T extends Currency>(value?: string, currency?: T): CurrencyAmount<T> | undefined {
if (!value || !currency) { if (!value || !currency) {
return undefined return undefined
} }
try { try {
const typedValueParsed = parseUnits(value, currency.decimals).toString() const typedValueParsed = parseUnits(value, currency.decimals).toString()
if (typedValueParsed !== '0') { if (typedValueParsed !== '0') {
return currency instanceof Token return CurrencyAmount.fromRawAmount(currency, JSBI.BigInt(typedValueParsed))
? new TokenAmount(currency, JSBI.BigInt(typedValueParsed))
: CurrencyAmount.ether(JSBI.BigInt(typedValueParsed))
} }
} catch (error) { } catch (error) {
// should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?) // should fail if the user specifies too many decimal places of precision (or maybe exceed max uint?)
...@@ -99,7 +98,10 @@ const BAD_RECIPIENT_ADDRESSES: { [address: string]: true } = { ...@@ -99,7 +98,10 @@ const BAD_RECIPIENT_ADDRESSES: { [address: string]: true } = {
* @param trade to check for the given address * @param trade to check for the given address
* @param checksummedAddress address to check in the pairs and tokens * @param checksummedAddress address to check in the pairs and tokens
*/ */
function involvesAddress(trade: V2Trade | V3Trade, checksummedAddress: string): boolean { function involvesAddress(
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>,
checksummedAddress: string
): boolean {
const path = trade instanceof V2Trade ? trade.route.path : trade.route.tokenPath const path = trade instanceof V2Trade ? trade.route.path : trade.route.tokenPath
return ( return (
path.some((token) => token.address === checksummedAddress) || path.some((token) => token.address === checksummedAddress) ||
...@@ -114,12 +116,12 @@ export function useDerivedSwapInfo( ...@@ -114,12 +116,12 @@ export function useDerivedSwapInfo(
toggledVersion: Version toggledVersion: Version
): { ): {
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
currencyBalances: { [field in Field]?: CurrencyAmount } currencyBalances: { [field in Field]?: CurrencyAmount<Currency> }
parsedAmount: CurrencyAmount | undefined parsedAmount: CurrencyAmount<Currency> | undefined
inputError?: string inputError?: string
v2Trade: V2Trade | undefined v2Trade: V2Trade<Currency, Currency, TradeType> | undefined
v3TradeState: { trade: V3Trade | null; state: V3TradeState } v3TradeState: { trade: V3Trade<Currency, Currency, TradeType> | null; state: V3TradeState }
toggledTrade: V2Trade | V3Trade | undefined toggledTrade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined
allowedSlippage: Percent allowedSlippage: Percent
} { } {
const { account } = useActiveWeb3React() const { account } = useActiveWeb3React()
......
import { Currency, CurrencyAmount, ETHER, Token, TokenAmount } from '@uniswap/sdk-core' import { Currency, Token, CurrencyAmount } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useActiveWeb3React } from '../../hooks' import { useActiveWeb3React } from '../../hooks'
import { useAllTokens } from '../../hooks/Tokens' import { useAllTokens } from '../../hooks/Tokens'
...@@ -17,7 +17,7 @@ import { Erc20Interface } from 'abis/types/Erc20' ...@@ -17,7 +17,7 @@ import { Erc20Interface } from 'abis/types/Erc20'
*/ */
export function useETHBalances( export function useETHBalances(
uncheckedAddresses?: (string | undefined)[] uncheckedAddresses?: (string | undefined)[]
): { [address: string]: CurrencyAmount | undefined } { ): { [address: string]: CurrencyAmount<Currency> | undefined } {
const multicallContract = useMulticall2Contract() const multicallContract = useMulticall2Contract()
const addresses: string[] = useMemo( const addresses: string[] = useMemo(
...@@ -39,7 +39,7 @@ export function useETHBalances( ...@@ -39,7 +39,7 @@ export function useETHBalances(
return useMemo( return useMemo(
() => () =>
addresses.reduce<{ [address: string]: CurrencyAmount }>((memo, address, i) => { addresses.reduce<{ [address: string]: CurrencyAmount<Currency> }>((memo, address, i) => {
const value = results?.[i]?.result?.[0] const value = results?.[i]?.result?.[0]
if (value) memo[address] = CurrencyAmount.ether(JSBI.BigInt(value.toString())) if (value) memo[address] = CurrencyAmount.ether(JSBI.BigInt(value.toString()))
return memo return memo
...@@ -54,7 +54,7 @@ export function useETHBalances( ...@@ -54,7 +54,7 @@ export function useETHBalances(
export function useTokenBalancesWithLoadingIndicator( export function useTokenBalancesWithLoadingIndicator(
address?: string, address?: string,
tokens?: (Token | undefined)[] tokens?: (Token | undefined)[]
): [{ [tokenAddress: string]: TokenAmount | undefined }, boolean] { ): [{ [tokenAddress: string]: CurrencyAmount<Token> | undefined }, boolean] {
const validatedTokens: Token[] = useMemo( const validatedTokens: Token[] = useMemo(
() => tokens?.filter((t?: Token): t is Token => isAddress(t?.address) !== false) ?? [], () => tokens?.filter((t?: Token): t is Token => isAddress(t?.address) !== false) ?? [],
[tokens] [tokens]
...@@ -77,11 +77,11 @@ export function useTokenBalancesWithLoadingIndicator( ...@@ -77,11 +77,11 @@ export function useTokenBalancesWithLoadingIndicator(
useMemo( useMemo(
() => () =>
address && validatedTokens.length > 0 address && validatedTokens.length > 0
? validatedTokens.reduce<{ [tokenAddress: string]: TokenAmount | undefined }>((memo, token, i) => { ? validatedTokens.reduce<{ [tokenAddress: string]: CurrencyAmount<Token> | undefined }>((memo, token, i) => {
const value = balances?.[i]?.result?.[0] const value = balances?.[i]?.result?.[0]
const amount = value ? JSBI.BigInt(value.toString()) : undefined const amount = value ? JSBI.BigInt(value.toString()) : undefined
if (amount) { if (amount) {
memo[token.address] = new TokenAmount(token, amount) memo[token.address] = CurrencyAmount.fromRawAmount(token, amount)
} }
return memo return memo
}, {}) }, {})
...@@ -95,12 +95,12 @@ export function useTokenBalancesWithLoadingIndicator( ...@@ -95,12 +95,12 @@ export function useTokenBalancesWithLoadingIndicator(
export function useTokenBalances( export function useTokenBalances(
address?: string, address?: string,
tokens?: (Token | undefined)[] tokens?: (Token | undefined)[]
): { [tokenAddress: string]: TokenAmount | undefined } { ): { [tokenAddress: string]: CurrencyAmount<Token> | undefined } {
return useTokenBalancesWithLoadingIndicator(address, tokens)[0] return useTokenBalancesWithLoadingIndicator(address, tokens)[0]
} }
// get the balance for a single token/account combo // get the balance for a single token/account combo
export function useTokenBalance(account?: string, token?: Token): TokenAmount | undefined { export function useTokenBalance(account?: string, token?: Token): CurrencyAmount<Token> | undefined {
const tokenBalances = useTokenBalances(account, [token]) const tokenBalances = useTokenBalances(account, [token])
if (!token) return undefined if (!token) return undefined
return tokenBalances[token.address] return tokenBalances[token.address]
...@@ -109,33 +109,33 @@ export function useTokenBalance(account?: string, token?: Token): TokenAmount | ...@@ -109,33 +109,33 @@ export function useTokenBalance(account?: string, token?: Token): TokenAmount |
export function useCurrencyBalances( export function useCurrencyBalances(
account?: string, account?: string,
currencies?: (Currency | undefined)[] currencies?: (Currency | undefined)[]
): (CurrencyAmount | undefined)[] { ): (CurrencyAmount<Currency> | undefined)[] {
const tokens = useMemo(() => currencies?.filter((currency): currency is Token => currency instanceof Token) ?? [], [ const tokens = useMemo(() => currencies?.filter((currency): currency is Token => currency?.isToken ?? false) ?? [], [
currencies, currencies,
]) ])
const tokenBalances = useTokenBalances(account, tokens) const tokenBalances = useTokenBalances(account, tokens)
const containsETH: boolean = useMemo(() => currencies?.some((currency) => currency === ETHER) ?? false, [currencies]) const containsETH: boolean = useMemo(() => currencies?.some((currency) => currency?.isEther) ?? false, [currencies])
const ethBalance = useETHBalances(containsETH ? [account] : []) const ethBalance = useETHBalances(containsETH ? [account] : [])
return useMemo( return useMemo(
() => () =>
currencies?.map((currency) => { currencies?.map((currency) => {
if (!account || !currency) return undefined if (!account || !currency) return undefined
if (currency instanceof Token) return tokenBalances[currency.address] if (currency.isToken) return tokenBalances[currency.address]
if (currency === ETHER) return ethBalance[account] if (currency.isEther) return ethBalance[account]
return undefined return undefined
}) ?? [], }) ?? [],
[account, currencies, ethBalance, tokenBalances] [account, currencies, ethBalance, tokenBalances]
) )
} }
export function useCurrencyBalance(account?: string, currency?: Currency): CurrencyAmount | undefined { export function useCurrencyBalance(account?: string, currency?: Currency): CurrencyAmount<Currency> | undefined {
return useCurrencyBalances(account, [currency])[0] return useCurrencyBalances(account, [currency])[0]
} }
// mimics useAllBalances // mimics useAllBalances
export function useAllTokenBalances(): { [tokenAddress: string]: TokenAmount | undefined } { export function useAllTokenBalances(): { [tokenAddress: string]: CurrencyAmount<Token> | undefined } {
const { account } = useActiveWeb3React() const { account } = useActiveWeb3React()
const allTokens = useAllTokens() const allTokens = useAllTokens()
const allTokensArray = useMemo(() => Object.values(allTokens ?? {}), [allTokens]) const allTokensArray = useMemo(() => Object.values(allTokens ?? {}), [allTokens])
...@@ -144,22 +144,22 @@ export function useAllTokenBalances(): { [tokenAddress: string]: TokenAmount | u ...@@ -144,22 +144,22 @@ export function useAllTokenBalances(): { [tokenAddress: string]: TokenAmount | u
} }
// get the total owned, unclaimed, and unharvested UNI for account // get the total owned, unclaimed, and unharvested UNI for account
export function useAggregateUniBalance(): TokenAmount | undefined { export function useAggregateUniBalance(): CurrencyAmount<Token> | undefined {
const { account, chainId } = useActiveWeb3React() const { account, chainId } = useActiveWeb3React()
const uni = chainId ? UNI[chainId] : undefined const uni = chainId ? UNI[chainId] : undefined
const uniBalance: TokenAmount | undefined = useTokenBalance(account ?? undefined, uni) const uniBalance: CurrencyAmount<Token> | undefined = useTokenBalance(account ?? undefined, uni)
const uniUnclaimed: TokenAmount | undefined = useUserUnclaimedAmount(account) const uniUnclaimed: CurrencyAmount<Token> | undefined = useUserUnclaimedAmount(account)
const uniUnHarvested: TokenAmount | undefined = useTotalUniEarned() const uniUnHarvested: CurrencyAmount<Token> | undefined = useTotalUniEarned()
if (!uni) return undefined if (!uni) return undefined
return new TokenAmount( return CurrencyAmount.fromRawAmount(
uni, uni,
JSBI.add( JSBI.add(
JSBI.add(uniBalance?.raw ?? JSBI.BigInt(0), uniUnclaimed?.raw ?? JSBI.BigInt(0)), JSBI.add(uniBalance?.quotient ?? JSBI.BigInt(0), uniUnclaimed?.quotient ?? JSBI.BigInt(0)),
uniUnHarvested?.raw ?? JSBI.BigInt(0) uniUnHarvested?.quotient ?? JSBI.BigInt(0)
) )
) )
} }
import { CurrencyAmount, currencyEquals, Percent } from '@uniswap/sdk-core' import { Token, CurrencyAmount, currencyEquals, Percent } from '@uniswap/sdk-core'
import JSBI from 'jsbi' import JSBI from 'jsbi'
import { ONE_HUNDRED_PERCENT } from '../constants' import { ONE_HUNDRED_PERCENT } from '../constants'
export function computeFiatValuePriceImpact( export function computeFiatValuePriceImpact(
fiatValueInput: CurrencyAmount | undefined | null, fiatValueInput: CurrencyAmount<Token> | undefined | null,
fiatValueOutput: CurrencyAmount | undefined | null fiatValueOutput: CurrencyAmount<Token> | undefined | null
): Percent | undefined { ): Percent | undefined {
if (!fiatValueOutput || !fiatValueInput) return undefined if (!fiatValueOutput || !fiatValueInput) return undefined
if (!currencyEquals(fiatValueInput.currency, fiatValueOutput.currency)) return undefined if (!currencyEquals(fiatValueInput.currency, fiatValueOutput.currency)) return undefined
if (JSBI.equal(fiatValueInput.raw, JSBI.BigInt(0))) return undefined if (JSBI.equal(fiatValueInput.quotient, JSBI.BigInt(0))) return undefined
const pct = ONE_HUNDRED_PERCENT.subtract(fiatValueOutput.divide(fiatValueInput)) const pct = ONE_HUNDRED_PERCENT.subtract(fiatValueOutput.divide(fiatValueInput))
return new Percent(pct.numerator, pct.denominator) return new Percent(pct.numerator, pct.denominator)
} }
import { CurrencyAmount, Percent, Price } from '@uniswap/sdk-core' import { computePriceImpact, Currency, Percent, TradeType } 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 } from '@uniswap/v3-sdk'
function computePriceImpact(midPrice: Price, inputAmount: CurrencyAmount, outputAmount: CurrencyAmount): Percent { export function computePriceImpactWithMaximumSlippage(
const exactQuote = midPrice.raw.multiply(inputAmount.raw) trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>,
// calculate slippage := (exactQuote - outputAmount) / exactQuote allowedSlippage: Percent
const slippage = exactQuote.subtract(outputAmount.raw).divide(exactQuote) ): Percent {
return new Percent(slippage.numerator, slippage.denominator)
}
export function computePriceImpactWithMaximumSlippage(trade: V2Trade | V3Trade, allowedSlippage: Percent): Percent {
return computePriceImpact( return computePriceImpact(
trade.route.midPrice, trade.route.midPrice,
trade.maximumAmountIn(allowedSlippage), trade.maximumAmountIn(allowedSlippage),
......
import { ChainId, Token, TokenAmount } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI } from '@uniswap/v2-sdk' import { ChainId, Token, CurrencyAmount } from '@uniswap/sdk-core'
import { BigNumber } from 'ethers' import { BigNumber } from 'ethers'
import { ZERO_ADDRESS } from '../constants' import { ZERO_ADDRESS } from '../constants'
import { computeUniCirculation } from './computeUniCirculation' import { computeUniCirculation } from './computeUniCirculation'
...@@ -12,7 +12,7 @@ describe('computeUniCirculation', () => { ...@@ -12,7 +12,7 @@ describe('computeUniCirculation', () => {
} }
function tokenAmount(num: JSBI | string | number) { function tokenAmount(num: JSBI | string | number) {
return new TokenAmount(token, expandTo18Decimals(num)) return CurrencyAmount.fromRawAmount(token, expandTo18Decimals(num))
} }
it('before staking', () => { it('before staking', () => {
......
import { Token, TokenAmount } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI } from '@uniswap/v2-sdk' import { Token, CurrencyAmount } from '@uniswap/sdk-core'
import { BigNumber } from 'ethers' import { BigNumber } from 'ethers'
import { STAKING_GENESIS } from '../state/stake/hooks' import { STAKING_GENESIS } from '../state/stake/hooks'
...@@ -57,8 +57,8 @@ function withVesting(before: JSBI, time: BigNumber, amount: number, start: numbe ...@@ -57,8 +57,8 @@ function withVesting(before: JSBI, time: BigNumber, amount: number, start: numbe
export function computeUniCirculation( export function computeUniCirculation(
uni: Token, uni: Token,
blockTimestamp: BigNumber, blockTimestamp: BigNumber,
unclaimedUni: TokenAmount | undefined unclaimedUni: CurrencyAmount<Token> | undefined
): TokenAmount { ): CurrencyAmount<Token> {
let wholeAmount = JSBI.BigInt(USERS_AMOUNT) let wholeAmount = JSBI.BigInt(USERS_AMOUNT)
// staking rewards // staking rewards
...@@ -108,6 +108,9 @@ export function computeUniCirculation( ...@@ -108,6 +108,9 @@ export function computeUniCirculation(
wholeAmount = withVesting(wholeAmount, blockTimestamp, TEAM_YEAR_3_AMOUNT, TREASURY_BEGIN_YEAR_3, TREASURY_END_YEAR_3) wholeAmount = withVesting(wholeAmount, blockTimestamp, TEAM_YEAR_3_AMOUNT, TREASURY_BEGIN_YEAR_3, TREASURY_END_YEAR_3)
wholeAmount = withVesting(wholeAmount, blockTimestamp, TEAM_YEAR_4_AMOUNT, TREASURY_BEGIN_YEAR_4, TREASURY_END_YEAR_4) wholeAmount = withVesting(wholeAmount, blockTimestamp, TEAM_YEAR_4_AMOUNT, TREASURY_BEGIN_YEAR_4, TREASURY_END_YEAR_4)
const total = new TokenAmount(uni, JSBI.multiply(wholeAmount, JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)))) const total = CurrencyAmount.fromRawAmount(
uni,
JSBI.multiply(wholeAmount, JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(18)))
)
return unclaimedUni ? total.subtract(unclaimedUni) : total return unclaimedUni ? total.subtract(unclaimedUni) : total
} }
import { Currency, ETHER, Token } from '@uniswap/sdk-core' import { Currency } from '@uniswap/sdk-core'
export function currencyId(currency: Currency): string { export function currencyId(currency: Currency): string {
if (currency === ETHER) return 'ETH' if (currency.isEther) return 'ETH'
if (currency instanceof Token) return currency.address if (currency.isToken) return currency.address
throw new Error('invalid currency') throw new Error('invalid currency')
} }
import { Price, TokenAmount } from '@uniswap/sdk-core' import { Price, CurrencyAmount, Currency } from '@uniswap/sdk-core'
import JSBI from 'jsbi' import JSBI from 'jsbi'
export function formatTokenAmount(amount: TokenAmount | undefined, sigFigs: number) { export function formatTokenAmount(amount: CurrencyAmount<Currency> | undefined, sigFigs: number) {
if (!amount) { if (!amount) {
return '-' return '-'
} }
if (JSBI.equal(amount.raw, JSBI.BigInt(0))) { if (JSBI.equal(amount.quotient, JSBI.BigInt(0))) {
return '0' return '0'
} }
if (parseFloat(amount.toFixed(Math.min(sigFigs, amount.token.decimals))) < 0.0001) { if (parseFloat(amount.toFixed(Math.min(sigFigs, amount.currency.decimals))) < 0.0001) {
return '<0.0001' return '<0.0001'
} }
return amount.toFixed(Math.min(sigFigs, amount.token.decimals)) return amount.toFixed(Math.min(sigFigs, amount.currency.decimals))
} }
export function formatPrice(price: Price | undefined, sigFigs: number) { export function formatPrice(price: Price<Currency, Currency> | undefined, sigFigs: number) {
if (!price) { if (!price) {
return '-' return '-'
} }
......
import { Token, Price } from '@uniswap/sdk-core' import { Token, Price } from '@uniswap/sdk-core'
import { tickToPrice } from '@uniswap/v3-sdk' import { tickToPrice } from '@uniswap/v3-sdk'
export function getTickToPrice(baseToken?: Token, quoteToken?: Token, tick?: number): Price | undefined { export function getTickToPrice(baseToken?: Token, quoteToken?: Token, tick?: number): Price<Token, Token> | undefined {
if (!baseToken || !quoteToken || typeof tick !== 'number') { if (!baseToken || !quoteToken || typeof tick !== 'number') {
return undefined return undefined
} }
......
import { Currency, TradeType } 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 } from '@uniswap/v3-sdk'
import { Version } from '../hooks/useToggledVersion' import { Version } from '../hooks/useToggledVersion'
export function getTradeVersion(trade?: V2Trade | V3Trade): Version | undefined { export function getTradeVersion(
trade?: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
): Version | undefined {
if (!trade) return undefined if (!trade) return undefined
if (trade instanceof V2Trade) return Version.v2 if (trade instanceof V2Trade) return Version.v2
return Version.v3 return Version.v3
......
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { AddressZero } from '@ethersproject/constants' import { AddressZero } from '@ethersproject/constants'
import { TokenAmount, Token, ChainId, Percent } from '@uniswap/sdk-core' import { CurrencyAmount, Token, ChainId, Percent } from '@uniswap/sdk-core'
import { getEtherscanLink, calculateSlippageAmount, isAddress, shortenAddress, calculateGasMargin } from '.' import { getEtherscanLink, calculateSlippageAmount, isAddress, shortenAddress, calculateGasMargin } from '.'
describe('utils', () => { describe('utils', () => {
...@@ -27,7 +27,7 @@ describe('utils', () => { ...@@ -27,7 +27,7 @@ describe('utils', () => {
describe('#calculateSlippageAmount', () => { describe('#calculateSlippageAmount', () => {
it('bounds are correct', () => { it('bounds are correct', () => {
const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100') const tokenAmount = CurrencyAmount.fromRawAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow('Unexpected slippage') expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow('Unexpected slippage')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(10_001, 10_000))).toThrow('Unexpected slippage') expect(() => calculateSlippageAmount(tokenAmount, new Percent(10_001, 10_000))).toThrow('Unexpected slippage')
expect(calculateSlippageAmount(tokenAmount, new Percent(0, 10_000)).map((bound) => bound.toString())).toEqual([ expect(calculateSlippageAmount(tokenAmount, new Percent(0, 10_000)).map((bound) => bound.toString())).toEqual([
...@@ -51,7 +51,7 @@ describe('utils', () => { ...@@ -51,7 +51,7 @@ describe('utils', () => {
).toEqual(['0', '200']) ).toEqual(['0', '200'])
}) })
it('works for 18 decimals', () => { it('works for 18 decimals', () => {
const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 18), '100') const tokenAmount = CurrencyAmount.fromRawAmount(new Token(ChainId.MAINNET, AddressZero, 18), '100')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow('Unexpected slippage') expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow('Unexpected slippage')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(10_001, 10_000))).toThrow('Unexpected slippage') expect(() => calculateSlippageAmount(tokenAmount, new Percent(10_001, 10_000))).toThrow('Unexpected slippage')
expect(calculateSlippageAmount(tokenAmount, new Percent(0, 10_000)).map((bound) => bound.toString())).toEqual([ expect(calculateSlippageAmount(tokenAmount, new Percent(0, 10_000)).map((bound) => bound.toString())).toEqual([
......
...@@ -3,9 +3,9 @@ import { getAddress } from '@ethersproject/address' ...@@ -3,9 +3,9 @@ import { getAddress } from '@ethersproject/address'
import { AddressZero } from '@ethersproject/constants' import { AddressZero } from '@ethersproject/constants'
import { JsonRpcSigner, Web3Provider } from '@ethersproject/providers' import { JsonRpcSigner, Web3Provider } from '@ethersproject/providers'
import { BigNumber } from '@ethersproject/bignumber' import { BigNumber } from '@ethersproject/bignumber'
import { ChainId, Percent, Token, CurrencyAmount, Currency, ETHER, Fraction } from '@uniswap/sdk-core' import { ChainId, Percent, CurrencyAmount, Currency, Fraction } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk'
import { FeeAmount } from '@uniswap/v3-sdk/dist/' import { FeeAmount } from '@uniswap/v3-sdk/dist/'
import JSBI from 'jsbi'
import { TokenAddressMap } from '../state/lists/hooks' import { TokenAddressMap } from '../state/lists/hooks'
// returns the checksummed address if the address is valid, otherwise returns false // returns the checksummed address if the address is valid, otherwise returns false
...@@ -64,13 +64,9 @@ export function calculateGasMargin(value: BigNumber): BigNumber { ...@@ -64,13 +64,9 @@ export function calculateGasMargin(value: BigNumber): BigNumber {
} }
const ONE = new Fraction(1, 1) const ONE = new Fraction(1, 1)
export function calculateSlippageAmount(value: CurrencyAmount, slippage: Percent): [JSBI, JSBI] { export function calculateSlippageAmount(value: CurrencyAmount<Currency>, slippage: Percent): [JSBI, JSBI] {
if (slippage.lessThan(0) || slippage.greaterThan(ONE)) throw new Error('Unexpected slippage') if (slippage.lessThan(0) || slippage.greaterThan(ONE)) throw new Error('Unexpected slippage')
const decimalScaled = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(value.currency.decimals)) return [value.multiply(ONE.subtract(slippage)).quotient, value.multiply(ONE.add(slippage)).quotient]
return [
value.multiply(ONE.subtract(slippage)).multiply(decimalScaled).quotient,
value.multiply(ONE.add(slippage)).multiply(decimalScaled).quotient,
]
} }
// account is not optional // account is not optional
...@@ -97,8 +93,8 @@ export function escapeRegExp(string: string): string { ...@@ -97,8 +93,8 @@ export function escapeRegExp(string: string): string {
} }
export function isTokenOnList(defaultTokens: TokenAddressMap, currency?: Currency): boolean { export function isTokenOnList(defaultTokens: TokenAddressMap, currency?: Currency): boolean {
if (currency === ETHER) return true if (currency?.isEther) return true
return Boolean(currency instanceof Token && defaultTokens[currency.chainId as ChainId]?.[currency.address]) return Boolean(currency?.isToken && defaultTokens[currency.chainId as ChainId]?.[currency.address])
} }
/** /**
......
import { ZERO_PERCENT, ONE_HUNDRED_PERCENT } from './../constants/index' import { ZERO_PERCENT, ONE_HUNDRED_PERCENT } from './../constants/index'
import { Percent, currencyEquals } from '@uniswap/sdk-core' import { Percent, currencyEquals, Currency, TradeType } 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 } from '@uniswap/v3-sdk'
// returns whether tradeB is better than tradeA by at least a threshold percentage amount // returns whether tradeB is better than tradeA by at least a threshold percentage amount
export function isTradeBetter( export function isTradeBetter(
tradeA: V2Trade | V3Trade | undefined | null, tradeA: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined | null,
tradeB: V2Trade | V3Trade | undefined | null, tradeB: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | undefined | null,
minimumDelta: Percent = ZERO_PERCENT minimumDelta: Percent = ZERO_PERCENT
): boolean | undefined { ): boolean | undefined {
if (tradeA && !tradeB) return false if (tradeA && !tradeB) return false
...@@ -24,6 +24,8 @@ export function isTradeBetter( ...@@ -24,6 +24,8 @@ export function isTradeBetter(
if (minimumDelta.equalTo(ZERO_PERCENT)) { if (minimumDelta.equalTo(ZERO_PERCENT)) {
return tradeA.executionPrice.lessThan(tradeB.executionPrice) return tradeA.executionPrice.lessThan(tradeB.executionPrice)
} else { } else {
return tradeA.executionPrice.raw.multiply(minimumDelta.add(ONE_HUNDRED_PERCENT)).lessThan(tradeB.executionPrice) return tradeA.executionPrice.asFraction
.multiply(minimumDelta.add(ONE_HUNDRED_PERCENT))
.lessThan(tradeB.executionPrice)
} }
} }
import { DEFAULT_LIST_OF_LISTS } from './../constants/lists' import { DEFAULT_LIST_OF_LISTS } from './../constants/lists'
const DEFAULT_LIST_PRIORITIES = DEFAULT_LIST_OF_LISTS.reduce<{ [listUrl: string]: number }>((memo, listUrl, index) => {
memo[listUrl] = index + 1
return memo
}, {})
// use ordering of default list of lists to assign priority // use ordering of default list of lists to assign priority
export default function sortByListPriority(urlA: string, urlB: string) { export default function sortByListPriority(urlA: string, urlB: string) {
const first = DEFAULT_LIST_OF_LISTS.includes(urlA) ? DEFAULT_LIST_OF_LISTS.indexOf(urlA) : Number.MAX_SAFE_INTEGER if (DEFAULT_LIST_PRIORITIES[urlA] && DEFAULT_LIST_PRIORITIES[urlB]) {
const second = DEFAULT_LIST_OF_LISTS.includes(urlB) ? DEFAULT_LIST_OF_LISTS.indexOf(urlB) : Number.MAX_SAFE_INTEGER return DEFAULT_LIST_PRIORITIES[urlA] - DEFAULT_LIST_PRIORITIES[urlB]
}
// need reverse order to make sure mapping includes top priority last
if (first < second) return 1
else if (first > second) return -1
return 0 return 0
} }
import { CurrencyAmount, ETHER } from '@uniswap/sdk-core' import { Currency, CurrencyAmount } from '@uniswap/sdk-core'
import { JSBI } from '@uniswap/v2-sdk' import JSBI from 'jsbi'
import { MIN_ETH } from '../constants' import { MIN_ETH } from '../constants'
/** /**
* Given some token amount, return the max that can be spent of it * Given some token amount, return the max that can be spent of it
* @param currencyAmount to return max of * @param currencyAmount to return max of
*/ */
export function maxAmountSpend(currencyAmount?: CurrencyAmount): CurrencyAmount | undefined { export function maxAmountSpend(currencyAmount?: CurrencyAmount<Currency>): CurrencyAmount<Currency> | undefined {
if (!currencyAmount) return undefined if (!currencyAmount) return undefined
if (currencyAmount.currency === ETHER) { if (currencyAmount.currency.isEther) {
if (JSBI.greaterThan(currencyAmount.raw, MIN_ETH)) { if (JSBI.greaterThan(currencyAmount.quotient, MIN_ETH)) {
return CurrencyAmount.ether(JSBI.subtract(currencyAmount.raw, MIN_ETH)) return CurrencyAmount.ether(JSBI.subtract(currencyAmount.quotient, MIN_ETH))
} else { } else {
return CurrencyAmount.ether(JSBI.BigInt(0)) return CurrencyAmount.ether(JSBI.BigInt(0))
} }
......
import { ChainId, Percent, Token, TokenAmount, TradeType } from '@uniswap/sdk-core' import JSBI from 'jsbi'
import { JSBI, Trade, Pair, Route } from '@uniswap/v2-sdk' import { ChainId, Percent, Token, CurrencyAmount, TradeType } from '@uniswap/sdk-core'
import { Trade, Pair, Route } from '@uniswap/v2-sdk'
import { computeRealizedLPFeeAmount, warningSeverity } from './prices' import { computeRealizedLPFeeAmount, warningSeverity } from './prices'
describe('prices', () => { describe('prices', () => {
...@@ -7,8 +8,14 @@ describe('prices', () => { ...@@ -7,8 +8,14 @@ describe('prices', () => {
const token2 = new Token(ChainId.MAINNET, '0x0000000000000000000000000000000000000002', 18) const token2 = new Token(ChainId.MAINNET, '0x0000000000000000000000000000000000000002', 18)
const token3 = new Token(ChainId.MAINNET, '0x0000000000000000000000000000000000000003', 18) const token3 = new Token(ChainId.MAINNET, '0x0000000000000000000000000000000000000003', 18)
const pair12 = new Pair(new TokenAmount(token1, JSBI.BigInt(10000)), new TokenAmount(token2, JSBI.BigInt(20000))) const pair12 = new Pair(
const pair23 = new Pair(new TokenAmount(token2, JSBI.BigInt(20000)), new TokenAmount(token3, JSBI.BigInt(30000))) CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(10000)),
CurrencyAmount.fromRawAmount(token2, JSBI.BigInt(20000))
)
const pair23 = new Pair(
CurrencyAmount.fromRawAmount(token2, JSBI.BigInt(20000)),
CurrencyAmount.fromRawAmount(token3, JSBI.BigInt(30000))
)
describe('#computeRealizedLPFeeAmount', () => { describe('#computeRealizedLPFeeAmount', () => {
it('returns undefined for undefined', () => { it('returns undefined for undefined', () => {
...@@ -18,21 +25,25 @@ describe('prices', () => { ...@@ -18,21 +25,25 @@ describe('prices', () => {
it('correct realized lp fee for single hop', () => { it('correct realized lp fee for single hop', () => {
expect( expect(
computeRealizedLPFeeAmount( computeRealizedLPFeeAmount(
new Trade(new Route([pair12], token1), new TokenAmount(token1, JSBI.BigInt(1000)), TradeType.EXACT_INPUT) new Trade(
new Route([pair12], token1, token2),
CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(1000)),
TradeType.EXACT_INPUT
)
) )
).toEqual(new TokenAmount(token1, JSBI.BigInt(3))) ).toEqual(CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(3)))
}) })
it('correct realized lp fee for double hop', () => { it('correct realized lp fee for double hop', () => {
expect( expect(
computeRealizedLPFeeAmount( computeRealizedLPFeeAmount(
new Trade( new Trade(
new Route([pair12, pair23], token1), new Route([pair12, pair23], token1, token3),
new TokenAmount(token1, JSBI.BigInt(1000)), CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(1000)),
TradeType.EXACT_INPUT TradeType.EXACT_INPUT
) )
) )
).toEqual(new TokenAmount(token1, JSBI.BigInt(5))) ).toEqual(CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(5)))
}) })
}) })
......
import JSBI from 'jsbi' import JSBI from 'jsbi'
import { CurrencyAmount, Fraction, Percent, TokenAmount } from '@uniswap/sdk-core' import { Currency, CurrencyAmount, Fraction, Percent, TradeType } 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 } from '@uniswap/v3-sdk'
import { import {
...@@ -14,7 +14,9 @@ const ONE_HUNDRED_PERCENT = new Percent(JSBI.BigInt(10000), JSBI.BigInt(10000)) ...@@ -14,7 +14,9 @@ const ONE_HUNDRED_PERCENT = new Percent(JSBI.BigInt(10000), JSBI.BigInt(10000))
const INPUT_FRACTION_AFTER_FEE = ONE_HUNDRED_PERCENT.subtract(THIRTY_BIPS_FEE) const INPUT_FRACTION_AFTER_FEE = ONE_HUNDRED_PERCENT.subtract(THIRTY_BIPS_FEE)
// computes realized lp fee as a percent // computes realized lp fee as a percent
export function computeRealizedLPFeePercent(trade: V2Trade | V3Trade): Percent { export function computeRealizedLPFeePercent(
trade: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType>
): Percent {
let percent: Percent let percent: Percent
if (trade instanceof V2Trade) { if (trade instanceof V2Trade) {
// for each hop in our trade, take away the x*y=k price impact from 0.3% fees // for each hop in our trade, take away the x*y=k price impact from 0.3% fees
...@@ -39,20 +41,17 @@ export function computeRealizedLPFeePercent(trade: V2Trade | V3Trade): Percent { ...@@ -39,20 +41,17 @@ export function computeRealizedLPFeePercent(trade: V2Trade | V3Trade): Percent {
} }
// computes price breakdown for the trade // computes price breakdown for the trade
export function computeRealizedLPFeeAmount(trade?: V2Trade | V3Trade | null): CurrencyAmount | undefined { export function computeRealizedLPFeeAmount(
if (trade instanceof V2Trade) { trade?: V2Trade<Currency, Currency, TradeType> | V3Trade<Currency, Currency, TradeType> | null
): CurrencyAmount<Currency> | undefined {
if (trade instanceof V2Trade || trade instanceof V3Trade) {
const realizedLPFee = computeRealizedLPFeePercent(trade) const realizedLPFee = computeRealizedLPFeePercent(trade)
// the amount of the input that accrues to LPs // the amount of the input that accrues to LPs
return trade.inputAmount instanceof TokenAmount return CurrencyAmount.fromRawAmount(
? new TokenAmount(trade.inputAmount.token, realizedLPFee.multiply(trade.inputAmount.raw).quotient) trade.inputAmount.currency,
: CurrencyAmount.ether(realizedLPFee.multiply(trade.inputAmount.raw).quotient) trade.inputAmount.asFraction.multiply(realizedLPFee).quotient
} else if (trade instanceof V3Trade) { )
const realizedLPFee = computeRealizedLPFeePercent(trade)
return trade.inputAmount instanceof TokenAmount
? new TokenAmount(trade.inputAmount.token, realizedLPFee.multiply(trade.inputAmount.raw).quotient)
: CurrencyAmount.ether(realizedLPFee.multiply(trade.inputAmount.raw).quotient)
} }
return undefined return undefined
......
import { supportedChainId } from 'utils' import { supportedChainId } from 'utils'
import { ChainId, Currency, CurrencyAmount, ETHER, Token, TokenAmount, WETH9 } from '@uniswap/sdk-core' import {
ChainId,
Currency,
ETHER,
Token,
CurrencyAmount,
WETH9,
wrappedCurrency as wrappedCurrencyInternal,
wrappedCurrencyAmount as wrappedCurrencyAmountInternal,
} from '@uniswap/sdk-core'
export function wrappedCurrency(currency: Currency | undefined, chainId: ChainId | undefined): Token | undefined { export function wrappedCurrency(currency: Currency | undefined, chainId: ChainId | undefined): Token | undefined {
return chainId && currency === ETHER ? WETH9[chainId] : currency instanceof Token ? currency : undefined return chainId && currency ? wrappedCurrencyInternal(currency, chainId) : undefined
} }
export function wrappedCurrencyAmount( export function wrappedCurrencyAmount(
currencyAmount: CurrencyAmount | undefined, currencyAmount: CurrencyAmount<Currency> | undefined,
chainId: ChainId | undefined chainId: ChainId | undefined
): TokenAmount | undefined { ): CurrencyAmount<Token> | undefined {
const token = currencyAmount && chainId ? wrappedCurrency(currencyAmount.currency, chainId) : undefined return currencyAmount && chainId ? wrappedCurrencyAmountInternal(currencyAmount, chainId) : undefined
return token && currencyAmount ? new TokenAmount(token, currencyAmount.raw) : undefined
} }
export function unwrappedToken(token: Token): Currency { export function unwrappedToken(currency: Currency): Currency {
const formattedChainId = supportedChainId(token.chainId) if (currency.isEther) return currency
if (formattedChainId && token.equals(WETH9[formattedChainId])) return ETHER const formattedChainId = supportedChainId(currency.chainId)
return token if (formattedChainId && currency.equals(WETH9[formattedChainId])) return ETHER
return currency
} }
...@@ -4085,10 +4085,10 @@ ...@@ -4085,10 +4085,10 @@
resolved "https://registry.yarnpkg.com/@uniswap/merkle-distributor/-/merkle-distributor-1.0.1.tgz#dc3d911f65a860fc3f0cae074bdcd08ed6a27a4d" resolved "https://registry.yarnpkg.com/@uniswap/merkle-distributor/-/merkle-distributor-1.0.1.tgz#dc3d911f65a860fc3f0cae074bdcd08ed6a27a4d"
integrity sha512-5gDiTI5hrXIh5UWTrxKYjw30QQDnpl8ckDSpefldNenDlYO1RKkdUYMYpvrqGi2r7YzLYTlO6+TDlNs6O7hDRw== integrity sha512-5gDiTI5hrXIh5UWTrxKYjw30QQDnpl8ckDSpefldNenDlYO1RKkdUYMYpvrqGi2r7YzLYTlO6+TDlNs6O7hDRw==
"@uniswap/sdk-core@^1.0.10": "@uniswap/sdk-core@^3.0.0-alpha.1":
version "1.0.10" version "3.0.0-alpha.1"
resolved "https://registry.yarnpkg.com/@uniswap/sdk-core/-/sdk-core-1.0.10.tgz#a30118ac29319bd83113f9c90eab99f803ec9267" resolved "https://registry.yarnpkg.com/@uniswap/sdk-core/-/sdk-core-3.0.0-alpha.1.tgz#8d735755818658fd4a6113cb6d30ed637f9e8347"
integrity sha512-8aD3xkzNDI3Ffh7PdLIcmraZr/6knqQuamVOv96EN8lhouEYH2ZuRbBWb7eZa/W7NwOLjlXM7XHi5gWJKzvbkg== integrity sha512-dCRBMKtmVmQCoG6sju3j/ki81e82zyqcWm0g+eU3JU0hzbSo6i31wzkOQPHMRO6FcYIJ6+9qx3Sy0B7VoZ6t9g==
dependencies: dependencies:
"@ethersproject/address" "^5.0.2" "@ethersproject/address" "^5.0.2"
big.js "^5.2.2" big.js "^5.2.2"
...@@ -4120,14 +4120,14 @@ ...@@ -4120,14 +4120,14 @@
"@uniswap/lib" "1.1.1" "@uniswap/lib" "1.1.1"
"@uniswap/v2-core" "1.0.0" "@uniswap/v2-core" "1.0.0"
"@uniswap/v2-sdk@^1.0.9": "@uniswap/v2-sdk@^3.0.0-alpha.0":
version "1.0.9" version "3.0.0-alpha.0"
resolved "https://registry.yarnpkg.com/@uniswap/v2-sdk/-/v2-sdk-1.0.9.tgz#cd9e69b5b25c9ca8f1daec19d1859f48241b4d5c" resolved "https://registry.yarnpkg.com/@uniswap/v2-sdk/-/v2-sdk-3.0.0-alpha.0.tgz#5bbd3133f832bf8b36bacf9213b06de520313e28"
integrity sha512-/dWJvTx1ssi+DFp05tEnoBtgLQdihlEOL9rlFMPEMTz0f0GsgYOTEh8Z4I7UhS6aGdZ/lCGSfJJRjDiDO7IDEw== integrity sha512-KHgdCldJ0JY6NC7KImJuU00G5E7X3LNq5yyVy5tGqf2S9fzBf/az91tlVSZzkEyALmH+8RiSvtqKjSNMXTXTfw==
dependencies: dependencies:
"@ethersproject/address" "^5.0.0" "@ethersproject/address" "^5.0.0"
"@ethersproject/solidity" "^5.0.0" "@ethersproject/solidity" "^5.0.0"
"@uniswap/sdk-core" "^1.0.10" "@uniswap/sdk-core" "^3.0.0-alpha.1"
tiny-invariant "^1.1.0" tiny-invariant "^1.1.0"
tiny-warning "^1.0.3" tiny-warning "^1.0.3"
...@@ -4147,14 +4147,14 @@ ...@@ -4147,14 +4147,14 @@
"@uniswap/v3-core" "1.0.0" "@uniswap/v3-core" "1.0.0"
base64-sol "1.0.1" base64-sol "1.0.1"
"@uniswap/v3-sdk@^1.0.8": "@uniswap/v3-sdk@^3.0.0-alpha.0":
version "1.0.8" version "3.0.0-alpha.0"
resolved "https://registry.yarnpkg.com/@uniswap/v3-sdk/-/v3-sdk-1.0.8.tgz#c85b229ac9448d19dfb1cb4a7891478c003a72f4" resolved "https://registry.yarnpkg.com/@uniswap/v3-sdk/-/v3-sdk-3.0.0-alpha.0.tgz#155067312f07d0f09f69df4c64726287fe762c48"
integrity sha512-Kg0P4KZI07m6B6L5EEtkEX/Q6QOdbWnVAHiy8y1XJOxORGw4DS0vklG5IRJAVhgLsVlosbmjxELsBjVMuKtypQ== integrity sha512-wlXX7otryzTOzTPx9u2p4U1ZXOVanL/I523s2AHLkxGVDlzwl0SiCtj7qLj65cet8u0eG9hlLw1N8GNQx4EMrQ==
dependencies: dependencies:
"@ethersproject/abi" "^5.0.12" "@ethersproject/abi" "^5.0.12"
"@ethersproject/solidity" "^5.0.9" "@ethersproject/solidity" "^5.0.9"
"@uniswap/sdk-core" "^1.0.10" "@uniswap/sdk-core" "^3.0.0-alpha.1"
"@uniswap/v3-periphery" "1.0.0" "@uniswap/v3-periphery" "1.0.0"
tiny-invariant "^1.1.0" tiny-invariant "^1.1.0"
tiny-warning "^1.0.3" tiny-warning "^1.0.3"
......
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