Fix code style issues with ESLint

This commit is contained in:
Lint Action 2021-02-16 08:36:54 +00:00
parent 4e17107ac5
commit b6d8512316
166 changed files with 889 additions and 885 deletions

@ -3,23 +3,33 @@ describe('Swap', () => {
cy.visit('/swap') cy.visit('/swap')
}) })
it('can enter an amount into input', () => { it('can enter an amount into input', () => {
cy.get('#swap-currency-input .token-amount-input').type('0.001', { delay: 200 }).should('have.value', '0.001') cy.get('#swap-currency-input .token-amount-input')
.type('0.001', { delay: 200 })
.should('have.value', '0.001')
}) })
it('zero swap amount', () => { it('zero swap amount', () => {
cy.get('#swap-currency-input .token-amount-input').type('0.0', { delay: 200 }).should('have.value', '0.0') cy.get('#swap-currency-input .token-amount-input')
.type('0.0', { delay: 200 })
.should('have.value', '0.0')
}) })
it('invalid swap amount', () => { it('invalid swap amount', () => {
cy.get('#swap-currency-input .token-amount-input').type('\\', { delay: 200 }).should('have.value', '') cy.get('#swap-currency-input .token-amount-input')
.type('\\', { delay: 200 })
.should('have.value', '')
}) })
it('can enter an amount into output', () => { it('can enter an amount into output', () => {
cy.get('#swap-currency-output .token-amount-input').type('0.001', { delay: 200 }).should('have.value', '0.001') cy.get('#swap-currency-output .token-amount-input')
.type('0.001', { delay: 200 })
.should('have.value', '0.001')
}) })
it('zero output amount', () => { it('zero output amount', () => {
cy.get('#swap-currency-output .token-amount-input').type('0.0', { delay: 200 }).should('have.value', '0.0') cy.get('#swap-currency-output .token-amount-input')
.type('0.0', { delay: 200 })
.should('have.value', '0.0')
}) })
it('can swap ETH for DAI', () => { it('can swap ETH for DAI', () => {
@ -39,7 +49,7 @@ describe('Swap', () => {
describe('expert mode', () => { describe('expert mode', () => {
beforeEach(() => { beforeEach(() => {
cy.window().then((win) => { cy.window().then(win => {
cy.stub(win, 'prompt').returns('confirm') cy.stub(win, 'prompt').returns('confirm')
}) })
cy.get('#open-settings-dialog-button').click() cy.get('#open-settings-dialog-button').click()

@ -77,6 +77,6 @@ Cypress.Commands.overwrite('visit', (original, url, options) => {
const provider = new JsonRpcProvider('https://rinkeby.infura.io/v3/4bf032f2d38a4ed6bb975b80d6340847', 4) const provider = new JsonRpcProvider('https://rinkeby.infura.io/v3/4bf032f2d38a4ed6bb975b80d6340847', 4)
const signer = new Wallet(PRIVATE_KEY_TEST_NEVER_USE, provider) const signer = new Wallet(PRIVATE_KEY_TEST_NEVER_USE, provider)
win.ethereum = new CustomizedBridge(signer, provider) win.ethereum = new CustomizedBridge(signer, provider)
}, }
}) })
}) })

@ -26,7 +26,7 @@ const HeaderRow = styled.div`
${({ theme }) => theme.flexRowNoWrap}; ${({ theme }) => theme.flexRowNoWrap};
padding: 1rem 1rem; padding: 1rem 1rem;
font-weight: 500; font-weight: 500;
color: ${(props) => (props.color === 'blue' ? ({ theme }) => theme.primary1 : 'inherit')}; color: ${props => (props.color === 'blue' ? ({ theme }) => theme.primary1 : 'inherit')};
${({ theme }) => theme.mediaWidth.upToMedium` ${({ theme }) => theme.mediaWidth.upToMedium`
padding: 1rem; padding: 1rem;
`}; `};
@ -223,7 +223,7 @@ export default function AccountDetails({
pendingTransactions, pendingTransactions,
confirmedTransactions, confirmedTransactions,
ENSName, ENSName,
openOptions, openOptions
}: AccountDetailsProps) { }: AccountDetailsProps) {
const { chainId, account, connector } = useActiveWeb3React() const { chainId, account, connector } = useActiveWeb3React()
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
@ -234,10 +234,10 @@ export default function AccountDetails({
const isMetaMask = !!(ethereum && ethereum.isMetaMask) const isMetaMask = !!(ethereum && ethereum.isMetaMask)
const name = Object.keys(SUPPORTED_WALLETS) const name = Object.keys(SUPPORTED_WALLETS)
.filter( .filter(
(k) => k =>
SUPPORTED_WALLETS[k].connector === connector && (connector !== injected || isMetaMask === (k === 'METAMASK')) SUPPORTED_WALLETS[k].connector === connector && (connector !== injected || isMetaMask === (k === 'METAMASK'))
) )
.map((k) => SUPPORTED_WALLETS[k].name)[0] .map(k => SUPPORTED_WALLETS[k].name)[0]
return <WalletName>Connected with {name}</WalletName> return <WalletName>Connected with {name}</WalletName>
} }

@ -68,7 +68,7 @@ const Input = styled.input<{ error?: boolean }>`
export default function AddressInputPanel({ export default function AddressInputPanel({
id, id,
value, value,
onChange, onChange
}: { }: {
id?: string id?: string
// the typed string value // the typed string value
@ -82,7 +82,7 @@ export default function AddressInputPanel({
const { address, loading, name } = useENS(value) const { address, loading, name } = useENS(value)
const handleInput = useCallback( const handleInput = useCallback(
(event) => { event => {
const input = event.target.value const input = event.target.value
const withoutSpaces = input.replace(/\s+/g, '') const withoutSpaces = input.replace(/\s+/g, '')
onChange(withoutSpaces) onChange(withoutSpaces)

@ -20,7 +20,7 @@ export default function Confetti({ start, variant }: { start: boolean; variant?:
h: height, h: height,
w: width, w: width,
x: 0, x: 0,
y: _variant === 'top' ? height * 0.25 : _variant === 'bottom' ? height * 0.75 : height * 0.5, y: _variant === 'top' ? height * 0.25 : _variant === 'bottom' ? height * 0.75 : height * 0.5
}} }}
initialVelocityX={15} initialVelocityX={15}
initialVelocityY={30} initialVelocityY={30}

@ -147,7 +147,7 @@ export default function CurrencyInputPanel({
otherCurrency, otherCurrency,
id, id,
showCommonBases, showCommonBases,
customBalanceText, customBalanceText
}: CurrencyInputPanelProps) { }: CurrencyInputPanelProps) {
const { t } = useTranslation() const { t } = useTranslation()
@ -191,7 +191,7 @@ export default function CurrencyInputPanel({
<NumericalInput <NumericalInput
className="token-amount-input" className="token-amount-input"
value={value} value={value}
onUserInput={(val) => { onUserInput={val => {
onUserInput(val) onUserInput(val)
}} }}
/> />

@ -28,7 +28,7 @@ const StyledLogo = styled(Logo)<{ size: string }>`
export default function CurrencyLogo({ export default function CurrencyLogo({
currency, currency,
size = '24px', size = '24px',
style, style
}: { }: {
currency?: Currency currency?: Currency
size?: string size?: string

@ -29,7 +29,7 @@ export default function DoubleCurrencyLogo({
currency0, currency0,
currency1, currency1,
size = 16, size = 16,
margin = false, margin = false
}: DoubleCurrencyLogoProps) { }: DoubleCurrencyLogoProps) {
return ( return (
<Wrapper sizeraw={size} margin={margin}> <Wrapper sizeraw={size} margin={margin}>

@ -5,7 +5,7 @@ const CURRENCY_AMOUNT_MIN = new Fraction(JSBI.BigInt(1), JSBI.BigInt(1000000))
export default function FormattedCurrencyAmount({ export default function FormattedCurrencyAmount({
currencyAmount, currencyAmount,
significantDigits = 4, significantDigits = 4
}: { }: {
currencyAmount: CurrencyAmount currencyAmount: CurrencyAmount
significantDigits?: number significantDigits?: number

@ -201,7 +201,7 @@ const UniIcon = styled.div`
const activeClassName = 'ACTIVE' const activeClassName = 'ACTIVE'
const StyledNavLink = styled(NavLink).attrs({ const StyledNavLink = styled(NavLink).attrs({
activeClassName, activeClassName
})` })`
${({ theme }) => theme.flexRowNoWrap} ${({ theme }) => theme.flexRowNoWrap}
align-items: left; align-items: left;
@ -228,7 +228,7 @@ const StyledNavLink = styled(NavLink).attrs({
` `
const StyledExternalLink = styled(ExternalLink).attrs({ const StyledExternalLink = styled(ExternalLink).attrs({
activeClassName, activeClassName
})<{ isActive?: boolean }>` })<{ isActive?: boolean }>`
${({ theme }) => theme.flexRowNoWrap} ${({ theme }) => theme.flexRowNoWrap}
align-items: left; align-items: left;
@ -291,7 +291,7 @@ const NETWORK_LABELS: { [chainId in ChainId]?: string } = {
[ChainId.RINKEBY]: 'Rinkeby', [ChainId.RINKEBY]: 'Rinkeby',
[ChainId.ROPSTEN]: 'Ropsten', [ChainId.ROPSTEN]: 'Ropsten',
[ChainId.GÖRLI]: 'Görli', [ChainId.GÖRLI]: 'Görli',
[ChainId.KOVAN]: 'Kovan', [ChainId.KOVAN]: 'Kovan'
} }
export default function Header() { export default function Header() {
@ -380,7 +380,7 @@ export default function Header() {
<HideSmall> <HideSmall>
<TYPE.white <TYPE.white
style={{ style={{
paddingRight: '.4rem', paddingRight: '.4rem'
}} }}
> >
<CountUp <CountUp

@ -148,5 +148,5 @@ export const dummyData = [
{ time: '2019-05-22', value: 43.3 }, { time: '2019-05-22', value: 43.3 },
{ time: '2019-05-23', value: 42.73 }, { time: '2019-05-23', value: 42.73 },
{ time: '2019-05-24', value: 42.67 }, { time: '2019-05-24', value: 42.67 },
{ time: '2019-05-28', value: 42.75 }, { time: '2019-05-28', value: 42.75 }
] ]

@ -78,28 +78,28 @@ const LineChart = ({
layout: { layout: {
backgroundColor: 'transparent', backgroundColor: 'transparent',
textColor: textColor, textColor: textColor,
fontFamily: 'Inter', fontFamily: 'Inter'
}, },
rightPriceScale: { rightPriceScale: {
scaleMargins: { scaleMargins: {
top: 0.1, top: 0.1,
bottom: 0.1, bottom: 0.1
}, },
borderVisible: false, borderVisible: false
}, },
timeScale: { timeScale: {
borderVisible: false, borderVisible: false
}, },
watermark: { watermark: {
color: 'rgba(0, 0, 0, 0)', color: 'rgba(0, 0, 0, 0)'
}, },
grid: { grid: {
horzLines: { horzLines: {
visible: false, visible: false
}, },
vertLines: { vertLines: {
visible: false, visible: false
}, }
}, },
crosshair: { crosshair: {
horzLine: { horzLine: {
@ -107,16 +107,16 @@ const LineChart = ({
style: 3, style: 3,
width: 1, width: 1,
color: '#505050', color: '#505050',
labelBackgroundColor: color, labelBackgroundColor: color
}, },
vertLine: { vertLine: {
visible: true, visible: true,
style: 3, style: 3,
width: 1, width: 1,
color: '#505050', color: '#505050',
labelBackgroundColor: color, labelBackgroundColor: color
}, }
}, }
}) })
const series = chart.addAreaSeries({ const series = chart.addAreaSeries({
@ -124,13 +124,13 @@ const LineChart = ({
topColor: darken(0.4, color), topColor: darken(0.4, color),
bottomColor: theme.bg1, bottomColor: theme.bg1,
lineWidth: 2, lineWidth: 2,
priceLineVisible: false, priceLineVisible: false
}) })
series.setData(data) series.setData(data)
// update the title when hovering on the chart // update the title when hovering on the chart
chart.subscribeCrosshairMove(function (param) { chart.subscribeCrosshairMove(function(param) {
if ( if (
chartRef?.current && chartRef?.current &&
(param === undefined || (param === undefined ||

@ -13,7 +13,7 @@ export default function ListLogo({
logoURI, logoURI,
style, style,
size = '24px', size = '24px',
alt, alt
}: { }: {
logoURI: string logoURI: string
size?: string size?: string

@ -14,7 +14,7 @@ export interface LogoProps extends Pick<ImageProps, 'style' | 'alt' | 'className
export default function Logo({ srcs, alt, ...rest }: LogoProps) { export default function Logo({ srcs, alt, ...rest }: LogoProps) {
const [, refresh] = useState<number>(0) const [, refresh] = useState<number>(0)
const src: string | undefined = srcs.find((src) => !BAD_SRCS[src]) const src: string | undefined = srcs.find(src => !BAD_SRCS[src])
if (src) { if (src) {
return ( return (
@ -24,7 +24,7 @@ export default function Logo({ srcs, alt, ...rest }: LogoProps) {
src={src} src={src}
onError={() => { onError={() => {
if (src) BAD_SRCS[src] = true if (src) BAD_SRCS[src] = true
refresh((i) => i + 1) refresh(i => i + 1)
}} }}
/> />
) )

@ -29,7 +29,7 @@ const AnimatedDialogContent = animated(DialogContent)
const StyledDialogContent = styled(({ minHeight, maxHeight, mobile, isOpen, ...rest }) => ( const StyledDialogContent = styled(({ minHeight, maxHeight, mobile, isOpen, ...rest }) => (
<AnimatedDialogContent {...rest} /> <AnimatedDialogContent {...rest} />
)).attrs({ )).attrs({
'aria-label': 'dialog', 'aria-label': 'dialog'
})` })`
overflow-y: ${({ mobile }) => (mobile ? 'scroll' : 'hidden')}; overflow-y: ${({ mobile }) => (mobile ? 'scroll' : 'hidden')};
@ -63,15 +63,13 @@ const StyledDialogContent = styled(({ minHeight, maxHeight, mobile, isOpen, ...r
`} `}
${({ theme, mobile }) => theme.mediaWidth.upToSmall` ${({ theme, mobile }) => theme.mediaWidth.upToSmall`
width: 85vw; width: 85vw;
${ ${mobile &&
mobile &&
css` css`
width: 100vw; width: 100vw;
border-radius: 20px; border-radius: 20px;
border-bottom-left-radius: 0; border-bottom-left-radius: 0;
border-bottom-right-radius: 0; border-bottom-right-radius: 0;
` `}
}
`} `}
} }
` `
@ -91,25 +89,25 @@ export default function Modal({
minHeight = false, minHeight = false,
maxHeight = 90, maxHeight = 90,
initialFocusRef, initialFocusRef,
children, children
}: ModalProps) { }: ModalProps) {
const fadeTransition = useTransition(isOpen, null, { const fadeTransition = useTransition(isOpen, null, {
config: { duration: 200 }, config: { duration: 200 },
from: { opacity: 0 }, from: { opacity: 0 },
enter: { opacity: 1 }, enter: { opacity: 1 },
leave: { opacity: 0 }, leave: { opacity: 0 }
}) })
const [{ y }, set] = useSpring(() => ({ y: 0, config: { mass: 1, tension: 210, friction: 20 } })) const [{ y }, set] = useSpring(() => ({ y: 0, config: { mass: 1, tension: 210, friction: 20 } }))
const bind = useGesture({ const bind = useGesture({
onDrag: (state) => { onDrag: state => {
set({ set({
y: state.down ? state.movement[1] : 0, y: state.down ? state.movement[1] : 0
}) })
if (state.movement[1] > 300 || (state.velocity > 3 && state.direction[1] > 0)) { if (state.movement[1] > 300 || (state.velocity > 3 && state.direction[1] > 0)) {
onDismiss() onDismiss()
} }
}, }
}) })
return ( return (
@ -122,7 +120,7 @@ export default function Modal({
{...(isMobile {...(isMobile
? { ? {
...bind(), ...bind(),
style: { transform: y.interpolate((y) => `translateY(${y > 0 ? y : 0}px)`) }, style: { transform: y.interpolate(y => `translateY(${y > 0 ? y : 0}px)`) }
} }
: {})} : {})}
aria-label="dialog content" aria-label="dialog content"

@ -41,7 +41,7 @@ export function LoadingView({ children, onDismiss }: { children: any; onDismiss:
export function SubmittedView({ export function SubmittedView({
children, children,
onDismiss, onDismiss,
hash, hash
}: { }: {
children: any children: any
onDismiss: () => void onDismiss: () => void

@ -22,7 +22,7 @@ const Tabs = styled.div`
const activeClassName = 'ACTIVE' const activeClassName = 'ACTIVE'
const StyledNavLink = styled(NavLink).attrs({ const StyledNavLink = styled(NavLink).attrs({
activeClassName, activeClassName
})` })`
${({ theme }) => theme.flexRowNoWrap} ${({ theme }) => theme.flexRowNoWrap}
align-items: center; align-items: center;

@ -61,7 +61,7 @@ export const Input = React.memo(function InnerInput({
<StyledInput <StyledInput
{...rest} {...rest}
value={value} value={value}
onChange={(event) => { onChange={event => {
// replace commas with periods, because uniswap exclusively uses period as the decimal separator // replace commas with periods, because uniswap exclusively uses period as the decimal separator
enforcer(event.target.value.replace(/,/g, '.')) enforcer(event.target.value.replace(/,/g, '.'))
}} }}

@ -9,8 +9,8 @@ import Portal from '@reach/portal'
const PopoverContainer = styled.div<{ show: boolean }>` const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 9999; z-index: 9999;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')}; visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)}; opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear; transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2}; background: ${({ theme }) => theme.bg2};
@ -91,8 +91,8 @@ export default function Popover({ content, show, children, placement = 'auto' }:
strategy: 'fixed', strategy: 'fixed',
modifiers: [ modifiers: [
{ name: 'offset', options: { offset: [8, 8] } }, { name: 'offset', options: { offset: [8, 8] } },
{ name: 'arrow', options: { element: arrowElement } }, { name: 'arrow', options: { element: arrowElement } }
], ]
}) })
const updateCallback = useCallback(() => { const updateCallback = useCallback(() => {
update && update() update && update()

@ -10,7 +10,7 @@ import {
useModalOpen, useModalOpen,
useShowClaimPopup, useShowClaimPopup,
useToggleSelfClaimModal, useToggleSelfClaimModal,
useToggleShowClaimPopup, useToggleShowClaimPopup
} from '../../state/application/hooks' } from '../../state/application/hooks'
import { useUserHasAvailableClaim, useUserUnclaimedAmount } from '../../state/claim/hooks' import { useUserHasAvailableClaim, useUserUnclaimedAmount } from '../../state/claim/hooks'

@ -23,7 +23,7 @@ export default function ListUpdatePopup({
listUrl, listUrl,
oldList, oldList,
newList, newList,
auto, auto
}: { }: {
popKey: string popKey: string
listUrl: string listUrl: string
@ -40,7 +40,7 @@ export default function ListUpdatePopup({
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Update List from Popup', action: 'Update List from Popup',
label: listUrl, label: listUrl
}) })
dispatch(acceptListUpdate(listUrl)) dispatch(acceptListUpdate(listUrl))
removeThisPopup() removeThisPopup()

@ -49,7 +49,7 @@ const AnimatedFader = animated(Fader)
export default function PopupItem({ export default function PopupItem({
removeAfterMs, removeAfterMs,
content, content,
popKey, popKey
}: { }: {
removeAfterMs: number | null removeAfterMs: number | null
content: PopupContent content: PopupContent
@ -74,12 +74,12 @@ export default function PopupItem({
let popupContent let popupContent
if ('txn' in content) { if ('txn' in content) {
const { const {
txn: { hash, success, summary }, txn: { hash, success, summary }
} = content } = content
popupContent = <TransactionPopup hash={hash} success={success} summary={summary} /> popupContent = <TransactionPopup hash={hash} success={success} summary={summary} />
} else if ('listUpdate' in content) { } else if ('listUpdate' in content) {
const { const {
listUpdate: { listUrl, oldList, newList, auto }, listUpdate: { listUrl, oldList, newList, auto }
} = content } = content
popupContent = <ListUpdatePopup popKey={popKey} listUrl={listUrl} oldList={oldList} newList={newList} auto={auto} /> popupContent = <ListUpdatePopup popKey={popKey} listUrl={listUrl} oldList={oldList} newList={newList} auto={auto} />
} }
@ -87,7 +87,7 @@ export default function PopupItem({
const faderStyle = useSpring({ const faderStyle = useSpring({
from: { width: '100%' }, from: { width: '100%' },
to: { width: '0%' }, to: { width: '0%' },
config: { duration: removeAfterMs ?? undefined }, config: { duration: removeAfterMs ?? undefined }
}) })
return ( return (

@ -15,7 +15,7 @@ const RowNoFlex = styled(AutoRow)`
export default function TransactionPopup({ export default function TransactionPopup({
hash, hash,
success, success,
summary, summary
}: { }: {
hash: string hash: string
success?: boolean success?: boolean

@ -54,7 +54,7 @@ export default function Popups() {
<> <>
<FixedPopupColumn gap="20px" extraPadding={urlWarningActive}> <FixedPopupColumn gap="20px" extraPadding={urlWarningActive}>
<ClaimPopup /> <ClaimPopup />
{activePopups.map((item) => ( {activePopups.map(item => (
<PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} /> <PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} />
))} ))}
</FixedPopupColumn> </FixedPopupColumn>
@ -63,7 +63,7 @@ export default function Popups() {
{activePopups // reverse so new items up front {activePopups // reverse so new items up front
.slice(0) .slice(0)
.reverse() .reverse()
.map((item) => ( .map(item => (
<PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} /> <PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} />
))} ))}
</MobilePopupInner> </MobilePopupInner>

@ -75,7 +75,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [ ? [
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)
] ]
: [undefined, undefined] : [undefined, undefined]
@ -186,7 +186,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw) JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [ ? [
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)
] ]
: [undefined, undefined] : [undefined, undefined]

@ -28,7 +28,7 @@ const BaseWrapper = styled.div<{ disable?: boolean }>`
export default function CommonBases({ export default function CommonBases({
chainId, chainId,
onSelect, onSelect,
selectedCurrency, selectedCurrency
}: { }: {
chainId?: ChainId chainId?: ChainId
selectedCurrency?: Currency | null selectedCurrency?: Currency | null

@ -102,7 +102,7 @@ function CurrencyRow({
onSelect, onSelect,
isSelected, isSelected,
otherSelected, otherSelected,
style, style
}: { }: {
currency: Currency currency: Currency
onSelect: () => void onSelect: () => void
@ -153,7 +153,7 @@ export default function CurrencyList({
showETH, showETH,
showImportView, showImportView,
setImportToken, setImportToken,
breakIndex, breakIndex
}: { }: {
height: number height: number
currencies: Currency[] currencies: Currency[]
@ -241,7 +241,7 @@ export default function CurrencyList({
setImportToken, setImportToken,
showImportView, showImportView,
breakIndex, breakIndex,
theme.text1, theme.text1
] ]
) )

@ -61,7 +61,7 @@ export function CurrencySearch({
isOpen, isOpen,
showManageView, showManageView,
showImportView, showImportView,
setImportToken, setImportToken
}: CurrencySearchProps) { }: CurrencySearchProps) {
const { t } = useTranslation() const { t } = useTranslation()
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
@ -87,7 +87,7 @@ export function CurrencySearch({
ReactGA.event({ ReactGA.event({
category: 'Currency Select', category: 'Currency Select',
action: 'Search by address', action: 'Search by address',
label: isAddressSearch, label: isAddressSearch
}) })
} }
}, [isAddressSearch]) }, [isAddressSearch])
@ -124,7 +124,7 @@ export function CurrencySearch({
// manage focus on modal show // manage focus on modal show
const inputRef = useRef<HTMLInputElement>() const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => { const handleInput = useCallback(event => {
const input = event.target.value const input = event.target.value
const checksummedInput = isAddress(input) const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input) setSearchQuery(checksummedInput || input)

@ -22,7 +22,7 @@ export enum CurrencyModalView {
search, search,
manage, manage,
importToken, importToken,
importList, importList
} }
export default function CurrencySearchModal({ export default function CurrencySearchModal({
@ -31,7 +31,7 @@ export default function CurrencySearchModal({
onCurrencySelect, onCurrencySelect,
selectedCurrency, selectedCurrency,
otherSelectedCurrency, otherSelectedCurrency,
showCommonBases = false, showCommonBases = false
}: CurrencySearchModalProps) { }: CurrencySearchModalProps) {
const [modalView, setModalView] = useState<CurrencyModalView>(CurrencyModalView.manage) const [modalView, setModalView] = useState<CurrencyModalView>(CurrencyModalView.manage)
const lastOpen = useLast(isOpen) const lastOpen = useLast(isOpen)

@ -56,7 +56,7 @@ export function ImportList({ listURL, list, setModalView, onDismiss }: ImportPro
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Add List', action: 'Add List',
label: listURL, label: listURL
}) })
// turn list on // turn list on
@ -64,11 +64,11 @@ export function ImportList({ listURL, list, setModalView, onDismiss }: ImportPro
// go back to lists // go back to lists
setModalView(CurrencyModalView.manage) setModalView(CurrencyModalView.manage)
}) })
.catch((error) => { .catch(error => {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Add List Failed', action: 'Add List Failed',
label: listURL, label: listURL
}) })
setAddError(error.message) setAddError(error.message)
dispatch(removeList(listURL)) dispatch(removeList(listURL))

@ -45,7 +45,7 @@ export default function ImportRow({
style, style,
dim, dim,
showImportView, showImportView,
setImportToken, setImportToken
}: { }: {
token: Token token: Token
style?: CSSProperties style?: CSSProperties

@ -74,7 +74,7 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }:
</PaddedColumn> </PaddedColumn>
<SectionBreak /> <SectionBreak />
<PaddedColumn gap="md"> <PaddedColumn gap="md">
{tokens.map((token) => { {tokens.map(token => {
const list = chainId && inactiveTokenList?.[chainId]?.[token.address]?.list const list = chainId && inactiveTokenList?.[chainId]?.[token.address]?.list
return ( return (
<Card backgroundColor={theme.bg2} key={'import' + token.address} className=".token-warning-container"> <Card backgroundColor={theme.bg2} key={'import' + token.address} className=".token-warning-container">
@ -151,7 +151,7 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }:
borderRadius="20px" borderRadius="20px"
padding="10px 1rem" padding="10px 1rem"
onClick={() => { onClick={() => {
tokens.map((token) => addToken(token)) tokens.map(token => addToken(token))
handleCurrencySelect && handleCurrencySelect(tokens[0]) handleCurrencySelect && handleCurrencySelect(tokens[0])
}} }}
className=".token-dismiss-button" className=".token-dismiss-button"

@ -46,7 +46,7 @@ export default function Manage({
setModalView, setModalView,
setImportList, setImportList,
setImportToken, setImportToken,
setListUrl, setListUrl
}: { }: {
onDismiss: () => void onDismiss: () => void
setModalView: (view: CurrencyModalView) => void setModalView: (view: CurrencyModalView) => void

@ -42,8 +42,8 @@ const UnpaddedLinkStyledButton = styled(LinkStyledButton)`
const PopoverContainer = styled.div<{ show: boolean }>` const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 100; z-index: 100;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')}; visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)}; opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear; transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2}; background: ${({ theme }) => theme.bg2};
border: 1px solid ${({ theme }) => theme.bg3}; border: 1px solid ${({ theme }) => theme.bg3};
@ -93,7 +93,7 @@ function listUrlRowHTMLId(listUrl: string) {
} }
const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) { const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
const listsByUrl = useSelector<AppState, AppState['lists']['byUrl']>((state) => state.lists.byUrl) const listsByUrl = useSelector<AppState, AppState['lists']['byUrl']>(state => state.lists.byUrl)
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const { current: list, pendingUpdate: pending } = listsByUrl[listUrl] const { current: list, pendingUpdate: pending } = listsByUrl[listUrl]
@ -109,7 +109,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
const { styles, attributes } = usePopper(referenceElement, popperElement, { const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'auto', placement: 'auto',
strategy: 'fixed', strategy: 'fixed',
modifiers: [{ name: 'offset', options: { offset: [8, 8] } }], modifiers: [{ name: 'offset', options: { offset: [8, 8] } }]
}) })
useOnClickOutside(node, open ? toggle : undefined) useOnClickOutside(node, open ? toggle : undefined)
@ -119,7 +119,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Update List from List Select', action: 'Update List from List Select',
label: listUrl, label: listUrl
}) })
dispatch(acceptListUpdate(listUrl)) dispatch(acceptListUpdate(listUrl))
}, [dispatch, listUrl, pending]) }, [dispatch, listUrl, pending])
@ -128,13 +128,13 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Start Remove List', action: 'Start Remove List',
label: listUrl, label: listUrl
}) })
if (window.prompt(`Please confirm you would like to remove this list by typing REMOVE`) === `REMOVE`) { if (window.prompt(`Please confirm you would like to remove this list by typing REMOVE`) === `REMOVE`) {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Confirm Remove List', action: 'Confirm Remove List',
label: listUrl, label: listUrl
}) })
dispatch(removeList(listUrl)) dispatch(removeList(listUrl))
} }
@ -144,7 +144,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Enable List', action: 'Enable List',
label: listUrl, label: listUrl
}) })
dispatch(enableList(listUrl)) dispatch(enableList(listUrl))
}, [dispatch, listUrl]) }, [dispatch, listUrl])
@ -153,7 +153,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({ ReactGA.event({
category: 'Lists', category: 'Lists',
action: 'Disable List', action: 'Disable List',
label: listUrl, label: listUrl
}) })
dispatch(disableList(listUrl)) dispatch(disableList(listUrl))
}, [dispatch, listUrl]) }, [dispatch, listUrl])
@ -216,7 +216,7 @@ const ListContainer = styled.div`
export function ManageLists({ export function ManageLists({
setModalView, setModalView,
setImportList, setImportList,
setListUrl, setListUrl
}: { }: {
setModalView: (view: CurrencyModalView) => void setModalView: (view: CurrencyModalView) => void
setImportList: (list: TokenList) => void setImportList: (list: TokenList) => void
@ -237,7 +237,7 @@ export function ManageLists({
} }
}, [activeCopy, activeListUrls]) }, [activeCopy, activeListUrls])
const handleInput = useCallback((e) => { const handleInput = useCallback(e => {
setListUrlInput(e.target.value) setListUrlInput(e.target.value)
}, []) }, [])
@ -250,7 +250,7 @@ export function ManageLists({
const sortedLists = useMemo(() => { const sortedLists = useMemo(() => {
const listUrls = Object.keys(lists) const listUrls = Object.keys(lists)
return listUrls return listUrls
.filter((listUrl) => { .filter(listUrl => {
// only show loaded lists, hide unsupported lists // only show loaded lists, hide unsupported lists
return Boolean(lists[listUrl].current) && !Boolean(UNSUPPORTED_LIST_URLS.includes(listUrl)) return Boolean(lists[listUrl].current) && !Boolean(UNSUPPORTED_LIST_URLS.includes(listUrl))
}) })
@ -286,7 +286,7 @@ export function ManageLists({
useEffect(() => { useEffect(() => {
async function fetchTempList() { async function fetchTempList() {
fetchList(listUrlInput, false) fetchList(listUrlInput, false)
.then((list) => setTempList(list)) .then(list => setTempList(list))
.catch(() => setAddError('Error importing list')) .catch(() => setAddError('Error importing list'))
} }
// if valid url, fetch details for card // if valid url, fetch details for card
@ -367,7 +367,7 @@ export function ManageLists({
<Separator /> <Separator />
<ListContainer> <ListContainer>
<AutoColumn gap="md"> <AutoColumn gap="md">
{sortedLists.map((listUrl) => ( {sortedLists.map(listUrl => (
<ListRow key={listUrl} listUrl={listUrl} /> <ListRow key={listUrl} listUrl={listUrl} />
))} ))}
</AutoColumn> </AutoColumn>

@ -37,7 +37,7 @@ const Footer = styled.div`
export default function ManageTokens({ export default function ManageTokens({
setModalView, setModalView,
setImportToken, setImportToken
}: { }: {
setModalView: (view: CurrencyModalView) => void setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void setImportToken: (token: Token) => void
@ -49,7 +49,7 @@ export default function ManageTokens({
// manage focus on modal show // manage focus on modal show
const inputRef = useRef<HTMLInputElement>() const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => { const handleInput = useCallback(event => {
const input = event.target.value const input = event.target.value
const checksummedInput = isAddress(input) const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input) setSearchQuery(checksummedInput || input)
@ -65,7 +65,7 @@ export default function ManageTokens({
const handleRemoveAll = useCallback(() => { const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) { if (chainId && userAddedTokens) {
userAddedTokens.map((token) => { userAddedTokens.map(token => {
return removeToken(chainId, token.address) return removeToken(chainId, token.address)
}) })
} }
@ -74,7 +74,7 @@ export default function ManageTokens({
const tokenList = useMemo(() => { const tokenList = useMemo(() => {
return ( return (
chainId && chainId &&
userAddedTokens.map((token) => ( userAddedTokens.map(token => (
<RowBetween key={token.address} width="100%"> <RowBetween key={token.address} width="100%">
<RowFixed> <RowFixed>
<CurrencyLogo currency={token} size={'20px'} /> <CurrencyLogo currency={token} size={'20px'} />

@ -19,7 +19,7 @@ export const FilterWrapper = styled(RowFixed)`
export default function SortButton({ export default function SortButton({
toggleSortOrder, toggleSortOrder,
ascending, ascending
}: { }: {
toggleSortOrder: () => void toggleSortOrder: () => void
ascending: boolean ascending: boolean

@ -8,13 +8,13 @@ export function filterTokens(tokens: Token[], search: string): Token[] {
const searchingAddress = isAddress(search) const searchingAddress = isAddress(search)
if (searchingAddress) { if (searchingAddress) {
return tokens.filter((token) => token.address === searchingAddress) return tokens.filter(token => token.address === searchingAddress)
} }
const lowerSearchParts = search const lowerSearchParts = search
.toLowerCase() .toLowerCase()
.split(/\s+/) .split(/\s+/)
.filter((s) => s.length > 0) .filter(s => s.length > 0)
if (lowerSearchParts.length === 0) { if (lowerSearchParts.length === 0) {
return tokens return tokens
@ -24,12 +24,12 @@ export function filterTokens(tokens: Token[], search: string): Token[] {
const sParts = s const sParts = s
.toLowerCase() .toLowerCase()
.split(/\s+/) .split(/\s+/)
.filter((s) => s.length > 0) .filter(s => s.length > 0)
return lowerSearchParts.every((p) => p.length === 0 || sParts.some((sp) => sp.startsWith(p) || sp.endsWith(p))) return lowerSearchParts.every(p => p.length === 0 || sParts.some(sp => sp.startsWith(p) || sp.endsWith(p)))
} }
return tokens.filter((token) => { return tokens.filter(token => {
const { symbol, name } = token const { symbol, name } = token
return (symbol && matchesSearch(symbol)) || (name && matchesSearch(name)) return (symbol && matchesSearch(symbol)) || (name && matchesSearch(name))
}) })
@ -44,7 +44,7 @@ export function useSortedTokensByQuery(tokens: Token[] | undefined, searchQuery:
const symbolMatch = searchQuery const symbolMatch = searchQuery
.toLowerCase() .toLowerCase()
.split(/\s+/) .split(/\s+/)
.filter((s) => s.length > 0) .filter(s => s.length > 0)
if (symbolMatch.length > 1) { if (symbolMatch.length > 1) {
return tokens return tokens
@ -55,7 +55,7 @@ export function useSortedTokensByQuery(tokens: Token[] | undefined, searchQuery:
const rest: Token[] = [] const rest: Token[] = []
// sort tokens by exact match -> subtring on symbol match -> rest // sort tokens by exact match -> subtring on symbol match -> rest
tokens.map((token) => { tokens.map(token => {
if (token.symbol?.toLowerCase() === symbolMatch[0]) { if (token.symbol?.toLowerCase() === symbolMatch[0]) {
return exactMatches.push(token) return exactMatches.push(token)
} else if (token.symbol?.toLowerCase().startsWith(searchQuery.toLowerCase().trim())) { } else if (token.symbol?.toLowerCase().startsWith(searchQuery.toLowerCase().trim())) {

@ -21,8 +21,8 @@ export const StyledMenu = styled.div`
export const PopoverContainer = styled.div<{ show: boolean }>` export const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 100; z-index: 100;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')}; visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)}; opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear; transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2}; background: ${({ theme }) => theme.bg2};
border: 1px solid ${({ theme }) => theme.bg3}; border: 1px solid ${({ theme }) => theme.bg3};

@ -9,7 +9,7 @@ import {
useExpertModeManager, useExpertModeManager,
useUserTransactionTTL, useUserTransactionTTL,
useUserSlippageTolerance, useUserSlippageTolerance,
useUserSingleHopOnly, useUserSingleHopOnly
} from '../../state/user/hooks' } from '../../state/user/hooks'
import { TYPE } from '../../theme' import { TYPE } from '../../theme'
import { ButtonError } from '../Button' import { ButtonError } from '../Button'

@ -98,7 +98,7 @@ interface InputSliderProps {
export default function Slider({ value, onChange, min = 0, step = 1, max = 100, size = 28 }: InputSliderProps) { export default function Slider({ value, onChange, min = 0, step = 1, max = 100, size = 28 }: InputSliderProps) {
const changeCallback = useCallback( const changeCallback = useCallback(
(e) => { e => {
onChange(parseInt(e.target.value)) onChange(parseInt(e.target.value))
}, },
[onChange] [onChange]

@ -6,7 +6,7 @@ import { ImportToken } from 'components/SearchModal/ImportToken'
export default function TokenWarningModal({ export default function TokenWarningModal({
isOpen, isOpen,
tokens, tokens,
onConfirm, onConfirm
}: { }: {
isOpen: boolean isOpen: boolean
tokens: Token[] tokens: Token[]

@ -71,7 +71,7 @@ function TransactionSubmittedContent({
onDismiss, onDismiss,
chainId, chainId,
hash, hash,
currencyToAdd, currencyToAdd
}: { }: {
onDismiss: () => void onDismiss: () => void
hash: string | undefined hash: string | undefined
@ -134,7 +134,7 @@ export function ConfirmationModalContent({
title, title,
bottomContent, bottomContent,
onDismiss, onDismiss,
topContent, topContent
}: { }: {
title: string title: string
onDismiss: () => void onDismiss: () => void
@ -199,7 +199,7 @@ export default function TransactionConfirmationModal({
hash, hash,
pendingText, pendingText,
content, content,
currencyToAdd, currencyToAdd
}: ConfirmationModalProps) { }: ConfirmationModalProps) {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()

@ -11,11 +11,11 @@ import { darken } from 'polished'
enum SlippageError { enum SlippageError {
InvalidInput = 'InvalidInput', InvalidInput = 'InvalidInput',
RiskyLow = 'RiskyLow', RiskyLow = 'RiskyLow',
RiskyHigh = 'RiskyHigh', RiskyHigh = 'RiskyHigh'
} }
enum DeadlineError { enum DeadlineError {
InvalidInput = 'InvalidInput', InvalidInput = 'InvalidInput'
} }
const FancyButton = styled.button` const FancyButton = styled.button`
@ -199,7 +199,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
onBlur={() => { onBlur={() => {
parseCustomSlippage((rawSlippage / 100).toFixed(2)) parseCustomSlippage((rawSlippage / 100).toFixed(2))
}} }}
onChange={(e) => parseCustomSlippage(e.target.value)} onChange={e => parseCustomSlippage(e.target.value)}
color={!slippageInputIsValid ? 'red' : ''} color={!slippageInputIsValid ? 'red' : ''}
/> />
% %
@ -211,7 +211,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
style={{ style={{
fontSize: '14px', fontSize: '14px',
paddingTop: '7px', paddingTop: '7px',
color: slippageError === SlippageError.InvalidInput ? 'red' : '#F3841E', color: slippageError === SlippageError.InvalidInput ? 'red' : '#F3841E'
}} }}
> >
{slippageError === SlippageError.InvalidInput {slippageError === SlippageError.InvalidInput
@ -239,7 +239,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
}} }}
placeholder={(deadline / 60).toString()} placeholder={(deadline / 60).toString()}
value={deadlineInput} value={deadlineInput}
onChange={(e) => parseCustomDeadline(e.target.value)} onChange={e => parseCustomDeadline(e.target.value)}
/> />
</OptionCustom> </OptionCustom>
<TYPE.body style={{ paddingLeft: '8px' }} fontSize={14}> <TYPE.body style={{ paddingLeft: '8px' }} fontSize={14}>

@ -62,7 +62,7 @@ const CircleWrapper = styled.div`
const HeaderText = styled.div` const HeaderText = styled.div`
${({ theme }) => theme.flexRowNoWrap}; ${({ theme }) => theme.flexRowNoWrap};
color: ${(props) => (props.color === 'blue' ? ({ theme }) => theme.primary1 : ({ theme }) => theme.text1)}; color: ${props => (props.color === 'blue' ? ({ theme }) => theme.primary1 : ({ theme }) => theme.text1)};
font-size: 1rem; font-size: 1rem;
font-weight: 500; font-weight: 500;
` `
@ -97,7 +97,7 @@ export default function Option({
subheader = null, subheader = null,
icon, icon,
active = false, active = false,
id, id
}: { }: {
link?: string | null link?: string | null
clickable?: boolean clickable?: boolean

@ -67,7 +67,7 @@ export default function PendingView({
connector, connector,
error = false, error = false,
setPendingError, setPendingError,
tryActivation, tryActivation
}: { }: {
connector?: AbstractConnector connector?: AbstractConnector
error?: boolean error?: boolean
@ -100,7 +100,7 @@ export default function PendingView({
)} )}
</LoadingWrapper> </LoadingWrapper>
</LoadingMessage> </LoadingMessage>
{Object.keys(SUPPORTED_WALLETS).map((key) => { {Object.keys(SUPPORTED_WALLETS).map(key => {
const option = SUPPORTED_WALLETS[key] const option = SUPPORTED_WALLETS[key]
if (option.connector === connector) { if (option.connector === connector) {
if (option.connector === injected) { if (option.connector === injected) {

@ -47,7 +47,7 @@ const HeaderRow = styled.div`
${({ theme }) => theme.flexRowNoWrap}; ${({ theme }) => theme.flexRowNoWrap};
padding: 1rem 1rem; padding: 1rem 1rem;
font-weight: 500; font-weight: 500;
color: ${(props) => (props.color === 'blue' ? ({ theme }) => theme.primary1 : 'inherit')}; color: ${props => (props.color === 'blue' ? ({ theme }) => theme.primary1 : 'inherit')};
${({ theme }) => theme.mediaWidth.upToMedium` ${({ theme }) => theme.mediaWidth.upToMedium`
padding: 1rem; padding: 1rem;
`}; `};
@ -113,13 +113,13 @@ const WALLET_VIEWS = {
OPTIONS: 'options', OPTIONS: 'options',
OPTIONS_SECONDARY: 'options_secondary', OPTIONS_SECONDARY: 'options_secondary',
ACCOUNT: 'account', ACCOUNT: 'account',
PENDING: 'pending', PENDING: 'pending'
} }
export default function WalletModal({ export default function WalletModal({
pendingTransactions, pendingTransactions,
confirmedTransactions, confirmedTransactions,
ENSName, ENSName
}: { }: {
pendingTransactions: string[] // hashes of pending pendingTransactions: string[] // hashes of pending
confirmedTransactions: string[] // hashes of confirmed confirmedTransactions: string[] // hashes of confirmed
@ -165,7 +165,7 @@ export default function WalletModal({
const tryActivation = async (connector: AbstractConnector | undefined) => { const tryActivation = async (connector: AbstractConnector | undefined) => {
let name = '' let name = ''
Object.keys(SUPPORTED_WALLETS).map((key) => { Object.keys(SUPPORTED_WALLETS).map(key => {
if (connector === SUPPORTED_WALLETS[key].connector) { if (connector === SUPPORTED_WALLETS[key].connector) {
return (name = SUPPORTED_WALLETS[key].name) return (name = SUPPORTED_WALLETS[key].name)
} }
@ -175,7 +175,7 @@ export default function WalletModal({
ReactGA.event({ ReactGA.event({
category: 'Wallet', category: 'Wallet',
action: 'Change Wallet', action: 'Change Wallet',
label: name, label: name
}) })
setPendingWallet(connector) // set wallet for pending view setPendingWallet(connector) // set wallet for pending view
setWalletView(WALLET_VIEWS.PENDING) setWalletView(WALLET_VIEWS.PENDING)
@ -186,7 +186,7 @@ export default function WalletModal({
} }
connector && connector &&
activate(connector, undefined, true).catch((error) => { activate(connector, undefined, true).catch(error => {
if (error instanceof UnsupportedChainIdError) { if (error instanceof UnsupportedChainIdError) {
activate(connector) // a little janky...can't use setError because the connector isn't set activate(connector) // a little janky...can't use setError because the connector isn't set
} else { } else {
@ -205,7 +205,7 @@ export default function WalletModal({
// get wallets user can switch too, depending on device/browser // get wallets user can switch too, depending on device/browser
function getOptions() { function getOptions() {
const isMetamask = window.ethereum && window.ethereum.isMetaMask const isMetamask = window.ethereum && window.ethereum.isMetaMask
return Object.keys(SUPPORTED_WALLETS).map((key) => { return Object.keys(SUPPORTED_WALLETS).map(key => {
const option = SUPPORTED_WALLETS[key] const option = SUPPORTED_WALLETS[key]
// check for mobile options // check for mobile options
if (isMobile) { if (isMobile) {

@ -174,7 +174,7 @@ function Web3StatusInner() {
return txs.filter(isTransactionRecent).sort(newTransactionsFirst) return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [allTransactions]) }, [allTransactions])
const pending = sortedRecentTransactions.filter((tx) => !tx.receipt).map((tx) => tx.hash) const pending = sortedRecentTransactions.filter(tx => !tx.receipt).map(tx => tx.hash)
const hasPendingTransactions = !!pending.length const hasPendingTransactions = !!pending.length
const hasSocks = useHasSocks() const hasSocks = useHasSocks()
@ -225,8 +225,8 @@ export default function Web3Status() {
return txs.filter(isTransactionRecent).sort(newTransactionsFirst) return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [allTransactions]) }, [allTransactions])
const pending = sortedRecentTransactions.filter((tx) => !tx.receipt).map((tx) => tx.hash) const pending = sortedRecentTransactions.filter(tx => !tx.receipt).map(tx => tx.hash)
const confirmed = sortedRecentTransactions.filter((tx) => tx.receipt).map((tx) => tx.hash) const confirmed = sortedRecentTransactions.filter(tx => tx.receipt).map(tx => tx.hash)
if (!contextNetwork.active && !active) { if (!contextNetwork.active && !active) {
return null return null

@ -75,11 +75,11 @@ export default function AddressClaimModal({ isOpen, onDismiss }: { isOpen: boole
function onClaim() { function onClaim() {
setAttempting(true) setAttempting(true)
claimCallback() claimCallback()
.then((hash) => { .then(hash => {
setHash(hash) setHash(hash)
}) })
// reset modal and log error // reset modal and log error
.catch((error) => { .catch(error => {
setAttempting(false) setAttempting(false)
console.log(error) console.log(error)
}) })

@ -67,7 +67,7 @@ export default function ClaimModal() {
setAttempting(true) setAttempting(true)
claimCallback() claimCallback()
// reset modal and log error // reset modal and log error
.catch((error) => { .catch(error => {
setAttempting(false) setAttempting(false)
console.log(error) console.log(error)
}) })

@ -46,7 +46,7 @@ export default function ClaimRewardModal({ isOpen, onDismiss, stakingInfo }: Sta
.getReward({ gasLimit: 350000 }) .getReward({ gasLimit: 350000 })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Claim accumulated UNI rewards`, summary: `Claim accumulated UNI rewards`
}) })
setHash(response.hash) setHash(response.hash)
}) })

@ -97,7 +97,7 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
) )
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Deposit liquidity`, summary: `Deposit liquidity`
}) })
setHash(response.hash) setHash(response.hash)
}) })
@ -141,50 +141,50 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
{ name: 'name', type: 'string' }, { name: 'name', type: 'string' },
{ name: 'version', type: 'string' }, { name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' }, { name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' }, { name: 'verifyingContract', type: 'address' }
] ]
const domain = { const domain = {
name: 'Uniswap V2', name: 'Uniswap V2',
version: '1', version: '1',
chainId: chainId, chainId: chainId,
verifyingContract: pairContract.address, verifyingContract: pairContract.address
} }
const Permit = [ const Permit = [
{ name: 'owner', type: 'address' }, { name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' }, { name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' }, { name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' }, { name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }, { name: 'deadline', type: 'uint256' }
] ]
const message = { const message = {
owner: account, owner: account,
spender: stakingInfo.stakingRewardAddress, spender: stakingInfo.stakingRewardAddress,
value: liquidityAmount.raw.toString(), value: liquidityAmount.raw.toString(),
nonce: nonce.toHexString(), nonce: nonce.toHexString(),
deadline: deadline.toNumber(), deadline: deadline.toNumber()
} }
const data = JSON.stringify({ const data = JSON.stringify({
types: { types: {
EIP712Domain, EIP712Domain,
Permit, Permit
}, },
domain, domain,
primaryType: 'Permit', primaryType: 'Permit',
message, message
}) })
library library
.send('eth_signTypedData_v4', [account, data]) .send('eth_signTypedData_v4', [account, data])
.then(splitSignature) .then(splitSignature)
.then((signature) => { .then(signature => {
setSignatureData({ setSignatureData({
v: signature.v, v: signature.v,
r: signature.r, r: signature.r,
s: signature.s, s: signature.s,
deadline: deadline.toNumber(), deadline: deadline.toNumber()
}) })
}) })
.catch((error) => { .catch(error => {
// for all errors other than 4001 (EIP-1193 user rejected request), fall back to manual approve // for all errors other than 4001 (EIP-1193 user rejected request), fall back to manual approve
if (error?.code !== 4001) { if (error?.code !== 4001) {
approveCallback() approveCallback()

@ -47,7 +47,7 @@ export default function UnstakingModal({ isOpen, onDismiss, stakingInfo }: Staki
.exit({ gasLimit: 300000 }) .exit({ gasLimit: 300000 })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Withdraw deposited liquidity`, summary: `Withdraw deposited liquidity`
}) })
setHash(response.hash) setHash(response.hash)
}) })

@ -33,8 +33,8 @@ export default function BetterTradeLink({ version }: { version: Version }) {
...location, ...location,
search: `?${stringify({ search: `?${stringify({
...search, ...search,
use: version !== DEFAULT_VERSION ? version : undefined, use: version !== DEFAULT_VERSION ? version : undefined
})}`, })}`
} }
}, [location, search, version]) }, [location, search, version])
@ -58,8 +58,8 @@ export function DefaultVersionLink() {
...location, ...location,
search: `?${stringify({ search: `?${stringify({
...search, ...search,
use: DEFAULT_VERSION, use: DEFAULT_VERSION
})}`, })}`
} }
}, [location, search]) }, [location, search])

@ -2,7 +2,7 @@ import { currencyEquals, Trade } from '@uniswap/sdk'
import React, { useCallback, useMemo } from 'react' import React, { useCallback, useMemo } from 'react'
import TransactionConfirmationModal, { import TransactionConfirmationModal, {
ConfirmationModalContent, ConfirmationModalContent,
TransactionErrorContent, TransactionErrorContent
} from '../TransactionConfirmationModal' } from '../TransactionConfirmationModal'
import SwapModalFooter from './SwapModalFooter' import SwapModalFooter from './SwapModalFooter'
import SwapModalHeader from './SwapModalHeader' import SwapModalHeader from './SwapModalHeader'
@ -33,7 +33,7 @@ export default function ConfirmSwapModal({
swapErrorMessage, swapErrorMessage,
isOpen, isOpen,
attemptingTxn, attemptingTxn,
txHash, txHash
}: { }: {
isOpen: boolean isOpen: boolean
trade: Trade | undefined trade: Trade | undefined

@ -9,7 +9,7 @@ import {
computeSlippageAdjustedAmounts, computeSlippageAdjustedAmounts,
computeTradePriceBreakdown, computeTradePriceBreakdown,
formatExecutionPrice, formatExecutionPrice,
warningSeverity, warningSeverity
} from '../../utils/prices' } from '../../utils/prices'
import { ButtonError } from '../Button' import { ButtonError } from '../Button'
import { AutoColumn } from '../Column' import { AutoColumn } from '../Column'
@ -23,7 +23,7 @@ export default function SwapModalFooter({
onConfirm, onConfirm,
allowedSlippage, allowedSlippage,
swapErrorMessage, swapErrorMessage,
disabledConfirm, disabledConfirm
}: { }: {
trade: Trade trade: Trade
allowedSlippage: number allowedSlippage: number
@ -35,7 +35,7 @@ export default function SwapModalFooter({
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [ const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [
allowedSlippage, allowedSlippage,
trade, trade
]) ])
const { priceImpactWithoutFee, realizedLPFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade]) const { priceImpactWithoutFee, realizedLPFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade])
const severity = warningSeverity(priceImpactWithoutFee) const severity = warningSeverity(priceImpactWithoutFee)
@ -56,7 +56,7 @@ export default function SwapModalFooter({
alignItems: 'center', alignItems: 'center',
display: 'flex', display: 'flex',
textAlign: 'right', textAlign: 'right',
paddingLeft: '10px', paddingLeft: '10px'
}} }}
> >
{formatExecutionPrice(trade, showInverted)} {formatExecutionPrice(trade, showInverted)}

@ -18,7 +18,7 @@ export default function SwapModalHeader({
allowedSlippage, allowedSlippage,
recipient, recipient,
showAcceptChanges, showAcceptChanges,
onAcceptChanges, onAcceptChanges
}: { }: {
trade: Trade trade: Trade
allowedSlippage: number allowedSlippage: number
@ -28,7 +28,7 @@ export default function SwapModalHeader({
}) { }) {
const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [ const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [
trade, trade,
allowedSlippage, allowedSlippage
]) ])
const { priceImpactWithoutFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade]) const { priceImpactWithoutFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade])
const priceImpactSeverity = warningSeverity(priceImpactWithoutFee) const priceImpactSeverity = warningSeverity(priceImpactWithoutFee)

@ -40,7 +40,7 @@ const AddressText = styled(TYPE.blue)`
export default function UnsupportedCurrencyFooter({ export default function UnsupportedCurrencyFooter({
show, show,
currencies, currencies
}: { }: {
show: boolean show: boolean
currencies: (Currency | undefined)[] currencies: (Currency | undefined)[]
@ -50,7 +50,7 @@ export default function UnsupportedCurrencyFooter({
const tokens = const tokens =
chainId && currencies chainId && currencies
? currencies.map((currency) => { ? currencies.map(currency => {
return wrappedCurrency(currency, chainId) return wrappedCurrency(currency, chainId)
}) })
: [] : []
@ -67,7 +67,7 @@ export default function UnsupportedCurrencyFooter({
<CloseIcon onClick={() => setShowDetails(false)} /> <CloseIcon onClick={() => setShowDetails(false)} />
</RowBetween> </RowBetween>
{tokens.map((token) => { {tokens.map(token => {
return ( return (
token && token &&
unsupportedTokens && unsupportedTokens &&

@ -77,7 +77,7 @@ export default function DelegateModal({ isOpen, onDismiss, title }: VoteModalPro
if (!delegateCallback) return if (!delegateCallback) return
// try delegation and store hash // try delegation and store hash
const hash = await delegateCallback(parsedAddress ?? undefined)?.catch((error) => { const hash = await delegateCallback(parsedAddress ?? undefined)?.catch(error => {
setAttempting(false) setAttempting(false)
console.log(error) console.log(error)
}) })

@ -44,7 +44,7 @@ interface VoteModalProps {
export default function VoteModal({ isOpen, onDismiss, proposalId, support }: VoteModalProps) { export default function VoteModal({ isOpen, onDismiss, proposalId, support }: VoteModalProps) {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const { const {
voteCallback, voteCallback
}: { }: {
voteCallback: (proposalId: string | undefined, support: boolean) => Promise<string> | undefined voteCallback: (proposalId: string | undefined, support: boolean) => Promise<string> | undefined
} = useVoteCallback() } = useVoteCallback()
@ -71,7 +71,7 @@ export default function VoteModal({ isOpen, onDismiss, proposalId, support }: Vo
if (!voteCallback) return if (!voteCallback) return
// try delegation and store hash // try delegation and store hash
const hash = await voteCallback(proposalId, support)?.catch((error) => { const hash = await voteCallback(proposalId, support)?.catch(error => {
setAttempting(false) setAttempting(false)
console.log(error) console.log(error)
}) })

@ -9,7 +9,7 @@ const CHAIN_ID_NETWORK_ARGUMENT: { readonly [chainId in FormaticSupportedChains]
[ChainId.MAINNET]: undefined, [ChainId.MAINNET]: undefined,
[ChainId.ROPSTEN]: 'ropsten', [ChainId.ROPSTEN]: 'ropsten',
[ChainId.RINKEBY]: 'rinkeby', [ChainId.RINKEBY]: 'rinkeby',
[ChainId.KOVAN]: 'kovan', [ChainId.KOVAN]: 'kovan'
} }
export class FortmaticConnector extends FortmaticConnectorCore { export class FortmaticConnector extends FortmaticConnectorCore {
@ -27,7 +27,7 @@ export class FortmaticConnector extends FortmaticConnectorCore {
const provider = this.fortmatic.getProvider() const provider = this.fortmatic.getProvider()
const pollForOverlayReady = new Promise((resolve) => { const pollForOverlayReady = new Promise(resolve => {
const interval = setInterval(() => { const interval = setInterval(() => {
if (provider.overlayReady) { if (provider.overlayReady) {
clearInterval(interval) clearInterval(interval)
@ -39,7 +39,7 @@ export class FortmaticConnector extends FortmaticConnectorCore {
const [account] = await Promise.all([ const [account] = await Promise.all([
provider.enable().then((accounts: string[]) => accounts[0]), provider.enable().then((accounts: string[]) => accounts[0]),
pollForOverlayReady, pollForOverlayReady
]) ])
return { provider: this.fortmatic.getProvider(), chainId: (this as any).chainId, account } return { provider: this.fortmatic.getProvider(), chainId: (this as any).chainId, account }

@ -60,7 +60,7 @@ class MiniRpcProvider implements AsyncSendable {
response = await fetch(this.url, { response = await fetch(this.url, {
method: 'POST', method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' }, headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(batch.map((item) => item.request)), body: JSON.stringify(batch.map(item => item.request))
}) })
} catch (error) { } catch (error) {
batch.forEach(({ reject }) => reject(new Error('Failed to send batch call'))) batch.forEach(({ reject }) => reject(new Error('Failed to send batch call')))
@ -87,7 +87,7 @@ class MiniRpcProvider implements AsyncSendable {
const { const {
resolve, resolve,
reject, reject,
request: { method }, request: { method }
} = byKey[result.id] } = byKey[result.id]
if (resolve && reject) { if (resolve && reject) {
if ('error' in result) { if ('error' in result) {
@ -111,8 +111,8 @@ class MiniRpcProvider implements AsyncSendable {
callback: (error: any, response: any) => void callback: (error: any, response: any) => void
): void => { ): void => {
this.request(request.method, request.params) this.request(request.method, request.params)
.then((result) => callback(null, { jsonrpc: '2.0', id: request.id, result })) .then(result => callback(null, { jsonrpc: '2.0', id: request.id, result }))
.catch((error) => callback(error, null)) .catch(error => callback(error, null))
} }
public readonly request = async ( public readonly request = async (
@ -131,10 +131,10 @@ class MiniRpcProvider implements AsyncSendable {
jsonrpc: '2.0', jsonrpc: '2.0',
id: this.nextId++, id: this.nextId++,
method, method,
params, params
}, },
resolve, resolve,
reject, reject
}) })
}) })
this.batchTimeoutId = this.batchTimeoutId ?? setTimeout(this.clearBatch, this.batchWaitTimeMs) this.batchTimeoutId = this.batchTimeoutId ?? setTimeout(this.clearBatch, this.batchWaitTimeMs)

@ -18,7 +18,7 @@ if (typeof NETWORK_URL === 'undefined') {
} }
export const network = new NetworkConnector({ export const network = new NetworkConnector({
urls: { [NETWORK_CHAIN_ID]: NETWORK_URL }, urls: { [NETWORK_CHAIN_ID]: NETWORK_URL }
}) })
let networkLibrary: Web3Provider | undefined let networkLibrary: Web3Provider | undefined
@ -27,7 +27,7 @@ export function getNetworkLibrary(): Web3Provider {
} }
export const injected = new InjectedConnector({ export const injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42], supportedChainIds: [1, 3, 4, 5, 42]
}) })
// mainnet only // mainnet only
@ -35,19 +35,19 @@ export const walletconnect = new WalletConnectConnector({
rpc: { 1: NETWORK_URL }, rpc: { 1: NETWORK_URL },
bridge: 'https://bridge.walletconnect.org', bridge: 'https://bridge.walletconnect.org',
qrcode: true, qrcode: true,
pollingInterval: 15000, pollingInterval: 15000
}) })
// mainnet only // mainnet only
export const fortmatic = new FortmaticConnector({ export const fortmatic = new FortmaticConnector({
apiKey: FORMATIC_KEY ?? '', apiKey: FORMATIC_KEY ?? '',
chainId: 1, chainId: 1
}) })
// mainnet only // mainnet only
export const portis = new PortisConnector({ export const portis = new PortisConnector({
dAppId: PORTIS_ID ?? '', dAppId: PORTIS_ID ?? '',
networks: [1], networks: [1]
}) })
// mainnet only // mainnet only
@ -55,5 +55,5 @@ export const walletlink = new WalletLinkConnector({
url: NETWORK_URL, url: NETWORK_URL,
appName: 'Uniswap', appName: 'Uniswap',
appLogoUrl: appLogoUrl:
'https://mpng.pngfly.com/20181202/bex/kisspng-emoji-domain-unicorn-pin-badges-sticker-unicorn-tumblr-emoji-unicorn-iphoneemoji-5c046729264a77.5671679315437924251569.jpg', 'https://mpng.pngfly.com/20181202/bex/kisspng-emoji-domain-unicorn-pin-badges-sticker-unicorn-tumblr-emoji-unicorn-iphoneemoji-5c046729264a77.5671679315437924251569.jpg'
}) })

@ -37,18 +37,18 @@ export const UNI: { [chainId in ChainId]: Token } = {
[ChainId.RINKEBY]: new Token(ChainId.RINKEBY, UNI_ADDRESS, 18, 'UNI', 'Uniswap'), [ChainId.RINKEBY]: new Token(ChainId.RINKEBY, UNI_ADDRESS, 18, 'UNI', 'Uniswap'),
[ChainId.ROPSTEN]: new Token(ChainId.ROPSTEN, UNI_ADDRESS, 18, 'UNI', 'Uniswap'), [ChainId.ROPSTEN]: new Token(ChainId.ROPSTEN, UNI_ADDRESS, 18, 'UNI', 'Uniswap'),
[ChainId.GÖRLI]: new Token(ChainId.GÖRLI, UNI_ADDRESS, 18, 'UNI', 'Uniswap'), [ChainId.GÖRLI]: new Token(ChainId.GÖRLI, UNI_ADDRESS, 18, 'UNI', 'Uniswap'),
[ChainId.KOVAN]: new Token(ChainId.KOVAN, UNI_ADDRESS, 18, 'UNI', 'Uniswap'), [ChainId.KOVAN]: new Token(ChainId.KOVAN, UNI_ADDRESS, 18, 'UNI', 'Uniswap')
} }
export const COMMON_CONTRACT_NAMES: { [address: string]: string } = { export const COMMON_CONTRACT_NAMES: { [address: string]: string } = {
[UNI_ADDRESS]: 'UNI', [UNI_ADDRESS]: 'UNI',
[GOVERNANCE_ADDRESS]: 'Governance', [GOVERNANCE_ADDRESS]: 'Governance',
[TIMELOCK_ADDRESS]: 'Timelock', [TIMELOCK_ADDRESS]: 'Timelock'
} }
// TODO: specify merkle distributor for mainnet // TODO: specify merkle distributor for mainnet
export const MERKLE_DISTRIBUTOR_ADDRESS: { [chainId in ChainId]?: string } = { export const MERKLE_DISTRIBUTOR_ADDRESS: { [chainId in ChainId]?: string } = {
[ChainId.MAINNET]: '0x090D4613473dEE047c3f2706764f49E0821D256e', [ChainId.MAINNET]: '0x090D4613473dEE047c3f2706764f49E0821D256e'
} }
const WETH_ONLY: ChainTokenList = { const WETH_ONLY: ChainTokenList = {
@ -56,13 +56,13 @@ const WETH_ONLY: ChainTokenList = {
[ChainId.ROPSTEN]: [WETH[ChainId.ROPSTEN]], [ChainId.ROPSTEN]: [WETH[ChainId.ROPSTEN]],
[ChainId.RINKEBY]: [WETH[ChainId.RINKEBY]], [ChainId.RINKEBY]: [WETH[ChainId.RINKEBY]],
[ChainId.GÖRLI]: [WETH[ChainId.GÖRLI]], [ChainId.GÖRLI]: [WETH[ChainId.GÖRLI]],
[ChainId.KOVAN]: [WETH[ChainId.KOVAN]], [ChainId.KOVAN]: [WETH[ChainId.KOVAN]]
} }
// used to construct intermediary pairs for trading // used to construct intermediary pairs for trading
export const BASES_TO_CHECK_TRADES_AGAINST: ChainTokenList = { export const BASES_TO_CHECK_TRADES_AGAINST: ChainTokenList = {
...WETH_ONLY, ...WETH_ONLY,
[ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, COMP, MKR, WBTC], [ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, COMP, MKR, WBTC]
} }
/** /**
@ -71,31 +71,31 @@ export const BASES_TO_CHECK_TRADES_AGAINST: ChainTokenList = {
*/ */
export const CUSTOM_BASES: { [chainId in ChainId]?: { [tokenAddress: string]: Token[] } } = { export const CUSTOM_BASES: { [chainId in ChainId]?: { [tokenAddress: string]: Token[] } } = {
[ChainId.MAINNET]: { [ChainId.MAINNET]: {
[AMPL.address]: [DAI, WETH[ChainId.MAINNET]], [AMPL.address]: [DAI, WETH[ChainId.MAINNET]]
}, }
} }
// used for display in the default list when adding liquidity // used for display in the default list when adding liquidity
export const SUGGESTED_BASES: ChainTokenList = { export const SUGGESTED_BASES: ChainTokenList = {
...WETH_ONLY, ...WETH_ONLY,
[ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, WBTC], [ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, WBTC]
} }
// used to construct the list of all pairs we consider by default in the frontend // used to construct the list of all pairs we consider by default in the frontend
export const BASES_TO_TRACK_LIQUIDITY_FOR: ChainTokenList = { export const BASES_TO_TRACK_LIQUIDITY_FOR: ChainTokenList = {
...WETH_ONLY, ...WETH_ONLY,
[ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, WBTC], [ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, WBTC]
} }
export const PINNED_PAIRS: { readonly [chainId in ChainId]?: [Token, Token][] } = { export const PINNED_PAIRS: { readonly [chainId in ChainId]?: [Token, Token][] } = {
[ChainId.MAINNET]: [ [ChainId.MAINNET]: [
[ [
new Token(ChainId.MAINNET, '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643', 8, 'cDAI', 'Compound Dai'), new Token(ChainId.MAINNET, '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643', 8, 'cDAI', 'Compound Dai'),
new Token(ChainId.MAINNET, '0x39AA39c021dfbaE8faC545936693aC917d5E7563', 8, 'cUSDC', 'Compound USD Coin'), new Token(ChainId.MAINNET, '0x39AA39c021dfbaE8faC545936693aC917d5E7563', 8, 'cUSDC', 'Compound USD Coin')
], ],
[USDC, USDT], [USDC, USDT],
[DAI, USDT], [DAI, USDT]
], ]
} }
export interface WalletInfo { export interface WalletInfo {
@ -118,7 +118,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Injected web3 provider.', description: 'Injected web3 provider.',
href: null, href: null,
color: '#010101', color: '#010101',
primary: true, primary: true
}, },
METAMASK: { METAMASK: {
connector: injected, connector: injected,
@ -126,7 +126,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
iconName: 'metamask.png', iconName: 'metamask.png',
description: 'Easy-to-use browser extension.', description: 'Easy-to-use browser extension.',
href: null, href: null,
color: '#E8831D', color: '#E8831D'
}, },
WALLET_CONNECT: { WALLET_CONNECT: {
connector: walletconnect, connector: walletconnect,
@ -135,7 +135,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Connect to Trust Wallet, Rainbow Wallet and more...', description: 'Connect to Trust Wallet, Rainbow Wallet and more...',
href: null, href: null,
color: '#4196FC', color: '#4196FC',
mobile: true, mobile: true
}, },
WALLET_LINK: { WALLET_LINK: {
connector: walletlink, connector: walletlink,
@ -143,7 +143,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
iconName: 'coinbaseWalletIcon.svg', iconName: 'coinbaseWalletIcon.svg',
description: 'Use Coinbase Wallet app on mobile device', description: 'Use Coinbase Wallet app on mobile device',
href: null, href: null,
color: '#315CF5', color: '#315CF5'
}, },
COINBASE_LINK: { COINBASE_LINK: {
name: 'Open in Coinbase Wallet', name: 'Open in Coinbase Wallet',
@ -152,7 +152,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
href: 'https://go.cb-w.com/mtUDhEZPy1', href: 'https://go.cb-w.com/mtUDhEZPy1',
color: '#315CF5', color: '#315CF5',
mobile: true, mobile: true,
mobileOnly: true, mobileOnly: true
}, },
FORTMATIC: { FORTMATIC: {
connector: fortmatic, connector: fortmatic,
@ -161,7 +161,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Login using Fortmatic hosted wallet', description: 'Login using Fortmatic hosted wallet',
href: null, href: null,
color: '#6748FF', color: '#6748FF',
mobile: true, mobile: true
}, },
Portis: { Portis: {
connector: portis, connector: portis,
@ -170,8 +170,8 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Login using Portis hosted wallet', description: 'Login using Portis hosted wallet',
href: null, href: null,
color: '#4A6C9B', color: '#4A6C9B',
mobile: true, mobile: true
}, }
} }
export const NetworkContextName = 'NETWORK' export const NetworkContextName = 'NETWORK'
@ -210,5 +210,5 @@ export const BLOCKED_ADDRESSES: string[] = [
'0x7F367cC41522cE07553e823bf3be79A889DEbe1B', '0x7F367cC41522cE07553e823bf3be79A889DEbe1B',
'0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b', '0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b',
'0x901bb9583b24D97e995513C6778dc6888AB6870e', '0x901bb9583b24D97e995513C6778dc6888AB6870e',
'0xA7e5d5A720f06526557c513402f2e6B5fA20b008', '0xA7e5d5A720f06526557c513402f2e6B5fA20b008'
] ]

@ -33,7 +33,7 @@ export const DEFAULT_LIST_OF_LISTS: string[] = [
CMC_STABLECOIN, CMC_STABLECOIN,
KLEROS_LIST, KLEROS_LIST,
GEMINI_LIST, GEMINI_LIST,
...UNSUPPORTED_LIST_URLS, // need to load unsupported tokens as well ...UNSUPPORTED_LIST_URLS // need to load unsupported tokens as well
] ]
// default lists to be 'active' aka searched across // default lists to be 'active' aka searched across

@ -6,7 +6,7 @@ const MULTICALL_NETWORKS: { [chainId in ChainId]: string } = {
[ChainId.ROPSTEN]: '0x53C43764255c17BD724F74c4eF150724AC50a3ed', [ChainId.ROPSTEN]: '0x53C43764255c17BD724F74c4eF150724AC50a3ed',
[ChainId.KOVAN]: '0x2cc8688C5f75E365aaEEb4ea8D6a480405A48D2A', [ChainId.KOVAN]: '0x2cc8688C5f75E365aaEEb4ea8D6a480405A48D2A',
[ChainId.RINKEBY]: '0x42Ad527de7d4e9d9d011aC45B31D8551f8Fe9821', [ChainId.RINKEBY]: '0x42Ad527de7d4e9d9d011aC45B31D8551f8Fe9821',
[ChainId.GÖRLI]: '0x77dCa2C955b15e9dE4dbBCf1246B4B85b651e50e', [ChainId.GÖRLI]: '0x77dCa2C955b15e9dE4dbBCf1246B4B85b651e50e'
} }
export { MULTICALL_ABI, MULTICALL_NETWORKS } export { MULTICALL_ABI, MULTICALL_NETWORKS }

@ -8,7 +8,7 @@ const V1_FACTORY_ADDRESSES: { [chainId in ChainId]: string } = {
[ChainId.ROPSTEN]: '0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351', [ChainId.ROPSTEN]: '0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351',
[ChainId.RINKEBY]: '0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36', [ChainId.RINKEBY]: '0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36',
[ChainId.GÖRLI]: '0x6Ce570d02D73d4c384b46135E87f8C592A8c86dA', [ChainId.GÖRLI]: '0x6Ce570d02D73d4c384b46135E87f8C592A8c86dA',
[ChainId.KOVAN]: '0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30', [ChainId.KOVAN]: '0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30'
} }
const V1_FACTORY_INTERFACE = new Interface(V1_FACTORY_ABI) const V1_FACTORY_INTERFACE = new Interface(V1_FACTORY_ABI)

@ -12,6 +12,6 @@ export function useTokenAllowance(token?: Token, owner?: string, spender?: strin
return useMemo(() => (token && allowance ? new TokenAmount(token, allowance.toString()) : undefined), [ return useMemo(() => (token && allowance ? new TokenAmount(token, allowance.toString()) : undefined), [
token, token,
allowance, allowance
]) ])
} }

@ -13,7 +13,7 @@ export enum PairState {
LOADING, LOADING,
NOT_EXISTS, NOT_EXISTS,
EXISTS, EXISTS,
INVALID, INVALID
} }
export function usePairs(currencies: [Currency | undefined, Currency | undefined][]): [PairState, Pair | null][] { export function usePairs(currencies: [Currency | undefined, Currency | undefined][]): [PairState, Pair | null][] {
@ -23,7 +23,7 @@ export function usePairs(currencies: [Currency | undefined, Currency | undefined
() => () =>
currencies.map(([currencyA, currencyB]) => [ currencies.map(([currencyA, currencyB]) => [
wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyA, chainId),
wrappedCurrency(currencyB, chainId), wrappedCurrency(currencyB, chainId)
]), ]),
[chainId, currencies] [chainId, currencies]
) )
@ -51,7 +51,7 @@ export function usePairs(currencies: [Currency | undefined, Currency | undefined
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(new TokenAmount(token0, reserve0.toString()), new TokenAmount(token1, reserve1.toString()))
] ]
}) })
}, [results, tokens]) }, [results, tokens])

@ -11,7 +11,7 @@ import {
TokenAmount, TokenAmount,
Trade, Trade,
TradeType, TradeType,
WETH, WETH
} from '@uniswap/sdk' } from '@uniswap/sdk'
import { useMemo } from 'react' import { useMemo } from 'react'
import { useActiveWeb3React } from '../hooks' import { useActiveWeb3React } from '../hooks'
@ -53,7 +53,7 @@ function useMockV1Pair(inputCurrency?: Currency): MockV1Pair | undefined {
export function useAllTokenV1Exchanges(): { [exchangeAddress: string]: Token } { export function useAllTokenV1Exchanges(): { [exchangeAddress: string]: Token } {
const allTokens = useAllTokens() const allTokens = useAllTokens()
const factory = useV1FactoryContract() const factory = useV1FactoryContract()
const args = useMemo(() => Object.keys(allTokens).map((tokenAddress) => [tokenAddress]), [allTokens]) const args = useMemo(() => Object.keys(allTokens).map(tokenAddress => [tokenAddress]), [allTokens])
const data = useSingleContractMultipleData(factory, 'getExchange', args, NEVER_RELOAD) const data = useSingleContractMultipleData(factory, 'getExchange', args, NEVER_RELOAD)
@ -77,7 +77,7 @@ export function useUserHasLiquidityInAllTokens(): boolean | undefined {
const v1ExchangeLiquidityTokens = useMemo( const v1ExchangeLiquidityTokens = useMemo(
() => () =>
chainId ? Object.keys(exchanges).map((address) => new Token(chainId, address, 18, 'UNI-V1', 'Uniswap V1')) : [], chainId ? Object.keys(exchanges).map(address => new Token(chainId, address, 18, 'UNI-V1', 'Uniswap V1')) : [],
[chainId, exchanges] [chainId, exchanges]
) )
@ -85,7 +85,7 @@ export function useUserHasLiquidityInAllTokens(): boolean | undefined {
return useMemo( return useMemo(
() => () =>
Object.keys(balances).some((tokenAddress) => { Object.keys(balances).some(tokenAddress => {
const b = balances[tokenAddress]?.raw const b = balances[tokenAddress]?.raw
return b && JSBI.greaterThan(b, JSBI.BigInt(0)) return b && JSBI.greaterThan(b, JSBI.BigInt(0))
}), }),
@ -135,7 +135,7 @@ export function useV1Trade(
} }
export function getTradeVersion(trade?: Trade): Version | undefined { export function getTradeVersion(trade?: Trade): Version | undefined {
const isV1 = trade?.route?.pairs?.some((pair) => pair instanceof MockV1Pair) const isV1 = trade?.route?.pairs?.some(pair => pair instanceof MockV1Pair)
if (isV1) return Version.v1 if (isV1) return Version.v1
if (isV1 === false) return Version.v2 if (isV1 === false) return Version.v2
return undefined return undefined

@ -113,7 +113,7 @@ export function useIsUserAddedToken(currency: Currency | undefined | null): bool
return false return false
} }
return !!userAddedTokens.find((token) => currencyEquals(currency, token)) return !!userAddedTokens.find(token => currencyEquals(currency, token))
} }
// parse a name or symbol from a token response // parse a name or symbol from a token response
@ -177,7 +177,7 @@ export function useToken(tokenAddress?: string): Token | undefined | null {
token, token,
tokenName.loading, tokenName.loading,
tokenName.result, tokenName.result,
tokenNameBytes32.result, tokenNameBytes32.result
]) ])
} }

@ -22,7 +22,7 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
const basePairs: [Token, Token][] = useMemo( const basePairs: [Token, Token][] = useMemo(
() => () =>
flatMap(bases, (base): [Token, Token][] => bases.map((otherBase) => [base, otherBase])).filter( flatMap(bases, (base): [Token, Token][] => bases.map(otherBase => [base, otherBase])).filter(
([t0, t1]) => t0.address !== t1.address ([t0, t1]) => t0.address !== t1.address
), ),
[bases] [bases]
@ -39,7 +39,7 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
// token B against all bases // token B against all bases
...bases.map((base): [Token, Token] => [tokenB, base]), ...bases.map((base): [Token, Token] => [tokenB, base]),
// each base against all bases // each base against all bases
...basePairs, ...basePairs
] ]
.filter((tokens): tokens is [Token, Token] => Boolean(tokens[0] && tokens[1])) .filter((tokens): tokens is [Token, Token] => Boolean(tokens[0] && tokens[1]))
.filter(([t0, t1]) => t0.address !== t1.address) .filter(([t0, t1]) => t0.address !== t1.address)
@ -53,8 +53,8 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
if (!customBasesA && !customBasesB) return true if (!customBasesA && !customBasesB) return true
if (customBasesA && !customBasesA.find((base) => tokenB.equals(base))) return false if (customBasesA && !customBasesA.find(base => tokenB.equals(base))) return false
if (customBasesB && !customBasesB.find((base) => tokenA.equals(base))) return false if (customBasesB && !customBasesB.find(base => tokenA.equals(base))) return false
return true return true
}) })

@ -18,7 +18,7 @@ export function useEagerConnect() {
const [tried, setTried] = useState(false) const [tried, setTried] = useState(false)
useEffect(() => { useEffect(() => {
injected.isAuthorized().then((isAuthorized) => { injected.isAuthorized().then(isAuthorized => {
if (isAuthorized) { if (isAuthorized) {
activate(injected, undefined, true).catch(() => { activate(injected, undefined, true).catch(() => {
setTried(true) setTried(true)
@ -58,7 +58,7 @@ export function useInactiveListener(suppress = false) {
if (ethereum && ethereum.on && !active && !error && !suppress) { if (ethereum && ethereum.on && !active && !error && !suppress) {
const handleChainChanged = () => { const handleChainChanged = () => {
// eat errors // eat errors
activate(injected, undefined, true).catch((error) => { activate(injected, undefined, true).catch(error => {
console.error('Failed to activate after chain changed', error) console.error('Failed to activate after chain changed', error)
}) })
} }
@ -66,7 +66,7 @@ export function useInactiveListener(suppress = false) {
const handleAccountsChanged = (accounts: string[]) => { const handleAccountsChanged = (accounts: string[]) => {
if (accounts.length > 0) { if (accounts.length > 0) {
// eat errors // eat errors
activate(injected, undefined, true).catch((error) => { activate(injected, undefined, true).catch(error => {
console.error('Failed to activate after accounts changed', error) console.error('Failed to activate after accounts changed', error)
}) })
} }

@ -25,11 +25,11 @@ export default function useAddTokenToMetamask(
address: token.address, address: token.address,
symbol: token.symbol, symbol: token.symbol,
decimals: token.decimals, decimals: token.decimals,
image: getTokenLogoURL(token.address), image: getTokenLogoURL(token.address)
}, }
}, }
}) })
.then((success) => { .then(success => {
setSuccess(success) setSuccess(success)
}) })
.catch(() => setSuccess(false)) .catch(() => setSuccess(false))

@ -17,7 +17,7 @@ export enum ApprovalState {
UNKNOWN, UNKNOWN,
NOT_APPROVED, NOT_APPROVED,
PENDING, PENDING,
APPROVED, APPROVED
} }
// 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
@ -82,12 +82,12 @@ export function useApproveCallback(
return tokenContract return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, { .approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas), gasLimit: calculateGasMargin(estimatedGas)
}) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol, summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender }, approval: { tokenAddress: token.address, spender: spender }
}) })
}) })
.catch((error: Error) => { .catch((error: Error) => {

@ -14,7 +14,7 @@ async function getColorFromToken(token: Token): Promise<string | null> {
return Vibrant.from(path) return Vibrant.from(path)
.getPalette() .getPalette()
.then((palette) => { .then(palette => {
if (palette?.Vibrant) { if (palette?.Vibrant) {
let detectedHex = palette.Vibrant.hex let detectedHex = palette.Vibrant.hex
let AAscore = hex(detectedHex, '#FFF') let AAscore = hex(detectedHex, '#FFF')
@ -34,7 +34,7 @@ async function getColorFromUriPath(uri: string): Promise<string | null> {
return Vibrant.from(formattedPath) return Vibrant.from(formattedPath)
.getPalette() .getPalette()
.then((palette) => { .then(palette => {
if (palette?.Vibrant) { if (palette?.Vibrant) {
return palette.Vibrant.hex return palette.Vibrant.hex
} }
@ -50,7 +50,7 @@ export function useColor(token?: Token) {
let stale = false let stale = false
if (token) { if (token) {
getColorFromToken(token).then((tokenColor) => { getColorFromToken(token).then(tokenColor => {
if (!stale && tokenColor !== null) { if (!stale && tokenColor !== null) {
setColor(tokenColor) setColor(tokenColor)
} }
@ -73,7 +73,7 @@ export function useListColor(listImageUri?: string) {
let stale = false let stale = false
if (listImageUri) { if (listImageUri) {
getColorFromUriPath(listImageUri).then((color) => { getColorFromUriPath(listImageUri).then(color => {
if (!stale && color !== null) { if (!stale && color !== null) {
setColor(color) setColor(color)
} }

@ -9,7 +9,7 @@ import { useMemo } from 'react'
import { GOVERNANCE_ADDRESS, MERKLE_DISTRIBUTOR_ADDRESS, UNI } from '../constants' import { GOVERNANCE_ADDRESS, MERKLE_DISTRIBUTOR_ADDRESS, UNI } from '../constants'
import { import {
ARGENT_WALLET_DETECTOR_ABI, ARGENT_WALLET_DETECTOR_ABI,
ARGENT_WALLET_DETECTOR_MAINNET_ADDRESS, ARGENT_WALLET_DETECTOR_MAINNET_ADDRESS
} from '../constants/abis/argent-wallet-detector' } from '../constants/abis/argent-wallet-detector'
import ENS_PUBLIC_RESOLVER_ABI from '../constants/abis/ens-public-resolver.json' import ENS_PUBLIC_RESOLVER_ABI from '../constants/abis/ens-public-resolver.json'
import ENS_ABI from '../constants/abis/ens-registrar.json' import ENS_ABI from '../constants/abis/ens-registrar.json'

@ -4,7 +4,7 @@ import { useCallback, useEffect, useState } from 'react'
export default function useCopyClipboard(timeout = 500): [boolean, (toCopy: string) => void] { export default function useCopyClipboard(timeout = 500): [boolean, (toCopy: string) => void] {
const [isCopied, setIsCopied] = useState(false) const [isCopied, setIsCopied] = useState(false)
const staticCopy = useCallback((text) => { const staticCopy = useCallback(text => {
const didCopy = copy(text) const didCopy = copy(text)
setIsCopied(didCopy) setIsCopied(didCopy)
}, []) }, [])

@ -16,6 +16,6 @@ export default function useENS(
return { return {
loading: reverseLookup.loading || lookup.loading, loading: reverseLookup.loading || lookup.loading,
address: validated ? validated : lookup.address, address: validated ? validated : lookup.address,
name: reverseLookup.ENSName ? reverseLookup.ENSName : !validated && lookup.address ? nameOrAddress || null : null, name: reverseLookup.ENSName ? reverseLookup.ENSName : !validated && lookup.address ? nameOrAddress || null : null
} }
} }

@ -30,6 +30,6 @@ export default function useENSAddress(ensName?: string | null): { loading: boole
const changed = debouncedName !== ensName const changed = debouncedName !== ensName
return { return {
address: changed ? null : addr.result?.[0] ?? null, address: changed ? null : addr.result?.[0] ?? null,
loading: changed || resolverAddress.loading || addr.loading, loading: changed || resolverAddress.loading || addr.loading
} }
} }

@ -27,6 +27,6 @@ export default function useENSContentHash(ensName?: string | null): { loading: b
return { return {
contenthash: contenthash.result?.[0] ?? null, contenthash: contenthash.result?.[0] ?? null,
loading: resolverAddressResult.loading || contenthash.loading, loading: resolverAddressResult.loading || contenthash.loading
} }
} }

@ -32,6 +32,6 @@ export default function useENSName(address?: string): { ENSName: string | null;
const changed = debouncedAddress !== address const changed = debouncedAddress !== address
return { return {
ENSName: changed ? null : name.result?.[0] ?? null, ENSName: changed ? null : name.result?.[0] ?? null,
loading: changed || resolverAddress.loading || name.loading, loading: changed || resolverAddress.loading || name.loading
} }
} }

@ -36,11 +36,11 @@ export function useFetchListCallback(): (listUrl: string, sendDispatch?: boolean
const requestId = nanoid() const requestId = nanoid()
sendDispatch && dispatch(fetchTokenList.pending({ requestId, url: listUrl })) sendDispatch && dispatch(fetchTokenList.pending({ requestId, url: listUrl }))
return getTokenList(listUrl, ensResolver) return getTokenList(listUrl, ensResolver)
.then((tokenList) => { .then(tokenList => {
sendDispatch && dispatch(fetchTokenList.fulfilled({ url: listUrl, tokenList, requestId })) sendDispatch && dispatch(fetchTokenList.fulfilled({ url: listUrl, tokenList, requestId }))
return tokenList return tokenList
}) })
.catch((error) => { .catch(error => {
console.debug(`Failed to get list at url ${listUrl}`, error) console.debug(`Failed to get list at url ${listUrl}`, error)
sendDispatch && dispatch(fetchTokenList.rejected({ url: listUrl, requestId, errorMessage: error.message })) sendDispatch && dispatch(fetchTokenList.rejected({ url: listUrl, requestId, errorMessage: error.message }))
throw error throw error

@ -11,7 +11,7 @@ export default function useLast<T>(
): T | null | undefined { ): T | null | undefined {
const [last, setLast] = useState<T | null | undefined>(filterFn && filterFn(value) ? value : undefined) const [last, setLast] = useState<T | null | undefined>(filterFn && filterFn(value) ? value : undefined)
useEffect(() => { useEffect(() => {
setLast((last) => { setLast(last => {
const shouldUse: boolean = filterFn ? filterFn(value) : true const shouldUse: boolean = filterFn ? filterFn(value) : true
if (shouldUse) return value if (shouldUse) return value
return last return last

@ -17,7 +17,7 @@ import { Version } from './useToggledVersion'
export enum SwapCallbackState { export enum SwapCallbackState {
INVALID, INVALID,
LOADING, LOADING,
VALID, VALID
} }
interface SwapCall { interface SwapCall {
@ -75,7 +75,7 @@ function useSwapCallArguments(
feeOnTransfer: false, feeOnTransfer: false,
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE), allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient, recipient,
deadline: deadline.toNumber(), deadline: deadline.toNumber()
}) })
) )
@ -85,7 +85,7 @@ function useSwapCallArguments(
feeOnTransfer: true, feeOnTransfer: true,
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE), allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient, recipient,
deadline: deadline.toNumber(), deadline: deadline.toNumber()
}) })
) )
} }
@ -95,12 +95,12 @@ function useSwapCallArguments(
v1SwapArguments(trade, { v1SwapArguments(trade, {
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE), allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient, recipient,
deadline: deadline.toNumber(), deadline: deadline.toNumber()
}) })
) )
break break
} }
return swapMethods.map((parameters) => ({ parameters, contract })) return swapMethods.map(parameters => ({ parameters, contract }))
}, [account, allowedSlippage, chainId, deadline, library, recipient, trade, v1Exchange]) }, [account, allowedSlippage, chainId, deadline, library, recipient, trade, v1Exchange])
} }
@ -138,29 +138,29 @@ export function useSwapCallback(
state: SwapCallbackState.VALID, state: SwapCallbackState.VALID,
callback: async function onSwap(): Promise<string> { callback: async function onSwap(): Promise<string> {
const estimatedCalls: EstimatedSwapCall[] = await Promise.all( const estimatedCalls: EstimatedSwapCall[] = await Promise.all(
swapCalls.map((call) => { swapCalls.map(call => {
const { const {
parameters: { methodName, args, value }, parameters: { methodName, args, value },
contract, contract
} = call } = call
const options = !value || isZero(value) ? {} : { value } const options = !value || isZero(value) ? {} : { value }
return contract.estimateGas[methodName](...args, options) return contract.estimateGas[methodName](...args, options)
.then((gasEstimate) => { .then(gasEstimate => {
return { return {
call, call,
gasEstimate, gasEstimate
} }
}) })
.catch((gasError) => { .catch(gasError => {
console.debug('Gas estimate failed, trying eth_call to extract error', call) console.debug('Gas estimate failed, trying eth_call to extract error', call)
return contract.callStatic[methodName](...args, options) return contract.callStatic[methodName](...args, options)
.then((result) => { .then(result => {
console.debug('Unexpected successful call after failed estimate gas', call, gasError, result) console.debug('Unexpected successful call after failed estimate gas', call, gasError, result)
return { call, error: new Error('Unexpected issue with estimating the gas. Please try again.') } return { call, error: new Error('Unexpected issue with estimating the gas. Please try again.') }
}) })
.catch((callError) => { .catch(callError => {
console.debug('Call threw error', call, callError) console.debug('Call threw error', call, callError)
let errorMessage: string let errorMessage: string
switch (callError.reason) { switch (callError.reason) {
@ -193,14 +193,14 @@ export function useSwapCallback(
const { const {
call: { call: {
contract, contract,
parameters: { methodName, args, value }, parameters: { methodName, args, value }
}, },
gasEstimate, gasEstimate
} = successfulEstimation } = successfulEstimation
return contract[methodName](...args, { return contract[methodName](...args, {
gasLimit: calculateGasMargin(gasEstimate), gasLimit: calculateGasMargin(gasEstimate),
...(value && !isZero(value) ? { value, from: account } : { from: account }), ...(value && !isZero(value) ? { value, from: account } : { from: account })
}) })
.then((response: any) => { .then((response: any) => {
const inputSymbol = trade.inputAmount.currency.symbol const inputSymbol = trade.inputAmount.currency.symbol
@ -222,7 +222,7 @@ export function useSwapCallback(
tradeVersion === Version.v2 ? withRecipient : `${withRecipient} on ${(tradeVersion as any).toUpperCase()}` tradeVersion === Version.v2 ? withRecipient : `${withRecipient} on ${(tradeVersion as any).toUpperCase()}`
addTransaction(response, { addTransaction(response, {
summary: withVersion, summary: withVersion
}) })
return response.hash return response.hash
@ -238,7 +238,7 @@ export function useSwapCallback(
} }
}) })
}, },
error: null, error: null
} }
}, [trade, library, account, chainId, recipient, recipientAddressOrName, swapCalls, addTransaction]) }, [trade, library, account, chainId, recipient, recipientAddressOrName, swapCalls, addTransaction])
} }

@ -2,6 +2,6 @@ import { useCallback, useState } from 'react'
export default function useToggle(initialState = false): [boolean, () => void] { export default function useToggle(initialState = false): [boolean, () => void] {
const [state, setState] = useState(initialState) const [state, setState] = useState(initialState)
const toggle = useCallback(() => setState((state) => !state), []) const toggle = useCallback(() => setState(state => !state), [])
return [state, toggle] return [state, toggle]
} }

@ -2,7 +2,7 @@ import useParsedQueryString from './useParsedQueryString'
export enum Version { export enum Version {
v1 = 'v1', v1 = 'v1',
v2 = 'v2', v2 = 'v2'
} }
export const DEFAULT_VERSION: Version = Version.v2 export const DEFAULT_VERSION: Version = Version.v2

@ -6,7 +6,7 @@ import useCurrentBlockTimestamp from './useCurrentBlockTimestamp'
// combines the block timestamp with the user setting to give the deadline that should be used for any submitted transaction // combines the block timestamp with the user setting to give the deadline that should be used for any submitted transaction
export default function useTransactionDeadline(): BigNumber | undefined { export default function useTransactionDeadline(): BigNumber | undefined {
const ttl = useSelector<AppState, number>((state) => state.user.userDeadline) const ttl = useSelector<AppState, number>(state => state.user.userDeadline)
const blockTimestamp = useCurrentBlockTimestamp() const blockTimestamp = useCurrentBlockTimestamp()
return useMemo(() => { return useMemo(() => {
if (blockTimestamp && ttl) return blockTimestamp.add(ttl) if (blockTimestamp && ttl) return blockTimestamp.add(ttl)

@ -5,7 +5,7 @@ const isClient = typeof window === 'object'
function getSize() { function getSize() {
return { return {
width: isClient ? window.innerWidth : undefined, width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined, height: isClient ? window.innerHeight : undefined
} }
} }

@ -9,7 +9,7 @@ import { useWETHContract } from './useContract'
export enum WrapType { export enum WrapType {
NOT_APPLICABLE, NOT_APPLICABLE,
WRAP, WRAP,
UNWRAP, UNWRAP
} }
const NOT_APPLICABLE = { wrapType: WrapType.NOT_APPLICABLE } const NOT_APPLICABLE = { wrapType: WrapType.NOT_APPLICABLE }
@ -50,7 +50,7 @@ export default function useWrapCallback(
} }
} }
: undefined, : undefined,
inputError: sufficientBalance ? undefined : 'Insufficient ETH balance', inputError: sufficientBalance ? undefined : 'Insufficient ETH balance'
} }
} else if (currencyEquals(WETH[chainId], inputCurrency) && outputCurrency === ETHER) { } else if (currencyEquals(WETH[chainId], inputCurrency) && outputCurrency === ETHER) {
return { return {
@ -66,7 +66,7 @@ export default function useWrapCallback(
} }
} }
: undefined, : undefined,
inputError: sufficientBalance ? undefined : 'Insufficient WETH balance', inputError: sufficientBalance ? undefined : 'Insufficient WETH balance'
} }
} else { } else {
return NOT_APPLICABLE return NOT_APPLICABLE

@ -9,15 +9,15 @@ i18next
.use(initReactI18next) .use(initReactI18next)
.init({ .init({
backend: { backend: {
loadPath: `./locales/{{lng}}.json`, loadPath: `./locales/{{lng}}.json`
}, },
react: { react: {
useSuspense: true, useSuspense: true
}, },
fallbackLng: 'en', fallbackLng: 'en',
preload: ['en'], preload: ['en'],
keySeparator: false, keySeparator: false,
interpolation: { escapeValue: false }, interpolation: { escapeValue: false }
}) })
export default i18next export default i18next

@ -29,20 +29,16 @@ const GOOGLE_ANALYTICS_ID: string | undefined = process.env.REACT_APP_GOOGLE_ANA
if (typeof GOOGLE_ANALYTICS_ID === 'string') { if (typeof GOOGLE_ANALYTICS_ID === 'string') {
ReactGA.initialize(GOOGLE_ANALYTICS_ID) ReactGA.initialize(GOOGLE_ANALYTICS_ID)
ReactGA.set({ ReactGA.set({
customBrowserType: !isMobile customBrowserType: !isMobile ? 'desktop' : 'web3' in window || 'ethereum' in window ? 'mobileWeb3' : 'mobileRegular'
? 'desktop'
: 'web3' in window || 'ethereum' in window
? 'mobileWeb3'
: 'mobileRegular',
}) })
} else { } else {
ReactGA.initialize('test', { testMode: true, debug: true }) ReactGA.initialize('test', { testMode: true, debug: true })
} }
window.addEventListener('error', (error) => { window.addEventListener('error', error => {
ReactGA.exception({ ReactGA.exception({
description: `${error.message} @ ${error.filename}:${error.lineno}:${error.colno}`, description: `${error.message} @ ${error.filename}:${error.lineno}:${error.colno}`,
fatal: true, fatal: true
}) })
}) })

@ -13,7 +13,7 @@ export function ConfirmAddModalBottom({
currencies, currencies,
parsedAmounts, parsedAmounts,
poolTokenPercentage, poolTokenPercentage,
onAdd, onAdd
}: { }: {
noLiquidity?: boolean noLiquidity?: boolean
price?: Fraction price?: Fraction

@ -12,7 +12,7 @@ export function PoolPriceBar({
currencies, currencies,
noLiquidity, noLiquidity,
poolTokenPercentage, poolTokenPercentage,
price, price
}: { }: {
currencies: { [field in Field]?: Currency } currencies: { [field in Field]?: Currency }
noLiquidity?: boolean noLiquidity?: boolean

@ -43,9 +43,9 @@ import UnsupportedCurrencyFooter from 'components/swap/UnsupportedCurrencyFooter
export default function AddLiquidity({ export default function AddLiquidity({
match: { match: {
params: { currencyIdA, currencyIdB }, params: { currencyIdA, currencyIdB }
}, },
history, history
}: RouteComponentProps<{ currencyIdA?: string; currencyIdB?: string }>) { }: RouteComponentProps<{ currencyIdA?: string; currencyIdB?: string }>) {
const { account, chainId, library } = useActiveWeb3React() const { account, chainId, library } = useActiveWeb3React()
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
@ -76,7 +76,7 @@ export default function AddLiquidity({
noLiquidity, noLiquidity,
liquidityMinted, liquidityMinted,
poolTokenPercentage, poolTokenPercentage,
error, error
} = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined) } = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined)
const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity)
@ -95,7 +95,7 @@ export default function AddLiquidity({
// get formatted amounts // get formatted amounts
const formattedAmounts = { const formattedAmounts = {
[independentField]: typedValue, [independentField]: typedValue,
[dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? ''
} }
// get the max amounts user can add // get the max amounts user can add
@ -103,7 +103,7 @@ export default function AddLiquidity({
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
[field]: maxAmountSpend(currencyBalances[field]), [field]: maxAmountSpend(currencyBalances[field])
} }
}, },
{} {}
@ -113,7 +113,7 @@ export default function AddLiquidity({
(accumulator, field) => { (accumulator, field) => {
return { return {
...accumulator, ...accumulator,
[field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0')
} }
}, },
{} {}
@ -136,7 +136,7 @@ export default function AddLiquidity({
const amountsMin = { const amountsMin = {
[Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? 0 : allowedSlippage)[0], [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? 0 : allowedSlippage)[0],
[Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? 0 : allowedSlippage)[0], [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? 0 : allowedSlippage)[0]
} }
let estimate, let estimate,
@ -153,7 +153,7 @@ export default function AddLiquidity({
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).raw.toString())
} else { } else {
@ -167,18 +167,18 @@ export default function AddLiquidity({
amountsMin[Field.CURRENCY_A].toString(), amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(), amountsMin[Field.CURRENCY_B].toString(),
account, account,
deadline.toHexString(), deadline.toHexString()
] ]
value = null value = null
} }
setAttemptingTxn(true) setAttemptingTxn(true)
await estimate(...args, value ? { value } : {}) await estimate(...args, value ? { value } : {})
.then((estimatedGasLimit) => .then(estimatedGasLimit =>
method(...args, { method(...args, {
...(value ? { value } : {}), ...(value ? { value } : {}),
gasLimit: calculateGasMargin(estimatedGasLimit), gasLimit: calculateGasMargin(estimatedGasLimit)
}).then((response) => { }).then(response => {
setAttemptingTxn(false) setAttemptingTxn(false)
addTransaction(response, { addTransaction(response, {
@ -190,7 +190,7 @@ export default function AddLiquidity({
' and ' + ' and ' +
parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) + parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) +
' ' + ' ' +
currencies[Field.CURRENCY_B]?.symbol, currencies[Field.CURRENCY_B]?.symbol
}) })
setTxHash(response.hash) setTxHash(response.hash)
@ -198,11 +198,11 @@ export default function AddLiquidity({
ReactGA.event({ ReactGA.event({
category: 'Liquidity', category: 'Liquidity',
action: 'Add', action: 'Add',
label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'), label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/')
}) })
}) })
) )
.catch((error) => { .catch(error => {
setAttemptingTxn(false) setAttemptingTxn(false)
// we only care if the error is something _other_ than the user rejected the tx // we only care if the error is something _other_ than the user rejected the tx
if (error?.code !== 4001) { if (error?.code !== 4001) {
@ -245,9 +245,8 @@ export default function AddLiquidity({
</Text> </Text>
</Row> </Row>
<TYPE.italic fontSize={12} textAlign="left" padding={'8px 0 0 0 '}> <TYPE.italic fontSize={12} textAlign="left" padding={'8px 0 0 0 '}>
{`Output is estimated. If the price changes by more than ${ {`Output is estimated. If the price changes by more than ${allowedSlippage /
allowedSlippage / 100 100}% your transaction will revert.`}
}% your transaction will revert.`}
</TYPE.italic> </TYPE.italic>
</AutoColumn> </AutoColumn>
) )

@ -10,8 +10,8 @@ const OLD_PATH_STRUCTURE = /^(0x[a-fA-F0-9]{40})-(0x[a-fA-F0-9]{40})$/
export function RedirectOldAddLiquidityPathStructure(props: RouteComponentProps<{ currencyIdA: string }>) { export function RedirectOldAddLiquidityPathStructure(props: RouteComponentProps<{ currencyIdA: string }>) {
const { const {
match: { match: {
params: { currencyIdA }, params: { currencyIdA }
}, }
} = props } = props
const match = currencyIdA.match(OLD_PATH_STRUCTURE) const match = currencyIdA.match(OLD_PATH_STRUCTURE)
if (match?.length) { if (match?.length) {
@ -24,8 +24,8 @@ export function RedirectOldAddLiquidityPathStructure(props: RouteComponentProps<
export function RedirectDuplicateTokenIds(props: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) { export function RedirectDuplicateTokenIds(props: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const { const {
match: { match: {
params: { currencyIdA, currencyIdB }, params: { currencyIdA, currencyIdB }
}, }
} = props } = props
if (currencyIdA.toLowerCase() === currencyIdB.toLowerCase()) { if (currencyIdA.toLowerCase() === currencyIdB.toLowerCase()) {
return <Redirect to={`/add/${currencyIdA}`} /> return <Redirect to={`/add/${currencyIdA}`} />

@ -15,7 +15,7 @@ import AddLiquidity from './AddLiquidity'
import { import {
RedirectDuplicateTokenIds, RedirectDuplicateTokenIds,
RedirectOldAddLiquidityPathStructure, RedirectOldAddLiquidityPathStructure,
RedirectToAddLiquidity, RedirectToAddLiquidity
} from './AddLiquidity/redirects' } from './AddLiquidity/redirects'
import Earn from './Earn' import Earn from './Earn'
import Manage from './Earn/Manage' import Manage from './Earn/Manage'

@ -10,7 +10,7 @@ const REWARDS_DURATION = DAY * REWARDS_DURATION_DAYS
export function Countdown({ exactEnd }: { exactEnd?: Date }) { export function Countdown({ exactEnd }: { exactEnd?: Date }) {
// get end/beginning times // get end/beginning times
const end = useMemo(() => (exactEnd ? Math.floor(exactEnd.getTime() / 1000) : STAKING_GENESIS + REWARDS_DURATION), [ const end = useMemo(() => (exactEnd ? Math.floor(exactEnd.getTime() / 1000) : STAKING_GENESIS + REWARDS_DURATION), [
exactEnd, exactEnd
]) ])
const begin = useMemo(() => end - REWARDS_DURATION, [end]) const begin = useMemo(() => end - REWARDS_DURATION, [end])

@ -89,8 +89,8 @@ const DataRow = styled(RowBetween)`
export default function Manage({ export default function Manage({
match: { match: {
params: { currencyIdA, currencyIdB }, params: { currencyIdA, currencyIdB }
}, }
}: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) { }: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const { account, chainId } = useActiveWeb3React() const { account, chainId } = useActiveWeb3React()

@ -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.raw, 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)
@ -97,7 +97,7 @@ export default function Earn() {
) : stakingInfos?.length !== 0 && stakingInfosWithBalance.length === 0 ? ( ) : stakingInfos?.length !== 0 && stakingInfosWithBalance.length === 0 ? (
<OutlineCard>No active pools</OutlineCard> <OutlineCard>No active pools</OutlineCard>
) : ( ) : (
stakingInfosWithBalance?.map((stakingInfo) => { stakingInfosWithBalance?.map(stakingInfo => {
// need to sort by added liquidity here // need to sort by added liquidity here
return <PoolCard key={stakingInfo.stakingRewardAddress} stakingInfo={stakingInfo} /> return <PoolCard key={stakingInfo.stakingRewardAddress} stakingInfo={stakingInfo} />
}) })

@ -39,7 +39,7 @@ export function V1LiquidityInfo({
token, token,
liquidityTokenAmount, liquidityTokenAmount,
tokenWorth, tokenWorth,
ethWorth, ethWorth
}: { }: {
token: Token token: Token
liquidityTokenAmount: TokenAmount liquidityTokenAmount: TokenAmount
@ -118,7 +118,12 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
: null : null
const priceDifferenceFraction: Fraction | undefined = const priceDifferenceFraction: Fraction | undefined =
v1SpotPrice && v2SpotPrice ? v1SpotPrice.divide(v2SpotPrice).multiply('100').subtract('100') : undefined v1SpotPrice && v2SpotPrice
? v1SpotPrice
.divide(v2SpotPrice)
.multiply('100')
.subtract('100')
: undefined
const priceDifferenceAbs: Fraction | undefined = priceDifferenceFraction?.lessThan(ZERO) const priceDifferenceAbs: Fraction | undefined = priceDifferenceFraction?.lessThan(ZERO)
? priceDifferenceFraction?.multiply('-1') ? priceDifferenceFraction?.multiply('-1')
@ -126,7 +131,10 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
const minAmountETH: JSBI | undefined = const minAmountETH: JSBI | undefined =
v2SpotPrice && tokenWorth v2SpotPrice && tokenWorth
? tokenWorth.divide(v2SpotPrice).multiply(WEI_DENOM).multiply(ALLOWED_OUTPUT_MIN_PERCENT).quotient ? tokenWorth
.divide(v2SpotPrice)
.multiply(WEI_DENOM)
.multiply(ALLOWED_OUTPUT_MIN_PERCENT).quotient
: ethWorth?.numerator : ethWorth?.numerator
const minAmountToken: JSBI | undefined = const minAmountToken: JSBI | undefined =
@ -157,11 +165,11 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
ReactGA.event({ ReactGA.event({
category: 'Migrate', category: 'Migrate',
action: 'V1->V2', action: 'V1->V2',
label: token?.symbol, label: token?.symbol
}) })
addTransaction(response, { addTransaction(response, {
summary: `Migrate ${token.symbol} liquidity to V2`, summary: `Migrate ${token.symbol} liquidity to V2`
}) })
setPendingMigrationHash(response.hash) setPendingMigrationHash(response.hash)
}) })
@ -305,8 +313,8 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
export default function MigrateV1Exchange({ export default function MigrateV1Exchange({
history, history,
match: { match: {
params: { address }, params: { address }
}, }
}: RouteComponentProps<{ address: string }>) { }: RouteComponentProps<{ address: string }>) {
const validatedAddress = isAddress(address) const validatedAddress = isAddress(address)
const { chainId, account } = useActiveWeb3React() const { chainId, account } = useActiveWeb3React()

Some files were not shown because too many files have changed in this diff Show More