Commit b6d85123 authored by Lint Action's avatar Lint Action

Fix code style issues with ESLint

parent 4e17107a
...@@ -3,23 +3,33 @@ describe('Swap', () => { ...@@ -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', () => { ...@@ -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) => { ...@@ -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` ...@@ -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({ ...@@ -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({ ...@@ -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 }>` ...@@ -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({ ...@@ -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?: ...@@ -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({ ...@@ -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({ ...@@ -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 }>` ...@@ -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({ ...@@ -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)) ...@@ -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` ...@@ -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({ ...@@ -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 } = { ...@@ -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() { ...@@ -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 = [ ...@@ -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 = ({ ...@@ -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 = ({ ...@@ -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 = ({ ...@@ -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({ ...@@ -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 ...@@ -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) { ...@@ -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) ...@@ -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 ...@@ -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({ ...@@ -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({ ...@@ -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: ...@@ -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` ...@@ -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({ ...@@ -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' ...@@ -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' }: ...@@ -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 { ...@@ -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({ ...@@ -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({ ...@@ -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) ...@@ -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({ ...@@ -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({ ...@@ -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)` ...@@ -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() { ...@@ -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() { ...@@ -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 ...@@ -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 ...@@ -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 }>` ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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 { ...@@ -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({ ...@@ -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 ...@@ -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 ...@@ -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({ ...@@ -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 }: ...@@ -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 }: ...@@ -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({ ...@@ -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)` ...@@ -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) { ...@@ -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 }) { ...@@ -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 }) { ...@@ -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 }) { ...@@ -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 }) { ...@@ -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 }) { ...@@ -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` ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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` ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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)` ...@@ -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[] { ...@@ -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[] { ...@@ -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: ...@@ -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: ...@@ -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` ...@@ -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 { ...@@ -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 { ...@@ -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' ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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' ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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` ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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` ...@@ -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 = { ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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() { ...@@ -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() { ...@@ -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 ...@@ -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() { ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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 }) { ...@@ -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() { ...@@ -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' ...@@ -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({ ...@@ -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 { ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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)` ...@@ -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({ ...@@ -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({ ...@@ -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 ...@@ -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 { ...@@ -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 ...@@ -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] ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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') { ...@@ -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 { ...@@ -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({ ...@@ -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({ ...@@ -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 } = { ...@@ -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 = { ...@@ -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 = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 } = { ...@@ -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[] = [ ...@@ -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[] = [ ...@@ -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 } = { ...@@ -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 } = { ...@@ -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 ...@@ -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 { ...@@ -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 ...@@ -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 ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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 { ...@@ -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( ...@@ -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 ...@@ -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 { ...@@ -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[] { ...@@ -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[] { ...@@ -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[] { ...@@ -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() { ...@@ -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) { ...@@ -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) { ...@@ -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( ...@@ -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 { ...@@ -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( ...@@ -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> { ...@@ -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> { ...@@ -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) { ...@@ -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) { ...@@ -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' ...@@ -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' ...@@ -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( ...@@ -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 ...@@ -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 ...@@ -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; ...@@ -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 ...@@ -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>( ...@@ -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' ...@@ -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( ...@@ -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( ...@@ -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( ...@@ -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( ...@@ -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( ...@@ -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( ...@@ -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( ...@@ -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' ...@@ -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' ...@@ -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' ...@@ -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' ...@@ -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' ...@@ -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( ...@@ -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( ...@@ -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 ...@@ -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 ...@@ -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({ ...@@ -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({ ...@@ -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 ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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({ ...@@ -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})$/ ...@@ -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< ...@@ -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' ...@@ -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 ...@@ -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)` ...@@ -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() { ...@@ -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() { ...@@ -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({ ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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()
......
...@@ -33,7 +33,7 @@ const ZERO_FRACTION = new Fraction(ZERO, ONE) ...@@ -33,7 +33,7 @@ const ZERO_FRACTION = new Fraction(ZERO, ONE)
function V1PairRemoval({ function V1PairRemoval({
exchangeContract, exchangeContract,
liquidityTokenAmount, liquidityTokenAmount,
token, token
}: { }: {
exchangeContract: Contract exchangeContract: Contract
liquidityTokenAmount: TokenAmount liquidityTokenAmount: TokenAmount
...@@ -75,11 +75,11 @@ function V1PairRemoval({ ...@@ -75,11 +75,11 @@ function V1PairRemoval({
ReactGA.event({ ReactGA.event({
category: 'Remove', category: 'Remove',
action: 'V1', action: 'V1',
label: token?.symbol, label: token?.symbol
}) })
addTransaction(response, { addTransaction(response, {
summary: `Remove ${chainId && token.equals(WETH[chainId]) ? 'WETH' : token.symbol}/ETH V1 liquidity`, summary: `Remove ${chainId && token.equals(WETH[chainId]) ? 'WETH' : token.symbol}/ETH V1 liquidity`
}) })
setPendingRemovalHash(response.hash) setPendingRemovalHash(response.hash)
}) })
...@@ -128,8 +128,8 @@ function V1PairRemoval({ ...@@ -128,8 +128,8 @@ function V1PairRemoval({
export default function RemoveV1Exchange({ export default function RemoveV1Exchange({
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()
......
...@@ -24,7 +24,7 @@ export default function MigrateV1() { ...@@ -24,7 +24,7 @@ export default function MigrateV1() {
const { account, chainId } = useActiveWeb3React() const { account, chainId } = useActiveWeb3React()
const [tokenSearch, setTokenSearch] = useState<string>('') const [tokenSearch, setTokenSearch] = useState<string>('')
const handleTokenSearchChange = useCallback((e) => setTokenSearch(e.target.value), [setTokenSearch]) const handleTokenSearchChange = useCallback(e => setTokenSearch(e.target.value), [setTokenSearch])
// automatically add the search token // automatically add the search token
const token = useToken(tokenSearch) const token = useToken(tokenSearch)
...@@ -42,19 +42,17 @@ export default function MigrateV1() { ...@@ -42,19 +42,17 @@ export default function MigrateV1() {
const V1Exchanges = useAllTokenV1Exchanges() const V1Exchanges = useAllTokenV1Exchanges()
const V1LiquidityTokens: Token[] = useMemo(() => { const V1LiquidityTokens: Token[] = useMemo(() => {
return chainId return chainId
? Object.keys(V1Exchanges).map( ? Object.keys(V1Exchanges).map(exchangeAddress => new Token(chainId, exchangeAddress, 18, 'UNI-V1', 'Uniswap V1'))
(exchangeAddress) => new Token(chainId, exchangeAddress, 18, 'UNI-V1', 'Uniswap V1')
)
: [] : []
}, [chainId, V1Exchanges]) }, [chainId, V1Exchanges])
const [V1LiquidityBalances, V1LiquidityBalancesLoading] = useTokenBalancesWithLoadingIndicator( const [V1LiquidityBalances, V1LiquidityBalancesLoading] = useTokenBalancesWithLoadingIndicator(
account ?? undefined, account ?? undefined,
V1LiquidityTokens V1LiquidityTokens
) )
const allV1PairsWithLiquidity = V1LiquidityTokens.filter((V1LiquidityToken) => { const allV1PairsWithLiquidity = V1LiquidityTokens.filter(V1LiquidityToken => {
const balance = V1LiquidityBalances?.[V1LiquidityToken.address] const balance = V1LiquidityBalances?.[V1LiquidityToken.address]
return balance && JSBI.greaterThan(balance.raw, JSBI.BigInt(0)) return balance && JSBI.greaterThan(balance.raw, JSBI.BigInt(0))
}).map((V1LiquidityToken) => { }).map(V1LiquidityToken => {
const balance = V1LiquidityBalances[V1LiquidityToken.address] const balance = V1LiquidityBalances[V1LiquidityToken.address]
return balance ? ( return balance ? (
<V1PositionCard <V1PositionCard
......
...@@ -81,11 +81,11 @@ export default function Pool() { ...@@ -81,11 +81,11 @@ export default function Pool() {
// fetch the user's balances of all tracked V2 LP tokens // fetch the user's balances of all tracked V2 LP tokens
const trackedTokenPairs = useTrackedTokenPairs() const trackedTokenPairs = useTrackedTokenPairs()
const tokenPairsWithLiquidityTokens = useMemo( const tokenPairsWithLiquidityTokens = useMemo(
() => trackedTokenPairs.map((tokens) => ({ liquidityToken: toV2LiquidityToken(tokens), tokens })), () => trackedTokenPairs.map(tokens => ({ liquidityToken: toV2LiquidityToken(tokens), tokens })),
[trackedTokenPairs] [trackedTokenPairs]
) )
const liquidityTokens = useMemo(() => tokenPairsWithLiquidityTokens.map((tpwlt) => tpwlt.liquidityToken), [ const liquidityTokens = useMemo(() => tokenPairsWithLiquidityTokens.map(tpwlt => tpwlt.liquidityToken), [
tokenPairsWithLiquidityTokens, tokenPairsWithLiquidityTokens
]) ])
const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator(
account ?? undefined, account ?? undefined,
...@@ -103,7 +103,7 @@ export default function Pool() { ...@@ -103,7 +103,7 @@ export default function Pool() {
const v2Pairs = usePairs(liquidityTokensWithBalances.map(({ tokens }) => tokens)) const v2Pairs = usePairs(liquidityTokensWithBalances.map(({ tokens }) => tokens))
const v2IsLoading = const v2IsLoading =
fetchingV2PairBalances || v2Pairs?.length < liquidityTokensWithBalances.length || v2Pairs?.some((V2Pair) => !V2Pair) fetchingV2PairBalances || v2Pairs?.length < liquidityTokensWithBalances.length || v2Pairs?.some(V2Pair => !V2Pair)
const allV2PairsWithLiquidity = v2Pairs.map(([, pair]) => pair).filter((v2Pair): v2Pair is Pair => Boolean(v2Pair)) const allV2PairsWithLiquidity = v2Pairs.map(([, pair]) => pair).filter((v2Pair): v2Pair is Pair => Boolean(v2Pair))
...@@ -111,15 +111,15 @@ export default function Pool() { ...@@ -111,15 +111,15 @@ export default function Pool() {
// show liquidity even if its deposited in rewards contract // show liquidity even if its deposited in rewards contract
const stakingInfo = useStakingInfo() const stakingInfo = useStakingInfo()
const stakingInfosWithBalance = stakingInfo?.filter((pool) => JSBI.greaterThan(pool.stakedAmount.raw, BIG_INT_ZERO)) const stakingInfosWithBalance = stakingInfo?.filter(pool => JSBI.greaterThan(pool.stakedAmount.raw, BIG_INT_ZERO))
const stakingPairs = usePairs(stakingInfosWithBalance?.map((stakingInfo) => stakingInfo.tokens)) const stakingPairs = usePairs(stakingInfosWithBalance?.map(stakingInfo => stakingInfo.tokens))
// remove any pairs that also are included in pairs with stake in mining pool // remove any pairs that also are included in pairs with stake in mining pool
const v2PairsWithoutStakedAmount = allV2PairsWithLiquidity.filter((v2Pair) => { const v2PairsWithoutStakedAmount = allV2PairsWithLiquidity.filter(v2Pair => {
return ( return (
stakingPairs stakingPairs
?.map((stakingPair) => stakingPair[1]) ?.map(stakingPair => stakingPair[1])
.filter((stakingPair) => stakingPair?.liquidityToken.address === v2Pair.liquidityToken.address).length === 0 .filter(stakingPair => stakingPair?.liquidityToken.address === v2Pair.liquidityToken.address).length === 0
) )
}) })
...@@ -201,7 +201,7 @@ export default function Pool() { ...@@ -201,7 +201,7 @@ export default function Pool() {
<span></span> <span></span>
</RowBetween> </RowBetween>
</ButtonSecondary> </ButtonSecondary>
{v2PairsWithoutStakedAmount.map((v2Pair) => ( {v2PairsWithoutStakedAmount.map(v2Pair => (
<FullPositionCard key={v2Pair.liquidityToken.address} pair={v2Pair} /> <FullPositionCard key={v2Pair.liquidityToken.address} pair={v2Pair} />
))} ))}
{stakingPairs.map( {stakingPairs.map(
......
...@@ -23,7 +23,7 @@ import { TYPE } from '../../theme' ...@@ -23,7 +23,7 @@ import { TYPE } from '../../theme'
enum Fields { enum Fields {
TOKEN0 = 0, TOKEN0 = 0,
TOKEN1 = 1, TOKEN1 = 1
} }
export default function PoolFinder() { export default function PoolFinder() {
......
...@@ -47,15 +47,15 @@ import { BigNumber } from '@ethersproject/bignumber' ...@@ -47,15 +47,15 @@ import { BigNumber } from '@ethersproject/bignumber'
export default function RemoveLiquidity({ export default function RemoveLiquidity({
history, history,
match: { match: {
params: { currencyIdA, currencyIdB }, params: { currencyIdA, currencyIdB }
}, }
}: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) { }: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const [currencyA, currencyB] = [useCurrency(currencyIdA) ?? undefined, useCurrency(currencyIdB) ?? undefined] const [currencyA, currencyB] = [useCurrency(currencyIdA) ?? undefined, useCurrency(currencyIdB) ?? undefined]
const { account, chainId, library } = useActiveWeb3React() const { account, chainId, library } = useActiveWeb3React()
const [tokenA, tokenB] = useMemo(() => [wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId)], [ const [tokenA, tokenB] = useMemo(() => [wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId)], [
currencyA, currencyA,
currencyB, currencyB,
chainId, chainId
]) ])
const theme = useContext(ThemeContext) const theme = useContext(ThemeContext)
...@@ -90,7 +90,7 @@ export default function RemoveLiquidity({ ...@@ -90,7 +90,7 @@ export default function RemoveLiquidity({
[Field.CURRENCY_A]: [Field.CURRENCY_A]:
independentField === Field.CURRENCY_A ? typedValue : parsedAmounts[Field.CURRENCY_A]?.toSignificant(6) ?? '', independentField === Field.CURRENCY_A ? typedValue : parsedAmounts[Field.CURRENCY_A]?.toSignificant(6) ?? '',
[Field.CURRENCY_B]: [Field.CURRENCY_B]:
independentField === Field.CURRENCY_B ? typedValue : parsedAmounts[Field.CURRENCY_B]?.toSignificant(6) ?? '', independentField === Field.CURRENCY_B ? typedValue : parsedAmounts[Field.CURRENCY_B]?.toSignificant(6) ?? ''
} }
const atMaxAmount = parsedAmounts[Field.LIQUIDITY_PERCENT]?.equalTo(new Percent('1')) const atMaxAmount = parsedAmounts[Field.LIQUIDITY_PERCENT]?.equalTo(new Percent('1'))
...@@ -120,50 +120,50 @@ export default function RemoveLiquidity({ ...@@ -120,50 +120,50 @@ export default function RemoveLiquidity({
{ 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: pair.liquidityToken.address, verifyingContract: pair.liquidityToken.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: ROUTER_ADDRESS, spender: ROUTER_ADDRESS,
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()
...@@ -181,13 +181,13 @@ export default function RemoveLiquidity({ ...@@ -181,13 +181,13 @@ export default function RemoveLiquidity({
) )
const onLiquidityInput = useCallback((typedValue: string): void => onUserInput(Field.LIQUIDITY, typedValue), [ const onLiquidityInput = useCallback((typedValue: string): void => onUserInput(Field.LIQUIDITY, typedValue), [
onUserInput, onUserInput
]) ])
const onCurrencyAInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_A, typedValue), [ const onCurrencyAInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_A, typedValue), [
onUserInput, onUserInput
]) ])
const onCurrencyBInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_B, typedValue), [ const onCurrencyBInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_B, typedValue), [
onUserInput, onUserInput
]) ])
// tx sending // tx sending
...@@ -202,7 +202,7 @@ export default function RemoveLiquidity({ ...@@ -202,7 +202,7 @@ export default function RemoveLiquidity({
const amountsMin = { const amountsMin = {
[Field.CURRENCY_A]: calculateSlippageAmount(currencyAmountA, allowedSlippage)[0], [Field.CURRENCY_A]: calculateSlippageAmount(currencyAmountA, allowedSlippage)[0],
[Field.CURRENCY_B]: calculateSlippageAmount(currencyAmountB, allowedSlippage)[0], [Field.CURRENCY_B]: calculateSlippageAmount(currencyAmountB, allowedSlippage)[0]
} }
if (!currencyA || !currencyB) throw new Error('missing tokens') if (!currencyA || !currencyB) throw new Error('missing tokens')
...@@ -226,7 +226,7 @@ export default function RemoveLiquidity({ ...@@ -226,7 +226,7 @@ export default function RemoveLiquidity({
amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(),
account, account,
deadline.toHexString(), deadline.toHexString()
] ]
} }
// removeLiquidity // removeLiquidity
...@@ -239,7 +239,7 @@ export default function RemoveLiquidity({ ...@@ -239,7 +239,7 @@ export default function RemoveLiquidity({
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()
] ]
} }
} }
...@@ -258,7 +258,7 @@ export default function RemoveLiquidity({ ...@@ -258,7 +258,7 @@ export default function RemoveLiquidity({
false, false,
signatureData.v, signatureData.v,
signatureData.r, signatureData.r,
signatureData.s, signatureData.s
] ]
} }
// removeLiquidityETHWithPermit // removeLiquidityETHWithPermit
...@@ -275,7 +275,7 @@ export default function RemoveLiquidity({ ...@@ -275,7 +275,7 @@ export default function RemoveLiquidity({
false, false,
signatureData.v, signatureData.v,
signatureData.r, signatureData.r,
signatureData.s, signatureData.s
] ]
} }
} else { } else {
...@@ -283,17 +283,17 @@ export default function RemoveLiquidity({ ...@@ -283,17 +283,17 @@ export default function RemoveLiquidity({
} }
const safeGasEstimates: (BigNumber | undefined)[] = await Promise.all( const safeGasEstimates: (BigNumber | undefined)[] = await Promise.all(
methodNames.map((methodName) => methodNames.map(methodName =>
router.estimateGas[methodName](...args) router.estimateGas[methodName](...args)
.then(calculateGasMargin) .then(calculateGasMargin)
.catch((error) => { .catch(error => {
console.error(`estimateGas failed`, methodName, args, error) console.error(`estimateGas failed`, methodName, args, error)
return undefined return undefined
}) })
) )
) )
const indexOfSuccessfulEstimation = safeGasEstimates.findIndex((safeGasEstimate) => const indexOfSuccessfulEstimation = safeGasEstimates.findIndex(safeGasEstimate =>
BigNumber.isBigNumber(safeGasEstimate) BigNumber.isBigNumber(safeGasEstimate)
) )
...@@ -306,7 +306,7 @@ export default function RemoveLiquidity({ ...@@ -306,7 +306,7 @@ export default function RemoveLiquidity({
setAttemptingTxn(true) setAttemptingTxn(true)
await router[methodName](...args, { await router[methodName](...args, {
gasLimit: safeGasEstimate, gasLimit: safeGasEstimate
}) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
setAttemptingTxn(false) setAttemptingTxn(false)
...@@ -320,7 +320,7 @@ export default function RemoveLiquidity({ ...@@ -320,7 +320,7 @@ export default function RemoveLiquidity({
' and ' + ' and ' +
parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) + parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) +
' ' + ' ' +
currencyB?.symbol, currencyB?.symbol
}) })
setTxHash(response.hash) setTxHash(response.hash)
...@@ -328,7 +328,7 @@ export default function RemoveLiquidity({ ...@@ -328,7 +328,7 @@ export default function RemoveLiquidity({
ReactGA.event({ ReactGA.event({
category: 'Liquidity', category: 'Liquidity',
action: 'Remove', action: 'Remove',
label: [currencyA?.symbol, currencyB?.symbol].join('/'), label: [currencyA?.symbol, currencyB?.symbol].join('/')
}) })
}) })
.catch((error: Error) => { .catch((error: Error) => {
...@@ -369,9 +369,8 @@ export default function RemoveLiquidity({ ...@@ -369,9 +369,8 @@ export default function RemoveLiquidity({
</RowBetween> </RowBetween>
<TYPE.italic fontSize={12} color={theme.text2} textAlign="left" padding={'12px 0 0 0'}> <TYPE.italic fontSize={12} color={theme.text2} textAlign="left" padding={'12px 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>
) )
......
...@@ -5,8 +5,8 @@ const OLD_PATH_STRUCTURE = /^(0x[a-fA-F0-9]{40})-(0x[a-fA-F0-9]{40})$/ ...@@ -5,8 +5,8 @@ const OLD_PATH_STRUCTURE = /^(0x[a-fA-F0-9]{40})-(0x[a-fA-F0-9]{40})$/
export function RedirectOldRemoveLiquidityPathStructure({ export function RedirectOldRemoveLiquidityPathStructure({
match: { match: {
params: { tokens }, params: { tokens }
}, }
}: RouteComponentProps<{ tokens: string }>) { }: RouteComponentProps<{ tokens: string }>) {
if (!OLD_PATH_STRUCTURE.test(tokens)) { if (!OLD_PATH_STRUCTURE.test(tokens)) {
return <Redirect to="/pool" /> return <Redirect to="/pool" />
......
...@@ -36,7 +36,7 @@ import { ...@@ -36,7 +36,7 @@ import {
useDefaultsFromURLSearch, useDefaultsFromURLSearch,
useDerivedSwapInfo, useDerivedSwapInfo,
useSwapActionHandlers, useSwapActionHandlers,
useSwapState, useSwapState
} from '../../state/swap/hooks' } from '../../state/swap/hooks'
import { useExpertModeManager, useUserSlippageTolerance, useUserSingleHopOnly } from '../../state/user/hooks' import { useExpertModeManager, useUserSlippageTolerance, useUserSingleHopOnly } from '../../state/user/hooks'
import { LinkStyledButton, TYPE } from '../../theme' import { LinkStyledButton, TYPE } from '../../theme'
...@@ -55,7 +55,7 @@ export default function Swap() { ...@@ -55,7 +55,7 @@ export default function Swap() {
// token warning stuff // token warning stuff
const [loadedInputCurrency, loadedOutputCurrency] = [ const [loadedInputCurrency, loadedOutputCurrency] = [
useCurrency(loadedUrlParams?.inputCurrencyId), useCurrency(loadedUrlParams?.inputCurrencyId),
useCurrency(loadedUrlParams?.outputCurrencyId), useCurrency(loadedUrlParams?.outputCurrencyId)
] ]
const [dismissTokenWarning, setDismissTokenWarning] = useState<boolean>(false) const [dismissTokenWarning, setDismissTokenWarning] = useState<boolean>(false)
const urlLoadedTokens: Token[] = useMemo( const urlLoadedTokens: Token[] = useMemo(
...@@ -95,7 +95,7 @@ export default function Swap() { ...@@ -95,7 +95,7 @@ export default function Swap() {
currencyBalances, currencyBalances,
parsedAmount, parsedAmount,
currencies, currencies,
inputError: swapInputError, inputError: swapInputError
} = useDerivedSwapInfo() } = useDerivedSwapInfo()
const { wrapType, execute: onWrap, inputError: wrapInputError } = useWrapCallback( const { wrapType, execute: onWrap, inputError: wrapInputError } = useWrapCallback(
currencies[Field.INPUT], currencies[Field.INPUT],
...@@ -107,7 +107,7 @@ export default function Swap() { ...@@ -107,7 +107,7 @@ export default function Swap() {
const toggledVersion = useToggledVersion() const toggledVersion = useToggledVersion()
const tradesByVersion = { const tradesByVersion = {
[Version.v1]: v1Trade, [Version.v1]: v1Trade,
[Version.v2]: v2Trade, [Version.v2]: v2Trade
} }
const trade = showWrap ? undefined : tradesByVersion[toggledVersion] const trade = showWrap ? undefined : tradesByVersion[toggledVersion]
const defaultTrade = showWrap ? undefined : tradesByVersion[DEFAULT_VERSION] const defaultTrade = showWrap ? undefined : tradesByVersion[DEFAULT_VERSION]
...@@ -118,11 +118,11 @@ export default function Swap() { ...@@ -118,11 +118,11 @@ export default function Swap() {
const parsedAmounts = showWrap const parsedAmounts = showWrap
? { ? {
[Field.INPUT]: parsedAmount, [Field.INPUT]: parsedAmount,
[Field.OUTPUT]: parsedAmount, [Field.OUTPUT]: parsedAmount
} }
: { : {
[Field.INPUT]: independentField === Field.INPUT ? parsedAmount : trade?.inputAmount, [Field.INPUT]: independentField === Field.INPUT ? parsedAmount : trade?.inputAmount,
[Field.OUTPUT]: independentField === Field.OUTPUT ? parsedAmount : trade?.outputAmount, [Field.OUTPUT]: independentField === Field.OUTPUT ? parsedAmount : trade?.outputAmount
} }
const { onSwitchTokens, onCurrencySelection, onUserInput, onChangeRecipient } = useSwapActionHandlers() const { onSwitchTokens, onCurrencySelection, onUserInput, onChangeRecipient } = useSwapActionHandlers()
...@@ -154,14 +154,14 @@ export default function Swap() { ...@@ -154,14 +154,14 @@ export default function Swap() {
tradeToConfirm: undefined, tradeToConfirm: undefined,
attemptingTxn: false, attemptingTxn: false,
swapErrorMessage: undefined, swapErrorMessage: undefined,
txHash: undefined, txHash: undefined
}) })
const formattedAmounts = { const formattedAmounts = {
[independentField]: typedValue, [independentField]: typedValue,
[dependentField]: showWrap [dependentField]: showWrap
? parsedAmounts[independentField]?.toExact() ?? '' ? parsedAmounts[independentField]?.toExact() ?? ''
: parsedAmounts[dependentField]?.toSignificant(6) ?? '', : parsedAmounts[dependentField]?.toSignificant(6) ?? ''
} }
const route = trade?.route const route = trade?.route
...@@ -202,7 +202,7 @@ export default function Swap() { ...@@ -202,7 +202,7 @@ export default function Swap() {
} }
setSwapState({ attemptingTxn: true, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: undefined }) setSwapState({ attemptingTxn: true, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: undefined })
swapCallback() swapCallback()
.then((hash) => { .then(hash => {
setSwapState({ attemptingTxn: false, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: hash }) setSwapState({ attemptingTxn: false, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: hash })
ReactGA.event({ ReactGA.event({
...@@ -216,22 +216,22 @@ export default function Swap() { ...@@ -216,22 +216,22 @@ export default function Swap() {
label: [ label: [
trade?.inputAmount?.currency?.symbol, trade?.inputAmount?.currency?.symbol,
trade?.outputAmount?.currency?.symbol, trade?.outputAmount?.currency?.symbol,
getTradeVersion(trade), getTradeVersion(trade)
].join('/'), ].join('/')
}) })
ReactGA.event({ ReactGA.event({
category: 'Routing', category: 'Routing',
action: singleHopOnly ? 'Swap with multihop disabled' : 'Swap with multihop enabled', action: singleHopOnly ? 'Swap with multihop disabled' : 'Swap with multihop enabled'
}) })
}) })
.catch((error) => { .catch(error => {
setSwapState({ setSwapState({
attemptingTxn: false, attemptingTxn: false,
tradeToConfirm, tradeToConfirm,
showConfirm, showConfirm,
swapErrorMessage: error.message, swapErrorMessage: error.message,
txHash: undefined, txHash: undefined
}) })
}) })
}, [ }, [
...@@ -243,7 +243,7 @@ export default function Swap() { ...@@ -243,7 +243,7 @@ export default function Swap() {
recipientAddress, recipientAddress,
account, account,
trade, trade,
singleHopOnly, singleHopOnly
]) ])
// errors // errors
...@@ -274,7 +274,7 @@ export default function Swap() { ...@@ -274,7 +274,7 @@ export default function Swap() {
}, [attemptingTxn, showConfirm, swapErrorMessage, trade, txHash]) }, [attemptingTxn, showConfirm, swapErrorMessage, trade, txHash])
const handleInputSelect = useCallback( const handleInputSelect = useCallback(
(inputCurrency) => { inputCurrency => {
setApprovalSubmitted(false) // reset 2 step UI for approvals setApprovalSubmitted(false) // reset 2 step UI for approvals
onCurrencySelection(Field.INPUT, inputCurrency) onCurrencySelection(Field.INPUT, inputCurrency)
}, },
...@@ -285,8 +285,8 @@ export default function Swap() { ...@@ -285,8 +285,8 @@ export default function Swap() {
maxAmountInput && onUserInput(Field.INPUT, maxAmountInput.toExact()) maxAmountInput && onUserInput(Field.INPUT, maxAmountInput.toExact())
}, [maxAmountInput, onUserInput]) }, [maxAmountInput, onUserInput])
const handleOutputSelect = useCallback((outputCurrency) => onCurrencySelection(Field.OUTPUT, outputCurrency), [ const handleOutputSelect = useCallback(outputCurrency => onCurrencySelection(Field.OUTPUT, outputCurrency), [
onCurrencySelection, onCurrencySelection
]) ])
const swapIsUnsupported = useIsTransactionUnsupported(currencies?.INPUT, currencies?.OUTPUT) const swapIsUnsupported = useIsTransactionUnsupported(currencies?.INPUT, currencies?.OUTPUT)
...@@ -447,7 +447,7 @@ export default function Swap() { ...@@ -447,7 +447,7 @@ export default function Swap() {
attemptingTxn: false, attemptingTxn: false,
swapErrorMessage: undefined, swapErrorMessage: undefined,
showConfirm: true, showConfirm: true,
txHash: undefined, txHash: undefined
}) })
} }
}} }}
...@@ -476,7 +476,7 @@ export default function Swap() { ...@@ -476,7 +476,7 @@ export default function Swap() {
attemptingTxn: false, attemptingTxn: false,
swapErrorMessage: undefined, swapErrorMessage: undefined,
showConfirm: true, showConfirm: true,
txHash: undefined, txHash: undefined
}) })
} }
}} }}
......
...@@ -14,8 +14,8 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri ...@@ -14,8 +14,8 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri
const { const {
location: { search }, location: { search },
match: { match: {
params: { outputCurrency }, params: { outputCurrency }
}, }
} = props } = props
return ( return (
...@@ -26,7 +26,7 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri ...@@ -26,7 +26,7 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri
search: search:
search && search.length > 1 search && search.length > 1
? `${search}&outputCurrency=${outputCurrency}` ? `${search}&outputCurrency=${outputCurrency}`
: `?outputCurrency=${outputCurrency}`, : `?outputCurrency=${outputCurrency}`
}} }}
/> />
) )
......
...@@ -105,8 +105,8 @@ const ProposerAddressLink = styled(ExternalLink)` ...@@ -105,8 +105,8 @@ const ProposerAddressLink = styled(ExternalLink)`
export default function VotePage({ export default function VotePage({
match: { match: {
params: { id }, params: { id }
}, }
}: RouteComponentProps<{ id: string }>) { }: RouteComponentProps<{ id: string }>) {
const { chainId, account } = useActiveWeb3React() const { chainId, account } = useActiveWeb3React()
......
/// <reference types="react-scripts" /> /// <reference types="react-scripts" />
declare module 'jazzicon' { declare module 'jazzicon' {
export default function (diameter: number, seed: number): HTMLElement export default function(diameter: number, seed: number): HTMLElement
} }
declare module 'fortmatic' declare module 'fortmatic'
......
...@@ -26,7 +26,7 @@ export enum ApplicationModal { ...@@ -26,7 +26,7 @@ export enum ApplicationModal {
CLAIM_POPUP, CLAIM_POPUP,
MENU, MENU,
DELEGATE, DELEGATE,
VOTE, VOTE
} }
export const updateBlockNumber = createAction<{ chainId: number; blockNumber: number }>('application/updateBlockNumber') export const updateBlockNumber = createAction<{ chainId: number; blockNumber: number }>('application/updateBlockNumber')
......
...@@ -85,5 +85,5 @@ export function useRemovePopup(): (key: string) => void { ...@@ -85,5 +85,5 @@ export function useRemovePopup(): (key: string) => void {
// get the list of active popups // get the list of active popups
export function useActivePopups(): AppState['application']['popupList'] { export function useActivePopups(): AppState['application']['popupList'] {
const list = useSelector((state: AppState) => state.application.popupList) const list = useSelector((state: AppState) => state.application.popupList)
return useMemo(() => list.filter((item) => item.show), [list]) return useMemo(() => list.filter(item => item.show), [list])
} }
...@@ -10,9 +10,9 @@ describe('application reducer', () => { ...@@ -10,9 +10,9 @@ describe('application reducer', () => {
store = createStore(reducer, { store = createStore(reducer, {
popupList: [], popupList: [],
blockNumber: { blockNumber: {
[ChainId.MAINNET]: 3, [ChainId.MAINNET]: 3
}, },
openModal: null, openModal: null
}) })
}) })
...@@ -65,7 +65,7 @@ describe('application reducer', () => { ...@@ -65,7 +65,7 @@ describe('application reducer', () => {
store.dispatch(updateBlockNumber({ chainId: ChainId.ROPSTEN, blockNumber: 2 })) store.dispatch(updateBlockNumber({ chainId: ChainId.ROPSTEN, blockNumber: 2 }))
expect(store.getState().blockNumber).toEqual({ expect(store.getState().blockNumber).toEqual({
[ChainId.MAINNET]: 3, [ChainId.MAINNET]: 3,
[ChainId.ROPSTEN]: 2, [ChainId.ROPSTEN]: 2
}) })
}) })
}) })
......
...@@ -12,10 +12,10 @@ export interface ApplicationState { ...@@ -12,10 +12,10 @@ export interface ApplicationState {
const initialState: ApplicationState = { const initialState: ApplicationState = {
blockNumber: {}, blockNumber: {},
popupList: [], popupList: [],
openModal: null, openModal: null
} }
export default createReducer(initialState, (builder) => export default createReducer(initialState, builder =>
builder builder
.addCase(updateBlockNumber, (state, action) => { .addCase(updateBlockNumber, (state, action) => {
const { chainId, blockNumber } = action.payload const { chainId, blockNumber } = action.payload
...@@ -29,17 +29,17 @@ export default createReducer(initialState, (builder) => ...@@ -29,17 +29,17 @@ export default createReducer(initialState, (builder) =>
state.openModal = action.payload state.openModal = action.payload
}) })
.addCase(addPopup, (state, { payload: { content, key, removeAfterMs = 15000 } }) => { .addCase(addPopup, (state, { payload: { content, key, removeAfterMs = 15000 } }) => {
state.popupList = (key ? state.popupList.filter((popup) => popup.key !== key) : state.popupList).concat([ state.popupList = (key ? state.popupList.filter(popup => popup.key !== key) : state.popupList).concat([
{ {
key: key || nanoid(), key: key || nanoid(),
show: true, show: true,
content, content,
removeAfterMs, removeAfterMs
}, }
]) ])
}) })
.addCase(removePopup, (state, { payload: { key } }) => { .addCase(removePopup, (state, { payload: { key } }) => {
state.popupList.forEach((p) => { state.popupList.forEach(p => {
if (p.key === key) { if (p.key === key) {
p.show = false p.show = false
} }
......
...@@ -13,12 +13,12 @@ export default function Updater(): null { ...@@ -13,12 +13,12 @@ export default function Updater(): null {
const [state, setState] = useState<{ chainId: number | undefined; blockNumber: number | null }>({ const [state, setState] = useState<{ chainId: number | undefined; blockNumber: number | null }>({
chainId, chainId,
blockNumber: null, blockNumber: null
}) })
const blockNumberCallback = useCallback( const blockNumberCallback = useCallback(
(blockNumber: number) => { (blockNumber: number) => {
setState((state) => { setState(state => {
if (chainId === state.chainId) { if (chainId === state.chainId) {
if (typeof state.blockNumber !== 'number') return { chainId, blockNumber } if (typeof state.blockNumber !== 'number') return { chainId, blockNumber }
return { chainId, blockNumber: Math.max(blockNumber, state.blockNumber) } return { chainId, blockNumber: Math.max(blockNumber, state.blockNumber) }
...@@ -38,7 +38,7 @@ export default function Updater(): null { ...@@ -38,7 +38,7 @@ export default function Updater(): null {
library library
.getBlockNumber() .getBlockNumber()
.then(blockNumberCallback) .then(blockNumberCallback)
.catch((error) => console.error(`Failed to get block number for chainId: ${chainId}`, error)) .catch(error => console.error(`Failed to get block number for chainId: ${chainId}`, error))
library.on('block', blockNumberCallback) library.on('block', blockNumberCallback)
return () => { return () => {
......
...@@ -4,7 +4,7 @@ export enum Field { ...@@ -4,7 +4,7 @@ export enum Field {
LIQUIDITY_PERCENT = 'LIQUIDITY_PERCENT', LIQUIDITY_PERCENT = 'LIQUIDITY_PERCENT',
LIQUIDITY = 'LIQUIDITY', LIQUIDITY = 'LIQUIDITY',
CURRENCY_A = 'CURRENCY_A', CURRENCY_A = 'CURRENCY_A',
CURRENCY_B = 'CURRENCY_B', CURRENCY_B = 'CURRENCY_B'
} }
export const typeInput = createAction<{ field: Field; typedValue: string }>('burn/typeInputBurn') export const typeInput = createAction<{ field: Field; typedValue: string }>('burn/typeInputBurn')
...@@ -12,7 +12,7 @@ import { useTokenBalances } from '../wallet/hooks' ...@@ -12,7 +12,7 @@ import { useTokenBalances } from '../wallet/hooks'
import { Field, typeInput } from './actions' import { Field, typeInput } from './actions'
export function useBurnState(): AppState['burn'] { export function useBurnState(): AppState['burn'] {
return useSelector<AppState, AppState['burn']>((state) => state.burn) return useSelector<AppState, AppState['burn']>(state => state.burn)
} }
export function useDerivedBurnInfo( export function useDerivedBurnInfo(
...@@ -43,7 +43,7 @@ export function useDerivedBurnInfo( ...@@ -43,7 +43,7 @@ export function useDerivedBurnInfo(
const tokens = { const tokens = {
[Field.CURRENCY_A]: tokenA, [Field.CURRENCY_A]: tokenA,
[Field.CURRENCY_B]: tokenB, [Field.CURRENCY_B]: tokenB,
[Field.LIQUIDITY]: pair?.liquidityToken, [Field.LIQUIDITY]: pair?.liquidityToken
} }
// liquidity values // liquidity values
...@@ -68,7 +68,7 @@ export function useDerivedBurnInfo( ...@@ -68,7 +68,7 @@ export function useDerivedBurnInfo(
: undefined : undefined
const liquidityValues: { [Field.CURRENCY_A]?: TokenAmount; [Field.CURRENCY_B]?: TokenAmount } = { const liquidityValues: { [Field.CURRENCY_A]?: TokenAmount; [Field.CURRENCY_B]?: TokenAmount } = {
[Field.CURRENCY_A]: liquidityValueA, [Field.CURRENCY_A]: liquidityValueA,
[Field.CURRENCY_B]: liquidityValueB, [Field.CURRENCY_B]: liquidityValueB
} }
let percentToRemove: Percent = new Percent('0', '100') let percentToRemove: Percent = new Percent('0', '100')
...@@ -114,7 +114,7 @@ export function useDerivedBurnInfo( ...@@ -114,7 +114,7 @@ export function useDerivedBurnInfo(
[Field.CURRENCY_B]: [Field.CURRENCY_B]:
tokenB && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueB tokenB && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueB
? new TokenAmount(tokenB, percentToRemove.multiply(liquidityValueB.raw).quotient) ? new TokenAmount(tokenB, percentToRemove.multiply(liquidityValueB.raw).quotient)
: undefined, : undefined
} }
let error: string | undefined let error: string | undefined
...@@ -142,6 +142,6 @@ export function useBurnActionHandlers(): { ...@@ -142,6 +142,6 @@ export function useBurnActionHandlers(): {
) )
return { return {
onUserInput, onUserInput
} }
} }
...@@ -8,15 +8,15 @@ export interface BurnState { ...@@ -8,15 +8,15 @@ export interface BurnState {
const initialState: BurnState = { const initialState: BurnState = {
independentField: Field.LIQUIDITY_PERCENT, independentField: Field.LIQUIDITY_PERCENT,
typedValue: '0', typedValue: '0'
} }
export default createReducer<BurnState>(initialState, (builder) => export default createReducer<BurnState>(initialState, builder =>
builder.addCase(typeInput, (state, { payload: { field, typedValue } }) => { builder.addCase(typeInput, (state, { payload: { field, typedValue } }) => {
return { return {
...state, ...state,
independentField: field, independentField: field,
typedValue, typedValue
} }
}) })
) )
...@@ -30,7 +30,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData | ...@@ -30,7 +30,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData |
return (CLAIM_PROMISES[key] = return (CLAIM_PROMISES[key] =
CLAIM_PROMISES[key] ?? CLAIM_PROMISES[key] ??
fetch(`https://gentle-frost-9e74.uniswap.workers.dev/${chainId}/${formatted}`) fetch(`https://gentle-frost-9e74.uniswap.workers.dev/${chainId}/${formatted}`)
.then((res) => { .then(res => {
if (res.status === 200) { if (res.status === 200) {
return res.json() return res.json()
} else { } else {
...@@ -38,7 +38,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData | ...@@ -38,7 +38,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData |
return null return null
} }
}) })
.catch((error) => { .catch(error => {
console.error('Failed to get claim data', error) console.error('Failed to get claim data', error)
})) }))
} }
...@@ -53,11 +53,11 @@ export function useUserClaimData(account: string | null | undefined): UserClaimD ...@@ -53,11 +53,11 @@ export function useUserClaimData(account: string | null | undefined): UserClaimD
useEffect(() => { useEffect(() => {
if (!account || !chainId) return if (!account || !chainId) return
fetchClaim(account, chainId).then((accountClaimInfo) => fetchClaim(account, chainId).then(accountClaimInfo =>
setClaimInfo((claimInfo) => { setClaimInfo(claimInfo => {
return { return {
...claimInfo, ...claimInfo,
[key]: accountClaimInfo, [key]: accountClaimInfo
} }
}) })
) )
...@@ -102,18 +102,18 @@ export function useClaimCallback( ...@@ -102,18 +102,18 @@ export function useClaimCallback(
const addTransaction = useTransactionAdder() const addTransaction = useTransactionAdder()
const distributorContract = useMerkleDistributorContract() const distributorContract = useMerkleDistributorContract()
const claimCallback = async function () { const claimCallback = async function() {
if (!claimData || !account || !library || !chainId || !distributorContract) return if (!claimData || !account || !library || !chainId || !distributorContract) return
const args = [claimData.index, account, claimData.amount, claimData.proof] const args = [claimData.index, account, claimData.amount, claimData.proof]
return distributorContract.estimateGas['claim'](...args, {}).then((estimatedGasLimit) => { return distributorContract.estimateGas['claim'](...args, {}).then(estimatedGasLimit => {
return distributorContract return distributorContract
.claim(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) }) .claim(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Claimed ${unClaimedAmount?.toSignificant(4)} UNI`, summary: `Claimed ${unClaimedAmount?.toSignificant(4)} UNI`,
claim: { recipient: account }, claim: { recipient: account }
}) })
return response.hash return response.hash
}) })
......
...@@ -63,7 +63,7 @@ export function useDataFromEventLogs() { ...@@ -63,7 +63,7 @@ export function useDataFromEventLogs() {
const pastEvents = await library?.getLogs(filter) const pastEvents = await library?.getLogs(filter)
// reverse events to get them from newest to odlest // reverse events to get them from newest to odlest
const formattedEventData = pastEvents const formattedEventData = pastEvents
?.map((event) => { ?.map(event => {
const eventParsed = eventParser.parseLog(event).args const eventParsed = eventParser.parseLog(event).args
return { return {
description: eventParsed.description, description: eventParsed.description,
...@@ -77,9 +77,9 @@ export function useDataFromEventLogs() { ...@@ -77,9 +77,9 @@ export function useDataFromEventLogs() {
return { return {
target, target,
functionSig: name, functionSig: name,
callData: decoded.join(', '), callData: decoded.join(', ')
} }
}), })
} }
}) })
.reverse() .reverse()
...@@ -132,7 +132,7 @@ export function useAllProposalData() { ...@@ -132,7 +132,7 @@ export function useAllProposalData() {
againstCount: parseFloat(ethers.utils.formatUnits(allProposals[i]?.result?.againstVotes.toString(), 18)), againstCount: parseFloat(ethers.utils.formatUnits(allProposals[i]?.result?.againstVotes.toString(), 18)),
startBlock: parseInt(allProposals[i]?.result?.startBlock?.toString()), startBlock: parseInt(allProposals[i]?.result?.startBlock?.toString()),
endBlock: parseInt(allProposals[i]?.result?.endBlock?.toString()), endBlock: parseInt(allProposals[i]?.result?.endBlock?.toString()),
details: formattedEvents[i].details, details: formattedEvents[i].details
} }
return formattedProposal return formattedProposal
}) })
...@@ -143,7 +143,7 @@ export function useAllProposalData() { ...@@ -143,7 +143,7 @@ export function useAllProposalData() {
export function useProposalData(id: string): ProposalData | undefined { export function useProposalData(id: string): ProposalData | undefined {
const allProposalData = useAllProposalData() const allProposalData = useAllProposalData()
return allProposalData?.find((p) => p.id === id) return allProposalData?.find(p => p.id === id)
} }
// get the users delegatee if it exists // get the users delegatee if it exists
...@@ -188,12 +188,12 @@ export function useDelegateCallback(): (delegatee: string | undefined) => undefi ...@@ -188,12 +188,12 @@ export function useDelegateCallback(): (delegatee: string | undefined) => undefi
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee] const args = [delegatee]
if (!uniContract) throw new Error('No UNI Contract!') if (!uniContract) throw new Error('No UNI Contract!')
return uniContract.estimateGas.delegate(...args, {}).then((estimatedGasLimit) => { return uniContract.estimateGas.delegate(...args, {}).then(estimatedGasLimit => {
return uniContract return uniContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) }) .delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Delegated votes`, summary: `Delegated votes`
}) })
return response.hash return response.hash
}) })
...@@ -215,12 +215,12 @@ export function useVoteCallback(): { ...@@ -215,12 +215,12 @@ export function useVoteCallback(): {
(proposalId: string | undefined, support: boolean) => { (proposalId: string | undefined, support: boolean) => {
if (!account || !govContract || !proposalId) return if (!account || !govContract || !proposalId) return
const args = [proposalId, support] const args = [proposalId, support]
return govContract.estimateGas.castVote(...args, {}).then((estimatedGasLimit) => { return govContract.estimateGas.castVote(...args, {}).then(estimatedGasLimit => {
return govContract return govContract
.castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) }) .castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => { .then((response: TransactionResponse) => {
addTransaction(response, { addTransaction(response, {
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`, summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`
}) })
return response.hash return response.hash
}) })
......
...@@ -22,10 +22,10 @@ const store = configureStore({ ...@@ -22,10 +22,10 @@ const store = configureStore({
mint, mint,
burn, burn,
multicall, multicall,
lists, lists
}, },
middleware: [...getDefaultMiddleware({ thunk: false }), save({ states: PERSISTED_KEYS })], middleware: [...getDefaultMiddleware({ thunk: false }), save({ states: PERSISTED_KEYS })],
preloadedState: load({ states: PERSISTED_KEYS }), preloadedState: load({ states: PERSISTED_KEYS })
}) })
store.dispatch(updateVersion()) store.dispatch(updateVersion())
......
...@@ -8,7 +8,7 @@ export const fetchTokenList: Readonly<{ ...@@ -8,7 +8,7 @@ export const fetchTokenList: Readonly<{
}> = { }> = {
pending: createAction('lists/fetchTokenList/pending'), pending: createAction('lists/fetchTokenList/pending'),
fulfilled: createAction('lists/fetchTokenList/fulfilled'), fulfilled: createAction('lists/fetchTokenList/fulfilled'),
rejected: createAction('lists/fetchTokenList/rejected'), rejected: createAction('lists/fetchTokenList/rejected')
} }
// add and remove from list options // add and remove from list options
export const addList = createAction<string>('lists/addList') export const addList = createAction<string>('lists/addList')
......
...@@ -41,7 +41,7 @@ const EMPTY_LIST: TokenAddressMap = { ...@@ -41,7 +41,7 @@ const EMPTY_LIST: TokenAddressMap = {
[ChainId.RINKEBY]: {}, [ChainId.RINKEBY]: {},
[ChainId.ROPSTEN]: {}, [ChainId.ROPSTEN]: {},
[ChainId.GÖRLI]: {}, [ChainId.GÖRLI]: {},
[ChainId.MAINNET]: {}, [ChainId.MAINNET]: {}
} }
const listCache: WeakMap<TokenList, TokenAddressMap> | null = const listCache: WeakMap<TokenList, TokenAddressMap> | null =
...@@ -55,7 +55,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap { ...@@ -55,7 +55,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
(tokenMap, tokenInfo) => { (tokenMap, tokenInfo) => {
const tags: TagInfo[] = const tags: TagInfo[] =
tokenInfo.tags tokenInfo.tags
?.map((tagId) => { ?.map(tagId => {
if (!list.tags?.[tagId]) return undefined if (!list.tags?.[tagId]) return undefined
return { ...list.tags[tagId], id: tagId } return { ...list.tags[tagId], id: tagId }
}) })
...@@ -68,9 +68,9 @@ export function listToTokenMap(list: TokenList): TokenAddressMap { ...@@ -68,9 +68,9 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
...tokenMap[token.chainId], ...tokenMap[token.chainId],
[token.address]: { [token.address]: {
token, token,
list: list, list: list
}, }
}, }
} }
}, },
{ ...EMPTY_LIST } { ...EMPTY_LIST }
...@@ -87,7 +87,7 @@ export function useAllLists(): { ...@@ -87,7 +87,7 @@ export function useAllLists(): {
readonly error: string | null readonly error: string | null
} }
} { } {
return useSelector<AppState, AppState['lists']['byUrl']>((state) => state.lists.byUrl) return useSelector<AppState, AppState['lists']['byUrl']>(state => state.lists.byUrl)
} }
function combineMaps(map1: TokenAddressMap, map2: TokenAddressMap): TokenAddressMap { function combineMaps(map1: TokenAddressMap, map2: TokenAddressMap): TokenAddressMap {
...@@ -96,7 +96,7 @@ function combineMaps(map1: TokenAddressMap, map2: TokenAddressMap): TokenAddress ...@@ -96,7 +96,7 @@ function combineMaps(map1: TokenAddressMap, map2: TokenAddressMap): TokenAddress
3: { ...map1[3], ...map2[3] }, 3: { ...map1[3], ...map2[3] },
4: { ...map1[4], ...map2[4] }, 4: { ...map1[4], ...map2[4] },
5: { ...map1[5], ...map2[5] }, 5: { ...map1[5], ...map2[5] },
42: { ...map1[42], ...map2[42] }, 42: { ...map1[42], ...map2[42] }
} }
} }
...@@ -129,15 +129,15 @@ function useCombinedTokenMapFromUrls(urls: string[] | undefined): TokenAddressMa ...@@ -129,15 +129,15 @@ function useCombinedTokenMapFromUrls(urls: string[] | undefined): TokenAddressMa
// filter out unsupported lists // filter out unsupported lists
export function useActiveListUrls(): string[] | undefined { export function useActiveListUrls(): string[] | undefined {
return useSelector<AppState, AppState['lists']['activeListUrls']>((state) => state.lists.activeListUrls)?.filter( return useSelector<AppState, AppState['lists']['activeListUrls']>(state => state.lists.activeListUrls)?.filter(
(url) => !UNSUPPORTED_LIST_URLS.includes(url) url => !UNSUPPORTED_LIST_URLS.includes(url)
) )
} }
export function useInactiveListUrls(): string[] { export function useInactiveListUrls(): string[] {
const lists = useAllLists() const lists = useAllLists()
const allActiveListUrls = useActiveListUrls() const allActiveListUrls = useActiveListUrls()
return Object.keys(lists).filter((url) => !allActiveListUrls?.includes(url) && !UNSUPPORTED_LIST_URLS.includes(url)) return Object.keys(lists).filter(url => !allActiveListUrls?.includes(url) && !UNSUPPORTED_LIST_URLS.includes(url))
} }
// get all the tokens from active lists, combine with local default tokens // get all the tokens from active lists, combine with local default tokens
......
...@@ -9,20 +9,20 @@ const STUB_TOKEN_LIST = { ...@@ -9,20 +9,20 @@ const STUB_TOKEN_LIST = {
name: '', name: '',
timestamp: '', timestamp: '',
version: { major: 1, minor: 1, patch: 1 }, version: { major: 1, minor: 1, patch: 1 },
tokens: [], tokens: []
} }
const PATCHED_STUB_LIST = { const PATCHED_STUB_LIST = {
...STUB_TOKEN_LIST, ...STUB_TOKEN_LIST,
version: { ...STUB_TOKEN_LIST.version, patch: STUB_TOKEN_LIST.version.patch + 1 }, version: { ...STUB_TOKEN_LIST.version, patch: STUB_TOKEN_LIST.version.patch + 1 }
} }
const MINOR_UPDATED_STUB_LIST = { const MINOR_UPDATED_STUB_LIST = {
...STUB_TOKEN_LIST, ...STUB_TOKEN_LIST,
version: { ...STUB_TOKEN_LIST.version, minor: STUB_TOKEN_LIST.version.minor + 1 }, version: { ...STUB_TOKEN_LIST.version, minor: STUB_TOKEN_LIST.version.minor + 1 }
} }
const MAJOR_UPDATED_STUB_LIST = { const MAJOR_UPDATED_STUB_LIST = {
...STUB_TOKEN_LIST, ...STUB_TOKEN_LIST,
version: { ...STUB_TOKEN_LIST.version, major: STUB_TOKEN_LIST.version.major + 1 }, version: { ...STUB_TOKEN_LIST.version, major: STUB_TOKEN_LIST.version.major + 1 }
} }
describe('list reducer', () => { describe('list reducer', () => {
...@@ -31,7 +31,7 @@ describe('list reducer', () => { ...@@ -31,7 +31,7 @@ describe('list reducer', () => {
beforeEach(() => { beforeEach(() => {
store = createStore(reducer, { store = createStore(reducer, {
byUrl: {}, byUrl: {},
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
...@@ -45,10 +45,10 @@ describe('list reducer', () => { ...@@ -45,10 +45,10 @@ describe('list reducer', () => {
error: null, error: null,
loadingRequestId: 'request-id', loadingRequestId: 'request-id',
current: null, current: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
selectedListUrl: undefined, selectedListUrl: undefined
}) })
}) })
...@@ -59,10 +59,10 @@ describe('list reducer', () => { ...@@ -59,10 +59,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
pendingUpdate: null, pendingUpdate: null,
loadingRequestId: null, loadingRequestId: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(fetchTokenList.pending({ requestId: 'request-id', url: 'fake-url' })) store.dispatch(fetchTokenList.pending({ requestId: 'request-id', url: 'fake-url' }))
...@@ -72,10 +72,10 @@ describe('list reducer', () => { ...@@ -72,10 +72,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: 'request-id', loadingRequestId: 'request-id',
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
}) })
...@@ -91,10 +91,10 @@ describe('list reducer', () => { ...@@ -91,10 +91,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
...@@ -111,10 +111,10 @@ describe('list reducer', () => { ...@@ -111,10 +111,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
...@@ -132,10 +132,10 @@ describe('list reducer', () => { ...@@ -132,10 +132,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
it('does not save to current if list is newer minor version', () => { it('does not save to current if list is newer minor version', () => {
...@@ -152,10 +152,10 @@ describe('list reducer', () => { ...@@ -152,10 +152,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: MINOR_UPDATED_STUB_LIST, pendingUpdate: MINOR_UPDATED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
it('does not save to pending if list is newer major version', () => { it('does not save to pending if list is newer major version', () => {
...@@ -172,10 +172,10 @@ describe('list reducer', () => { ...@@ -172,10 +172,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: MAJOR_UPDATED_STUB_LIST, pendingUpdate: MAJOR_UPDATED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
}) })
...@@ -185,7 +185,7 @@ describe('list reducer', () => { ...@@ -185,7 +185,7 @@ describe('list reducer', () => {
store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' })) store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' }))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
byUrl: {}, byUrl: {},
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
...@@ -196,10 +196,10 @@ describe('list reducer', () => { ...@@ -196,10 +196,10 @@ describe('list reducer', () => {
error: null, error: null,
current: null, current: null,
loadingRequestId: 'request-id', loadingRequestId: 'request-id',
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' })) store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' }))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -208,10 +208,10 @@ describe('list reducer', () => { ...@@ -208,10 +208,10 @@ describe('list reducer', () => {
error: 'abcd', error: 'abcd',
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
}) })
...@@ -226,10 +226,10 @@ describe('list reducer', () => { ...@@ -226,10 +226,10 @@ describe('list reducer', () => {
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
it('no op for existing list', () => { it('no op for existing list', () => {
...@@ -239,10 +239,10 @@ describe('list reducer', () => { ...@@ -239,10 +239,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(addList('fake-url')) store.dispatch(addList('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -251,10 +251,10 @@ describe('list reducer', () => { ...@@ -251,10 +251,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
}) })
...@@ -267,10 +267,10 @@ describe('list reducer', () => { ...@@ -267,10 +267,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(acceptListUpdate('fake-url')) store.dispatch(acceptListUpdate('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -279,10 +279,10 @@ describe('list reducer', () => { ...@@ -279,10 +279,10 @@ describe('list reducer', () => {
error: null, error: null,
current: PATCHED_STUB_LIST, current: PATCHED_STUB_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
}) })
...@@ -295,15 +295,15 @@ describe('list reducer', () => { ...@@ -295,15 +295,15 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(removeList('fake-url')) store.dispatch(removeList('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
byUrl: {}, byUrl: {},
activeListUrls: undefined, activeListUrls: undefined
}) })
}) })
it('Removes from active lists if active list is removed', () => { it('Removes from active lists if active list is removed', () => {
...@@ -313,15 +313,15 @@ describe('list reducer', () => { ...@@ -313,15 +313,15 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: ['fake-url'], activeListUrls: ['fake-url']
}) })
store.dispatch(removeList('fake-url')) store.dispatch(removeList('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
byUrl: {}, byUrl: {},
activeListUrls: [], activeListUrls: []
}) })
}) })
}) })
...@@ -334,10 +334,10 @@ describe('list reducer', () => { ...@@ -334,10 +334,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(enableList('fake-url')) store.dispatch(enableList('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -346,10 +346,10 @@ describe('list reducer', () => { ...@@ -346,10 +346,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: ['fake-url'], activeListUrls: ['fake-url']
}) })
}) })
it('adds to url keys if not present already on enable', () => { it('adds to url keys if not present already on enable', () => {
...@@ -359,10 +359,10 @@ describe('list reducer', () => { ...@@ -359,10 +359,10 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(enableList('fake-url-invalid')) store.dispatch(enableList('fake-url-invalid'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -371,16 +371,16 @@ describe('list reducer', () => { ...@@ -371,16 +371,16 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST, pendingUpdate: PATCHED_STUB_LIST
}, },
'fake-url-invalid': { 'fake-url-invalid': {
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: ['fake-url-invalid'], activeListUrls: ['fake-url-invalid']
}) })
}) })
it('enable works if list already added', () => { it('enable works if list already added', () => {
...@@ -390,10 +390,10 @@ describe('list reducer', () => { ...@@ -390,10 +390,10 @@ describe('list reducer', () => {
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(enableList('fake-url')) store.dispatch(enableList('fake-url'))
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -402,10 +402,10 @@ describe('list reducer', () => { ...@@ -402,10 +402,10 @@ describe('list reducer', () => {
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: ['fake-url'], activeListUrls: ['fake-url']
}) })
}) })
}) })
...@@ -419,16 +419,16 @@ describe('list reducer', () => { ...@@ -419,16 +419,16 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, },
'https://unpkg.com/@uniswap/default-token-list@latest': { 'https://unpkg.com/@uniswap/default-token-list@latest': {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined
}) })
store.dispatch(updateVersion()) store.dispatch(updateVersion())
}) })
...@@ -445,12 +445,12 @@ describe('list reducer', () => { ...@@ -445,12 +445,12 @@ describe('list reducer', () => {
}) })
it('all lists are empty', () => { it('all lists are empty', () => {
const s = store.getState() const s = store.getState()
Object.keys(s.byUrl).forEach((url) => { Object.keys(s.byUrl).forEach(url => {
expect(s.byUrl[url]).toEqual({ expect(s.byUrl[url]).toEqual({
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}) })
}) })
}) })
...@@ -469,17 +469,17 @@ describe('list reducer', () => { ...@@ -469,17 +469,17 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, },
'https://unpkg.com/@uniswap/default-token-list@latest': { 'https://unpkg.com/@uniswap/default-token-list@latest': {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}, }
}, },
activeListUrls: undefined, activeListUrls: undefined,
lastInitializedDefaultListOfLists: ['https://unpkg.com/@uniswap/default-token-list@latest'], lastInitializedDefaultListOfLists: ['https://unpkg.com/@uniswap/default-token-list@latest']
}) })
store.dispatch(updateVersion()) store.dispatch(updateVersion())
}) })
...@@ -491,7 +491,7 @@ describe('list reducer', () => { ...@@ -491,7 +491,7 @@ describe('list reducer', () => {
error: null, error: null,
current: STUB_TOKEN_LIST, current: STUB_TOKEN_LIST,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}) })
}) })
it('removes lists in the last initialized list of lists', () => { it('removes lists in the last initialized list of lists', () => {
...@@ -502,13 +502,13 @@ describe('list reducer', () => { ...@@ -502,13 +502,13 @@ describe('list reducer', () => {
const byUrl = store.getState().byUrl const byUrl = store.getState().byUrl
// note we don't expect the uniswap default list to be prepopulated // note we don't expect the uniswap default list to be prepopulated
// this is ok. // this is ok.
Object.keys(byUrl).forEach((url) => { Object.keys(byUrl).forEach(url => {
if (url !== 'https://unpkg.com/@uniswap/default-token-list@latest/uniswap-default.tokenlist.json') { if (url !== 'https://unpkg.com/@uniswap/default-token-list@latest/uniswap-default.tokenlist.json') {
expect(byUrl[url]).toEqual({ expect(byUrl[url]).toEqual({
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
}) })
} }
}) })
......
...@@ -28,7 +28,7 @@ const NEW_LIST_STATE: ListState = { ...@@ -28,7 +28,7 @@ const NEW_LIST_STATE: ListState = {
error: null, error: null,
current: null, current: null,
loadingRequestId: null, loadingRequestId: null,
pendingUpdate: null, pendingUpdate: null
} }
type Mutable<T> = { -readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? U[] : T[P] } type Mutable<T> = { -readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? U[] : T[P] }
...@@ -39,12 +39,12 @@ const initialState: ListsState = { ...@@ -39,12 +39,12 @@ const initialState: ListsState = {
...DEFAULT_LIST_OF_LISTS.reduce<Mutable<ListsState['byUrl']>>((memo, listUrl) => { ...DEFAULT_LIST_OF_LISTS.reduce<Mutable<ListsState['byUrl']>>((memo, listUrl) => {
memo[listUrl] = NEW_LIST_STATE memo[listUrl] = NEW_LIST_STATE
return memo return memo
}, {}), }, {})
}, },
activeListUrls: DEFAULT_ACTIVE_LIST_URLS, activeListUrls: DEFAULT_ACTIVE_LIST_URLS
} }
export default createReducer(initialState, (builder) => export default createReducer(initialState, builder =>
builder builder
.addCase(fetchTokenList.pending, (state, { payload: { requestId, url } }) => { .addCase(fetchTokenList.pending, (state, { payload: { requestId, url } }) => {
state.byUrl[url] = { state.byUrl[url] = {
...@@ -52,7 +52,7 @@ export default createReducer(initialState, (builder) => ...@@ -52,7 +52,7 @@ export default createReducer(initialState, (builder) =>
pendingUpdate: null, pendingUpdate: null,
...state.byUrl[url], ...state.byUrl[url],
loadingRequestId: requestId, loadingRequestId: requestId,
error: null, error: null
} }
}) })
.addCase(fetchTokenList.fulfilled, (state, { payload: { requestId, tokenList, url } }) => { .addCase(fetchTokenList.fulfilled, (state, { payload: { requestId, tokenList, url } }) => {
...@@ -70,7 +70,7 @@ export default createReducer(initialState, (builder) => ...@@ -70,7 +70,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null, loadingRequestId: null,
error: null, error: null,
current: current, current: current,
pendingUpdate: tokenList, pendingUpdate: tokenList
} }
} }
} else { } else {
...@@ -84,7 +84,7 @@ export default createReducer(initialState, (builder) => ...@@ -84,7 +84,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null, loadingRequestId: null,
error: null, error: null,
current: tokenList, current: tokenList,
pendingUpdate: null, pendingUpdate: null
} }
} }
}) })
...@@ -99,7 +99,7 @@ export default createReducer(initialState, (builder) => ...@@ -99,7 +99,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null, loadingRequestId: null,
error: errorMessage, error: errorMessage,
current: null, current: null,
pendingUpdate: null, pendingUpdate: null
} }
}) })
.addCase(addList, (state, { payload: url }) => { .addCase(addList, (state, { payload: url }) => {
...@@ -113,7 +113,7 @@ export default createReducer(initialState, (builder) => ...@@ -113,7 +113,7 @@ export default createReducer(initialState, (builder) =>
} }
// remove list from active urls if needed // remove list from active urls if needed
if (state.activeListUrls && state.activeListUrls.includes(url)) { if (state.activeListUrls && state.activeListUrls.includes(url)) {
state.activeListUrls = state.activeListUrls.filter((u) => u !== url) state.activeListUrls = state.activeListUrls.filter(u => u !== url)
} }
}) })
.addCase(enableList, (state, { payload: url }) => { .addCase(enableList, (state, { payload: url }) => {
...@@ -131,7 +131,7 @@ export default createReducer(initialState, (builder) => ...@@ -131,7 +131,7 @@ export default createReducer(initialState, (builder) =>
}) })
.addCase(disableList, (state, { payload: url }) => { .addCase(disableList, (state, { payload: url }) => {
if (state.activeListUrls && state.activeListUrls.includes(url)) { if (state.activeListUrls && state.activeListUrls.includes(url)) {
state.activeListUrls = state.activeListUrls.filter((u) => u !== url) state.activeListUrls = state.activeListUrls.filter(u => u !== url)
} }
}) })
.addCase(acceptListUpdate, (state, { payload: url }) => { .addCase(acceptListUpdate, (state, { payload: url }) => {
...@@ -141,10 +141,10 @@ export default createReducer(initialState, (builder) => ...@@ -141,10 +141,10 @@ export default createReducer(initialState, (builder) =>
state.byUrl[url] = { state.byUrl[url] = {
...state.byUrl[url], ...state.byUrl[url],
pendingUpdate: null, pendingUpdate: null,
current: state.byUrl[url].pendingUpdate, current: state.byUrl[url].pendingUpdate
} }
}) })
.addCase(updateVersion, (state) => { .addCase(updateVersion, state => {
// state loaded from localStorage, but new lists have never been initialized // state loaded from localStorage, but new lists have never been initialized
if (!state.lastInitializedDefaultListOfLists) { if (!state.lastInitializedDefaultListOfLists) {
state.byUrl = initialState.byUrl state.byUrl = initialState.byUrl
...@@ -156,13 +156,13 @@ export default createReducer(initialState, (builder) => ...@@ -156,13 +156,13 @@ export default createReducer(initialState, (builder) =>
) )
const newListOfListsSet = DEFAULT_LIST_OF_LISTS.reduce<Set<string>>((s, l) => s.add(l), new Set()) const newListOfListsSet = DEFAULT_LIST_OF_LISTS.reduce<Set<string>>((s, l) => s.add(l), new Set())
DEFAULT_LIST_OF_LISTS.forEach((listUrl) => { DEFAULT_LIST_OF_LISTS.forEach(listUrl => {
if (!lastInitializedSet.has(listUrl)) { if (!lastInitializedSet.has(listUrl)) {
state.byUrl[listUrl] = NEW_LIST_STATE state.byUrl[listUrl] = NEW_LIST_STATE
} }
}) })
state.lastInitializedDefaultListOfLists.forEach((listUrl) => { state.lastInitializedDefaultListOfLists.forEach(listUrl => {
if (!newListOfListsSet.has(listUrl)) { if (!newListOfListsSet.has(listUrl)) {
delete state.byUrl[listUrl] delete state.byUrl[listUrl]
} }
......
...@@ -26,8 +26,8 @@ export default function Updater(): null { ...@@ -26,8 +26,8 @@ export default function Updater(): null {
const fetchList = useFetchListCallback() const fetchList = useFetchListCallback()
const fetchAllListsCallback = useCallback(() => { const fetchAllListsCallback = useCallback(() => {
if (!isWindowVisible) return if (!isWindowVisible) return
Object.keys(lists).forEach((url) => Object.keys(lists).forEach(url =>
fetchList(url).catch((error) => console.debug('interval list fetching error', error)) fetchList(url).catch(error => console.debug('interval list fetching error', error))
) )
}, [fetchList, isWindowVisible, lists]) }, [fetchList, isWindowVisible, lists])
...@@ -36,17 +36,17 @@ export default function Updater(): null { ...@@ -36,17 +36,17 @@ export default function Updater(): null {
// whenever a list is not loaded and not loading, try again to load it // whenever a list is not loaded and not loading, try again to load it
useEffect(() => { useEffect(() => {
Object.keys(lists).forEach((listUrl) => { Object.keys(lists).forEach(listUrl => {
const list = lists[listUrl] const list = lists[listUrl]
if (!list.current && !list.loadingRequestId && !list.error) { if (!list.current && !list.loadingRequestId && !list.error) {
fetchList(listUrl).catch((error) => console.debug('list added fetching error', error)) fetchList(listUrl).catch(error => console.debug('list added fetching error', error))
} }
}) })
}, [dispatch, fetchList, library, lists]) }, [dispatch, fetchList, library, lists])
// automatically update lists if versions are minor/patch // automatically update lists if versions are minor/patch
useEffect(() => { useEffect(() => {
Object.keys(lists).forEach((listUrl) => { Object.keys(lists).forEach(listUrl => {
const list = lists[listUrl] const list = lists[listUrl]
if (list.current && list.pendingUpdate) { if (list.current && list.pendingUpdate) {
const bump = getVersionUpgrade(list.current.version, list.pendingUpdate.version) const bump = getVersionUpgrade(list.current.version, list.pendingUpdate.version)
......
...@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit' ...@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit'
export enum Field { export enum Field {
CURRENCY_A = 'CURRENCY_A', CURRENCY_A = 'CURRENCY_A',
CURRENCY_B = 'CURRENCY_B', CURRENCY_B = 'CURRENCY_B'
} }
export const typeInput = createAction<{ field: Field; typedValue: string; noLiquidity: boolean }>('mint/typeInputMint') export const typeInput = createAction<{ field: Field; typedValue: string; noLiquidity: boolean }>('mint/typeInputMint')
......
...@@ -14,7 +14,7 @@ import { Field, typeInput } from './actions' ...@@ -14,7 +14,7 @@ import { Field, typeInput } from './actions'
const ZERO = JSBI.BigInt(0) const ZERO = JSBI.BigInt(0)
export function useMintState(): AppState['mint'] { export function useMintState(): AppState['mint'] {
return useSelector<AppState, AppState['mint']>((state) => state.mint) return useSelector<AppState, AppState['mint']>(state => state.mint)
} }
export function useMintActionHandlers( export function useMintActionHandlers(
...@@ -40,7 +40,7 @@ export function useMintActionHandlers( ...@@ -40,7 +40,7 @@ export function useMintActionHandlers(
return { return {
onFieldAInput, onFieldAInput,
onFieldBInput, onFieldBInput
} }
} }
...@@ -70,7 +70,7 @@ export function useDerivedMintInfo( ...@@ -70,7 +70,7 @@ export function useDerivedMintInfo(
const currencies: { [field in Field]?: Currency } = useMemo( const currencies: { [field in Field]?: Currency } = useMemo(
() => ({ () => ({
[Field.CURRENCY_A]: currencyA ?? undefined, [Field.CURRENCY_A]: currencyA ?? undefined,
[Field.CURRENCY_B]: currencyB ?? undefined, [Field.CURRENCY_B]: currencyB ?? undefined
}), }),
[currencyA, currencyB] [currencyA, currencyB]
) )
...@@ -85,11 +85,11 @@ export function useDerivedMintInfo( ...@@ -85,11 +85,11 @@ export function useDerivedMintInfo(
// balances // balances
const balances = useCurrencyBalances(account ?? undefined, [ const balances = useCurrencyBalances(account ?? undefined, [
currencies[Field.CURRENCY_A], currencies[Field.CURRENCY_A],
currencies[Field.CURRENCY_B], currencies[Field.CURRENCY_B]
]) ])
const currencyBalances: { [field in Field]?: CurrencyAmount } = { const currencyBalances: { [field in Field]?: CurrencyAmount } = {
[Field.CURRENCY_A]: balances[0], [Field.CURRENCY_A]: balances[0],
[Field.CURRENCY_B]: balances[1], [Field.CURRENCY_B]: balances[1]
} }
// amounts // amounts
...@@ -119,7 +119,7 @@ export function useDerivedMintInfo( ...@@ -119,7 +119,7 @@ export function useDerivedMintInfo(
}, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, chainId, currencyB, pair]) }, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, chainId, currencyB, pair])
const parsedAmounts: { [field in Field]: CurrencyAmount | undefined } = { const parsedAmounts: { [field in Field]: CurrencyAmount | undefined } = {
[Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount, [Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount,
[Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount, [Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount
} }
const price = useMemo(() => { const price = useMemo(() => {
...@@ -140,7 +140,7 @@ export function useDerivedMintInfo( ...@@ -140,7 +140,7 @@ export function useDerivedMintInfo(
const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts
const [tokenAmountA, tokenAmountB] = [ const [tokenAmountA, tokenAmountB] = [
wrappedCurrencyAmount(currencyAAmount, chainId), wrappedCurrencyAmount(currencyAAmount, chainId),
wrappedCurrencyAmount(currencyBAmount, chainId), wrappedCurrencyAmount(currencyBAmount, chainId)
] ]
if (pair && totalSupply && tokenAmountA && tokenAmountB) { if (pair && totalSupply && tokenAmountA && tokenAmountB) {
return pair.getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) return pair.getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB)
...@@ -191,6 +191,6 @@ export function useDerivedMintInfo( ...@@ -191,6 +191,6 @@ export function useDerivedMintInfo(
noLiquidity, noLiquidity,
liquidityMinted, liquidityMinted,
poolTokenPercentage, poolTokenPercentage,
error, error
} }
} }
...@@ -10,7 +10,7 @@ describe('mint reducer', () => { ...@@ -10,7 +10,7 @@ describe('mint reducer', () => {
store = createStore(reducer, { store = createStore(reducer, {
independentField: Field.CURRENCY_A, independentField: Field.CURRENCY_A,
typedValue: '', typedValue: '',
otherTypedValue: '', otherTypedValue: ''
}) })
}) })
......
...@@ -10,10 +10,10 @@ export interface MintState { ...@@ -10,10 +10,10 @@ export interface MintState {
const initialState: MintState = { const initialState: MintState = {
independentField: Field.CURRENCY_A, independentField: Field.CURRENCY_A,
typedValue: '', typedValue: '',
otherTypedValue: '', otherTypedValue: ''
} }
export default createReducer<MintState>(initialState, (builder) => export default createReducer<MintState>(initialState, builder =>
builder builder
.addCase(resetMintState, () => initialState) .addCase(resetMintState, () => initialState)
.addCase(typeInput, (state, { payload: { field, typedValue, noLiquidity } }) => { .addCase(typeInput, (state, { payload: { field, typedValue, noLiquidity } }) => {
...@@ -23,7 +23,7 @@ export default createReducer<MintState>(initialState, (builder) => ...@@ -23,7 +23,7 @@ export default createReducer<MintState>(initialState, (builder) =>
return { return {
...state, ...state,
independentField: field, independentField: field,
typedValue, typedValue
} }
} }
// they're typing into a new field, store the other value // they're typing into a new field, store the other value
...@@ -32,7 +32,7 @@ export default createReducer<MintState>(initialState, (builder) => ...@@ -32,7 +32,7 @@ export default createReducer<MintState>(initialState, (builder) =>
...state, ...state,
independentField: field, independentField: field,
typedValue, typedValue,
otherTypedValue: state.typedValue, otherTypedValue: state.typedValue
} }
} }
} else { } else {
...@@ -40,7 +40,7 @@ export default createReducer<MintState>(initialState, (builder) => ...@@ -40,7 +40,7 @@ export default createReducer<MintState>(initialState, (builder) =>
...state, ...state,
independentField: field, independentField: field,
typedValue, typedValue,
otherTypedValue: '', otherTypedValue: ''
} }
} }
}) })
......
...@@ -8,7 +8,7 @@ describe('actions', () => { ...@@ -8,7 +8,7 @@ describe('actions', () => {
it('does not throw for invalid calldata', () => { it('does not throw for invalid calldata', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-abc')).toEqual({ expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-abc')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f', address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: 'abc', callData: 'abc'
}) })
}) })
it('throws for invalid format', () => { it('throws for invalid format', () => {
...@@ -17,13 +17,13 @@ describe('actions', () => { ...@@ -17,13 +17,13 @@ describe('actions', () => {
it('throws for uppercase calldata', () => { it('throws for uppercase calldata', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcD')).toEqual({ expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcD')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f', address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcD', callData: '0xabcD'
}) })
}) })
it('parses pieces into address', () => { it('parses pieces into address', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcd')).toEqual({ expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcd')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f', address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcd', callData: '0xabcd'
}) })
}) })
}) })
...@@ -36,7 +36,7 @@ describe('actions', () => { ...@@ -36,7 +36,7 @@ describe('actions', () => {
expect(() => expect(() =>
toCallKey({ toCallKey({
address: '0x6b175474e89094c44da98b954eedeac495271d0f', address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: 'abc', callData: 'abc'
}) })
).toThrow('Invalid hex: abc') ).toThrow('Invalid hex: abc')
}) })
...@@ -44,7 +44,7 @@ describe('actions', () => { ...@@ -44,7 +44,7 @@ describe('actions', () => {
expect(() => expect(() =>
toCallKey({ toCallKey({
address: '0x6b175474e89094c44da98b954eedeac495271d0f', address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcD', callData: '0xabcD'
}) })
).toThrow('Invalid hex: 0xabcD') ).toThrow('Invalid hex: 0xabcD')
}) })
......
...@@ -24,7 +24,7 @@ export function parseCallKey(callKey: string): Call { ...@@ -24,7 +24,7 @@ export function parseCallKey(callKey: string): Call {
} }
return { return {
address: pcs[0], address: pcs[0],
callData: pcs[1], callData: pcs[1]
} }
} }
......
...@@ -12,7 +12,7 @@ import { ...@@ -12,7 +12,7 @@ import {
removeMulticallListeners, removeMulticallListeners,
parseCallKey, parseCallKey,
toCallKey, toCallKey,
ListenerOptions, ListenerOptions
} from './actions' } from './actions'
export interface Result extends ReadonlyArray<any> { export interface Result extends ReadonlyArray<any> {
...@@ -31,7 +31,7 @@ function isMethodArg(x: unknown): x is MethodArg { ...@@ -31,7 +31,7 @@ function isMethodArg(x: unknown): x is MethodArg {
function isValidMethodArgs(x: unknown): x is MethodArgs | undefined { function isValidMethodArgs(x: unknown): x is MethodArgs | undefined {
return ( return (
x === undefined || x === undefined ||
(Array.isArray(x) && x.every((xi) => isMethodArg(xi) || (Array.isArray(xi) && xi.every(isMethodArg)))) (Array.isArray(x) && x.every(xi => isMethodArg(xi) || (Array.isArray(xi) && xi.every(isMethodArg))))
) )
} }
...@@ -45,15 +45,13 @@ const INVALID_RESULT: CallResult = { valid: false, blockNumber: undefined, data: ...@@ -45,15 +45,13 @@ const INVALID_RESULT: CallResult = { valid: false, blockNumber: undefined, data:
// use this options object // use this options object
export const NEVER_RELOAD: ListenerOptions = { export const NEVER_RELOAD: ListenerOptions = {
blocksPerFetch: Infinity, blocksPerFetch: Infinity
} }
// the lowest level call for subscribing to contract data // the lowest level call for subscribing to contract data
function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): CallResult[] { function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): CallResult[] {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const callResults = useSelector<AppState, AppState['multicall']['callResults']>( const callResults = useSelector<AppState, AppState['multicall']['callResults']>(state => state.multicall.callResults)
(state) => state.multicall.callResults
)
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const serializedCallKeys: string = useMemo( const serializedCallKeys: string = useMemo(
...@@ -71,12 +69,12 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C ...@@ -71,12 +69,12 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
useEffect(() => { useEffect(() => {
const callKeys: string[] = JSON.parse(serializedCallKeys) const callKeys: string[] = JSON.parse(serializedCallKeys)
if (!chainId || callKeys.length === 0) return undefined if (!chainId || callKeys.length === 0) return undefined
const calls = callKeys.map((key) => parseCallKey(key)) const calls = callKeys.map(key => parseCallKey(key))
dispatch( dispatch(
addMulticallListeners({ addMulticallListeners({
chainId, chainId,
calls, calls,
options, options
}) })
) )
...@@ -85,7 +83,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C ...@@ -85,7 +83,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
removeMulticallListeners({ removeMulticallListeners({
chainId, chainId,
calls, calls,
options, options
}) })
) )
} }
...@@ -93,7 +91,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C ...@@ -93,7 +91,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
return useMemo( return useMemo(
() => () =>
calls.map<CallResult>((call) => { calls.map<CallResult>(call => {
if (!chainId || !call) return INVALID_RESULT if (!chainId || !call) return INVALID_RESULT
const result = callResults[chainId]?.[toCallKey(call)] const result = callResults[chainId]?.[toCallKey(call)]
...@@ -147,7 +145,7 @@ function toCallState( ...@@ -147,7 +145,7 @@ function toCallState(
loading: false, loading: false,
error: true, error: true,
syncing, syncing,
result, result
} }
} }
} }
...@@ -156,7 +154,7 @@ function toCallState( ...@@ -156,7 +154,7 @@ function toCallState(
loading: false, loading: false,
syncing, syncing,
result: result, result: result,
error: !success, error: !success
} }
} }
...@@ -171,10 +169,10 @@ export function useSingleContractMultipleData( ...@@ -171,10 +169,10 @@ export function useSingleContractMultipleData(
const calls = useMemo( const calls = useMemo(
() => () =>
contract && fragment && callInputs && callInputs.length > 0 contract && fragment && callInputs && callInputs.length > 0
? callInputs.map<Call>((inputs) => { ? callInputs.map<Call>(inputs => {
return { return {
address: contract.address, address: contract.address,
callData: contract.interface.encodeFunctionData(fragment, inputs), callData: contract.interface.encodeFunctionData(fragment, inputs)
} }
}) })
: [], : [],
...@@ -186,7 +184,7 @@ export function useSingleContractMultipleData( ...@@ -186,7 +184,7 @@ export function useSingleContractMultipleData(
const latestBlockNumber = useBlockNumber() const latestBlockNumber = useBlockNumber()
return useMemo(() => { return useMemo(() => {
return results.map((result) => toCallState(result, contract?.interface, fragment, latestBlockNumber)) return results.map(result => toCallState(result, contract?.interface, fragment, latestBlockNumber))
}, [fragment, contract, results, latestBlockNumber]) }, [fragment, contract, results, latestBlockNumber])
} }
...@@ -209,11 +207,11 @@ export function useMultipleContractSingleData( ...@@ -209,11 +207,11 @@ export function useMultipleContractSingleData(
const calls = useMemo( const calls = useMemo(
() => () =>
fragment && addresses && addresses.length > 0 && callData fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => { ? addresses.map<Call | undefined>(address => {
return address && callData return address && callData
? { ? {
address, address,
callData, callData
} }
: undefined : undefined
}) })
...@@ -226,7 +224,7 @@ export function useMultipleContractSingleData( ...@@ -226,7 +224,7 @@ export function useMultipleContractSingleData(
const latestBlockNumber = useBlockNumber() const latestBlockNumber = useBlockNumber()
return useMemo(() => { return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, latestBlockNumber)) return results.map(result => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber]) }, [fragment, results, contractInterface, latestBlockNumber])
} }
...@@ -243,8 +241,8 @@ export function useSingleCallResult( ...@@ -243,8 +241,8 @@ export function useSingleCallResult(
? [ ? [
{ {
address: contract.address, address: contract.address,
callData: contract.interface.encodeFunctionData(fragment, inputs), callData: contract.interface.encodeFunctionData(fragment, inputs)
}, }
] ]
: [] : []
}, [contract, fragment, inputs]) }, [contract, fragment, inputs])
......
...@@ -3,7 +3,7 @@ import { ...@@ -3,7 +3,7 @@ import {
errorFetchingMulticallResults, errorFetchingMulticallResults,
fetchingMulticallResults, fetchingMulticallResults,
removeMulticallListeners, removeMulticallListeners,
updateMulticallResults, updateMulticallResults
} from './actions' } from './actions'
import reducer, { MulticallState } from './reducer' import reducer, { MulticallState } from './reducer'
import { Store, createStore } from '@reduxjs/toolkit' import { Store, createStore } from '@reduxjs/toolkit'
...@@ -29,20 +29,20 @@ describe('multicall reducer', () => { ...@@ -29,20 +29,20 @@ describe('multicall reducer', () => {
calls: [ calls: [
{ {
address: DAI_ADDRESS, address: DAI_ADDRESS,
callData: '0x', callData: '0x'
}, }
], ]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callListeners: { callListeners: {
[1]: { [1]: {
[`${DAI_ADDRESS}-0x`]: { [`${DAI_ADDRESS}-0x`]: {
[1]: 1, [1]: 1
}, }
}
}, },
}, callResults: {}
callResults: {},
}) })
}) })
}) })
...@@ -54,10 +54,10 @@ describe('multicall reducer', () => { ...@@ -54,10 +54,10 @@ describe('multicall reducer', () => {
calls: [ calls: [
{ {
address: DAI_ADDRESS, address: DAI_ADDRESS,
callData: '0x', callData: '0x'
}, }
], ],
chainId: 1, chainId: 1
}) })
) )
expect(store.getState()).toEqual({ callResults: {}, callListeners: {} }) expect(store.getState()).toEqual({ callResults: {}, callListeners: {} })
...@@ -69,9 +69,9 @@ describe('multicall reducer', () => { ...@@ -69,9 +69,9 @@ describe('multicall reducer', () => {
calls: [ calls: [
{ {
address: DAI_ADDRESS, address: DAI_ADDRESS,
callData: '0x', callData: '0x'
}, }
], ]
}) })
) )
store.dispatch( store.dispatch(
...@@ -79,15 +79,15 @@ describe('multicall reducer', () => { ...@@ -79,15 +79,15 @@ describe('multicall reducer', () => {
calls: [ calls: [
{ {
address: DAI_ADDRESS, address: DAI_ADDRESS,
callData: '0x', callData: '0x'
}, }
], ],
chainId: 1, chainId: 1
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: {}, callResults: {},
callListeners: { [1]: { [`${DAI_ADDRESS}-0x`]: {} } }, callListeners: { [1]: { [`${DAI_ADDRESS}-0x`]: {} } }
}) })
}) })
}) })
...@@ -99,8 +99,8 @@ describe('multicall reducer', () => { ...@@ -99,8 +99,8 @@ describe('multicall reducer', () => {
chainId: 1, chainId: 1,
blockNumber: 1, blockNumber: 1,
results: { results: {
abc: '0x', abc: '0x'
}, }
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -108,10 +108,10 @@ describe('multicall reducer', () => { ...@@ -108,10 +108,10 @@ describe('multicall reducer', () => {
[1]: { [1]: {
abc: { abc: {
blockNumber: 1, blockNumber: 1,
data: '0x', data: '0x'
}, }
}, }
}, }
}) })
}) })
it('updates old data', () => { it('updates old data', () => {
...@@ -120,8 +120,8 @@ describe('multicall reducer', () => { ...@@ -120,8 +120,8 @@ describe('multicall reducer', () => {
chainId: 1, chainId: 1,
blockNumber: 1, blockNumber: 1,
results: { results: {
abc: '0x', abc: '0x'
}, }
}) })
) )
store.dispatch( store.dispatch(
...@@ -129,8 +129,8 @@ describe('multicall reducer', () => { ...@@ -129,8 +129,8 @@ describe('multicall reducer', () => {
chainId: 1, chainId: 1,
blockNumber: 2, blockNumber: 2,
results: { results: {
abc: '0x2', abc: '0x2'
}, }
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -138,10 +138,10 @@ describe('multicall reducer', () => { ...@@ -138,10 +138,10 @@ describe('multicall reducer', () => {
[1]: { [1]: {
abc: { abc: {
blockNumber: 2, blockNumber: 2,
data: '0x2', data: '0x2'
}, }
}, }
}, }
}) })
}) })
it('ignores late updates', () => { it('ignores late updates', () => {
...@@ -150,8 +150,8 @@ describe('multicall reducer', () => { ...@@ -150,8 +150,8 @@ describe('multicall reducer', () => {
chainId: 1, chainId: 1,
blockNumber: 2, blockNumber: 2,
results: { results: {
abc: '0x2', abc: '0x2'
}, }
}) })
) )
store.dispatch( store.dispatch(
...@@ -159,8 +159,8 @@ describe('multicall reducer', () => { ...@@ -159,8 +159,8 @@ describe('multicall reducer', () => {
chainId: 1, chainId: 1,
blockNumber: 1, blockNumber: 1,
results: { results: {
abc: '0x1', abc: '0x1'
}, }
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -168,10 +168,10 @@ describe('multicall reducer', () => { ...@@ -168,10 +168,10 @@ describe('multicall reducer', () => {
[1]: { [1]: {
abc: { abc: {
blockNumber: 2, blockNumber: 2,
data: '0x2', data: '0x2'
}, }
}, }
}, }
}) })
}) })
}) })
...@@ -181,15 +181,15 @@ describe('multicall reducer', () => { ...@@ -181,15 +181,15 @@ describe('multicall reducer', () => {
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: { callResults: {
[1]: { [1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }, [`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }
}, }
}, }
}) })
}) })
...@@ -198,22 +198,22 @@ describe('multicall reducer', () => { ...@@ -198,22 +198,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
store.dispatch( store.dispatch(
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 3, fetchingBlockNumber: 3,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: { callResults: {
[1]: { [1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }, [`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }
}, }
}, }
}) })
}) })
...@@ -222,22 +222,22 @@ describe('multicall reducer', () => { ...@@ -222,22 +222,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
store.dispatch( store.dispatch(
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 1, fetchingBlockNumber: 1,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: { callResults: {
[1]: { [1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }, [`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }
}, }
}, }
}) })
}) })
}) })
...@@ -248,13 +248,13 @@ describe('multicall reducer', () => { ...@@ -248,13 +248,13 @@ describe('multicall reducer', () => {
errorFetchingMulticallResults({ errorFetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 1, fetchingBlockNumber: 1,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: { callResults: {
[1]: {}, [1]: {}
}, }
}) })
}) })
it('updates block number if we were fetching', () => { it('updates block number if we were fetching', () => {
...@@ -262,14 +262,14 @@ describe('multicall reducer', () => { ...@@ -262,14 +262,14 @@ describe('multicall reducer', () => {
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
store.dispatch( store.dispatch(
errorFetchingMulticallResults({ errorFetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
...@@ -278,10 +278,10 @@ describe('multicall reducer', () => { ...@@ -278,10 +278,10 @@ describe('multicall reducer', () => {
[`${DAI_ADDRESS}-0x0`]: { [`${DAI_ADDRESS}-0x0`]: {
blockNumber: 2, blockNumber: 2,
// null data indicates error // null data indicates error
data: null, data: null
}, }
}, }
}, }
}) })
}) })
it('does nothing if not errored on latest block', () => { it('does nothing if not errored on latest block', () => {
...@@ -289,22 +289,22 @@ describe('multicall reducer', () => { ...@@ -289,22 +289,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({ fetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 3, fetchingBlockNumber: 3,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
store.dispatch( store.dispatch(
errorFetchingMulticallResults({ errorFetchingMulticallResults({
chainId: 1, chainId: 1,
fetchingBlockNumber: 2, fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }], calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
}) })
) )
expect(store.getState()).toEqual({ expect(store.getState()).toEqual({
callResults: { callResults: {
[1]: { [1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }, [`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }
}, }
}, }
}) })
}) })
}) })
......
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
fetchingMulticallResults, fetchingMulticallResults,
removeMulticallListeners, removeMulticallListeners,
toCallKey, toCallKey,
updateMulticallResults, updateMulticallResults
} from './actions' } from './actions'
export interface MulticallState { export interface MulticallState {
...@@ -32,17 +32,17 @@ export interface MulticallState { ...@@ -32,17 +32,17 @@ export interface MulticallState {
} }
const initialState: MulticallState = { const initialState: MulticallState = {
callResults: {}, callResults: {}
} }
export default createReducer(initialState, (builder) => export default createReducer(initialState, builder =>
builder builder
.addCase(addMulticallListeners, (state, { payload: { calls, chainId, options: { blocksPerFetch = 1 } = {} } }) => { .addCase(addMulticallListeners, (state, { payload: { calls, chainId, options: { blocksPerFetch = 1 } = {} } }) => {
const listeners: MulticallState['callListeners'] = state.callListeners const listeners: MulticallState['callListeners'] = state.callListeners
? state.callListeners ? state.callListeners
: (state.callListeners = {}) : (state.callListeners = {})
listeners[chainId] = listeners[chainId] ?? {} listeners[chainId] = listeners[chainId] ?? {}
calls.forEach((call) => { calls.forEach(call => {
const callKey = toCallKey(call) const callKey = toCallKey(call)
listeners[chainId][callKey] = listeners[chainId][callKey] ?? {} listeners[chainId][callKey] = listeners[chainId][callKey] ?? {}
listeners[chainId][callKey][blocksPerFetch] = (listeners[chainId][callKey][blocksPerFetch] ?? 0) + 1 listeners[chainId][callKey][blocksPerFetch] = (listeners[chainId][callKey][blocksPerFetch] ?? 0) + 1
...@@ -56,7 +56,7 @@ export default createReducer(initialState, (builder) => ...@@ -56,7 +56,7 @@ export default createReducer(initialState, (builder) =>
: (state.callListeners = {}) : (state.callListeners = {})
if (!listeners[chainId]) return if (!listeners[chainId]) return
calls.forEach((call) => { calls.forEach(call => {
const callKey = toCallKey(call) const callKey = toCallKey(call)
if (!listeners[chainId][callKey]) return if (!listeners[chainId][callKey]) return
if (!listeners[chainId][callKey][blocksPerFetch]) return if (!listeners[chainId][callKey][blocksPerFetch]) return
...@@ -71,12 +71,12 @@ export default createReducer(initialState, (builder) => ...@@ -71,12 +71,12 @@ export default createReducer(initialState, (builder) =>
) )
.addCase(fetchingMulticallResults, (state, { payload: { chainId, fetchingBlockNumber, calls } }) => { .addCase(fetchingMulticallResults, (state, { payload: { chainId, fetchingBlockNumber, calls } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {} state.callResults[chainId] = state.callResults[chainId] ?? {}
calls.forEach((call) => { calls.forEach(call => {
const callKey = toCallKey(call) const callKey = toCallKey(call)
const current = state.callResults[chainId][callKey] const current = state.callResults[chainId][callKey]
if (!current) { if (!current) {
state.callResults[chainId][callKey] = { state.callResults[chainId][callKey] = {
fetchingBlockNumber, fetchingBlockNumber
} }
} else { } else {
if ((current.fetchingBlockNumber ?? 0) >= fetchingBlockNumber) return if ((current.fetchingBlockNumber ?? 0) >= fetchingBlockNumber) return
...@@ -86,7 +86,7 @@ export default createReducer(initialState, (builder) => ...@@ -86,7 +86,7 @@ export default createReducer(initialState, (builder) =>
}) })
.addCase(errorFetchingMulticallResults, (state, { payload: { fetchingBlockNumber, chainId, calls } }) => { .addCase(errorFetchingMulticallResults, (state, { payload: { fetchingBlockNumber, chainId, calls } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {} state.callResults[chainId] = state.callResults[chainId] ?? {}
calls.forEach((call) => { calls.forEach(call => {
const callKey = toCallKey(call) const callKey = toCallKey(call)
const current = state.callResults[chainId][callKey] const current = state.callResults[chainId][callKey]
if (!current) return // only should be dispatched if we are already fetching if (!current) return // only should be dispatched if we are already fetching
...@@ -99,12 +99,12 @@ export default createReducer(initialState, (builder) => ...@@ -99,12 +99,12 @@ export default createReducer(initialState, (builder) =>
}) })
.addCase(updateMulticallResults, (state, { payload: { chainId, results, blockNumber } }) => { .addCase(updateMulticallResults, (state, { payload: { chainId, results, blockNumber } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {} state.callResults[chainId] = state.callResults[chainId] ?? {}
Object.keys(results).forEach((callKey) => { Object.keys(results).forEach(callKey => {
const current = state.callResults[chainId][callKey] const current = state.callResults[chainId][callKey]
if ((current?.blockNumber ?? 0) > blockNumber) return if ((current?.blockNumber ?? 0) > blockNumber) return
state.callResults[chainId][callKey] = { state.callResults[chainId][callKey] = {
data: results[callKey], data: results[callKey],
blockNumber, blockNumber
} }
}) })
}) })
......
...@@ -9,14 +9,14 @@ describe('multicall updater', () => { ...@@ -9,14 +9,14 @@ describe('multicall updater', () => {
[1]: { [1]: {
['abc']: { ['abc']: {
4: 2, // 2 listeners care about 4 block old data 4: 2, // 2 listeners care about 4 block old data
1: 0, // 0 listeners care about 1 block old data 1: 0 // 0 listeners care about 1 block old data
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 4, abc: 4
}) })
}) })
it('applies min', () => { it('applies min', () => {
...@@ -27,14 +27,14 @@ describe('multicall updater', () => { ...@@ -27,14 +27,14 @@ describe('multicall updater', () => {
['abc']: { ['abc']: {
4: 2, // 2 listeners care about 4 block old data 4: 2, // 2 listeners care about 4 block old data
3: 1, // 1 listener cares about 3 block old data 3: 1, // 1 listener cares about 3 block old data
1: 0, // 0 listeners care about 1 block old data 1: 0 // 0 listeners care about 1 block old data
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 3, abc: 3
}) })
}) })
it('works for infinity', () => { it('works for infinity', () => {
...@@ -44,18 +44,18 @@ describe('multicall updater', () => { ...@@ -44,18 +44,18 @@ describe('multicall updater', () => {
[1]: { [1]: {
['abc']: { ['abc']: {
4: 2, // 2 listeners care about 4 block old data 4: 2, // 2 listeners care about 4 block old data
1: 0, // 0 listeners care about 1 block old data 1: 0 // 0 listeners care about 1 block old data
}, },
['def']: { ['def']: {
Infinity: 2, Infinity: 2
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 4, abc: 4,
def: Infinity, def: Infinity
}) })
}) })
it('multiple keys', () => { it('multiple keys', () => {
...@@ -65,19 +65,19 @@ describe('multicall updater', () => { ...@@ -65,19 +65,19 @@ describe('multicall updater', () => {
[1]: { [1]: {
['abc']: { ['abc']: {
4: 2, // 2 listeners care about 4 block old data 4: 2, // 2 listeners care about 4 block old data
1: 0, // 0 listeners care about 1 block old data 1: 0 // 0 listeners care about 1 block old data
}, },
['def']: { ['def']: {
2: 1, 2: 1,
5: 2, 5: 2
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 4, abc: 4,
def: 2, def: 2
}) })
}) })
it('ignores negative numbers', () => { it('ignores negative numbers', () => {
...@@ -88,14 +88,14 @@ describe('multicall updater', () => { ...@@ -88,14 +88,14 @@ describe('multicall updater', () => {
['abc']: { ['abc']: {
4: 2, 4: 2,
1: -1, 1: -1,
[-3]: 4, [-3]: 4
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 4, abc: 4
}) })
}) })
it('applies min to infinity', () => { it('applies min to infinity', () => {
...@@ -106,14 +106,14 @@ describe('multicall updater', () => { ...@@ -106,14 +106,14 @@ describe('multicall updater', () => {
['abc']: { ['abc']: {
Infinity: 2, // 2 listeners care about any data Infinity: 2, // 2 listeners care about any data
4: 2, // 2 listeners care about 4 block old data 4: 2, // 2 listeners care about 4 block old data
1: 0, // 0 listeners care about 1 block old data 1: 0 // 0 listeners care about 1 block old data
}, }
}, }
}, },
1 1
) )
).toEqual({ ).toEqual({
abc: 4, abc: 4
}) })
}) })
}) })
...@@ -136,7 +136,7 @@ describe('multicall updater', () => { ...@@ -136,7 +136,7 @@ describe('multicall updater', () => {
expect( expect(
outdatedListeningKeys( outdatedListeningKeys(
{ {
[1]: { abc: { data: '0x', blockNumber: 2 }, def: { fetchingBlockNumber: 2 } }, [1]: { abc: { data: '0x', blockNumber: 2 }, def: { fetchingBlockNumber: 2 } }
}, },
{ abc: 1, def: 1 }, { abc: 1, def: 1 },
1, 1,
......
...@@ -13,7 +13,7 @@ import { ...@@ -13,7 +13,7 @@ import {
errorFetchingMulticallResults, errorFetchingMulticallResults,
fetchingMulticallResults, fetchingMulticallResults,
parseCallKey, parseCallKey,
updateMulticallResults, updateMulticallResults
} from './actions' } from './actions'
// chunk calls so we do not exceed the gas limit // chunk calls so we do not exceed the gas limit
...@@ -33,9 +33,7 @@ async function fetchChunk( ...@@ -33,9 +33,7 @@ async function fetchChunk(
console.debug('Fetching chunk', multicallContract, chunk, minBlockNumber) console.debug('Fetching chunk', multicallContract, chunk, minBlockNumber)
let resultsBlockNumber, returnData let resultsBlockNumber, returnData
try { try {
;[resultsBlockNumber, returnData] = await multicallContract.aggregate( ;[resultsBlockNumber, returnData] = await multicallContract.aggregate(chunk.map(obj => [obj.address, obj.callData]))
chunk.map((obj) => [obj.address, obj.callData])
)
} catch (error) { } catch (error) {
console.debug('Failed to fetch chunk inside retry', error) console.debug('Failed to fetch chunk inside retry', error)
throw error throw error
...@@ -65,7 +63,7 @@ export function activeListeningKeys( ...@@ -65,7 +63,7 @@ export function activeListeningKeys(
const keyListeners = listeners[callKey] const keyListeners = listeners[callKey]
memo[callKey] = Object.keys(keyListeners) memo[callKey] = Object.keys(keyListeners)
.filter((key) => { .filter(key => {
const blocksPerFetch = parseInt(key) const blocksPerFetch = parseInt(key)
if (blocksPerFetch <= 0) return false if (blocksPerFetch <= 0) return false
return keyListeners[blocksPerFetch] > 0 return keyListeners[blocksPerFetch] > 0
...@@ -95,7 +93,7 @@ export function outdatedListeningKeys( ...@@ -95,7 +93,7 @@ export function outdatedListeningKeys(
// no results at all, load everything // no results at all, load everything
if (!results) return Object.keys(listeningKeys) if (!results) return Object.keys(listeningKeys)
return Object.keys(listeningKeys).filter((callKey) => { return Object.keys(listeningKeys).filter(callKey => {
const blocksPerFetch = listeningKeys[callKey] const blocksPerFetch = listeningKeys[callKey]
const data = callResults[chainId][callKey] const data = callResults[chainId][callKey]
...@@ -114,7 +112,7 @@ export function outdatedListeningKeys( ...@@ -114,7 +112,7 @@ export function outdatedListeningKeys(
export default function Updater(): null { export default function Updater(): null {
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const state = useSelector<AppState, AppState['multicall']>((state) => state.multicall) const state = useSelector<AppState, AppState['multicall']>(state => state.multicall)
// wait for listeners to settle before triggering updates // wait for listeners to settle before triggering updates
const debouncedListeners = useDebounce(state.callListeners, 100) const debouncedListeners = useDebounce(state.callListeners, 100)
const latestBlockNumber = useBlockNumber() const latestBlockNumber = useBlockNumber()
...@@ -131,7 +129,7 @@ export default function Updater(): null { ...@@ -131,7 +129,7 @@ export default function Updater(): null {
}, [chainId, state.callResults, listeningKeys, latestBlockNumber]) }, [chainId, state.callResults, listeningKeys, latestBlockNumber])
const serializedOutdatedCallKeys = useMemo(() => JSON.stringify(unserializedOutdatedCallKeys.sort()), [ const serializedOutdatedCallKeys = useMemo(() => JSON.stringify(unserializedOutdatedCallKeys.sort()), [
unserializedOutdatedCallKeys, unserializedOutdatedCallKeys
]) ])
useEffect(() => { useEffect(() => {
...@@ -139,19 +137,19 @@ export default function Updater(): null { ...@@ -139,19 +137,19 @@ export default function Updater(): null {
const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys) const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys)
if (outdatedCallKeys.length === 0) return if (outdatedCallKeys.length === 0) return
const calls = outdatedCallKeys.map((key) => parseCallKey(key)) const calls = outdatedCallKeys.map(key => parseCallKey(key))
const chunkedCalls = chunkArray(calls, CALL_CHUNK_SIZE) const chunkedCalls = chunkArray(calls, CALL_CHUNK_SIZE)
if (cancellations.current?.blockNumber !== latestBlockNumber) { if (cancellations.current?.blockNumber !== latestBlockNumber) {
cancellations.current?.cancellations?.forEach((c) => c()) cancellations.current?.cancellations?.forEach(c => c())
} }
dispatch( dispatch(
fetchingMulticallResults({ fetchingMulticallResults({
calls, calls,
chainId, chainId,
fetchingBlockNumber: latestBlockNumber, fetchingBlockNumber: latestBlockNumber
}) })
) )
...@@ -161,7 +159,7 @@ export default function Updater(): null { ...@@ -161,7 +159,7 @@ export default function Updater(): null {
const { cancel, promise } = retry(() => fetchChunk(multicallContract, chunk, latestBlockNumber), { const { cancel, promise } = retry(() => fetchChunk(multicallContract, chunk, latestBlockNumber), {
n: Infinity, n: Infinity,
minWait: 2500, minWait: 2500,
maxWait: 3500, maxWait: 3500
}) })
promise promise
.then(({ results: returnData, blockNumber: fetchBlockNumber }) => { .then(({ results: returnData, blockNumber: fetchBlockNumber }) => {
...@@ -180,7 +178,7 @@ export default function Updater(): null { ...@@ -180,7 +178,7 @@ export default function Updater(): null {
memo[callKey] = returnData[i] ?? null memo[callKey] = returnData[i] ?? null
return memo return memo
}, {}), }, {}),
blockNumber: fetchBlockNumber, blockNumber: fetchBlockNumber
}) })
) )
}) })
...@@ -194,12 +192,12 @@ export default function Updater(): null { ...@@ -194,12 +192,12 @@ export default function Updater(): null {
errorFetchingMulticallResults({ errorFetchingMulticallResults({
calls: chunk, calls: chunk,
chainId, chainId,
fetchingBlockNumber: latestBlockNumber, fetchingBlockNumber: latestBlockNumber
}) })
) )
}) })
return cancel return cancel
}), })
} }
}, [chainId, multicallContract, dispatch, serializedOutdatedCallKeys, latestBlockNumber]) }, [chainId, multicallContract, dispatch, serializedOutdatedCallKeys, latestBlockNumber])
......
...@@ -21,21 +21,21 @@ export const STAKING_REWARDS_INFO: { ...@@ -21,21 +21,21 @@ export const STAKING_REWARDS_INFO: {
[ChainId.MAINNET]: [ [ChainId.MAINNET]: [
{ {
tokens: [WETH[ChainId.MAINNET], DAI], tokens: [WETH[ChainId.MAINNET], DAI],
stakingRewardAddress: '0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711', stakingRewardAddress: '0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711'
}, },
{ {
tokens: [WETH[ChainId.MAINNET], USDC], tokens: [WETH[ChainId.MAINNET], USDC],
stakingRewardAddress: '0x7FBa4B8Dc5E7616e59622806932DBea72537A56b', stakingRewardAddress: '0x7FBa4B8Dc5E7616e59622806932DBea72537A56b'
}, },
{ {
tokens: [WETH[ChainId.MAINNET], USDT], tokens: [WETH[ChainId.MAINNET], USDT],
stakingRewardAddress: '0x6C3e4cb2E96B01F4b866965A91ed4437839A121a', stakingRewardAddress: '0x6C3e4cb2E96B01F4b866965A91ed4437839A121a'
}, },
{ {
tokens: [WETH[ChainId.MAINNET], WBTC], tokens: [WETH[ChainId.MAINNET], WBTC],
stakingRewardAddress: '0xCA35e32e7926b96A9988f61d510E038108d8068e', stakingRewardAddress: '0xCA35e32e7926b96A9988f61d510E038108d8068e'
}, }
], ]
} }
export interface StakingInfo { export interface StakingInfo {
...@@ -76,7 +76,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -76,7 +76,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
const info = useMemo( const info = useMemo(
() => () =>
chainId chainId
? STAKING_REWARDS_INFO[chainId]?.filter((stakingRewardInfo) => ? STAKING_REWARDS_INFO[chainId]?.filter(stakingRewardInfo =>
pairToFilterBy === undefined pairToFilterBy === undefined
? true ? true
: pairToFilterBy === null : pairToFilterBy === null
...@@ -193,7 +193,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -193,7 +193,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
stakedAmount: stakedAmount, stakedAmount: stakedAmount,
totalStakedAmount: totalStakedAmount, totalStakedAmount: totalStakedAmount,
getHypotheticalRewardRate, getHypotheticalRewardRate,
active, active
}) })
} }
return memo return memo
...@@ -208,7 +208,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] { ...@@ -208,7 +208,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
rewardRates, rewardRates,
rewardsAddresses, rewardsAddresses,
totalSupplies, totalSupplies,
uni, uni
]) ])
} }
...@@ -256,7 +256,7 @@ export function useDerivedStakeInfo( ...@@ -256,7 +256,7 @@ export function useDerivedStakeInfo(
return { return {
parsedAmount, parsedAmount,
error, error
} }
} }
...@@ -284,6 +284,6 @@ export function useDerivedUnstakeInfo( ...@@ -284,6 +284,6 @@ export function useDerivedUnstakeInfo(
return { return {
parsedAmount, parsedAmount,
error, error
} }
} }
...@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit' ...@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit'
export enum Field { export enum Field {
INPUT = 'INPUT', INPUT = 'INPUT',
OUTPUT = 'OUTPUT', OUTPUT = 'OUTPUT'
} }
export const selectCurrency = createAction<{ field: Field; currencyId: string }>('swap/selectCurrency') export const selectCurrency = createAction<{ field: Field; currencyId: string }>('swap/selectCurrency')
......
...@@ -17,7 +17,7 @@ describe('hooks', () => { ...@@ -17,7 +17,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: 'ETH' }, [Field.INPUT]: { currencyId: 'ETH' },
typedValue: '20.5', typedValue: '20.5',
independentField: Field.OUTPUT, independentField: Field.OUTPUT,
recipient: null, recipient: null
}) })
}) })
...@@ -29,7 +29,7 @@ describe('hooks', () => { ...@@ -29,7 +29,7 @@ describe('hooks', () => {
[Field.OUTPUT]: { currencyId: 'ETH' }, [Field.OUTPUT]: { currencyId: 'ETH' },
typedValue: '', typedValue: '',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: null, recipient: null
}) })
}) })
...@@ -43,7 +43,7 @@ describe('hooks', () => { ...@@ -43,7 +43,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '20.5', typedValue: '20.5',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: null, recipient: null
}) })
}) })
...@@ -57,7 +57,7 @@ describe('hooks', () => { ...@@ -57,7 +57,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '20.5', typedValue: '20.5',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: null, recipient: null
}) })
}) })
...@@ -66,7 +66,7 @@ describe('hooks', () => { ...@@ -66,7 +66,7 @@ describe('hooks', () => {
queryParametersToSwapState( queryParametersToSwapState(
parse('?outputCurrency=eth&exactAmount=20.5&recipient=0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5', { parse('?outputCurrency=eth&exactAmount=20.5&recipient=0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5', {
parseArrays: false, parseArrays: false,
ignoreQueryPrefix: true, ignoreQueryPrefix: true
}) })
) )
).toEqual({ ).toEqual({
...@@ -74,7 +74,7 @@ describe('hooks', () => { ...@@ -74,7 +74,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '20.5', typedValue: '20.5',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: '0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5', recipient: '0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5'
}) })
}) })
test('accepts any recipient', () => { test('accepts any recipient', () => {
...@@ -82,7 +82,7 @@ describe('hooks', () => { ...@@ -82,7 +82,7 @@ describe('hooks', () => {
queryParametersToSwapState( queryParametersToSwapState(
parse('?outputCurrency=eth&exactAmount=20.5&recipient=bob.argent.xyz', { parse('?outputCurrency=eth&exactAmount=20.5&recipient=bob.argent.xyz', {
parseArrays: false, parseArrays: false,
ignoreQueryPrefix: true, ignoreQueryPrefix: true
}) })
) )
).toEqual({ ).toEqual({
...@@ -90,7 +90,7 @@ describe('hooks', () => { ...@@ -90,7 +90,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '20.5', typedValue: '20.5',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: 'bob.argent.xyz', recipient: 'bob.argent.xyz'
}) })
}) })
}) })
......
...@@ -20,7 +20,7 @@ import { useUserSlippageTolerance } from '../user/hooks' ...@@ -20,7 +20,7 @@ import { useUserSlippageTolerance } from '../user/hooks'
import { computeSlippageAdjustedAmounts } from '../../utils/prices' import { computeSlippageAdjustedAmounts } from '../../utils/prices'
export function useSwapState(): AppState['swap'] { export function useSwapState(): AppState['swap'] {
return useSelector<AppState, AppState['swap']>((state) => state.swap) return useSelector<AppState, AppState['swap']>(state => state.swap)
} }
export function useSwapActionHandlers(): { export function useSwapActionHandlers(): {
...@@ -35,7 +35,7 @@ export function useSwapActionHandlers(): { ...@@ -35,7 +35,7 @@ export function useSwapActionHandlers(): {
dispatch( dispatch(
selectCurrency({ selectCurrency({
field, field,
currencyId: currency instanceof Token ? currency.address : currency === ETHER ? 'ETH' : '', currencyId: currency instanceof Token ? currency.address : currency === ETHER ? 'ETH' : ''
}) })
) )
}, },
...@@ -64,7 +64,7 @@ export function useSwapActionHandlers(): { ...@@ -64,7 +64,7 @@ export function useSwapActionHandlers(): {
onSwitchTokens, onSwitchTokens,
onCurrencySelection, onCurrencySelection,
onUserInput, onUserInput,
onChangeRecipient, onChangeRecipient
} }
} }
...@@ -91,7 +91,7 @@ export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmo ...@@ -91,7 +91,7 @@ export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmo
const BAD_RECIPIENT_ADDRESSES: string[] = [ const BAD_RECIPIENT_ADDRESSES: string[] = [
'0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', // v2 factory '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', // v2 factory
'0xf164fC0Ec4E93095b804a4795bBe1e041497b92a', // v2 router 01 '0xf164fC0Ec4E93095b804a4795bBe1e041497b92a', // v2 router 01
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', // v2 router 02 '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' // v2 router 02
] ]
/** /**
...@@ -101,8 +101,8 @@ const BAD_RECIPIENT_ADDRESSES: string[] = [ ...@@ -101,8 +101,8 @@ const BAD_RECIPIENT_ADDRESSES: string[] = [
*/ */
function involvesAddress(trade: Trade, checksummedAddress: string): boolean { function involvesAddress(trade: Trade, checksummedAddress: string): boolean {
return ( return (
trade.route.path.some((token) => token.address === checksummedAddress) || trade.route.path.some(token => token.address === checksummedAddress) ||
trade.route.pairs.some((pair) => pair.liquidityToken.address === checksummedAddress) trade.route.pairs.some(pair => pair.liquidityToken.address === checksummedAddress)
) )
} }
...@@ -124,7 +124,7 @@ export function useDerivedSwapInfo(): { ...@@ -124,7 +124,7 @@ export function useDerivedSwapInfo(): {
typedValue, typedValue,
[Field.INPUT]: { currencyId: inputCurrencyId }, [Field.INPUT]: { currencyId: inputCurrencyId },
[Field.OUTPUT]: { currencyId: outputCurrencyId }, [Field.OUTPUT]: { currencyId: outputCurrencyId },
recipient, recipient
} = useSwapState() } = useSwapState()
const inputCurrency = useCurrency(inputCurrencyId) const inputCurrency = useCurrency(inputCurrencyId)
...@@ -134,7 +134,7 @@ export function useDerivedSwapInfo(): { ...@@ -134,7 +134,7 @@ export function useDerivedSwapInfo(): {
const relevantTokenBalances = useCurrencyBalances(account ?? undefined, [ const relevantTokenBalances = useCurrencyBalances(account ?? undefined, [
inputCurrency ?? undefined, inputCurrency ?? undefined,
outputCurrency ?? undefined, outputCurrency ?? undefined
]) ])
const isExactIn: boolean = independentField === Field.INPUT const isExactIn: boolean = independentField === Field.INPUT
...@@ -147,12 +147,12 @@ export function useDerivedSwapInfo(): { ...@@ -147,12 +147,12 @@ export function useDerivedSwapInfo(): {
const currencyBalances = { const currencyBalances = {
[Field.INPUT]: relevantTokenBalances[0], [Field.INPUT]: relevantTokenBalances[0],
[Field.OUTPUT]: relevantTokenBalances[1], [Field.OUTPUT]: relevantTokenBalances[1]
} }
const currencies: { [field in Field]?: Currency } = { const currencies: { [field in Field]?: Currency } = {
[Field.INPUT]: inputCurrency ?? undefined, [Field.INPUT]: inputCurrency ?? undefined,
[Field.OUTPUT]: outputCurrency ?? undefined, [Field.OUTPUT]: outputCurrency ?? undefined
} }
// get link to trade on v1, if a better rate exists // get link to trade on v1, if a better rate exists
...@@ -200,7 +200,7 @@ export function useDerivedSwapInfo(): { ...@@ -200,7 +200,7 @@ export function useDerivedSwapInfo(): {
: null : null
: slippageAdjustedAmounts : slippageAdjustedAmounts
? slippageAdjustedAmounts[Field.INPUT] ? slippageAdjustedAmounts[Field.INPUT]
: null, : null
] ]
if (balanceIn && amountIn && balanceIn.lessThan(amountIn)) { if (balanceIn && amountIn && balanceIn.lessThan(amountIn)) {
...@@ -213,7 +213,7 @@ export function useDerivedSwapInfo(): { ...@@ -213,7 +213,7 @@ export function useDerivedSwapInfo(): {
parsedAmount, parsedAmount,
v2Trade: v2Trade ?? undefined, v2Trade: v2Trade ?? undefined,
inputError, inputError,
v1Trade, v1Trade
} }
} }
...@@ -261,14 +261,14 @@ export function queryParametersToSwapState(parsedQs: ParsedQs): SwapState { ...@@ -261,14 +261,14 @@ export function queryParametersToSwapState(parsedQs: ParsedQs): SwapState {
return { return {
[Field.INPUT]: { [Field.INPUT]: {
currencyId: inputCurrency, currencyId: inputCurrency
}, },
[Field.OUTPUT]: { [Field.OUTPUT]: {
currencyId: outputCurrency, currencyId: outputCurrency
}, },
typedValue: parseTokenAmountURLParameter(parsedQs.exactAmount), typedValue: parseTokenAmountURLParameter(parsedQs.exactAmount),
independentField: parseIndependentFieldURLParameter(parsedQs.exactField), independentField: parseIndependentFieldURLParameter(parsedQs.exactField),
recipient, recipient
} }
} }
...@@ -293,7 +293,7 @@ export function useDefaultsFromURLSearch(): ...@@ -293,7 +293,7 @@ export function useDefaultsFromURLSearch():
field: parsed.independentField, field: parsed.independentField,
inputCurrencyId: parsed[Field.INPUT].currencyId, inputCurrencyId: parsed[Field.INPUT].currencyId,
outputCurrencyId: parsed[Field.OUTPUT].currencyId, outputCurrencyId: parsed[Field.OUTPUT].currencyId,
recipient: parsed.recipient, recipient: parsed.recipient
}) })
) )
......
...@@ -11,7 +11,7 @@ describe('swap reducer', () => { ...@@ -11,7 +11,7 @@ describe('swap reducer', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '', typedValue: '',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: null, recipient: null
}) })
}) })
...@@ -20,7 +20,7 @@ describe('swap reducer', () => { ...@@ -20,7 +20,7 @@ describe('swap reducer', () => {
store.dispatch( store.dispatch(
selectCurrency({ selectCurrency({
field: Field.OUTPUT, field: Field.OUTPUT,
currencyId: '0x0000', currencyId: '0x0000'
}) })
) )
...@@ -29,7 +29,7 @@ describe('swap reducer', () => { ...@@ -29,7 +29,7 @@ describe('swap reducer', () => {
[Field.INPUT]: { currencyId: '' }, [Field.INPUT]: { currencyId: '' },
typedValue: '', typedValue: '',
independentField: Field.INPUT, independentField: Field.INPUT,
recipient: null, recipient: null
}) })
}) })
}) })
......
...@@ -18,29 +18,29 @@ const initialState: SwapState = { ...@@ -18,29 +18,29 @@ const initialState: SwapState = {
independentField: Field.INPUT, independentField: Field.INPUT,
typedValue: '', typedValue: '',
[Field.INPUT]: { [Field.INPUT]: {
currencyId: '', currencyId: ''
}, },
[Field.OUTPUT]: { [Field.OUTPUT]: {
currencyId: '', currencyId: ''
}, },
recipient: null, recipient: null
} }
export default createReducer<SwapState>(initialState, (builder) => export default createReducer<SwapState>(initialState, builder =>
builder builder
.addCase( .addCase(
replaceSwapState, replaceSwapState,
(state, { payload: { typedValue, recipient, field, inputCurrencyId, outputCurrencyId } }) => { (state, { payload: { typedValue, recipient, field, inputCurrencyId, outputCurrencyId } }) => {
return { return {
[Field.INPUT]: { [Field.INPUT]: {
currencyId: inputCurrencyId, currencyId: inputCurrencyId
}, },
[Field.OUTPUT]: { [Field.OUTPUT]: {
currencyId: outputCurrencyId, currencyId: outputCurrencyId
}, },
independentField: field, independentField: field,
typedValue: typedValue, typedValue: typedValue,
recipient, recipient
} }
} }
) )
...@@ -52,29 +52,29 @@ export default createReducer<SwapState>(initialState, (builder) => ...@@ -52,29 +52,29 @@ export default createReducer<SwapState>(initialState, (builder) =>
...state, ...state,
independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT, independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT,
[field]: { currencyId: currencyId }, [field]: { currencyId: currencyId },
[otherField]: { currencyId: state[field].currencyId }, [otherField]: { currencyId: state[field].currencyId }
} }
} else { } else {
// the normal case // the normal case
return { return {
...state, ...state,
[field]: { currencyId: currencyId }, [field]: { currencyId: currencyId }
} }
} }
}) })
.addCase(switchCurrencies, (state) => { .addCase(switchCurrencies, state => {
return { return {
...state, ...state,
independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT, independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT,
[Field.INPUT]: { currencyId: state[Field.OUTPUT].currencyId }, [Field.INPUT]: { currencyId: state[Field.OUTPUT].currencyId },
[Field.OUTPUT]: { currencyId: state[Field.INPUT].currencyId }, [Field.OUTPUT]: { currencyId: state[Field.INPUT].currencyId }
} }
}) })
.addCase(typeInput, (state, { payload: { field, typedValue } }) => { .addCase(typeInput, (state, { payload: { field, typedValue } }) => {
return { return {
...state, ...state,
independentField: field, independentField: field,
typedValue, typedValue
} }
}) })
.addCase(setRecipient, (state, { payload: { recipient } }) => { .addCase(setRecipient, (state, { payload: { recipient } }) => {
......
...@@ -21,7 +21,7 @@ export function useTransactionAdder(): ( ...@@ -21,7 +21,7 @@ export function useTransactionAdder(): (
{ {
summary, summary,
approval, approval,
claim, claim
}: { summary?: string; claim?: { recipient: string }; approval?: { tokenAddress: string; spender: string } } = {} }: { summary?: string; claim?: { recipient: string }; approval?: { tokenAddress: string; spender: string } } = {}
) => { ) => {
if (!account) return if (!account) return
...@@ -41,7 +41,7 @@ export function useTransactionAdder(): ( ...@@ -41,7 +41,7 @@ export function useTransactionAdder(): (
export function useAllTransactions(): { [txHash: string]: TransactionDetails } { export function useAllTransactions(): { [txHash: string]: TransactionDetails } {
const { chainId } = useActiveWeb3React() const { chainId } = useActiveWeb3React()
const state = useSelector<AppState, AppState['transactions']>((state) => state.transactions) const state = useSelector<AppState, AppState['transactions']>(state => state.transactions)
return chainId ? state[chainId] ?? {} : {} return chainId ? state[chainId] ?? {} : {}
} }
...@@ -69,7 +69,7 @@ export function useHasPendingApproval(tokenAddress: string | undefined, spender: ...@@ -69,7 +69,7 @@ export function useHasPendingApproval(tokenAddress: string | undefined, spender:
() => () =>
typeof tokenAddress === 'string' && typeof tokenAddress === 'string' &&
typeof spender === 'string' && typeof spender === 'string' &&
Object.keys(allTransactions).some((hash) => { Object.keys(allTransactions).some(hash => {
const tx = allTransactions[hash] const tx = allTransactions[hash]
if (!tx) return false if (!tx) return false
if (tx.receipt) { if (tx.receipt) {
...@@ -93,7 +93,7 @@ export function useUserHasSubmittedClaim( ...@@ -93,7 +93,7 @@ export function useUserHasSubmittedClaim(
// get the txn if it has been submitted // get the txn if it has been submitted
const claimTxn = useMemo(() => { const claimTxn = useMemo(() => {
const txnIndex = Object.keys(allTransactions).find((hash) => { const txnIndex = Object.keys(allTransactions).find(hash => {
const tx = allTransactions[hash] const tx = allTransactions[hash]
return tx.claim && tx.claim.recipient === account return tx.claim && tx.claim.recipient === account
}) })
......
...@@ -19,7 +19,7 @@ describe('transaction reducer', () => { ...@@ -19,7 +19,7 @@ describe('transaction reducer', () => {
summary: 'hello world', summary: 'hello world',
hash: '0x0', hash: '0x0',
approval: { tokenAddress: 'abc', spender: 'def' }, approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc', from: 'abc'
}) })
) )
const txs = store.getState() const txs = store.getState()
...@@ -49,8 +49,8 @@ describe('transaction reducer', () => { ...@@ -49,8 +49,8 @@ describe('transaction reducer', () => {
from: '0x0', from: '0x0',
contractAddress: '0x0', contractAddress: '0x0',
blockHash: '0x0', blockHash: '0x0',
blockNumber: 1, blockNumber: 1
}, }
}) })
) )
expect(store.getState()).toEqual({}) expect(store.getState()).toEqual({})
...@@ -62,7 +62,7 @@ describe('transaction reducer', () => { ...@@ -62,7 +62,7 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' }, approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world', summary: 'hello world',
from: '0x0', from: '0x0'
}) })
) )
const beforeTime = new Date().getTime() const beforeTime = new Date().getTime()
...@@ -78,8 +78,8 @@ describe('transaction reducer', () => { ...@@ -78,8 +78,8 @@ describe('transaction reducer', () => {
from: '0x0', from: '0x0',
contractAddress: '0x0', contractAddress: '0x0',
blockHash: '0x0', blockHash: '0x0',
blockNumber: 1, blockNumber: 1
}, }
}) })
) )
const tx = store.getState()[ChainId.RINKEBY]?.['0x0'] const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
...@@ -93,7 +93,7 @@ describe('transaction reducer', () => { ...@@ -93,7 +93,7 @@ describe('transaction reducer', () => {
from: '0x0', from: '0x0',
contractAddress: '0x0', contractAddress: '0x0',
blockHash: '0x0', blockHash: '0x0',
blockNumber: 1, blockNumber: 1
}) })
}) })
}) })
...@@ -104,7 +104,7 @@ describe('transaction reducer', () => { ...@@ -104,7 +104,7 @@ describe('transaction reducer', () => {
checkedTransaction({ checkedTransaction({
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
hash: '0x0', hash: '0x0',
blockNumber: 1, blockNumber: 1
}) })
) )
expect(store.getState()).toEqual({}) expect(store.getState()).toEqual({})
...@@ -116,14 +116,14 @@ describe('transaction reducer', () => { ...@@ -116,14 +116,14 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' }, approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world', summary: 'hello world',
from: '0x0', from: '0x0'
}) })
) )
store.dispatch( store.dispatch(
checkedTransaction({ checkedTransaction({
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
hash: '0x0', hash: '0x0',
blockNumber: 1, blockNumber: 1
}) })
) )
const tx = store.getState()[ChainId.RINKEBY]?.['0x0'] const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
...@@ -136,21 +136,21 @@ describe('transaction reducer', () => { ...@@ -136,21 +136,21 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' }, approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world', summary: 'hello world',
from: '0x0', from: '0x0'
}) })
) )
store.dispatch( store.dispatch(
checkedTransaction({ checkedTransaction({
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
hash: '0x0', hash: '0x0',
blockNumber: 3, blockNumber: 3
}) })
) )
store.dispatch( store.dispatch(
checkedTransaction({ checkedTransaction({
chainId: ChainId.RINKEBY, chainId: ChainId.RINKEBY,
hash: '0x0', hash: '0x0',
blockNumber: 1, blockNumber: 1
}) })
) )
const tx = store.getState()[ChainId.RINKEBY]?.['0x0'] const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
...@@ -166,7 +166,7 @@ describe('transaction reducer', () => { ...@@ -166,7 +166,7 @@ describe('transaction reducer', () => {
summary: 'hello world', summary: 'hello world',
hash: '0x0', hash: '0x0',
approval: { tokenAddress: 'abc', spender: 'def' }, approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc', from: 'abc'
}) })
) )
store.dispatch( store.dispatch(
...@@ -175,7 +175,7 @@ describe('transaction reducer', () => { ...@@ -175,7 +175,7 @@ describe('transaction reducer', () => {
summary: 'hello world', summary: 'hello world',
hash: '0x1', hash: '0x1',
approval: { tokenAddress: 'abc', spender: 'def' }, approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc', from: 'abc'
}) })
) )
expect(Object.keys(store.getState())).toHaveLength(2) expect(Object.keys(store.getState())).toHaveLength(2)
......
...@@ -4,7 +4,7 @@ import { ...@@ -4,7 +4,7 @@ import {
checkedTransaction, checkedTransaction,
clearAllTransactions, clearAllTransactions,
finalizeTransaction, finalizeTransaction,
SerializableTransactionReceipt, SerializableTransactionReceipt
} from './actions' } from './actions'
const now = () => new Date().getTime() const now = () => new Date().getTime()
...@@ -29,7 +29,7 @@ export interface TransactionState { ...@@ -29,7 +29,7 @@ export interface TransactionState {
export const initialState: TransactionState = {} export const initialState: TransactionState = {}
export default createReducer(initialState, (builder) => export default createReducer(initialState, builder =>
builder builder
.addCase(addTransaction, (transactions, { payload: { chainId, from, hash, approval, summary, claim } }) => { .addCase(addTransaction, (transactions, { payload: { chainId, from, hash, approval, summary, claim } }) => {
if (transactions[chainId]?.[hash]) { if (transactions[chainId]?.[hash]) {
......
...@@ -35,7 +35,7 @@ export default function Updater(): null { ...@@ -35,7 +35,7 @@ export default function Updater(): null {
const lastBlockNumber = useBlockNumber() const lastBlockNumber = useBlockNumber()
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const state = useSelector<AppState, AppState['transactions']>((state) => state.transactions) const state = useSelector<AppState, AppState['transactions']>(state => state.transactions)
const transactions = chainId ? state[chainId] ?? {} : {} const transactions = chainId ? state[chainId] ?? {} : {}
...@@ -46,11 +46,11 @@ export default function Updater(): null { ...@@ -46,11 +46,11 @@ export default function Updater(): null {
if (!chainId || !library || !lastBlockNumber) return if (!chainId || !library || !lastBlockNumber) return
Object.keys(transactions) Object.keys(transactions)
.filter((hash) => shouldCheck(lastBlockNumber, transactions[hash])) .filter(hash => shouldCheck(lastBlockNumber, transactions[hash]))
.forEach((hash) => { .forEach(hash => {
library library
.getTransactionReceipt(hash) .getTransactionReceipt(hash)
.then((receipt) => { .then(receipt => {
if (receipt) { if (receipt) {
dispatch( dispatch(
finalizeTransaction({ finalizeTransaction({
...@@ -64,8 +64,8 @@ export default function Updater(): null { ...@@ -64,8 +64,8 @@ export default function Updater(): null {
status: receipt.status, status: receipt.status,
to: receipt.to, to: receipt.to,
transactionHash: receipt.transactionHash, transactionHash: receipt.transactionHash,
transactionIndex: receipt.transactionIndex, transactionIndex: receipt.transactionIndex
}, }
}) })
) )
...@@ -74,8 +74,8 @@ export default function Updater(): null { ...@@ -74,8 +74,8 @@ export default function Updater(): null {
txn: { txn: {
hash, hash,
success: receipt.status === 1, success: receipt.status === 1,
summary: transactions[hash]?.summary, summary: transactions[hash]?.summary
}, }
}, },
hash hash
) )
...@@ -83,7 +83,7 @@ export default function Updater(): null { ...@@ -83,7 +83,7 @@ export default function Updater(): null {
dispatch(checkedTransaction({ chainId, hash, blockNumber: lastBlockNumber })) dispatch(checkedTransaction({ chainId, hash, blockNumber: lastBlockNumber }))
} }
}) })
.catch((error) => { .catch(error => {
console.error(`failed to check transaction hash: ${hash}`, error) console.error(`failed to check transaction hash: ${hash}`, error)
}) })
}) })
......
...@@ -19,7 +19,7 @@ import { ...@@ -19,7 +19,7 @@ import {
updateUserExpertMode, updateUserExpertMode,
updateUserSlippageTolerance, updateUserSlippageTolerance,
toggleURLWarning, toggleURLWarning,
updateUserSingleHopOnly, updateUserSingleHopOnly
} from './actions' } from './actions'
function serializeToken(token: Token): SerializedToken { function serializeToken(token: Token): SerializedToken {
...@@ -28,7 +28,7 @@ function serializeToken(token: Token): SerializedToken { ...@@ -28,7 +28,7 @@ function serializeToken(token: Token): SerializedToken {
address: token.address, address: token.address,
decimals: token.decimals, decimals: token.decimals,
symbol: token.symbol, symbol: token.symbol,
name: token.name, name: token.name
} }
} }
...@@ -49,7 +49,7 @@ export function useIsDarkMode(): boolean { ...@@ -49,7 +49,7 @@ export function useIsDarkMode(): boolean {
>( >(
({ user: { matchesDarkMode, userDarkMode } }) => ({ ({ user: { matchesDarkMode, userDarkMode } }) => ({
userDarkMode, userDarkMode,
matchesDarkMode, matchesDarkMode
}), }),
shallowEqual shallowEqual
) )
...@@ -69,7 +69,7 @@ export function useDarkModeManager(): [boolean, () => void] { ...@@ -69,7 +69,7 @@ export function useDarkModeManager(): [boolean, () => void] {
} }
export function useIsExpertMode(): boolean { export function useIsExpertMode(): boolean {
return useSelector<AppState, AppState['user']['userExpertMode']>((state) => state.user.userExpertMode) return useSelector<AppState, AppState['user']['userExpertMode']>(state => state.user.userExpertMode)
} }
export function useExpertModeManager(): [boolean, () => void] { export function useExpertModeManager(): [boolean, () => void] {
...@@ -87,14 +87,14 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) => ...@@ -87,14 +87,14 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) =>
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const singleHopOnly = useSelector<AppState, AppState['user']['userSingleHopOnly']>( const singleHopOnly = useSelector<AppState, AppState['user']['userSingleHopOnly']>(
(state) => state.user.userSingleHopOnly state => state.user.userSingleHopOnly
) )
const setSingleHopOnly = useCallback( const setSingleHopOnly = useCallback(
(newSingleHopOnly: boolean) => { (newSingleHopOnly: boolean) => {
ReactGA.event({ ReactGA.event({
category: 'Routing', category: 'Routing',
action: newSingleHopOnly ? 'enable single hop' : 'disable single hop', action: newSingleHopOnly ? 'enable single hop' : 'disable single hop'
}) })
dispatch(updateUserSingleHopOnly({ userSingleHopOnly: newSingleHopOnly })) dispatch(updateUserSingleHopOnly({ userSingleHopOnly: newSingleHopOnly }))
}, },
...@@ -106,7 +106,7 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) => ...@@ -106,7 +106,7 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) =>
export function useUserSlippageTolerance(): [number, (slippage: number) => void] { export function useUserSlippageTolerance(): [number, (slippage: number) => void] {
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const userSlippageTolerance = useSelector<AppState, AppState['user']['userSlippageTolerance']>((state) => { const userSlippageTolerance = useSelector<AppState, AppState['user']['userSlippageTolerance']>(state => {
return state.user.userSlippageTolerance return state.user.userSlippageTolerance
}) })
...@@ -122,7 +122,7 @@ export function useUserSlippageTolerance(): [number, (slippage: number) => void] ...@@ -122,7 +122,7 @@ export function useUserSlippageTolerance(): [number, (slippage: number) => void]
export function useUserTransactionTTL(): [number, (slippage: number) => void] { export function useUserTransactionTTL(): [number, (slippage: number) => void] {
const dispatch = useDispatch<AppDispatch>() const dispatch = useDispatch<AppDispatch>()
const userDeadline = useSelector<AppState, AppState['user']['userDeadline']>((state) => { const userDeadline = useSelector<AppState, AppState['user']['userDeadline']>(state => {
return state.user.userDeadline return state.user.userDeadline
}) })
...@@ -169,7 +169,7 @@ export function useUserAddedTokens(): Token[] { ...@@ -169,7 +169,7 @@ export function useUserAddedTokens(): Token[] {
function serializePair(pair: Pair): SerializedPair { function serializePair(pair: Pair): SerializedPair {
return { return {
token0: serializeToken(pair.token0), token0: serializeToken(pair.token0),
token1: serializeToken(pair.token1), token1: serializeToken(pair.token1)
} }
} }
...@@ -216,14 +216,14 @@ export function useTrackedTokenPairs(): [Token, Token][] { ...@@ -216,14 +216,14 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const generatedPairs: [Token, Token][] = useMemo( const generatedPairs: [Token, Token][] = useMemo(
() => () =>
chainId chainId
? flatMap(Object.keys(tokens), (tokenAddress) => { ? flatMap(Object.keys(tokens), tokenAddress => {
const token = tokens[tokenAddress] const token = tokens[tokenAddress]
// for each token on the current chain, // for each token on the current chain,
return ( return (
// loop though all bases on the current chain // loop though all bases on the current chain
(BASES_TO_TRACK_LIQUIDITY_FOR[chainId] ?? []) (BASES_TO_TRACK_LIQUIDITY_FOR[chainId] ?? [])
// to construct pairs of the given token with each base // to construct pairs of the given token with each base
.map((base) => { .map(base => {
if (base.address === token.address) { if (base.address === token.address) {
return null return null
} else { } else {
...@@ -245,7 +245,7 @@ export function useTrackedTokenPairs(): [Token, Token][] { ...@@ -245,7 +245,7 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const forChain = savedSerializedPairs[chainId] const forChain = savedSerializedPairs[chainId]
if (!forChain) return [] if (!forChain) return []
return Object.keys(forChain).map((pairId) => { return Object.keys(forChain).map(pairId => {
return [deserializeToken(forChain[pairId].token0), deserializeToken(forChain[pairId].token1)] return [deserializeToken(forChain[pairId].token0), deserializeToken(forChain[pairId].token1)]
}) })
}, [savedSerializedPairs, chainId]) }, [savedSerializedPairs, chainId])
...@@ -253,7 +253,7 @@ export function useTrackedTokenPairs(): [Token, Token][] { ...@@ -253,7 +253,7 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const combinedList = useMemo(() => userPairs.concat(generatedPairs).concat(pinnedPairs), [ const combinedList = useMemo(() => userPairs.concat(generatedPairs).concat(pinnedPairs), [
generatedPairs, generatedPairs,
pinnedPairs, pinnedPairs,
userPairs, userPairs
]) ])
return useMemo(() => { return useMemo(() => {
...@@ -266,6 +266,6 @@ export function useTrackedTokenPairs(): [Token, Token][] { ...@@ -266,6 +266,6 @@ export function useTrackedTokenPairs(): [Token, Token][] {
return memo return memo
}, {}) }, {})
return Object.keys(keyed).map((key) => keyed[key]) return Object.keys(keyed).map(key => keyed[key])
}, [combinedList]) }, [combinedList])
} }
...@@ -23,7 +23,7 @@ describe('swap reducer', () => { ...@@ -23,7 +23,7 @@ describe('swap reducer', () => {
store = createStore(reducer, { store = createStore(reducer, {
...initialState, ...initialState,
userDeadline: undefined, userDeadline: undefined,
userSlippageTolerance: undefined, userSlippageTolerance: undefined
} as any) } as any)
store.dispatch(updateVersion()) store.dispatch(updateVersion())
expect(store.getState().userDeadline).toEqual(DEFAULT_DEADLINE_FROM_NOW) expect(store.getState().userDeadline).toEqual(DEFAULT_DEADLINE_FROM_NOW)
......
...@@ -14,7 +14,7 @@ import { ...@@ -14,7 +14,7 @@ import {
updateUserSlippageTolerance, updateUserSlippageTolerance,
updateUserDeadline, updateUserDeadline,
toggleURLWarning, toggleURLWarning,
updateUserSingleHopOnly, updateUserSingleHopOnly
} from './actions' } from './actions'
const currentTimestamp = () => new Date().getTime() const currentTimestamp = () => new Date().getTime()
...@@ -67,12 +67,12 @@ export const initialState: UserState = { ...@@ -67,12 +67,12 @@ export const initialState: UserState = {
tokens: {}, tokens: {},
pairs: {}, pairs: {},
timestamp: currentTimestamp(), timestamp: currentTimestamp(),
URLWarningVisible: true, URLWarningVisible: true
} }
export default createReducer(initialState, (builder) => export default createReducer(initialState, builder =>
builder builder
.addCase(updateVersion, (state) => { .addCase(updateVersion, state => {
// slippage isnt being tracked in local storage, reset to default // slippage isnt being tracked in local storage, reset to default
// noinspection SuspiciousTypeOfGuard // noinspection SuspiciousTypeOfGuard
if (typeof state.userSlippageTolerance !== 'number') { if (typeof state.userSlippageTolerance !== 'number') {
...@@ -139,7 +139,7 @@ export default createReducer(initialState, (builder) => ...@@ -139,7 +139,7 @@ export default createReducer(initialState, (builder) =>
} }
state.timestamp = currentTimestamp() state.timestamp = currentTimestamp()
}) })
.addCase(toggleURLWarning, (state) => { .addCase(toggleURLWarning, state => {
state.URLWarningVisible = !state.URLWarningVisible state.URLWarningVisible = !state.URLWarningVisible
}) })
) )
...@@ -32,7 +32,7 @@ export function useETHBalances( ...@@ -32,7 +32,7 @@ export function useETHBalances(
const results = useSingleContractMultipleData( const results = useSingleContractMultipleData(
multicallContract, multicallContract,
'getEthBalance', 'getEthBalance',
addresses.map((address) => [address]) addresses.map(address => [address])
) )
return useMemo( return useMemo(
...@@ -58,11 +58,11 @@ export function useTokenBalancesWithLoadingIndicator( ...@@ -58,11 +58,11 @@ export function useTokenBalancesWithLoadingIndicator(
[tokens] [tokens]
) )
const validatedTokenAddresses = useMemo(() => validatedTokens.map((vt) => vt.address), [validatedTokens]) const validatedTokenAddresses = useMemo(() => validatedTokens.map(vt => vt.address), [validatedTokens])
const balances = useMultipleContractSingleData(validatedTokenAddresses, ERC20_INTERFACE, 'balanceOf', [address]) const balances = useMultipleContractSingleData(validatedTokenAddresses, ERC20_INTERFACE, 'balanceOf', [address])
const anyLoading: boolean = useMemo(() => balances.some((callState) => callState.loading), [balances]) const anyLoading: boolean = useMemo(() => balances.some(callState => callState.loading), [balances])
return [ return [
useMemo( useMemo(
...@@ -79,7 +79,7 @@ export function useTokenBalancesWithLoadingIndicator( ...@@ -79,7 +79,7 @@ export function useTokenBalancesWithLoadingIndicator(
: {}, : {},
[address, validatedTokens, balances] [address, validatedTokens, balances]
), ),
anyLoading, anyLoading
] ]
} }
...@@ -102,16 +102,16 @@ export function useCurrencyBalances( ...@@ -102,16 +102,16 @@ export function useCurrencyBalances(
currencies?: (Currency | undefined)[] currencies?: (Currency | undefined)[]
): (CurrencyAmount | undefined)[] { ): (CurrencyAmount | undefined)[] {
const tokens = useMemo(() => currencies?.filter((currency): currency is Token => currency instanceof Token) ?? [], [ const tokens = useMemo(() => currencies?.filter((currency): currency is Token => currency instanceof Token) ?? [], [
currencies, currencies
]) ])
const tokenBalances = useTokenBalances(account, tokens) const tokenBalances = useTokenBalances(account, tokens)
const containsETH: boolean = useMemo(() => currencies?.some((currency) => currency === ETHER) ?? false, [currencies]) const containsETH: boolean = useMemo(() => currencies?.some(currency => currency === ETHER) ?? false, [currencies])
const ethBalance = useETHBalances(containsETH ? [account] : []) const ethBalance = useETHBalances(containsETH ? [account] : [])
return useMemo( return useMemo(
() => () =>
currencies?.map((currency) => { currencies?.map(currency => {
if (!account || !currency) return undefined if (!account || !currency) return undefined
if (currency instanceof Token) return tokenBalances[currency.address] if (currency instanceof Token) return tokenBalances[currency.address]
if (currency === ETHER) return ethBalance[account] if (currency === ETHER) return ethBalance[account]
......
...@@ -14,7 +14,7 @@ export default function DarkModeQueryParamReader({ location: { search } }: Route ...@@ -14,7 +14,7 @@ export default function DarkModeQueryParamReader({ location: { search } }: Route
const parsed = parse(search, { const parsed = parse(search, {
parseArrays: false, parseArrays: false,
ignoreQueryPrefix: true, ignoreQueryPrefix: true
}) })
const theme = parsed.theme const theme = parsed.theme
......
...@@ -24,7 +24,7 @@ export const ButtonText = styled.button` ...@@ -24,7 +24,7 @@ export const ButtonText = styled.button`
` `
export const Button = styled.button.attrs<{ warning: boolean }, { backgroundColor: string }>(({ warning, theme }) => ({ export const Button = styled.button.attrs<{ warning: boolean }, { backgroundColor: string }>(({ warning, theme }) => ({
backgroundColor: warning ? theme.red1 : theme.primary1, backgroundColor: warning ? theme.red1 : theme.primary1
}))` }))`
padding: 1rem 2rem 1rem 2rem; padding: 1rem 2rem 1rem 2rem;
border-radius: 3rem; border-radius: 3rem;
......
...@@ -4,7 +4,7 @@ import styled, { ...@@ -4,7 +4,7 @@ import styled, {
ThemeProvider as StyledComponentsThemeProvider, ThemeProvider as StyledComponentsThemeProvider,
createGlobalStyle, createGlobalStyle,
css, css,
DefaultTheme, DefaultTheme
} from 'styled-components' } from 'styled-components'
import { useIsDarkMode } from '../state/user/hooks' import { useIsDarkMode } from '../state/user/hooks'
import { Text, TextProps } from 'rebass' import { Text, TextProps } from 'rebass'
...@@ -16,7 +16,7 @@ const MEDIA_WIDTHS = { ...@@ -16,7 +16,7 @@ const MEDIA_WIDTHS = {
upToExtraSmall: 500, upToExtraSmall: 500,
upToSmall: 720, upToSmall: 720,
upToMedium: 960, upToMedium: 960,
upToLarge: 1280, upToLarge: 1280
} }
const mediaWidthTemplates: { [width in keyof typeof MEDIA_WIDTHS]: typeof css } = Object.keys(MEDIA_WIDTHS).reduce( const mediaWidthTemplates: { [width in keyof typeof MEDIA_WIDTHS]: typeof css } = Object.keys(MEDIA_WIDTHS).reduce(
...@@ -80,7 +80,7 @@ export function colors(darkMode: boolean): Colors { ...@@ -80,7 +80,7 @@ export function colors(darkMode: boolean): Colors {
green1: '#27AE60', green1: '#27AE60',
yellow1: '#FFE270', yellow1: '#FFE270',
yellow2: '#F3841E', yellow2: '#F3841E',
blue1: '#2172E5', blue1: '#2172E5'
// dont wanna forget these blue yet // dont wanna forget these blue yet
// blue4: darkMode ? '#153d6f70' : '#C4D9F8', // blue4: darkMode ? '#153d6f70' : '#C4D9F8',
...@@ -95,7 +95,7 @@ export function theme(darkMode: boolean): DefaultTheme { ...@@ -95,7 +95,7 @@ export function theme(darkMode: boolean): DefaultTheme {
grids: { grids: {
sm: 8, sm: 8,
md: 12, md: 12,
lg: 24, lg: 24
}, },
//shadows //shadows
...@@ -112,7 +112,7 @@ export function theme(darkMode: boolean): DefaultTheme { ...@@ -112,7 +112,7 @@ export function theme(darkMode: boolean): DefaultTheme {
flexRowNoWrap: css` flexRowNoWrap: css`
display: flex; display: flex;
flex-flow: row nowrap; flex-flow: row nowrap;
`, `
} }
} }
...@@ -173,7 +173,7 @@ export const TYPE = { ...@@ -173,7 +173,7 @@ export const TYPE = {
}, },
error({ error, ...props }: { error: boolean } & TextProps) { error({ error, ...props }: { error: boolean } & TextProps) {
return <TextWrapper fontWeight={500} color={error ? 'red1' : 'text2'} {...props} /> return <TextWrapper fontWeight={500} color={error ? 'red1' : 'text2'} {...props} />
}, }
} }
export const FixedGlobalStyle = createGlobalStyle` export const FixedGlobalStyle = createGlobalStyle`
......
...@@ -14,7 +14,7 @@ describe('#chunkArray', () => { ...@@ -14,7 +14,7 @@ describe('#chunkArray', () => {
it('size exact half', () => { it('size exact half', () => {
expect(chunkArray([1, 2, 3, 4], 2)).toEqual([ expect(chunkArray([1, 2, 3, 4], 2)).toEqual([
[1, 2], [1, 2],
[3, 4], [3, 4]
]) ])
}) })
it('evenly distributes', () => { it('evenly distributes', () => {
...@@ -22,8 +22,8 @@ describe('#chunkArray', () => { ...@@ -22,8 +22,8 @@ describe('#chunkArray', () => {
expect(chunked).toEqual([ expect(chunked).toEqual([
[...Array(34).keys()], [...Array(34).keys()],
[...Array(34).keys()].map((i) => i + 34), [...Array(34).keys()].map(i => i + 34),
[...Array(32).keys()].map((i) => i + 68), [...Array(32).keys()].map(i => i + 68)
]) ])
expect(chunked[0][0]).toEqual(0) expect(chunked[0][0]).toEqual(0)
......
...@@ -7,5 +7,5 @@ export default function chunkArray<T>(items: T[], maxChunkSize: number): T[][] { ...@@ -7,5 +7,5 @@ export default function chunkArray<T>(items: T[], maxChunkSize: number): T[][] {
const numChunks: number = Math.ceil(items.length / maxChunkSize) const numChunks: number = Math.ceil(items.length / maxChunkSize)
const chunkSize = Math.ceil(items.length / numChunks) const chunkSize = Math.ceil(items.length / numChunks)
return [...Array(numChunks).keys()].map((ix) => items.slice(ix * chunkSize, ix * chunkSize + chunkSize)) return [...Array(numChunks).keys()].map(ix => items.slice(ix * chunkSize, ix * chunkSize + chunkSize))
} }
...@@ -8,7 +8,7 @@ import { ...@@ -8,7 +8,7 @@ import {
isAddress, isAddress,
shortenAddress, shortenAddress,
calculateGasMargin, calculateGasMargin,
basisPointsToPercent, basisPointsToPercent
} from '.' } from '.'
describe('utils', () => { describe('utils', () => {
...@@ -37,10 +37,10 @@ describe('utils', () => { ...@@ -37,10 +37,10 @@ describe('utils', () => {
it('bounds are correct', () => { it('bounds are correct', () => {
const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100') const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100')
expect(() => calculateSlippageAmount(tokenAmount, -1)).toThrow() expect(() => calculateSlippageAmount(tokenAmount, -1)).toThrow()
expect(calculateSlippageAmount(tokenAmount, 0).map((bound) => bound.toString())).toEqual(['100', '100']) expect(calculateSlippageAmount(tokenAmount, 0).map(bound => bound.toString())).toEqual(['100', '100'])
expect(calculateSlippageAmount(tokenAmount, 100).map((bound) => bound.toString())).toEqual(['99', '101']) expect(calculateSlippageAmount(tokenAmount, 100).map(bound => bound.toString())).toEqual(['99', '101'])
expect(calculateSlippageAmount(tokenAmount, 200).map((bound) => bound.toString())).toEqual(['98', '102']) expect(calculateSlippageAmount(tokenAmount, 200).map(bound => bound.toString())).toEqual(['98', '102'])
expect(calculateSlippageAmount(tokenAmount, 10000).map((bound) => bound.toString())).toEqual(['0', '200']) expect(calculateSlippageAmount(tokenAmount, 10000).map(bound => bound.toString())).toEqual(['0', '200'])
expect(() => calculateSlippageAmount(tokenAmount, 10001)).toThrow() expect(() => calculateSlippageAmount(tokenAmount, 10001)).toThrow()
}) })
}) })
......
...@@ -22,7 +22,7 @@ const ETHERSCAN_PREFIXES: { [chainId in ChainId]: string } = { ...@@ -22,7 +22,7 @@ const ETHERSCAN_PREFIXES: { [chainId in ChainId]: string } = {
3: 'ropsten.', 3: 'ropsten.',
4: 'rinkeby.', 4: 'rinkeby.',
5: 'goerli.', 5: 'goerli.',
42: 'kovan.', 42: 'kovan.'
} }
export function getEtherscanLink( export function getEtherscanLink(
...@@ -74,7 +74,7 @@ export function calculateSlippageAmount(value: CurrencyAmount, slippage: number) ...@@ -74,7 +74,7 @@ export function calculateSlippageAmount(value: CurrencyAmount, slippage: number)
} }
return [ return [
JSBI.divide(JSBI.multiply(value.raw, JSBI.BigInt(10000 - slippage)), JSBI.BigInt(10000)), JSBI.divide(JSBI.multiply(value.raw, JSBI.BigInt(10000 - slippage)), JSBI.BigInt(10000)),
JSBI.divide(JSBI.multiply(value.raw, JSBI.BigInt(10000 + slippage)), JSBI.BigInt(10000)), JSBI.divide(JSBI.multiply(value.raw, JSBI.BigInt(10000 + slippage)), JSBI.BigInt(10000))
] ]
} }
......
...@@ -13,7 +13,7 @@ describe('prices', () => { ...@@ -13,7 +13,7 @@ describe('prices', () => {
it('returns undefined for undefined', () => { it('returns undefined for undefined', () => {
expect(computeTradePriceBreakdown(undefined)).toEqual({ expect(computeTradePriceBreakdown(undefined)).toEqual({
priceImpactWithoutFee: undefined, priceImpactWithoutFee: undefined,
realizedLPFee: undefined, realizedLPFee: undefined
}) })
}) })
......
...@@ -50,7 +50,7 @@ export function computeSlippageAdjustedAmounts( ...@@ -50,7 +50,7 @@ export function computeSlippageAdjustedAmounts(
const pct = basisPointsToPercent(allowedSlippage) const pct = basisPointsToPercent(allowedSlippage)
return { return {
[Field.INPUT]: trade?.maximumAmountIn(pct), [Field.INPUT]: trade?.maximumAmountIn(pct),
[Field.OUTPUT]: trade?.minimumAmountOut(pct), [Field.OUTPUT]: trade?.minimumAmountOut(pct)
} }
} }
......
...@@ -8,20 +8,20 @@ const REGISTRAR_ABI = [ ...@@ -8,20 +8,20 @@ const REGISTRAR_ABI = [
inputs: [ inputs: [
{ {
name: 'node', name: 'node',
type: 'bytes32', type: 'bytes32'
}, }
], ],
name: 'resolver', name: 'resolver',
outputs: [ outputs: [
{ {
name: 'resolverAddress', name: 'resolverAddress',
type: 'address', type: 'address'
}, }
], ],
payable: false, payable: false,
stateMutability: 'view', stateMutability: 'view',
type: 'function', type: 'function'
}, }
] ]
const REGISTRAR_ADDRESS = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' const REGISTRAR_ADDRESS = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'
...@@ -32,21 +32,21 @@ const RESOLVER_ABI = [ ...@@ -32,21 +32,21 @@ const RESOLVER_ABI = [
{ {
internalType: 'bytes32', internalType: 'bytes32',
name: 'node', name: 'node',
type: 'bytes32', type: 'bytes32'
}, }
], ],
name: 'contenthash', name: 'contenthash',
outputs: [ outputs: [
{ {
internalType: 'bytes', internalType: 'bytes',
name: '', name: '',
type: 'bytes', type: 'bytes'
}, }
], ],
payable: false, payable: false,
stateMutability: 'view', stateMutability: 'view',
type: 'function', type: 'function'
}, }
] ]
// cache the resolver contracts since most of them are the public resolver // cache the resolver contracts since most of them are the public resolver
......
function wait(ms: number): Promise<void> { function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms)) return new Promise(resolve => setTimeout(resolve, ms))
} }
function waitRandom(min: number, max: number): Promise<void> { function waitRandom(min: number, max: number): Promise<void> {
...@@ -64,6 +64,6 @@ export function retry<T>( ...@@ -64,6 +64,6 @@ export function retry<T>(
if (completed) return if (completed) return
completed = true completed = true
rejectCancelled(new CancelledError()) rejectCancelled(new CancelledError())
}, }
} }
} }
...@@ -13,13 +13,13 @@ describe('uriToHttp', () => { ...@@ -13,13 +13,13 @@ describe('uriToHttp', () => {
it('returns ipfs gateways for ipfs:// urls', () => { it('returns ipfs gateways for ipfs:// urls', () => {
expect(uriToHttp('ipfs://QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ')).toEqual([ expect(uriToHttp('ipfs://QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ')).toEqual([
'https://cloudflare-ipfs.com/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/', 'https://cloudflare-ipfs.com/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/',
'https://ipfs.io/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/', 'https://ipfs.io/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/'
]) ])
}) })
it('returns ipns gateways for ipns:// urls', () => { it('returns ipns gateways for ipns:// urls', () => {
expect(uriToHttp('ipns://app.uniswap.org')).toEqual([ expect(uriToHttp('ipns://app.uniswap.org')).toEqual([
'https://cloudflare-ipfs.com/ipns/app.uniswap.org/', 'https://cloudflare-ipfs.com/ipns/app.uniswap.org/',
'https://ipfs.io/ipns/app.uniswap.org/', 'https://ipfs.io/ipns/app.uniswap.org/'
]) ])
}) })
it('returns empty array for invalid scheme', () => { it('returns empty array for invalid scheme', () => {
......
...@@ -16,10 +16,10 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined { ...@@ -16,10 +16,10 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined {
() => [ () => [
[ [
chainId && wrapped && currencyEquals(WETH[chainId], wrapped) ? undefined : currency, chainId && wrapped && currencyEquals(WETH[chainId], wrapped) ? undefined : currency,
chainId ? WETH[chainId] : undefined, chainId ? WETH[chainId] : undefined
], ],
[wrapped?.equals(USDC) ? undefined : wrapped, chainId === ChainId.MAINNET ? USDC : undefined], [wrapped?.equals(USDC) ? undefined : wrapped, chainId === ChainId.MAINNET ? USDC : undefined],
[chainId ? WETH[chainId] : undefined, chainId === ChainId.MAINNET ? USDC : undefined], [chainId ? WETH[chainId] : undefined, chainId === ChainId.MAINNET ? USDC : undefined]
], ],
[chainId, currency, wrapped] [chainId, currency, wrapped]
) )
......
...@@ -15,7 +15,7 @@ describe('v1SwapArguments', () => { ...@@ -15,7 +15,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60, deadline: 20 * 60
}) })
expect(result.methodName).toEqual('ethToTokenTransferInput') expect(result.methodName).toEqual('ethToTokenTransferInput')
expect(result.args).toEqual(['0x62', '0x4b0', TEST_RECIPIENT_ADDRESS]) expect(result.args).toEqual(['0x62', '0x4b0', TEST_RECIPIENT_ADDRESS])
...@@ -26,7 +26,7 @@ describe('v1SwapArguments', () => { ...@@ -26,7 +26,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 40 * 60, deadline: 40 * 60
}) })
expect(result.methodName).toEqual('tokenToEthTransferInput') expect(result.methodName).toEqual('tokenToEthTransferInput')
expect(result.args[0]).toEqual('0x64') expect(result.args[0]).toEqual('0x64')
...@@ -40,7 +40,7 @@ describe('v1SwapArguments', () => { ...@@ -40,7 +40,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60, deadline: 20 * 60
}) })
expect(result.methodName).toEqual('tokenToTokenTransferInput') expect(result.methodName).toEqual('tokenToTokenTransferInput')
expect(result.args[0]).toEqual('0x64') expect(result.args[0]).toEqual('0x64')
...@@ -56,7 +56,7 @@ describe('v1SwapArguments', () => { ...@@ -56,7 +56,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60, deadline: 20 * 60
}) })
expect(result.methodName).toEqual('ethToTokenTransferOutput') expect(result.methodName).toEqual('ethToTokenTransferOutput')
expect(result.args[0]).toEqual('0x64') expect(result.args[0]).toEqual('0x64')
...@@ -69,7 +69,7 @@ describe('v1SwapArguments', () => { ...@@ -69,7 +69,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60, deadline: 20 * 60
}) })
expect(result.methodName).toEqual('tokenToEthTransferOutput') expect(result.methodName).toEqual('tokenToEthTransferOutput')
expect(result.args[0]).toEqual('0x64') expect(result.args[0]).toEqual('0x64')
...@@ -83,7 +83,7 @@ describe('v1SwapArguments', () => { ...@@ -83,7 +83,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, { const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS, recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'), allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60, deadline: 20 * 60
}) })
expect(result.methodName).toEqual('tokenToTokenTransferOutput') expect(result.methodName).toEqual('tokenToTokenTransferOutput')
expect(result.args[0]).toEqual('0x64') expect(result.args[0]).toEqual('0x64')
......
...@@ -34,13 +34,13 @@ export default function v1SwapArguments( ...@@ -34,13 +34,13 @@ export default function v1SwapArguments(
return { return {
methodName: 'ethToTokenTransferInput', methodName: 'ethToTokenTransferInput',
args: [minimumAmountOut, deadline, options.recipient], args: [minimumAmountOut, deadline, options.recipient],
value: maximumAmountIn, value: maximumAmountIn
} }
} else if (outputETH) { } else if (outputETH) {
return { return {
methodName: 'tokenToEthTransferInput', methodName: 'tokenToEthTransferInput',
args: [maximumAmountIn, minimumAmountOut, deadline, options.recipient], args: [maximumAmountIn, minimumAmountOut, deadline, options.recipient],
value: '0x0', value: '0x0'
} }
} else { } else {
const outputToken = trade.outputAmount.currency const outputToken = trade.outputAmount.currency
...@@ -51,7 +51,7 @@ export default function v1SwapArguments( ...@@ -51,7 +51,7 @@ export default function v1SwapArguments(
return { return {
methodName: 'tokenToTokenTransferInput', methodName: 'tokenToTokenTransferInput',
args: [maximumAmountIn, minimumAmountOut, '0x1', deadline, options.recipient, outputToken.address], args: [maximumAmountIn, minimumAmountOut, '0x1', deadline, options.recipient, outputToken.address],
value: '0x0', value: '0x0'
} }
} }
} else { } else {
...@@ -59,13 +59,13 @@ export default function v1SwapArguments( ...@@ -59,13 +59,13 @@ export default function v1SwapArguments(
return { return {
methodName: 'ethToTokenTransferOutput', methodName: 'ethToTokenTransferOutput',
args: [minimumAmountOut, deadline, options.recipient], args: [minimumAmountOut, deadline, options.recipient],
value: maximumAmountIn, value: maximumAmountIn
} }
} else if (outputETH) { } else if (outputETH) {
return { return {
methodName: 'tokenToEthTransferOutput', methodName: 'tokenToEthTransferOutput',
args: [minimumAmountOut, maximumAmountIn, deadline, options.recipient], args: [minimumAmountOut, maximumAmountIn, deadline, options.recipient],
value: '0x0', value: '0x0'
} }
} else { } else {
const output = trade.outputAmount.currency const output = trade.outputAmount.currency
...@@ -81,9 +81,9 @@ export default function v1SwapArguments( ...@@ -81,9 +81,9 @@ export default function v1SwapArguments(
MaxUint256.toHexString(), MaxUint256.toHexString(),
deadline, deadline,
options.recipient, options.recipient,
output.address, output.address
], ],
value: '0x0', value: '0x0'
} }
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment