Commit 6965707d authored by Jordan Frankfurt's avatar Jordan Frankfurt

Revert "upgrade prettier"

This reverts commit 5fabe438.
parent d762836e
......@@ -8,7 +8,9 @@
"jsx": true
}
},
"ignorePatterns": ["node_modules/**/*"],
"ignorePatterns": [
"node_modules/**/*"
],
"settings": {
"react": {
"version": "detect"
......@@ -27,4 +29,4 @@
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/ban-ts-comment": "off"
}
}
}
\ No newline at end of file
......@@ -10,10 +10,9 @@ assignees: ''
A clear and concise description of the bug.
**Steps to Reproduce**
1. Go to ...
2. Click on ...
...
...
**Expected Behavior**
A clear and concise description of what you expected to happen.
......
name: Release
on:
# schedule:
# - cron: '0 12 * * 1-4' # every day 12:00 UTC Monday-Thursday
# schedule:
# - cron: '0 12 * * 1-4' # every day 12:00 UTC Monday-Thursday
# manual trigger
workflow_dispatch:
......
......@@ -35,7 +35,7 @@ jobs:
- run: yarn build
env:
CI: false
REACT_APP_NETWORK_URL: 'https://mainnet.infura.io/v3/4bf032f2d38a4ed6bb975b80d6340847'
REACT_APP_NETWORK_URL: "https://mainnet.infura.io/v3/4bf032f2d38a4ed6bb975b80d6340847"
- run: yarn integration-test
unit-tests:
......@@ -62,3 +62,4 @@ jobs:
${{ runner.os }}-yarn-
- run: yarn install --frozen-lockfile
- run: yarn test
......@@ -18,13 +18,13 @@ An open source interface for Uniswap -- a protocol for decentralized exchange of
## Accessing the Uniswap Interface
To access the Uniswap Interface, use an IPFS gateway link from the
[latest release](https://github.com/Uniswap/uniswap-interface/releases/latest),
[latest release](https://github.com/Uniswap/uniswap-interface/releases/latest),
or visit [app.uniswap.org](https://app.uniswap.org).
## Listing a token
Please see the
[@uniswap/default-token-list](https://github.com/uniswap/default-token-list)
[@uniswap/default-token-list](https://github.com/uniswap/default-token-list)
repository.
## Development
......@@ -47,20 +47,20 @@ To have the interface default to a different network when a wallet is not connec
1. Make a copy of `.env` named `.env.local`
2. Change `REACT_APP_NETWORK_ID` to `"{YOUR_NETWORK_ID}"`
3. Change `REACT_APP_NETWORK_URL` to e.g. `"https://{YOUR_NETWORK_ID}.infura.io/v3/{YOUR_INFURA_KEY}"`
3. Change `REACT_APP_NETWORK_URL` to e.g. `"https://{YOUR_NETWORK_ID}.infura.io/v3/{YOUR_INFURA_KEY}"`
Note that the interface only works on testnets where both
[Uniswap V2](https://uniswap.org/docs/v2/smart-contracts/factory/) and
Note that the interface only works on testnets where both
[Uniswap V2](https://uniswap.org/docs/v2/smart-contracts/factory/) and
[multicall](https://github.com/makerdao/multicall) are deployed.
The interface will not work on other networks.
## Contributions
**Please open all pull requests against the `master` branch.**
**Please open all pull requests against the `master` branch.**
CI checks will run against all PRs.
## Accessing Uniswap Interface V1
The Uniswap Interface supports swapping against, and migrating or removing liquidity from Uniswap V1. However,
if you would like to use Uniswap V1, the Uniswap V1 interface for mainnet and testnets is accessible via IPFS gateways
if you would like to use Uniswap V1, the Uniswap V1 interface for mainnet and testnets is accessible via IPFS gateways
linked from the [v1.0.0 release](https://github.com/Uniswap/uniswap-interface/releases/tag/v1.0.0).
......@@ -3,23 +3,33 @@ describe('Swap', () => {
cy.visit('/swap')
})
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', () => {
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', () => {
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', () => {
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', () => {
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', () => {
......@@ -39,7 +49,7 @@ describe('Swap', () => {
describe('expert mode', () => {
beforeEach(() => {
cy.window().then((win) => {
cy.window().then(win => {
cy.stub(win, 'prompt').returns('confirm')
})
cy.get('#open-settings-dialog-button').click()
......
......@@ -77,6 +77,6 @@ Cypress.Commands.overwrite('visit', (original, url, options) => {
const provider = new JsonRpcProvider('https://rinkeby.infura.io/v3/4bf032f2d38a4ed6bb975b80d6340847', 4)
const signer = new Wallet(PRIVATE_KEY_TEST_NEVER_USE, provider)
win.ethereum = new CustomizedBridge(signer, provider)
},
}
})
})
......@@ -26,7 +26,7 @@ const HeaderRow = styled.div`
${({ theme }) => theme.flexRowNoWrap};
padding: 1rem 1rem;
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`
padding: 1rem;
`};
......@@ -223,7 +223,7 @@ export default function AccountDetails({
pendingTransactions,
confirmedTransactions,
ENSName,
openOptions,
openOptions
}: AccountDetailsProps) {
const { chainId, account, connector } = useActiveWeb3React()
const theme = useContext(ThemeContext)
......@@ -234,10 +234,10 @@ export default function AccountDetails({
const isMetaMask = !!(ethereum && ethereum.isMetaMask)
const name = Object.keys(SUPPORTED_WALLETS)
.filter(
(k) =>
k =>
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>
}
......
......@@ -68,7 +68,7 @@ const Input = styled.input<{ error?: boolean }>`
export default function AddressInputPanel({
id,
value,
onChange,
onChange
}: {
id?: string
// the typed string value
......@@ -82,7 +82,7 @@ export default function AddressInputPanel({
const { address, loading, name } = useENS(value)
const handleInput = useCallback(
(event) => {
event => {
const input = event.target.value
const withoutSpaces = input.replace(/\s+/g, '')
onChange(withoutSpaces)
......
......@@ -20,7 +20,7 @@ export default function Confetti({ start, variant }: { start: boolean; variant?:
h: height,
w: width,
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}
initialVelocityY={30}
......
......@@ -148,7 +148,7 @@ export default function CurrencyInputPanel({
otherCurrency,
id,
showCommonBases,
customBalanceText,
customBalanceText
}: CurrencyInputPanelProps) {
const { t } = useTranslation()
......@@ -192,7 +192,7 @@ export default function CurrencyInputPanel({
<NumericalInput
className="token-amount-input"
value={value}
onUserInput={(val) => {
onUserInput={val => {
onUserInput(val)
}}
/>
......
......@@ -28,7 +28,7 @@ const StyledLogo = styled(Logo)<{ size: string }>`
export default function CurrencyLogo({
currency,
size = '24px',
style,
style
}: {
currency?: Currency
size?: string
......
......@@ -29,7 +29,7 @@ export default function DoubleCurrencyLogo({
currency0,
currency1,
size = 16,
margin = false,
margin = false
}: DoubleCurrencyLogoProps) {
return (
<Wrapper sizeraw={size} margin={margin}>
......
......@@ -5,7 +5,7 @@ const CURRENCY_AMOUNT_MIN = new Fraction(JSBI.BigInt(1), JSBI.BigInt(1000000))
export default function FormattedCurrencyAmount({
currencyAmount,
significantDigits = 4,
significantDigits = 4
}: {
currencyAmount: CurrencyAmount
significantDigits?: number
......
......@@ -201,7 +201,7 @@ const UniIcon = styled.div`
const activeClassName = 'ACTIVE'
const StyledNavLink = styled(NavLink).attrs({
activeClassName,
activeClassName
})`
${({ theme }) => theme.flexRowNoWrap}
align-items: left;
......@@ -228,7 +228,7 @@ const StyledNavLink = styled(NavLink).attrs({
`
const StyledExternalLink = styled(ExternalLink).attrs({
activeClassName,
activeClassName
})<{ isActive?: boolean }>`
${({ theme }) => theme.flexRowNoWrap}
align-items: left;
......@@ -291,7 +291,7 @@ const NETWORK_LABELS: { [chainId in ChainId]?: string } = {
[ChainId.RINKEBY]: 'Rinkeby',
[ChainId.ROPSTEN]: 'Ropsten',
[ChainId.GÖRLI]: 'Görli',
[ChainId.KOVAN]: 'Kovan',
[ChainId.KOVAN]: 'Kovan'
}
export default function Header() {
......@@ -380,7 +380,7 @@ export default function Header() {
<HideSmall>
<TYPE.white
style={{
paddingRight: '.4rem',
paddingRight: '.4rem'
}}
>
<CountUp
......
......@@ -148,5 +148,5 @@ export const dummyData = [
{ time: '2019-05-22', value: 43.3 },
{ time: '2019-05-23', value: 42.73 },
{ time: '2019-05-24', value: 42.67 },
{ time: '2019-05-28', value: 42.75 },
{ time: '2019-05-28', value: 42.75 }
]
......@@ -13,7 +13,7 @@ export default function ListLogo({
logoURI,
style,
size = '24px',
alt,
alt
}: {
logoURI: string
size?: string
......
......@@ -14,7 +14,7 @@ export interface LogoProps extends Pick<ImageProps, 'style' | 'alt' | 'className
export default function Logo({ srcs, alt, ...rest }: LogoProps) {
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) {
return (
......@@ -24,7 +24,7 @@ export default function Logo({ srcs, alt, ...rest }: LogoProps) {
src={src}
onError={() => {
if (src) BAD_SRCS[src] = true
refresh((i) => i + 1)
refresh(i => i + 1)
}}
/>
)
......
......@@ -29,7 +29,7 @@ const AnimatedDialogContent = animated(DialogContent)
const StyledDialogContent = styled(({ minHeight, maxHeight, mobile, isOpen, ...rest }) => (
<AnimatedDialogContent {...rest} />
)).attrs({
'aria-label': 'dialog',
'aria-label': 'dialog'
})`
overflow-y: ${({ mobile }) => (mobile ? 'scroll' : 'hidden')};
......@@ -63,15 +63,13 @@ const StyledDialogContent = styled(({ minHeight, maxHeight, mobile, isOpen, ...r
`}
${({ theme, mobile }) => theme.mediaWidth.upToSmall`
width: 85vw;
${
mobile &&
${mobile &&
css`
width: 100vw;
border-radius: 20px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
`
}
`}
`}
}
`
......@@ -91,25 +89,25 @@ export default function Modal({
minHeight = false,
maxHeight = 90,
initialFocusRef,
children,
children
}: ModalProps) {
const fadeTransition = useTransition(isOpen, null, {
config: { duration: 200 },
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 },
leave: { opacity: 0 }
})
const [{ y }, set] = useSpring(() => ({ y: 0, config: { mass: 1, tension: 210, friction: 20 } }))
const bind = useGesture({
onDrag: (state) => {
onDrag: state => {
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)) {
onDismiss()
}
},
}
})
return (
......@@ -122,7 +120,7 @@ export default function Modal({
{...(isMobile
? {
...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"
......
......@@ -41,7 +41,7 @@ export function LoadingView({ children, onDismiss }: { children: any; onDismiss:
export function SubmittedView({
children,
onDismiss,
hash,
hash
}: {
children: any
onDismiss: () => void
......
......@@ -22,7 +22,7 @@ const Tabs = styled.div`
const activeClassName = 'ACTIVE'
const StyledNavLink = styled(NavLink).attrs({
activeClassName,
activeClassName
})`
${({ theme }) => theme.flexRowNoWrap}
align-items: center;
......
......@@ -61,7 +61,7 @@ export const Input = React.memo(function InnerInput({
<StyledInput
{...rest}
value={value}
onChange={(event) => {
onChange={event => {
// replace commas with periods, because uniswap exclusively uses period as the decimal separator
enforcer(event.target.value.replace(/,/g, '.'))
}}
......
......@@ -9,8 +9,8 @@ import Portal from '@reach/portal'
const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 9999;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)};
visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2};
......@@ -91,8 +91,8 @@ export default function Popover({ content, show, children, placement = 'auto' }:
strategy: 'fixed',
modifiers: [
{ name: 'offset', options: { offset: [8, 8] } },
{ name: 'arrow', options: { element: arrowElement } },
],
{ name: 'arrow', options: { element: arrowElement } }
]
})
const updateCallback = useCallback(() => {
update && update()
......
......@@ -10,7 +10,7 @@ import {
useModalOpen,
useShowClaimPopup,
useToggleSelfClaimModal,
useToggleShowClaimPopup,
useToggleShowClaimPopup
} from '../../state/application/hooks'
import { useUserHasAvailableClaim, useUserUnclaimedAmount } from '../../state/claim/hooks'
......
......@@ -23,7 +23,7 @@ export default function ListUpdatePopup({
listUrl,
oldList,
newList,
auto,
auto
}: {
popKey: string
listUrl: string
......@@ -40,7 +40,7 @@ export default function ListUpdatePopup({
ReactGA.event({
category: 'Lists',
action: 'Update List from Popup',
label: listUrl,
label: listUrl
})
dispatch(acceptListUpdate(listUrl))
removeThisPopup()
......
......@@ -49,7 +49,7 @@ const AnimatedFader = animated(Fader)
export default function PopupItem({
removeAfterMs,
content,
popKey,
popKey
}: {
removeAfterMs: number | null
content: PopupContent
......@@ -74,12 +74,12 @@ export default function PopupItem({
let popupContent
if ('txn' in content) {
const {
txn: { hash, success, summary },
txn: { hash, success, summary }
} = content
popupContent = <TransactionPopup hash={hash} success={success} summary={summary} />
} else if ('listUpdate' in content) {
const {
listUpdate: { listUrl, oldList, newList, auto },
listUpdate: { listUrl, oldList, newList, auto }
} = content
popupContent = <ListUpdatePopup popKey={popKey} listUrl={listUrl} oldList={oldList} newList={newList} auto={auto} />
}
......@@ -87,7 +87,7 @@ export default function PopupItem({
const faderStyle = useSpring({
from: { width: '100%' },
to: { width: '0%' },
config: { duration: removeAfterMs ?? undefined },
config: { duration: removeAfterMs ?? undefined }
})
return (
......
......@@ -15,7 +15,7 @@ const RowNoFlex = styled(AutoRow)`
export default function TransactionPopup({
hash,
success,
summary,
summary
}: {
hash: string
success?: boolean
......
......@@ -54,7 +54,7 @@ export default function Popups() {
<>
<FixedPopupColumn gap="20px" extraPadding={urlWarningActive}>
<ClaimPopup />
{activePopups.map((item) => (
{activePopups.map(item => (
<PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} />
))}
</FixedPopupColumn>
......@@ -63,7 +63,7 @@ export default function Popups() {
{activePopups // reverse so new items up front
.slice(0)
.reverse()
.map((item) => (
.map(item => (
<PopupItem key={item.key} content={item.content} popKey={item.key} removeAfterMs={item.removeAfterMs} />
))}
</MobilePopupInner>
......
......@@ -75,7 +75,7 @@ export function MinimalPositionCard({ pair, showUnwrapped = false, border }: Pos
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false)
]
: [undefined, undefined]
......@@ -186,7 +186,7 @@ export default function FullPositionCard({ pair, border, stakedBalance }: Positi
JSBI.greaterThanOrEqual(totalPoolTokens.raw, userPoolBalance.raw)
? [
pair.getLiquidityValue(pair.token0, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false),
pair.getLiquidityValue(pair.token1, totalPoolTokens, userPoolBalance, false)
]
: [undefined, undefined]
......
......@@ -28,7 +28,7 @@ const BaseWrapper = styled.div<{ disable?: boolean }>`
export default function CommonBases({
chainId,
onSelect,
selectedCurrency,
selectedCurrency
}: {
chainId?: ChainId
selectedCurrency?: Currency | null
......
......@@ -102,7 +102,7 @@ function CurrencyRow({
onSelect,
isSelected,
otherSelected,
style,
style
}: {
currency: Currency
onSelect: () => void
......@@ -153,7 +153,7 @@ export default function CurrencyList({
showETH,
showImportView,
setImportToken,
breakIndex,
breakIndex
}: {
height: number
currencies: Currency[]
......@@ -241,7 +241,7 @@ export default function CurrencyList({
setImportToken,
showImportView,
breakIndex,
theme.text1,
theme.text1
]
)
......
......@@ -61,7 +61,7 @@ export function CurrencySearch({
isOpen,
showManageView,
showImportView,
setImportToken,
setImportToken
}: CurrencySearchProps) {
const { t } = useTranslation()
const { chainId } = useActiveWeb3React()
......@@ -87,7 +87,7 @@ export function CurrencySearch({
ReactGA.event({
category: 'Currency Select',
action: 'Search by address',
label: isAddressSearch,
label: isAddressSearch
})
}
}, [isAddressSearch])
......@@ -124,7 +124,7 @@ export function CurrencySearch({
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => {
const handleInput = useCallback(event => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
......
......@@ -22,7 +22,7 @@ export enum CurrencyModalView {
search,
manage,
importToken,
importList,
importList
}
export default function CurrencySearchModal({
......@@ -31,7 +31,7 @@ export default function CurrencySearchModal({
onCurrencySelect,
selectedCurrency,
otherSelectedCurrency,
showCommonBases = false,
showCommonBases = false
}: CurrencySearchModalProps) {
const [modalView, setModalView] = useState<CurrencyModalView>(CurrencyModalView.manage)
const lastOpen = useLast(isOpen)
......
......@@ -56,7 +56,7 @@ export function ImportList({ listURL, list, setModalView, onDismiss }: ImportPro
ReactGA.event({
category: 'Lists',
action: 'Add List',
label: listURL,
label: listURL
})
// turn list on
......@@ -64,11 +64,11 @@ export function ImportList({ listURL, list, setModalView, onDismiss }: ImportPro
// go back to lists
setModalView(CurrencyModalView.manage)
})
.catch((error) => {
.catch(error => {
ReactGA.event({
category: 'Lists',
action: 'Add List Failed',
label: listURL,
label: listURL
})
setAddError(error.message)
dispatch(removeList(listURL))
......
......@@ -45,7 +45,7 @@ export default function ImportRow({
style,
dim,
showImportView,
setImportToken,
setImportToken
}: {
token: Token
style?: CSSProperties
......
......@@ -74,7 +74,7 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }:
</PaddedColumn>
<SectionBreak />
<PaddedColumn gap="md">
{tokens.map((token) => {
{tokens.map(token => {
const list = chainId && inactiveTokenList?.[chainId]?.[token.address]?.list
return (
<Card backgroundColor={theme.bg2} key={'import' + token.address} className=".token-warning-container">
......@@ -151,7 +151,7 @@ export function ImportToken({ tokens, onBack, onDismiss, handleCurrencySelect }:
borderRadius="20px"
padding="10px 1rem"
onClick={() => {
tokens.map((token) => addToken(token))
tokens.map(token => addToken(token))
handleCurrencySelect && handleCurrencySelect(tokens[0])
}}
className=".token-dismiss-button"
......
......@@ -46,7 +46,7 @@ export default function Manage({
setModalView,
setImportList,
setImportToken,
setListUrl,
setListUrl
}: {
onDismiss: () => void
setModalView: (view: CurrencyModalView) => void
......
......@@ -42,8 +42,8 @@ const UnpaddedLinkStyledButton = styled(LinkStyledButton)`
const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 100;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)};
visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2};
border: 1px solid ${({ theme }) => theme.bg3};
......@@ -93,7 +93,7 @@ function listUrlRowHTMLId(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 { current: list, pendingUpdate: pending } = listsByUrl[listUrl]
......@@ -109,7 +109,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'auto',
strategy: 'fixed',
modifiers: [{ name: 'offset', options: { offset: [8, 8] } }],
modifiers: [{ name: 'offset', options: { offset: [8, 8] } }]
})
useOnClickOutside(node, open ? toggle : undefined)
......@@ -119,7 +119,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({
category: 'Lists',
action: 'Update List from List Select',
label: listUrl,
label: listUrl
})
dispatch(acceptListUpdate(listUrl))
}, [dispatch, listUrl, pending])
......@@ -128,13 +128,13 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({
category: 'Lists',
action: 'Start Remove List',
label: listUrl,
label: listUrl
})
if (window.prompt(`Please confirm you would like to remove this list by typing REMOVE`) === `REMOVE`) {
ReactGA.event({
category: 'Lists',
action: 'Confirm Remove List',
label: listUrl,
label: listUrl
})
dispatch(removeList(listUrl))
}
......@@ -144,7 +144,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({
category: 'Lists',
action: 'Enable List',
label: listUrl,
label: listUrl
})
dispatch(enableList(listUrl))
}, [dispatch, listUrl])
......@@ -153,7 +153,7 @@ const ListRow = memo(function ListRow({ listUrl }: { listUrl: string }) {
ReactGA.event({
category: 'Lists',
action: 'Disable List',
label: listUrl,
label: listUrl
})
dispatch(disableList(listUrl))
}, [dispatch, listUrl])
......@@ -216,7 +216,7 @@ const ListContainer = styled.div`
export function ManageLists({
setModalView,
setImportList,
setListUrl,
setListUrl
}: {
setModalView: (view: CurrencyModalView) => void
setImportList: (list: TokenList) => void
......@@ -237,7 +237,7 @@ export function ManageLists({
}
}, [activeCopy, activeListUrls])
const handleInput = useCallback((e) => {
const handleInput = useCallback(e => {
setListUrlInput(e.target.value)
}, [])
......@@ -250,7 +250,7 @@ export function ManageLists({
const sortedLists = useMemo(() => {
const listUrls = Object.keys(lists)
return listUrls
.filter((listUrl) => {
.filter(listUrl => {
// only show loaded lists, hide unsupported lists
return Boolean(lists[listUrl].current) && !Boolean(UNSUPPORTED_LIST_URLS.includes(listUrl))
})
......@@ -286,7 +286,7 @@ export function ManageLists({
useEffect(() => {
async function fetchTempList() {
fetchList(listUrlInput, false)
.then((list) => setTempList(list))
.then(list => setTempList(list))
.catch(() => setAddError('Error importing list'))
}
// if valid url, fetch details for card
......@@ -367,7 +367,7 @@ export function ManageLists({
<Separator />
<ListContainer>
<AutoColumn gap="md">
{sortedLists.map((listUrl) => (
{sortedLists.map(listUrl => (
<ListRow key={listUrl} listUrl={listUrl} />
))}
</AutoColumn>
......
......@@ -37,7 +37,7 @@ const Footer = styled.div`
export default function ManageTokens({
setModalView,
setImportToken,
setImportToken
}: {
setModalView: (view: CurrencyModalView) => void
setImportToken: (token: Token) => void
......@@ -49,7 +49,7 @@ export default function ManageTokens({
// manage focus on modal show
const inputRef = useRef<HTMLInputElement>()
const handleInput = useCallback((event) => {
const handleInput = useCallback(event => {
const input = event.target.value
const checksummedInput = isAddress(input)
setSearchQuery(checksummedInput || input)
......@@ -65,7 +65,7 @@ export default function ManageTokens({
const handleRemoveAll = useCallback(() => {
if (chainId && userAddedTokens) {
userAddedTokens.map((token) => {
userAddedTokens.map(token => {
return removeToken(chainId, token.address)
})
}
......@@ -74,7 +74,7 @@ export default function ManageTokens({
const tokenList = useMemo(() => {
return (
chainId &&
userAddedTokens.map((token) => (
userAddedTokens.map(token => (
<RowBetween key={token.address} width="100%">
<RowFixed>
<CurrencyLogo currency={token} size={'20px'} />
......
......@@ -19,7 +19,7 @@ export const FilterWrapper = styled(RowFixed)`
export default function SortButton({
toggleSortOrder,
ascending,
ascending
}: {
toggleSortOrder: () => void
ascending: boolean
......
......@@ -8,13 +8,13 @@ export function filterTokens(tokens: Token[], search: string): Token[] {
const searchingAddress = isAddress(search)
if (searchingAddress) {
return tokens.filter((token) => token.address === searchingAddress)
return tokens.filter(token => token.address === searchingAddress)
}
const lowerSearchParts = search
.toLowerCase()
.split(/\s+/)
.filter((s) => s.length > 0)
.filter(s => s.length > 0)
if (lowerSearchParts.length === 0) {
return tokens
......@@ -24,12 +24,12 @@ export function filterTokens(tokens: Token[], search: string): Token[] {
const sParts = s
.toLowerCase()
.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
return (symbol && matchesSearch(symbol)) || (name && matchesSearch(name))
})
......@@ -44,7 +44,7 @@ export function useSortedTokensByQuery(tokens: Token[] | undefined, searchQuery:
const symbolMatch = searchQuery
.toLowerCase()
.split(/\s+/)
.filter((s) => s.length > 0)
.filter(s => s.length > 0)
if (symbolMatch.length > 1) {
return tokens
......@@ -55,7 +55,7 @@ export function useSortedTokensByQuery(tokens: Token[] | undefined, searchQuery:
const rest: Token[] = []
// sort tokens by exact match -> subtring on symbol match -> rest
tokens.map((token) => {
tokens.map(token => {
if (token.symbol?.toLowerCase() === symbolMatch[0]) {
return exactMatches.push(token)
} else if (token.symbol?.toLowerCase().startsWith(searchQuery.toLowerCase().trim())) {
......
......@@ -21,8 +21,8 @@ export const StyledMenu = styled.div`
export const PopoverContainer = styled.div<{ show: boolean }>`
z-index: 100;
visibility: ${(props) => (props.show ? 'visible' : 'hidden')};
opacity: ${(props) => (props.show ? 1 : 0)};
visibility: ${props => (props.show ? 'visible' : 'hidden')};
opacity: ${props => (props.show ? 1 : 0)};
transition: visibility 150ms linear, opacity 150ms linear;
background: ${({ theme }) => theme.bg2};
border: 1px solid ${({ theme }) => theme.bg3};
......
......@@ -9,7 +9,7 @@ import {
useExpertModeManager,
useUserTransactionTTL,
useUserSlippageTolerance,
useUserSingleHopOnly,
useUserSingleHopOnly
} from '../../state/user/hooks'
import { TYPE } from '../../theme'
import { ButtonError } from '../Button'
......
......@@ -98,7 +98,7 @@ interface InputSliderProps {
export default function Slider({ value, onChange, min = 0, step = 1, max = 100, size = 28 }: InputSliderProps) {
const changeCallback = useCallback(
(e) => {
e => {
onChange(parseInt(e.target.value))
},
[onChange]
......
......@@ -6,7 +6,7 @@ import { ImportToken } from 'components/SearchModal/ImportToken'
export default function TokenWarningModal({
isOpen,
tokens,
onConfirm,
onConfirm
}: {
isOpen: boolean
tokens: Token[]
......
......@@ -71,7 +71,7 @@ function TransactionSubmittedContent({
onDismiss,
chainId,
hash,
currencyToAdd,
currencyToAdd
}: {
onDismiss: () => void
hash: string | undefined
......@@ -134,7 +134,7 @@ export function ConfirmationModalContent({
title,
bottomContent,
onDismiss,
topContent,
topContent
}: {
title: string
onDismiss: () => void
......@@ -199,7 +199,7 @@ export default function TransactionConfirmationModal({
hash,
pendingText,
content,
currencyToAdd,
currencyToAdd
}: ConfirmationModalProps) {
const { chainId } = useActiveWeb3React()
......
......@@ -11,11 +11,11 @@ import { darken } from 'polished'
enum SlippageError {
InvalidInput = 'InvalidInput',
RiskyLow = 'RiskyLow',
RiskyHigh = 'RiskyHigh',
RiskyHigh = 'RiskyHigh'
}
enum DeadlineError {
InvalidInput = 'InvalidInput',
InvalidInput = 'InvalidInput'
}
const FancyButton = styled.button`
......@@ -199,7 +199,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
onBlur={() => {
parseCustomSlippage((rawSlippage / 100).toFixed(2))
}}
onChange={(e) => parseCustomSlippage(e.target.value)}
onChange={e => parseCustomSlippage(e.target.value)}
color={!slippageInputIsValid ? 'red' : ''}
/>
%
......@@ -211,7 +211,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
style={{
fontSize: '14px',
paddingTop: '7px',
color: slippageError === SlippageError.InvalidInput ? 'red' : '#F3841E',
color: slippageError === SlippageError.InvalidInput ? 'red' : '#F3841E'
}}
>
{slippageError === SlippageError.InvalidInput
......@@ -239,7 +239,7 @@ export default function SlippageTabs({ rawSlippage, setRawSlippage, deadline, se
}}
placeholder={(deadline / 60).toString()}
value={deadlineInput}
onChange={(e) => parseCustomDeadline(e.target.value)}
onChange={e => parseCustomDeadline(e.target.value)}
/>
</OptionCustom>
<TYPE.body style={{ paddingLeft: '8px' }} fontSize={14}>
......
......@@ -62,7 +62,7 @@ const CircleWrapper = styled.div`
const HeaderText = styled.div`
${({ 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-weight: 500;
`
......@@ -97,7 +97,7 @@ export default function Option({
subheader = null,
icon,
active = false,
id,
id
}: {
link?: string | null
clickable?: boolean
......
......@@ -67,7 +67,7 @@ export default function PendingView({
connector,
error = false,
setPendingError,
tryActivation,
tryActivation
}: {
connector?: AbstractConnector
error?: boolean
......@@ -100,7 +100,7 @@ export default function PendingView({
)}
</LoadingWrapper>
</LoadingMessage>
{Object.keys(SUPPORTED_WALLETS).map((key) => {
{Object.keys(SUPPORTED_WALLETS).map(key => {
const option = SUPPORTED_WALLETS[key]
if (option.connector === connector) {
if (option.connector === injected) {
......
......@@ -47,7 +47,7 @@ const HeaderRow = styled.div`
${({ theme }) => theme.flexRowNoWrap};
padding: 1rem 1rem;
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`
padding: 1rem;
`};
......@@ -113,13 +113,13 @@ const WALLET_VIEWS = {
OPTIONS: 'options',
OPTIONS_SECONDARY: 'options_secondary',
ACCOUNT: 'account',
PENDING: 'pending',
PENDING: 'pending'
}
export default function WalletModal({
pendingTransactions,
confirmedTransactions,
ENSName,
ENSName
}: {
pendingTransactions: string[] // hashes of pending
confirmedTransactions: string[] // hashes of confirmed
......@@ -165,7 +165,7 @@ export default function WalletModal({
const tryActivation = async (connector: AbstractConnector | undefined) => {
let name = ''
Object.keys(SUPPORTED_WALLETS).map((key) => {
Object.keys(SUPPORTED_WALLETS).map(key => {
if (connector === SUPPORTED_WALLETS[key].connector) {
return (name = SUPPORTED_WALLETS[key].name)
}
......@@ -175,7 +175,7 @@ export default function WalletModal({
ReactGA.event({
category: 'Wallet',
action: 'Change Wallet',
label: name,
label: name
})
setPendingWallet(connector) // set wallet for pending view
setWalletView(WALLET_VIEWS.PENDING)
......@@ -186,7 +186,7 @@ export default function WalletModal({
}
connector &&
activate(connector, undefined, true).catch((error) => {
activate(connector, undefined, true).catch(error => {
if (error instanceof UnsupportedChainIdError) {
activate(connector) // a little janky...can't use setError because the connector isn't set
} else {
......@@ -205,7 +205,7 @@ export default function WalletModal({
// get wallets user can switch too, depending on device/browser
function getOptions() {
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]
// check for mobile options
if (isMobile) {
......
......@@ -174,7 +174,7 @@ function Web3StatusInner() {
return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [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 hasSocks = useHasSocks()
......@@ -225,8 +225,8 @@ export default function Web3Status() {
return txs.filter(isTransactionRecent).sort(newTransactionsFirst)
}, [allTransactions])
const pending = sortedRecentTransactions.filter((tx) => !tx.receipt).map((tx) => tx.hash)
const confirmed = 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)
if (!contextNetwork.active && !active) {
return null
......
......@@ -75,11 +75,11 @@ export default function AddressClaimModal({ isOpen, onDismiss }: { isOpen: boole
function onClaim() {
setAttempting(true)
claimCallback()
.then((hash) => {
.then(hash => {
setHash(hash)
})
// reset modal and log error
.catch((error) => {
.catch(error => {
setAttempting(false)
console.log(error)
})
......
......@@ -67,7 +67,7 @@ export default function ClaimModal() {
setAttempting(true)
claimCallback()
// reset modal and log error
.catch((error) => {
.catch(error => {
setAttempting(false)
console.log(error)
})
......
......@@ -46,7 +46,7 @@ export default function ClaimRewardModal({ isOpen, onDismiss, stakingInfo }: Sta
.getReward({ gasLimit: 350000 })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Claim accumulated UNI rewards`,
summary: `Claim accumulated UNI rewards`
})
setHash(response.hash)
})
......
......@@ -97,7 +97,7 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
)
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Deposit liquidity`,
summary: `Deposit liquidity`
})
setHash(response.hash)
})
......@@ -141,50 +141,50 @@ export default function StakingModal({ isOpen, onDismiss, stakingInfo, userLiqui
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
{ name: 'verifyingContract', type: 'address' }
]
const domain = {
name: 'Uniswap V2',
version: '1',
chainId: chainId,
verifyingContract: pairContract.address,
verifyingContract: pairContract.address
}
const Permit = [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }
]
const message = {
owner: account,
spender: stakingInfo.stakingRewardAddress,
value: liquidityAmount.raw.toString(),
nonce: nonce.toHexString(),
deadline: deadline.toNumber(),
deadline: deadline.toNumber()
}
const data = JSON.stringify({
types: {
EIP712Domain,
Permit,
Permit
},
domain,
primaryType: 'Permit',
message,
message
})
library
.send('eth_signTypedData_v4', [account, data])
.then(splitSignature)
.then((signature) => {
.then(signature => {
setSignatureData({
v: signature.v,
r: signature.r,
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
if (error?.code !== 4001) {
approveCallback()
......
......@@ -47,7 +47,7 @@ export default function UnstakingModal({ isOpen, onDismiss, stakingInfo }: Staki
.exit({ gasLimit: 300000 })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Withdraw deposited liquidity`,
summary: `Withdraw deposited liquidity`
})
setHash(response.hash)
})
......
......@@ -33,8 +33,8 @@ export default function BetterTradeLink({ version }: { version: Version }) {
...location,
search: `?${stringify({
...search,
use: version !== DEFAULT_VERSION ? version : undefined,
})}`,
use: version !== DEFAULT_VERSION ? version : undefined
})}`
}
}, [location, search, version])
......@@ -58,8 +58,8 @@ export function DefaultVersionLink() {
...location,
search: `?${stringify({
...search,
use: DEFAULT_VERSION,
})}`,
use: DEFAULT_VERSION
})}`
}
}, [location, search])
......
......@@ -2,7 +2,7 @@ import { currencyEquals, Trade } from '@uniswap/sdk'
import React, { useCallback, useMemo } from 'react'
import TransactionConfirmationModal, {
ConfirmationModalContent,
TransactionErrorContent,
TransactionErrorContent
} from '../TransactionConfirmationModal'
import SwapModalFooter from './SwapModalFooter'
import SwapModalHeader from './SwapModalHeader'
......@@ -33,7 +33,7 @@ export default function ConfirmSwapModal({
swapErrorMessage,
isOpen,
attemptingTxn,
txHash,
txHash
}: {
isOpen: boolean
trade: Trade | undefined
......
......@@ -9,7 +9,7 @@ import {
computeSlippageAdjustedAmounts,
computeTradePriceBreakdown,
formatExecutionPrice,
warningSeverity,
warningSeverity
} from '../../utils/prices'
import { ButtonError } from '../Button'
import { AutoColumn } from '../Column'
......@@ -23,7 +23,7 @@ export default function SwapModalFooter({
onConfirm,
allowedSlippage,
swapErrorMessage,
disabledConfirm,
disabledConfirm
}: {
trade: Trade
allowedSlippage: number
......@@ -35,7 +35,7 @@ export default function SwapModalFooter({
const theme = useContext(ThemeContext)
const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [
allowedSlippage,
trade,
trade
])
const { priceImpactWithoutFee, realizedLPFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade])
const severity = warningSeverity(priceImpactWithoutFee)
......@@ -56,7 +56,7 @@ export default function SwapModalFooter({
alignItems: 'center',
display: 'flex',
textAlign: 'right',
paddingLeft: '10px',
paddingLeft: '10px'
}}
>
{formatExecutionPrice(trade, showInverted)}
......
......@@ -18,7 +18,7 @@ export default function SwapModalHeader({
allowedSlippage,
recipient,
showAcceptChanges,
onAcceptChanges,
onAcceptChanges
}: {
trade: Trade
allowedSlippage: number
......@@ -28,7 +28,7 @@ export default function SwapModalHeader({
}) {
const slippageAdjustedAmounts = useMemo(() => computeSlippageAdjustedAmounts(trade, allowedSlippage), [
trade,
allowedSlippage,
allowedSlippage
])
const { priceImpactWithoutFee } = useMemo(() => computeTradePriceBreakdown(trade), [trade])
const priceImpactSeverity = warningSeverity(priceImpactWithoutFee)
......
......@@ -40,7 +40,7 @@ const AddressText = styled(TYPE.blue)`
export default function UnsupportedCurrencyFooter({
show,
currencies,
currencies
}: {
show: boolean
currencies: (Currency | undefined)[]
......@@ -50,7 +50,7 @@ export default function UnsupportedCurrencyFooter({
const tokens =
chainId && currencies
? currencies.map((currency) => {
? currencies.map(currency => {
return wrappedCurrency(currency, chainId)
})
: []
......@@ -67,7 +67,7 @@ export default function UnsupportedCurrencyFooter({
<CloseIcon onClick={() => setShowDetails(false)} />
</RowBetween>
{tokens.map((token) => {
{tokens.map(token => {
return (
token &&
unsupportedTokens &&
......
......@@ -77,7 +77,7 @@ export default function DelegateModal({ isOpen, onDismiss, title }: VoteModalPro
if (!delegateCallback) return
// try delegation and store hash
const hash = await delegateCallback(parsedAddress ?? undefined)?.catch((error) => {
const hash = await delegateCallback(parsedAddress ?? undefined)?.catch(error => {
setAttempting(false)
console.log(error)
})
......
......@@ -44,7 +44,7 @@ interface VoteModalProps {
export default function VoteModal({ isOpen, onDismiss, proposalId, support }: VoteModalProps) {
const { chainId } = useActiveWeb3React()
const {
voteCallback,
voteCallback
}: {
voteCallback: (proposalId: string | undefined, support: boolean) => Promise<string> | undefined
} = useVoteCallback()
......@@ -71,7 +71,7 @@ export default function VoteModal({ isOpen, onDismiss, proposalId, support }: Vo
if (!voteCallback) return
// try delegation and store hash
const hash = await voteCallback(proposalId, support)?.catch((error) => {
const hash = await voteCallback(proposalId, support)?.catch(error => {
setAttempting(false)
console.log(error)
})
......
......@@ -9,7 +9,7 @@ const CHAIN_ID_NETWORK_ARGUMENT: { readonly [chainId in FormaticSupportedChains]
[ChainId.MAINNET]: undefined,
[ChainId.ROPSTEN]: 'ropsten',
[ChainId.RINKEBY]: 'rinkeby',
[ChainId.KOVAN]: 'kovan',
[ChainId.KOVAN]: 'kovan'
}
export class FortmaticConnector extends FortmaticConnectorCore {
......@@ -27,7 +27,7 @@ export class FortmaticConnector extends FortmaticConnectorCore {
const provider = this.fortmatic.getProvider()
const pollForOverlayReady = new Promise((resolve) => {
const pollForOverlayReady = new Promise(resolve => {
const interval = setInterval(() => {
if (provider.overlayReady) {
clearInterval(interval)
......@@ -39,7 +39,7 @@ export class FortmaticConnector extends FortmaticConnectorCore {
const [account] = await Promise.all([
provider.enable().then((accounts: string[]) => accounts[0]),
pollForOverlayReady,
pollForOverlayReady
])
return { provider: this.fortmatic.getProvider(), chainId: (this as any).chainId, account }
......
......@@ -60,7 +60,7 @@ class MiniRpcProvider implements AsyncSendable {
response = await fetch(this.url, {
method: 'POST',
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) {
batch.forEach(({ reject }) => reject(new Error('Failed to send batch call')))
......@@ -87,7 +87,7 @@ class MiniRpcProvider implements AsyncSendable {
const {
resolve,
reject,
request: { method },
request: { method }
} = byKey[result.id]
if (resolve && reject) {
if ('error' in result) {
......@@ -111,8 +111,8 @@ class MiniRpcProvider implements AsyncSendable {
callback: (error: any, response: any) => void
): void => {
this.request(request.method, request.params)
.then((result) => callback(null, { jsonrpc: '2.0', id: request.id, result }))
.catch((error) => callback(error, null))
.then(result => callback(null, { jsonrpc: '2.0', id: request.id, result }))
.catch(error => callback(error, null))
}
public readonly request = async (
......@@ -131,10 +131,10 @@ class MiniRpcProvider implements AsyncSendable {
jsonrpc: '2.0',
id: this.nextId++,
method,
params,
params
},
resolve,
reject,
reject
})
})
this.batchTimeoutId = this.batchTimeoutId ?? setTimeout(this.clearBatch, this.batchWaitTimeMs)
......
......@@ -18,7 +18,7 @@ if (typeof NETWORK_URL === 'undefined') {
}
export const network = new NetworkConnector({
urls: { [NETWORK_CHAIN_ID]: NETWORK_URL },
urls: { [NETWORK_CHAIN_ID]: NETWORK_URL }
})
let networkLibrary: Web3Provider | undefined
......@@ -27,7 +27,7 @@ export function getNetworkLibrary(): Web3Provider {
}
export const injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42],
supportedChainIds: [1, 3, 4, 5, 42]
})
// mainnet only
......@@ -35,19 +35,19 @@ export const walletconnect = new WalletConnectConnector({
rpc: { 1: NETWORK_URL },
bridge: 'https://bridge.walletconnect.org',
qrcode: true,
pollingInterval: 15000,
pollingInterval: 15000
})
// mainnet only
export const fortmatic = new FortmaticConnector({
apiKey: FORMATIC_KEY ?? '',
chainId: 1,
chainId: 1
})
// mainnet only
export const portis = new PortisConnector({
dAppId: PORTIS_ID ?? '',
networks: [1],
networks: [1]
})
// mainnet only
......@@ -55,5 +55,5 @@ export const walletlink = new WalletLinkConnector({
url: NETWORK_URL,
appName: 'Uniswap',
appLogoUrl:
'https://mpng.pngfly.com/20181202/bex/kisspng-emoji-domain-unicorn-pin-badges-sticker-unicorn-tumblr-emoji-unicorn-iphoneemoji-5c046729264a77.5671679315437924251569.jpg',
'https://mpng.pngfly.com/20181202/bex/kisspng-emoji-domain-unicorn-pin-badges-sticker-unicorn-tumblr-emoji-unicorn-iphoneemoji-5c046729264a77.5671679315437924251569.jpg'
})
......@@ -37,18 +37,18 @@ export const UNI: { [chainId in ChainId]: Token } = {
[ChainId.RINKEBY]: new Token(ChainId.RINKEBY, UNI_ADDRESS, 18, 'UNI', 'Uniswap'),
[ChainId.ROPSTEN]: new Token(ChainId.ROPSTEN, 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 } = {
[UNI_ADDRESS]: 'UNI',
[GOVERNANCE_ADDRESS]: 'Governance',
[TIMELOCK_ADDRESS]: 'Timelock',
[TIMELOCK_ADDRESS]: 'Timelock'
}
// TODO: specify merkle distributor for mainnet
export const MERKLE_DISTRIBUTOR_ADDRESS: { [chainId in ChainId]?: string } = {
[ChainId.MAINNET]: '0x090D4613473dEE047c3f2706764f49E0821D256e',
[ChainId.MAINNET]: '0x090D4613473dEE047c3f2706764f49E0821D256e'
}
const WETH_ONLY: ChainTokenList = {
......@@ -56,13 +56,13 @@ const WETH_ONLY: ChainTokenList = {
[ChainId.ROPSTEN]: [WETH[ChainId.ROPSTEN]],
[ChainId.RINKEBY]: [WETH[ChainId.RINKEBY]],
[ChainId.GÖRLI]: [WETH[ChainId.GÖRLI]],
[ChainId.KOVAN]: [WETH[ChainId.KOVAN]],
[ChainId.KOVAN]: [WETH[ChainId.KOVAN]]
}
// used to construct intermediary pairs for trading
export const BASES_TO_CHECK_TRADES_AGAINST: ChainTokenList = {
...WETH_ONLY,
[ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, COMP, MKR, WBTC],
[ChainId.MAINNET]: [...WETH_ONLY[ChainId.MAINNET], DAI, USDC, USDT, COMP, MKR, WBTC]
}
/**
......@@ -71,31 +71,31 @@ export const BASES_TO_CHECK_TRADES_AGAINST: ChainTokenList = {
*/
export const CUSTOM_BASES: { [chainId in ChainId]?: { [tokenAddress: string]: Token[] } } = {
[ChainId.MAINNET]: {
[AMPL.address]: [DAI, WETH[ChainId.MAINNET]],
},
[AMPL.address]: [DAI, WETH[ChainId.MAINNET]]
}
}
// used for display in the default list when adding liquidity
export const SUGGESTED_BASES: ChainTokenList = {
...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
export const BASES_TO_TRACK_LIQUIDITY_FOR: ChainTokenList = {
...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][] } = {
[ChainId.MAINNET]: [
[
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],
[DAI, USDT],
],
[DAI, USDT]
]
}
export interface WalletInfo {
......@@ -118,7 +118,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Injected web3 provider.',
href: null,
color: '#010101',
primary: true,
primary: true
},
METAMASK: {
connector: injected,
......@@ -126,7 +126,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
iconName: 'metamask.png',
description: 'Easy-to-use browser extension.',
href: null,
color: '#E8831D',
color: '#E8831D'
},
WALLET_CONNECT: {
connector: walletconnect,
......@@ -135,7 +135,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Connect to Trust Wallet, Rainbow Wallet and more...',
href: null,
color: '#4196FC',
mobile: true,
mobile: true
},
WALLET_LINK: {
connector: walletlink,
......@@ -143,7 +143,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
iconName: 'coinbaseWalletIcon.svg',
description: 'Use Coinbase Wallet app on mobile device',
href: null,
color: '#315CF5',
color: '#315CF5'
},
COINBASE_LINK: {
name: 'Open in Coinbase Wallet',
......@@ -152,7 +152,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
href: 'https://go.cb-w.com/mtUDhEZPy1',
color: '#315CF5',
mobile: true,
mobileOnly: true,
mobileOnly: true
},
FORTMATIC: {
connector: fortmatic,
......@@ -161,7 +161,7 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Login using Fortmatic hosted wallet',
href: null,
color: '#6748FF',
mobile: true,
mobile: true
},
Portis: {
connector: portis,
......@@ -170,8 +170,8 @@ export const SUPPORTED_WALLETS: { [key: string]: WalletInfo } = {
description: 'Login using Portis hosted wallet',
href: null,
color: '#4A6C9B',
mobile: true,
},
mobile: true
}
}
export const NetworkContextName = 'NETWORK'
......@@ -210,5 +210,5 @@ export const BLOCKED_ADDRESSES: string[] = [
'0x7F367cC41522cE07553e823bf3be79A889DEbe1B',
'0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b',
'0x901bb9583b24D97e995513C6778dc6888AB6870e',
'0xA7e5d5A720f06526557c513402f2e6B5fA20b008',
'0xA7e5d5A720f06526557c513402f2e6B5fA20b008'
]
......@@ -33,7 +33,7 @@ export const DEFAULT_LIST_OF_LISTS: string[] = [
CMC_STABLECOIN,
KLEROS_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
......
......@@ -6,7 +6,7 @@ const MULTICALL_NETWORKS: { [chainId in ChainId]: string } = {
[ChainId.ROPSTEN]: '0x53C43764255c17BD724F74c4eF150724AC50a3ed',
[ChainId.KOVAN]: '0x2cc8688C5f75E365aaEEb4ea8D6a480405A48D2A',
[ChainId.RINKEBY]: '0x42Ad527de7d4e9d9d011aC45B31D8551f8Fe9821',
[ChainId.GÖRLI]: '0x77dCa2C955b15e9dE4dbBCf1246B4B85b651e50e',
[ChainId.GÖRLI]: '0x77dCa2C955b15e9dE4dbBCf1246B4B85b651e50e'
}
export { MULTICALL_ABI, MULTICALL_NETWORKS }
......@@ -8,7 +8,7 @@ const V1_FACTORY_ADDRESSES: { [chainId in ChainId]: string } = {
[ChainId.ROPSTEN]: '0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351',
[ChainId.RINKEBY]: '0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36',
[ChainId.GÖRLI]: '0x6Ce570d02D73d4c384b46135E87f8C592A8c86dA',
[ChainId.KOVAN]: '0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30',
[ChainId.KOVAN]: '0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30'
}
const V1_FACTORY_INTERFACE = new Interface(V1_FACTORY_ABI)
......
......@@ -12,6 +12,6 @@ export function useTokenAllowance(token?: Token, owner?: string, spender?: strin
return useMemo(() => (token && allowance ? new TokenAmount(token, allowance.toString()) : undefined), [
token,
allowance,
allowance
])
}
......@@ -13,7 +13,7 @@ export enum PairState {
LOADING,
NOT_EXISTS,
EXISTS,
INVALID,
INVALID
}
export function usePairs(currencies: [Currency | undefined, Currency | undefined][]): [PairState, Pair | null][] {
......@@ -23,7 +23,7 @@ export function usePairs(currencies: [Currency | undefined, Currency | undefined
() =>
currencies.map(([currencyA, currencyB]) => [
wrappedCurrency(currencyA, chainId),
wrappedCurrency(currencyB, chainId),
wrappedCurrency(currencyB, chainId)
]),
[chainId, currencies]
)
......@@ -51,7 +51,7 @@ export function usePairs(currencies: [Currency | undefined, Currency | undefined
const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]
return [
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])
......
......@@ -11,7 +11,7 @@ import {
TokenAmount,
Trade,
TradeType,
WETH,
WETH
} from '@uniswap/sdk'
import { useMemo } from 'react'
import { useActiveWeb3React } from '../hooks'
......@@ -53,7 +53,7 @@ function useMockV1Pair(inputCurrency?: Currency): MockV1Pair | undefined {
export function useAllTokenV1Exchanges(): { [exchangeAddress: string]: Token } {
const allTokens = useAllTokens()
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)
......@@ -77,7 +77,7 @@ export function useUserHasLiquidityInAllTokens(): boolean | undefined {
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]
)
......@@ -85,7 +85,7 @@ export function useUserHasLiquidityInAllTokens(): boolean | undefined {
return useMemo(
() =>
Object.keys(balances).some((tokenAddress) => {
Object.keys(balances).some(tokenAddress => {
const b = balances[tokenAddress]?.raw
return b && JSBI.greaterThan(b, JSBI.BigInt(0))
}),
......@@ -135,7 +135,7 @@ export function useV1Trade(
}
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 === false) return Version.v2
return undefined
......
......@@ -113,7 +113,7 @@ export function useIsUserAddedToken(currency: Currency | undefined | null): bool
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
......@@ -177,7 +177,7 @@ export function useToken(tokenAddress?: string): Token | undefined | null {
token,
tokenName.loading,
tokenName.result,
tokenNameBytes32.result,
tokenNameBytes32.result
])
}
......
......@@ -22,7 +22,7 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
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
),
[bases]
......@@ -39,7 +39,7 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
// token B against all bases
...bases.map((base): [Token, Token] => [tokenB, base]),
// each base against all bases
...basePairs,
...basePairs
]
.filter((tokens): tokens is [Token, Token] => Boolean(tokens[0] && tokens[1]))
.filter(([t0, t1]) => t0.address !== t1.address)
......@@ -53,8 +53,8 @@ function useAllCommonPairs(currencyA?: Currency, currencyB?: Currency): Pair[] {
if (!customBasesA && !customBasesB) return true
if (customBasesA && !customBasesA.find((base) => tokenB.equals(base))) return false
if (customBasesB && !customBasesB.find((base) => tokenA.equals(base))) return false
if (customBasesA && !customBasesA.find(base => tokenB.equals(base))) return false
if (customBasesB && !customBasesB.find(base => tokenA.equals(base))) return false
return true
})
......
......@@ -18,7 +18,7 @@ export function useEagerConnect() {
const [tried, setTried] = useState(false)
useEffect(() => {
injected.isAuthorized().then((isAuthorized) => {
injected.isAuthorized().then(isAuthorized => {
if (isAuthorized) {
activate(injected, undefined, true).catch(() => {
setTried(true)
......@@ -58,7 +58,7 @@ export function useInactiveListener(suppress = false) {
if (ethereum && ethereum.on && !active && !error && !suppress) {
const handleChainChanged = () => {
// eat errors
activate(injected, undefined, true).catch((error) => {
activate(injected, undefined, true).catch(error => {
console.error('Failed to activate after chain changed', error)
})
}
......@@ -66,7 +66,7 @@ export function useInactiveListener(suppress = false) {
const handleAccountsChanged = (accounts: string[]) => {
if (accounts.length > 0) {
// eat errors
activate(injected, undefined, true).catch((error) => {
activate(injected, undefined, true).catch(error => {
console.error('Failed to activate after accounts changed', error)
})
}
......
......@@ -26,11 +26,11 @@ export default function useAddTokenToMetamask(
address: token.address,
symbol: token.symbol,
decimals: token.decimals,
image: getTokenLogoURL(token.address),
},
},
image: getTokenLogoURL(token.address)
}
}
})
.then((success) => {
.then(success => {
setSuccess(success)
})
.catch(() => setSuccess(false))
......
......@@ -17,7 +17,7 @@ export enum ApprovalState {
UNKNOWN,
NOT_APPROVED,
PENDING,
APPROVED,
APPROVED
}
// returns a variable indicating the state of the approval and a function which approves if necessary or early returns
......@@ -82,12 +82,12 @@ export function useApproveCallback(
return tokenContract
.approve(spender, useExact ? amountToApprove.raw.toString() : MaxUint256, {
gasLimit: calculateGasMargin(estimatedGas),
gasLimit: calculateGasMargin(estimatedGas)
})
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender: spender },
approval: { tokenAddress: token.address, spender: spender }
})
})
.catch((error: Error) => {
......
......@@ -14,7 +14,7 @@ async function getColorFromToken(token: Token): Promise<string | null> {
return Vibrant.from(path)
.getPalette()
.then((palette) => {
.then(palette => {
if (palette?.Vibrant) {
let detectedHex = palette.Vibrant.hex
let AAscore = hex(detectedHex, '#FFF')
......@@ -34,7 +34,7 @@ async function getColorFromUriPath(uri: string): Promise<string | null> {
return Vibrant.from(formattedPath)
.getPalette()
.then((palette) => {
.then(palette => {
if (palette?.Vibrant) {
return palette.Vibrant.hex
}
......@@ -50,7 +50,7 @@ export function useColor(token?: Token) {
let stale = false
if (token) {
getColorFromToken(token).then((tokenColor) => {
getColorFromToken(token).then(tokenColor => {
if (!stale && tokenColor !== null) {
setColor(tokenColor)
}
......@@ -73,7 +73,7 @@ export function useListColor(listImageUri?: string) {
let stale = false
if (listImageUri) {
getColorFromUriPath(listImageUri).then((color) => {
getColorFromUriPath(listImageUri).then(color => {
if (!stale && color !== null) {
setColor(color)
}
......
......@@ -9,7 +9,7 @@ import { useMemo } from 'react'
import { GOVERNANCE_ADDRESS, MERKLE_DISTRIBUTOR_ADDRESS, UNI } from '../constants'
import {
ARGENT_WALLET_DETECTOR_ABI,
ARGENT_WALLET_DETECTOR_MAINNET_ADDRESS,
ARGENT_WALLET_DETECTOR_MAINNET_ADDRESS
} from '../constants/abis/argent-wallet-detector'
import ENS_PUBLIC_RESOLVER_ABI from '../constants/abis/ens-public-resolver.json'
import ENS_ABI from '../constants/abis/ens-registrar.json'
......
......@@ -4,7 +4,7 @@ import { useCallback, useEffect, useState } from 'react'
export default function useCopyClipboard(timeout = 500): [boolean, (toCopy: string) => void] {
const [isCopied, setIsCopied] = useState(false)
const staticCopy = useCallback((text) => {
const staticCopy = useCallback(text => {
const didCopy = copy(text)
setIsCopied(didCopy)
}, [])
......
......@@ -16,6 +16,6 @@ export default function useENS(
return {
loading: reverseLookup.loading || lookup.loading,
address: validated ? validated : lookup.address,
name: reverseLookup.ENSName ? reverseLookup.ENSName : !validated && lookup.address ? nameOrAddress || null : null,
name: reverseLookup.ENSName ? reverseLookup.ENSName : !validated && lookup.address ? nameOrAddress || null : null
}
}
......@@ -30,6 +30,6 @@ export default function useENSAddress(ensName?: string | null): { loading: boole
const changed = debouncedName !== ensName
return {
address: changed ? null : addr.result?.[0] ?? null,
loading: changed || resolverAddress.loading || addr.loading,
loading: changed || resolverAddress.loading || addr.loading
}
}
......@@ -27,6 +27,6 @@ export default function useENSContentHash(ensName?: string | null): { loading: b
return {
contenthash: contenthash.result?.[0] ?? null,
loading: resolverAddressResult.loading || contenthash.loading,
loading: resolverAddressResult.loading || contenthash.loading
}
}
......@@ -32,6 +32,6 @@ export default function useENSName(address?: string): { ENSName: string | null;
const changed = debouncedAddress !== address
return {
ENSName: changed ? null : name.result?.[0] ?? null,
loading: changed || resolverAddress.loading || name.loading,
loading: changed || resolverAddress.loading || name.loading
}
}
......@@ -36,11 +36,11 @@ export function useFetchListCallback(): (listUrl: string, sendDispatch?: boolean
const requestId = nanoid()
sendDispatch && dispatch(fetchTokenList.pending({ requestId, url: listUrl }))
return getTokenList(listUrl, ensResolver)
.then((tokenList) => {
.then(tokenList => {
sendDispatch && dispatch(fetchTokenList.fulfilled({ url: listUrl, tokenList, requestId }))
return tokenList
})
.catch((error) => {
.catch(error => {
console.debug(`Failed to get list at url ${listUrl}`, error)
sendDispatch && dispatch(fetchTokenList.rejected({ url: listUrl, requestId, errorMessage: error.message }))
throw error
......
......@@ -11,7 +11,7 @@ export default function useLast<T>(
): T | null | undefined {
const [last, setLast] = useState<T | null | undefined>(filterFn && filterFn(value) ? value : undefined)
useEffect(() => {
setLast((last) => {
setLast(last => {
const shouldUse: boolean = filterFn ? filterFn(value) : true
if (shouldUse) return value
return last
......
......@@ -17,7 +17,7 @@ import { Version } from './useToggledVersion'
export enum SwapCallbackState {
INVALID,
LOADING,
VALID,
VALID
}
interface SwapCall {
......@@ -75,7 +75,7 @@ function useSwapCallArguments(
feeOnTransfer: false,
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient,
deadline: deadline.toNumber(),
deadline: deadline.toNumber()
})
)
......@@ -85,7 +85,7 @@ function useSwapCallArguments(
feeOnTransfer: true,
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient,
deadline: deadline.toNumber(),
deadline: deadline.toNumber()
})
)
}
......@@ -95,12 +95,12 @@ function useSwapCallArguments(
v1SwapArguments(trade, {
allowedSlippage: new Percent(JSBI.BigInt(allowedSlippage), BIPS_BASE),
recipient,
deadline: deadline.toNumber(),
deadline: deadline.toNumber()
})
)
break
}
return swapMethods.map((parameters) => ({ parameters, contract }))
return swapMethods.map(parameters => ({ parameters, contract }))
}, [account, allowedSlippage, chainId, deadline, library, recipient, trade, v1Exchange])
}
......@@ -138,29 +138,29 @@ export function useSwapCallback(
state: SwapCallbackState.VALID,
callback: async function onSwap(): Promise<string> {
const estimatedCalls: EstimatedSwapCall[] = await Promise.all(
swapCalls.map((call) => {
swapCalls.map(call => {
const {
parameters: { methodName, args, value },
contract,
contract
} = call
const options = !value || isZero(value) ? {} : { value }
return contract.estimateGas[methodName](...args, options)
.then((gasEstimate) => {
.then(gasEstimate => {
return {
call,
gasEstimate,
gasEstimate
}
})
.catch((gasError) => {
.catch(gasError => {
console.debug('Gas estimate failed, trying eth_call to extract error', call)
return contract.callStatic[methodName](...args, options)
.then((result) => {
.then(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.') }
})
.catch((callError) => {
.catch(callError => {
console.debug('Call threw error', call, callError)
let errorMessage: string
switch (callError.reason) {
......@@ -193,14 +193,14 @@ export function useSwapCallback(
const {
call: {
contract,
parameters: { methodName, args, value },
parameters: { methodName, args, value }
},
gasEstimate,
gasEstimate
} = successfulEstimation
return contract[methodName](...args, {
gasLimit: calculateGasMargin(gasEstimate),
...(value && !isZero(value) ? { value, from: account } : { from: account }),
...(value && !isZero(value) ? { value, from: account } : { from: account })
})
.then((response: any) => {
const inputSymbol = trade.inputAmount.currency.symbol
......@@ -222,7 +222,7 @@ export function useSwapCallback(
tradeVersion === Version.v2 ? withRecipient : `${withRecipient} on ${(tradeVersion as any).toUpperCase()}`
addTransaction(response, {
summary: withVersion,
summary: withVersion
})
return response.hash
......@@ -238,7 +238,7 @@ export function useSwapCallback(
}
})
},
error: null,
error: null
}
}, [trade, library, account, chainId, recipient, recipientAddressOrName, swapCalls, addTransaction])
}
......@@ -2,6 +2,6 @@ import { useCallback, useState } from 'react'
export default function useToggle(initialState = false): [boolean, () => void] {
const [state, setState] = useState(initialState)
const toggle = useCallback(() => setState((state) => !state), [])
const toggle = useCallback(() => setState(state => !state), [])
return [state, toggle]
}
......@@ -2,7 +2,7 @@ import useParsedQueryString from './useParsedQueryString'
export enum Version {
v1 = 'v1',
v2 = 'v2',
v2 = 'v2'
}
export const DEFAULT_VERSION: Version = Version.v2
......
......@@ -6,7 +6,7 @@ import useCurrentBlockTimestamp from './useCurrentBlockTimestamp'
// combines the block timestamp with the user setting to give the deadline that should be used for any submitted transaction
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()
return useMemo(() => {
if (blockTimestamp && ttl) return blockTimestamp.add(ttl)
......
......@@ -5,7 +5,7 @@ const isClient = typeof window === 'object'
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined,
height: isClient ? window.innerHeight : undefined
}
}
......
......@@ -9,7 +9,7 @@ import { useWETHContract } from './useContract'
export enum WrapType {
NOT_APPLICABLE,
WRAP,
UNWRAP,
UNWRAP
}
const NOT_APPLICABLE = { wrapType: WrapType.NOT_APPLICABLE }
......@@ -50,7 +50,7 @@ export default function useWrapCallback(
}
}
: undefined,
inputError: sufficientBalance ? undefined : 'Insufficient ETH balance',
inputError: sufficientBalance ? undefined : 'Insufficient ETH balance'
}
} else if (currencyEquals(WETH[chainId], inputCurrency) && outputCurrency === ETHER) {
return {
......@@ -66,7 +66,7 @@ export default function useWrapCallback(
}
}
: undefined,
inputError: sufficientBalance ? undefined : 'Insufficient WETH balance',
inputError: sufficientBalance ? undefined : 'Insufficient WETH balance'
}
} else {
return NOT_APPLICABLE
......
......@@ -9,15 +9,15 @@ i18next
.use(initReactI18next)
.init({
backend: {
loadPath: `./locales/{{lng}}.json`,
loadPath: `./locales/{{lng}}.json`
},
react: {
useSuspense: true,
useSuspense: true
},
fallbackLng: 'en',
preload: ['en'],
keySeparator: false,
interpolation: { escapeValue: false },
interpolation: { escapeValue: false }
})
export default i18next
......@@ -29,20 +29,16 @@ const GOOGLE_ANALYTICS_ID: string | undefined = process.env.REACT_APP_GOOGLE_ANA
if (typeof GOOGLE_ANALYTICS_ID === 'string') {
ReactGA.initialize(GOOGLE_ANALYTICS_ID)
ReactGA.set({
customBrowserType: !isMobile
? 'desktop'
: 'web3' in window || 'ethereum' in window
? 'mobileWeb3'
: 'mobileRegular',
customBrowserType: !isMobile ? 'desktop' : 'web3' in window || 'ethereum' in window ? 'mobileWeb3' : 'mobileRegular'
})
} else {
ReactGA.initialize('test', { testMode: true, debug: true })
}
window.addEventListener('error', (error) => {
window.addEventListener('error', error => {
ReactGA.exception({
description: `${error.message} @ ${error.filename}:${error.lineno}:${error.colno}`,
fatal: true,
fatal: true
})
})
......
......@@ -13,7 +13,7 @@ export function ConfirmAddModalBottom({
currencies,
parsedAmounts,
poolTokenPercentage,
onAdd,
onAdd
}: {
noLiquidity?: boolean
price?: Fraction
......
......@@ -12,7 +12,7 @@ export function PoolPriceBar({
currencies,
noLiquidity,
poolTokenPercentage,
price,
price
}: {
currencies: { [field in Field]?: Currency }
noLiquidity?: boolean
......
......@@ -43,9 +43,9 @@ import UnsupportedCurrencyFooter from 'components/swap/UnsupportedCurrencyFooter
export default function AddLiquidity({
match: {
params: { currencyIdA, currencyIdB },
params: { currencyIdA, currencyIdB }
},
history,
history
}: RouteComponentProps<{ currencyIdA?: string; currencyIdB?: string }>) {
const { account, chainId, library } = useActiveWeb3React()
const theme = useContext(ThemeContext)
......@@ -76,7 +76,7 @@ export default function AddLiquidity({
noLiquidity,
liquidityMinted,
poolTokenPercentage,
error,
error
} = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined)
const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity)
......@@ -95,7 +95,7 @@ export default function AddLiquidity({
// get formatted amounts
const formattedAmounts = {
[independentField]: typedValue,
[dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '',
[dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? ''
}
// get the max amounts user can add
......@@ -103,7 +103,7 @@ export default function AddLiquidity({
(accumulator, field) => {
return {
...accumulator,
[field]: maxAmountSpend(currencyBalances[field]),
[field]: maxAmountSpend(currencyBalances[field])
}
},
{}
......@@ -113,7 +113,7 @@ export default function AddLiquidity({
(accumulator, field) => {
return {
...accumulator,
[field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'),
[field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0')
}
},
{}
......@@ -136,7 +136,7 @@ export default function AddLiquidity({
const amountsMin = {
[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,
......@@ -153,7 +153,7 @@ export default function AddLiquidity({
amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min
amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min
account,
deadline.toHexString(),
deadline.toHexString()
]
value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).raw.toString())
} else {
......@@ -167,18 +167,18 @@ export default function AddLiquidity({
amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(),
account,
deadline.toHexString(),
deadline.toHexString()
]
value = null
}
setAttemptingTxn(true)
await estimate(...args, value ? { value } : {})
.then((estimatedGasLimit) =>
.then(estimatedGasLimit =>
method(...args, {
...(value ? { value } : {}),
gasLimit: calculateGasMargin(estimatedGasLimit),
}).then((response) => {
gasLimit: calculateGasMargin(estimatedGasLimit)
}).then(response => {
setAttemptingTxn(false)
addTransaction(response, {
......@@ -190,7 +190,7 @@ export default function AddLiquidity({
' and ' +
parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) +
' ' +
currencies[Field.CURRENCY_B]?.symbol,
currencies[Field.CURRENCY_B]?.symbol
})
setTxHash(response.hash)
......@@ -198,11 +198,11 @@ export default function AddLiquidity({
ReactGA.event({
category: 'Liquidity',
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)
// we only care if the error is something _other_ than the user rejected the tx
if (error?.code !== 4001) {
......@@ -245,9 +245,8 @@ export default function AddLiquidity({
</Text>
</Row>
<TYPE.italic fontSize={12} textAlign="left" padding={'8px 0 0 0 '}>
{`Output is estimated. If the price changes by more than ${
allowedSlippage / 100
}% your transaction will revert.`}
{`Output is estimated. If the price changes by more than ${allowedSlippage /
100}% your transaction will revert.`}
</TYPE.italic>
</AutoColumn>
)
......
......@@ -10,8 +10,8 @@ const OLD_PATH_STRUCTURE = /^(0x[a-fA-F0-9]{40})-(0x[a-fA-F0-9]{40})$/
export function RedirectOldAddLiquidityPathStructure(props: RouteComponentProps<{ currencyIdA: string }>) {
const {
match: {
params: { currencyIdA },
},
params: { currencyIdA }
}
} = props
const match = currencyIdA.match(OLD_PATH_STRUCTURE)
if (match?.length) {
......@@ -24,8 +24,8 @@ export function RedirectOldAddLiquidityPathStructure(props: RouteComponentProps<
export function RedirectDuplicateTokenIds(props: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const {
match: {
params: { currencyIdA, currencyIdB },
},
params: { currencyIdA, currencyIdB }
}
} = props
if (currencyIdA.toLowerCase() === currencyIdB.toLowerCase()) {
return <Redirect to={`/add/${currencyIdA}`} />
......
......@@ -15,7 +15,7 @@ import AddLiquidity from './AddLiquidity'
import {
RedirectDuplicateTokenIds,
RedirectOldAddLiquidityPathStructure,
RedirectToAddLiquidity,
RedirectToAddLiquidity
} from './AddLiquidity/redirects'
import Earn from './Earn'
import Manage from './Earn/Manage'
......
......@@ -10,7 +10,7 @@ const REWARDS_DURATION = DAY * REWARDS_DURATION_DAYS
export function Countdown({ exactEnd }: { exactEnd?: Date }) {
// get end/beginning times
const end = useMemo(() => (exactEnd ? Math.floor(exactEnd.getTime() / 1000) : STAKING_GENESIS + REWARDS_DURATION), [
exactEnd,
exactEnd
])
const begin = useMemo(() => end - REWARDS_DURATION, [end])
......
......@@ -89,8 +89,8 @@ const DataRow = styled(RowBetween)`
export default function Manage({
match: {
params: { currencyIdA, currencyIdB },
},
params: { currencyIdA, currencyIdB }
}
}: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const { account, chainId } = useActiveWeb3React()
......
......@@ -48,7 +48,7 @@ export default function Earn() {
* only show staking cards with balance
* @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
const stakingRewardsExist = Boolean(typeof chainId === 'number' && (STAKING_REWARDS_INFO[chainId]?.length ?? 0) > 0)
......@@ -97,7 +97,7 @@ export default function Earn() {
) : stakingInfos?.length !== 0 && stakingInfosWithBalance.length === 0 ? (
<OutlineCard>No active pools</OutlineCard>
) : (
stakingInfosWithBalance?.map((stakingInfo) => {
stakingInfosWithBalance?.map(stakingInfo => {
// need to sort by added liquidity here
return <PoolCard key={stakingInfo.stakingRewardAddress} stakingInfo={stakingInfo} />
})
......
......@@ -39,7 +39,7 @@ export function V1LiquidityInfo({
token,
liquidityTokenAmount,
tokenWorth,
ethWorth,
ethWorth
}: {
token: Token
liquidityTokenAmount: TokenAmount
......@@ -118,7 +118,12 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
: null
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)
? priceDifferenceFraction?.multiply('-1')
......@@ -126,7 +131,10 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
const minAmountETH: JSBI | undefined =
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
const minAmountToken: JSBI | undefined =
......@@ -157,11 +165,11 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
ReactGA.event({
category: 'Migrate',
action: 'V1->V2',
label: token?.symbol,
label: token?.symbol
})
addTransaction(response, {
summary: `Migrate ${token.symbol} liquidity to V2`,
summary: `Migrate ${token.symbol} liquidity to V2`
})
setPendingMigrationHash(response.hash)
})
......@@ -305,8 +313,8 @@ function V1PairMigration({ liquidityTokenAmount, token }: { liquidityTokenAmount
export default function MigrateV1Exchange({
history,
match: {
params: { address },
},
params: { address }
}
}: RouteComponentProps<{ address: string }>) {
const validatedAddress = isAddress(address)
const { chainId, account } = useActiveWeb3React()
......
......@@ -33,7 +33,7 @@ const ZERO_FRACTION = new Fraction(ZERO, ONE)
function V1PairRemoval({
exchangeContract,
liquidityTokenAmount,
token,
token
}: {
exchangeContract: Contract
liquidityTokenAmount: TokenAmount
......@@ -75,11 +75,11 @@ function V1PairRemoval({
ReactGA.event({
category: 'Remove',
action: 'V1',
label: token?.symbol,
label: token?.symbol
})
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)
})
......@@ -128,8 +128,8 @@ function V1PairRemoval({
export default function RemoveV1Exchange({
match: {
params: { address },
},
params: { address }
}
}: RouteComponentProps<{ address: string }>) {
const validatedAddress = isAddress(address)
const { chainId, account } = useActiveWeb3React()
......
......@@ -24,7 +24,7 @@ export default function MigrateV1() {
const { account, chainId } = useActiveWeb3React()
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
const token = useToken(tokenSearch)
......@@ -42,19 +42,17 @@ export default function MigrateV1() {
const V1Exchanges = useAllTokenV1Exchanges()
const V1LiquidityTokens: Token[] = useMemo(() => {
return chainId
? Object.keys(V1Exchanges).map(
(exchangeAddress) => new Token(chainId, exchangeAddress, 18, 'UNI-V1', 'Uniswap V1')
)
? Object.keys(V1Exchanges).map(exchangeAddress => new Token(chainId, exchangeAddress, 18, 'UNI-V1', 'Uniswap V1'))
: []
}, [chainId, V1Exchanges])
const [V1LiquidityBalances, V1LiquidityBalancesLoading] = useTokenBalancesWithLoadingIndicator(
account ?? undefined,
V1LiquidityTokens
)
const allV1PairsWithLiquidity = V1LiquidityTokens.filter((V1LiquidityToken) => {
const allV1PairsWithLiquidity = V1LiquidityTokens.filter(V1LiquidityToken => {
const balance = V1LiquidityBalances?.[V1LiquidityToken.address]
return balance && JSBI.greaterThan(balance.raw, JSBI.BigInt(0))
}).map((V1LiquidityToken) => {
}).map(V1LiquidityToken => {
const balance = V1LiquidityBalances[V1LiquidityToken.address]
return balance ? (
<V1PositionCard
......
......@@ -81,11 +81,11 @@ export default function Pool() {
// fetch the user's balances of all tracked V2 LP tokens
const trackedTokenPairs = useTrackedTokenPairs()
const tokenPairsWithLiquidityTokens = useMemo(
() => trackedTokenPairs.map((tokens) => ({ liquidityToken: toV2LiquidityToken(tokens), tokens })),
() => trackedTokenPairs.map(tokens => ({ liquidityToken: toV2LiquidityToken(tokens), tokens })),
[trackedTokenPairs]
)
const liquidityTokens = useMemo(() => tokenPairsWithLiquidityTokens.map((tpwlt) => tpwlt.liquidityToken), [
tokenPairsWithLiquidityTokens,
const liquidityTokens = useMemo(() => tokenPairsWithLiquidityTokens.map(tpwlt => tpwlt.liquidityToken), [
tokenPairsWithLiquidityTokens
])
const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator(
account ?? undefined,
......@@ -103,7 +103,7 @@ export default function Pool() {
const v2Pairs = usePairs(liquidityTokensWithBalances.map(({ tokens }) => tokens))
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))
......@@ -111,15 +111,15 @@ export default function Pool() {
// show liquidity even if its deposited in rewards contract
const stakingInfo = useStakingInfo()
const stakingInfosWithBalance = stakingInfo?.filter((pool) => JSBI.greaterThan(pool.stakedAmount.raw, BIG_INT_ZERO))
const stakingPairs = usePairs(stakingInfosWithBalance?.map((stakingInfo) => stakingInfo.tokens))
const stakingInfosWithBalance = stakingInfo?.filter(pool => JSBI.greaterThan(pool.stakedAmount.raw, BIG_INT_ZERO))
const stakingPairs = usePairs(stakingInfosWithBalance?.map(stakingInfo => stakingInfo.tokens))
// 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 (
stakingPairs
?.map((stakingPair) => stakingPair[1])
.filter((stakingPair) => stakingPair?.liquidityToken.address === v2Pair.liquidityToken.address).length === 0
?.map(stakingPair => stakingPair[1])
.filter(stakingPair => stakingPair?.liquidityToken.address === v2Pair.liquidityToken.address).length === 0
)
})
......@@ -201,7 +201,7 @@ export default function Pool() {
<span></span>
</RowBetween>
</ButtonSecondary>
{v2PairsWithoutStakedAmount.map((v2Pair) => (
{v2PairsWithoutStakedAmount.map(v2Pair => (
<FullPositionCard key={v2Pair.liquidityToken.address} pair={v2Pair} />
))}
{stakingPairs.map(
......
......@@ -23,7 +23,7 @@ import { TYPE } from '../../theme'
enum Fields {
TOKEN0 = 0,
TOKEN1 = 1,
TOKEN1 = 1
}
export default function PoolFinder() {
......
......@@ -47,15 +47,15 @@ import { BigNumber } from '@ethersproject/bignumber'
export default function RemoveLiquidity({
history,
match: {
params: { currencyIdA, currencyIdB },
},
params: { currencyIdA, currencyIdB }
}
}: RouteComponentProps<{ currencyIdA: string; currencyIdB: string }>) {
const [currencyA, currencyB] = [useCurrency(currencyIdA) ?? undefined, useCurrency(currencyIdB) ?? undefined]
const { account, chainId, library } = useActiveWeb3React()
const [tokenA, tokenB] = useMemo(() => [wrappedCurrency(currencyA, chainId), wrappedCurrency(currencyB, chainId)], [
currencyA,
currencyB,
chainId,
chainId
])
const theme = useContext(ThemeContext)
......@@ -90,7 +90,7 @@ export default function RemoveLiquidity({
[Field.CURRENCY_A]:
independentField === Field.CURRENCY_A ? typedValue : parsedAmounts[Field.CURRENCY_A]?.toSignificant(6) ?? '',
[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'))
......@@ -120,50 +120,50 @@ export default function RemoveLiquidity({
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
{ name: 'verifyingContract', type: 'address' }
]
const domain = {
name: 'Uniswap V2',
version: '1',
chainId: chainId,
verifyingContract: pair.liquidityToken.address,
verifyingContract: pair.liquidityToken.address
}
const Permit = [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }
]
const message = {
owner: account,
spender: ROUTER_ADDRESS,
value: liquidityAmount.raw.toString(),
nonce: nonce.toHexString(),
deadline: deadline.toNumber(),
deadline: deadline.toNumber()
}
const data = JSON.stringify({
types: {
EIP712Domain,
Permit,
Permit
},
domain,
primaryType: 'Permit',
message,
message
})
library
.send('eth_signTypedData_v4', [account, data])
.then(splitSignature)
.then((signature) => {
.then(signature => {
setSignatureData({
v: signature.v,
r: signature.r,
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
if (error?.code !== 4001) {
approveCallback()
......@@ -181,13 +181,13 @@ export default function RemoveLiquidity({
)
const onLiquidityInput = useCallback((typedValue: string): void => onUserInput(Field.LIQUIDITY, typedValue), [
onUserInput,
onUserInput
])
const onCurrencyAInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_A, typedValue), [
onUserInput,
onUserInput
])
const onCurrencyBInput = useCallback((typedValue: string): void => onUserInput(Field.CURRENCY_B, typedValue), [
onUserInput,
onUserInput
])
// tx sending
......@@ -202,7 +202,7 @@ export default function RemoveLiquidity({
const amountsMin = {
[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')
......@@ -226,7 +226,7 @@ export default function RemoveLiquidity({
amountsMin[currencyBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(),
amountsMin[currencyBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(),
account,
deadline.toHexString(),
deadline.toHexString()
]
}
// removeLiquidity
......@@ -239,7 +239,7 @@ export default function RemoveLiquidity({
amountsMin[Field.CURRENCY_A].toString(),
amountsMin[Field.CURRENCY_B].toString(),
account,
deadline.toHexString(),
deadline.toHexString()
]
}
}
......@@ -258,7 +258,7 @@ export default function RemoveLiquidity({
false,
signatureData.v,
signatureData.r,
signatureData.s,
signatureData.s
]
}
// removeLiquidityETHWithPermit
......@@ -275,7 +275,7 @@ export default function RemoveLiquidity({
false,
signatureData.v,
signatureData.r,
signatureData.s,
signatureData.s
]
}
} else {
......@@ -283,17 +283,17 @@ export default function RemoveLiquidity({
}
const safeGasEstimates: (BigNumber | undefined)[] = await Promise.all(
methodNames.map((methodName) =>
methodNames.map(methodName =>
router.estimateGas[methodName](...args)
.then(calculateGasMargin)
.catch((error) => {
.catch(error => {
console.error(`estimateGas failed`, methodName, args, error)
return undefined
})
)
)
const indexOfSuccessfulEstimation = safeGasEstimates.findIndex((safeGasEstimate) =>
const indexOfSuccessfulEstimation = safeGasEstimates.findIndex(safeGasEstimate =>
BigNumber.isBigNumber(safeGasEstimate)
)
......@@ -306,7 +306,7 @@ export default function RemoveLiquidity({
setAttemptingTxn(true)
await router[methodName](...args, {
gasLimit: safeGasEstimate,
gasLimit: safeGasEstimate
})
.then((response: TransactionResponse) => {
setAttemptingTxn(false)
......@@ -320,7 +320,7 @@ export default function RemoveLiquidity({
' and ' +
parsedAmounts[Field.CURRENCY_B]?.toSignificant(3) +
' ' +
currencyB?.symbol,
currencyB?.symbol
})
setTxHash(response.hash)
......@@ -328,7 +328,7 @@ export default function RemoveLiquidity({
ReactGA.event({
category: 'Liquidity',
action: 'Remove',
label: [currencyA?.symbol, currencyB?.symbol].join('/'),
label: [currencyA?.symbol, currencyB?.symbol].join('/')
})
})
.catch((error: Error) => {
......@@ -369,9 +369,8 @@ export default function RemoveLiquidity({
</RowBetween>
<TYPE.italic fontSize={12} color={theme.text2} textAlign="left" padding={'12px 0 0 0'}>
{`Output is estimated. If the price changes by more than ${
allowedSlippage / 100
}% your transaction will revert.`}
{`Output is estimated. If the price changes by more than ${allowedSlippage /
100}% your transaction will revert.`}
</TYPE.italic>
</AutoColumn>
)
......
......@@ -5,8 +5,8 @@ const OLD_PATH_STRUCTURE = /^(0x[a-fA-F0-9]{40})-(0x[a-fA-F0-9]{40})$/
export function RedirectOldRemoveLiquidityPathStructure({
match: {
params: { tokens },
},
params: { tokens }
}
}: RouteComponentProps<{ tokens: string }>) {
if (!OLD_PATH_STRUCTURE.test(tokens)) {
return <Redirect to="/pool" />
......
......@@ -36,7 +36,7 @@ import {
useDefaultsFromURLSearch,
useDerivedSwapInfo,
useSwapActionHandlers,
useSwapState,
useSwapState
} from '../../state/swap/hooks'
import { useExpertModeManager, useUserSlippageTolerance, useUserSingleHopOnly } from '../../state/user/hooks'
import { LinkStyledButton, TYPE } from '../../theme'
......@@ -55,7 +55,7 @@ export default function Swap() {
// token warning stuff
const [loadedInputCurrency, loadedOutputCurrency] = [
useCurrency(loadedUrlParams?.inputCurrencyId),
useCurrency(loadedUrlParams?.outputCurrencyId),
useCurrency(loadedUrlParams?.outputCurrencyId)
]
const [dismissTokenWarning, setDismissTokenWarning] = useState<boolean>(false)
const urlLoadedTokens: Token[] = useMemo(
......@@ -95,7 +95,7 @@ export default function Swap() {
currencyBalances,
parsedAmount,
currencies,
inputError: swapInputError,
inputError: swapInputError
} = useDerivedSwapInfo()
const { wrapType, execute: onWrap, inputError: wrapInputError } = useWrapCallback(
currencies[Field.INPUT],
......@@ -107,7 +107,7 @@ export default function Swap() {
const toggledVersion = useToggledVersion()
const tradesByVersion = {
[Version.v1]: v1Trade,
[Version.v2]: v2Trade,
[Version.v2]: v2Trade
}
const trade = showWrap ? undefined : tradesByVersion[toggledVersion]
const defaultTrade = showWrap ? undefined : tradesByVersion[DEFAULT_VERSION]
......@@ -118,11 +118,11 @@ export default function Swap() {
const parsedAmounts = showWrap
? {
[Field.INPUT]: parsedAmount,
[Field.OUTPUT]: parsedAmount,
[Field.OUTPUT]: parsedAmount
}
: {
[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()
......@@ -154,14 +154,14 @@ export default function Swap() {
tradeToConfirm: undefined,
attemptingTxn: false,
swapErrorMessage: undefined,
txHash: undefined,
txHash: undefined
})
const formattedAmounts = {
[independentField]: typedValue,
[dependentField]: showWrap
? parsedAmounts[independentField]?.toExact() ?? ''
: parsedAmounts[dependentField]?.toSignificant(6) ?? '',
: parsedAmounts[dependentField]?.toSignificant(6) ?? ''
}
const route = trade?.route
......@@ -202,7 +202,7 @@ export default function Swap() {
}
setSwapState({ attemptingTxn: true, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: undefined })
swapCallback()
.then((hash) => {
.then(hash => {
setSwapState({ attemptingTxn: false, tradeToConfirm, showConfirm, swapErrorMessage: undefined, txHash: hash })
ReactGA.event({
......@@ -216,22 +216,22 @@ export default function Swap() {
label: [
trade?.inputAmount?.currency?.symbol,
trade?.outputAmount?.currency?.symbol,
getTradeVersion(trade),
].join('/'),
getTradeVersion(trade)
].join('/')
})
ReactGA.event({
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({
attemptingTxn: false,
tradeToConfirm,
showConfirm,
swapErrorMessage: error.message,
txHash: undefined,
txHash: undefined
})
})
}, [
......@@ -243,7 +243,7 @@ export default function Swap() {
recipientAddress,
account,
trade,
singleHopOnly,
singleHopOnly
])
// errors
......@@ -274,7 +274,7 @@ export default function Swap() {
}, [attemptingTxn, showConfirm, swapErrorMessage, trade, txHash])
const handleInputSelect = useCallback(
(inputCurrency) => {
inputCurrency => {
setApprovalSubmitted(false) // reset 2 step UI for approvals
onCurrencySelection(Field.INPUT, inputCurrency)
},
......@@ -285,8 +285,8 @@ export default function Swap() {
maxAmountInput && onUserInput(Field.INPUT, maxAmountInput.toExact())
}, [maxAmountInput, onUserInput])
const handleOutputSelect = useCallback((outputCurrency) => onCurrencySelection(Field.OUTPUT, outputCurrency), [
onCurrencySelection,
const handleOutputSelect = useCallback(outputCurrency => onCurrencySelection(Field.OUTPUT, outputCurrency), [
onCurrencySelection
])
const swapIsUnsupported = useIsTransactionUnsupported(currencies?.INPUT, currencies?.OUTPUT)
......@@ -447,7 +447,7 @@ export default function Swap() {
attemptingTxn: false,
swapErrorMessage: undefined,
showConfirm: true,
txHash: undefined,
txHash: undefined
})
}
}}
......@@ -476,7 +476,7 @@ export default function Swap() {
attemptingTxn: false,
swapErrorMessage: undefined,
showConfirm: true,
txHash: undefined,
txHash: undefined
})
}
}}
......
......@@ -14,8 +14,8 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri
const {
location: { search },
match: {
params: { outputCurrency },
},
params: { outputCurrency }
}
} = props
return (
......@@ -26,7 +26,7 @@ export function RedirectToSwap(props: RouteComponentProps<{ outputCurrency: stri
search:
search && search.length > 1
? `${search}&outputCurrency=${outputCurrency}`
: `?outputCurrency=${outputCurrency}`,
: `?outputCurrency=${outputCurrency}`
}}
/>
)
......
......@@ -105,8 +105,8 @@ const ProposerAddressLink = styled(ExternalLink)`
export default function VotePage({
match: {
params: { id },
},
params: { id }
}
}: RouteComponentProps<{ id: string }>) {
const { chainId, account } = useActiveWeb3React()
......
/// <reference types="react-scripts" />
declare module 'jazzicon' {
export default function (diameter: number, seed: number): HTMLElement
export default function(diameter: number, seed: number): HTMLElement
}
declare module 'fortmatic'
......
......@@ -26,7 +26,7 @@ export enum ApplicationModal {
CLAIM_POPUP,
MENU,
DELEGATE,
VOTE,
VOTE
}
export const updateBlockNumber = createAction<{ chainId: number; blockNumber: number }>('application/updateBlockNumber')
......
......@@ -85,5 +85,5 @@ export function useRemovePopup(): (key: string) => void {
// get the list of active popups
export function useActivePopups(): AppState['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', () => {
store = createStore(reducer, {
popupList: [],
blockNumber: {
[ChainId.MAINNET]: 3,
[ChainId.MAINNET]: 3
},
openModal: null,
openModal: null
})
})
......@@ -65,7 +65,7 @@ describe('application reducer', () => {
store.dispatch(updateBlockNumber({ chainId: ChainId.ROPSTEN, blockNumber: 2 }))
expect(store.getState().blockNumber).toEqual({
[ChainId.MAINNET]: 3,
[ChainId.ROPSTEN]: 2,
[ChainId.ROPSTEN]: 2
})
})
})
......
......@@ -12,10 +12,10 @@ export interface ApplicationState {
const initialState: ApplicationState = {
blockNumber: {},
popupList: [],
openModal: null,
openModal: null
}
export default createReducer(initialState, (builder) =>
export default createReducer(initialState, builder =>
builder
.addCase(updateBlockNumber, (state, action) => {
const { chainId, blockNumber } = action.payload
......@@ -29,17 +29,17 @@ export default createReducer(initialState, (builder) =>
state.openModal = action.payload
})
.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(),
show: true,
content,
removeAfterMs,
},
removeAfterMs
}
])
})
.addCase(removePopup, (state, { payload: { key } }) => {
state.popupList.forEach((p) => {
state.popupList.forEach(p => {
if (p.key === key) {
p.show = false
}
......
......@@ -13,12 +13,12 @@ export default function Updater(): null {
const [state, setState] = useState<{ chainId: number | undefined; blockNumber: number | null }>({
chainId,
blockNumber: null,
blockNumber: null
})
const blockNumberCallback = useCallback(
(blockNumber: number) => {
setState((state) => {
setState(state => {
if (chainId === state.chainId) {
if (typeof state.blockNumber !== 'number') return { chainId, blockNumber }
return { chainId, blockNumber: Math.max(blockNumber, state.blockNumber) }
......@@ -38,7 +38,7 @@ export default function Updater(): null {
library
.getBlockNumber()
.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)
return () => {
......
......@@ -4,7 +4,7 @@ export enum Field {
LIQUIDITY_PERCENT = 'LIQUIDITY_PERCENT',
LIQUIDITY = 'LIQUIDITY',
CURRENCY_A = 'CURRENCY_A',
CURRENCY_B = 'CURRENCY_B',
CURRENCY_B = 'CURRENCY_B'
}
export const typeInput = createAction<{ field: Field; typedValue: string }>('burn/typeInputBurn')
......@@ -12,7 +12,7 @@ import { useTokenBalances } from '../wallet/hooks'
import { Field, typeInput } from './actions'
export function useBurnState(): AppState['burn'] {
return useSelector<AppState, AppState['burn']>((state) => state.burn)
return useSelector<AppState, AppState['burn']>(state => state.burn)
}
export function useDerivedBurnInfo(
......@@ -43,7 +43,7 @@ export function useDerivedBurnInfo(
const tokens = {
[Field.CURRENCY_A]: tokenA,
[Field.CURRENCY_B]: tokenB,
[Field.LIQUIDITY]: pair?.liquidityToken,
[Field.LIQUIDITY]: pair?.liquidityToken
}
// liquidity values
......@@ -68,7 +68,7 @@ export function useDerivedBurnInfo(
: undefined
const liquidityValues: { [Field.CURRENCY_A]?: TokenAmount; [Field.CURRENCY_B]?: TokenAmount } = {
[Field.CURRENCY_A]: liquidityValueA,
[Field.CURRENCY_B]: liquidityValueB,
[Field.CURRENCY_B]: liquidityValueB
}
let percentToRemove: Percent = new Percent('0', '100')
......@@ -114,7 +114,7 @@ export function useDerivedBurnInfo(
[Field.CURRENCY_B]:
tokenB && percentToRemove && percentToRemove.greaterThan('0') && liquidityValueB
? new TokenAmount(tokenB, percentToRemove.multiply(liquidityValueB.raw).quotient)
: undefined,
: undefined
}
let error: string | undefined
......@@ -142,6 +142,6 @@ export function useBurnActionHandlers(): {
)
return {
onUserInput,
onUserInput
}
}
......@@ -8,15 +8,15 @@ export interface BurnState {
const initialState: BurnState = {
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 } }) => {
return {
...state,
independentField: field,
typedValue,
typedValue
}
})
)
......@@ -30,7 +30,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData |
return (CLAIM_PROMISES[key] =
CLAIM_PROMISES[key] ??
fetch(`https://gentle-frost-9e74.uniswap.workers.dev/${chainId}/${formatted}`)
.then((res) => {
.then(res => {
if (res.status === 200) {
return res.json()
} else {
......@@ -38,7 +38,7 @@ function fetchClaim(account: string, chainId: ChainId): Promise<UserClaimData |
return null
}
})
.catch((error) => {
.catch(error => {
console.error('Failed to get claim data', error)
}))
}
......@@ -53,11 +53,11 @@ export function useUserClaimData(account: string | null | undefined): UserClaimD
useEffect(() => {
if (!account || !chainId) return
fetchClaim(account, chainId).then((accountClaimInfo) =>
setClaimInfo((claimInfo) => {
fetchClaim(account, chainId).then(accountClaimInfo =>
setClaimInfo(claimInfo => {
return {
...claimInfo,
[key]: accountClaimInfo,
[key]: accountClaimInfo
}
})
)
......@@ -102,18 +102,18 @@ export function useClaimCallback(
const addTransaction = useTransactionAdder()
const distributorContract = useMerkleDistributorContract()
const claimCallback = async function () {
const claimCallback = async function() {
if (!claimData || !account || !library || !chainId || !distributorContract) return
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
.claim(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Claimed ${unClaimedAmount?.toSignificant(4)} UNI`,
claim: { recipient: account },
claim: { recipient: account }
})
return response.hash
})
......
......@@ -63,7 +63,7 @@ export function useDataFromEventLogs() {
const pastEvents = await library?.getLogs(filter)
// reverse events to get them from newest to odlest
const formattedEventData = pastEvents
?.map((event) => {
?.map(event => {
const eventParsed = eventParser.parseLog(event).args
return {
description: eventParsed.description,
......@@ -77,9 +77,9 @@ export function useDataFromEventLogs() {
return {
target,
functionSig: name,
callData: decoded.join(', '),
callData: decoded.join(', ')
}
}),
})
}
})
.reverse()
......@@ -132,7 +132,7 @@ export function useAllProposalData() {
againstCount: parseFloat(ethers.utils.formatUnits(allProposals[i]?.result?.againstVotes.toString(), 18)),
startBlock: parseInt(allProposals[i]?.result?.startBlock?.toString()),
endBlock: parseInt(allProposals[i]?.result?.endBlock?.toString()),
details: formattedEvents[i].details,
details: formattedEvents[i].details
}
return formattedProposal
})
......@@ -143,7 +143,7 @@ export function useAllProposalData() {
export function useProposalData(id: string): ProposalData | undefined {
const allProposalData = useAllProposalData()
return allProposalData?.find((p) => p.id === id)
return allProposalData?.find(p => p.id === id)
}
// get the users delegatee if it exists
......@@ -188,12 +188,12 @@ export function useDelegateCallback(): (delegatee: string | undefined) => undefi
if (!library || !chainId || !account || !isAddress(delegatee ?? '')) return undefined
const args = [delegatee]
if (!uniContract) throw new Error('No UNI Contract!')
return uniContract.estimateGas.delegate(...args, {}).then((estimatedGasLimit) => {
return uniContract.estimateGas.delegate(...args, {}).then(estimatedGasLimit => {
return uniContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Delegated votes`,
summary: `Delegated votes`
})
return response.hash
})
......@@ -215,12 +215,12 @@ export function useVoteCallback(): {
(proposalId: string | undefined, support: boolean) => {
if (!account || !govContract || !proposalId) return
const args = [proposalId, support]
return govContract.estimateGas.castVote(...args, {}).then((estimatedGasLimit) => {
return govContract.estimateGas.castVote(...args, {}).then(estimatedGasLimit => {
return govContract
.castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`,
summary: `Voted ${support ? 'for ' : 'against'} proposal ${proposalId}`
})
return response.hash
})
......
......@@ -22,10 +22,10 @@ const store = configureStore({
mint,
burn,
multicall,
lists,
lists
},
middleware: [...getDefaultMiddleware({ thunk: false }), save({ states: PERSISTED_KEYS })],
preloadedState: load({ states: PERSISTED_KEYS }),
preloadedState: load({ states: PERSISTED_KEYS })
})
store.dispatch(updateVersion())
......
......@@ -8,7 +8,7 @@ export const fetchTokenList: Readonly<{
}> = {
pending: createAction('lists/fetchTokenList/pending'),
fulfilled: createAction('lists/fetchTokenList/fulfilled'),
rejected: createAction('lists/fetchTokenList/rejected'),
rejected: createAction('lists/fetchTokenList/rejected')
}
// add and remove from list options
export const addList = createAction<string>('lists/addList')
......
......@@ -41,7 +41,7 @@ const EMPTY_LIST: TokenAddressMap = {
[ChainId.RINKEBY]: {},
[ChainId.ROPSTEN]: {},
[ChainId.GÖRLI]: {},
[ChainId.MAINNET]: {},
[ChainId.MAINNET]: {}
}
const listCache: WeakMap<TokenList, TokenAddressMap> | null =
......@@ -55,7 +55,7 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
(tokenMap, tokenInfo) => {
const tags: TagInfo[] =
tokenInfo.tags
?.map((tagId) => {
?.map(tagId => {
if (!list.tags?.[tagId]) return undefined
return { ...list.tags[tagId], id: tagId }
})
......@@ -68,9 +68,9 @@ export function listToTokenMap(list: TokenList): TokenAddressMap {
...tokenMap[token.chainId],
[token.address]: {
token,
list: list,
},
},
list: list
}
}
}
},
{ ...EMPTY_LIST }
......@@ -87,7 +87,7 @@ export function useAllLists(): {
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 {
......@@ -96,7 +96,7 @@ function combineMaps(map1: TokenAddressMap, map2: TokenAddressMap): TokenAddress
3: { ...map1[3], ...map2[3] },
4: { ...map1[4], ...map2[4] },
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
// filter out unsupported lists
export function useActiveListUrls(): string[] | undefined {
return useSelector<AppState, AppState['lists']['activeListUrls']>((state) => state.lists.activeListUrls)?.filter(
(url) => !UNSUPPORTED_LIST_URLS.includes(url)
return useSelector<AppState, AppState['lists']['activeListUrls']>(state => state.lists.activeListUrls)?.filter(
url => !UNSUPPORTED_LIST_URLS.includes(url)
)
}
export function useInactiveListUrls(): string[] {
const lists = useAllLists()
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
......
......@@ -9,20 +9,20 @@ const STUB_TOKEN_LIST = {
name: '',
timestamp: '',
version: { major: 1, minor: 1, patch: 1 },
tokens: [],
tokens: []
}
const PATCHED_STUB_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 = {
...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 = {
...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', () => {
......@@ -31,7 +31,7 @@ describe('list reducer', () => {
beforeEach(() => {
store = createStore(reducer, {
byUrl: {},
activeListUrls: undefined,
activeListUrls: undefined
})
})
......@@ -45,10 +45,10 @@ describe('list reducer', () => {
error: null,
loadingRequestId: 'request-id',
current: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
selectedListUrl: undefined,
selectedListUrl: undefined
})
})
......@@ -59,10 +59,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
pendingUpdate: null,
loadingRequestId: null,
},
loadingRequestId: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(fetchTokenList.pending({ requestId: 'request-id', url: 'fake-url' }))
......@@ -72,10 +72,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: 'request-id',
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
})
......@@ -91,10 +91,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
......@@ -111,10 +111,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
......@@ -132,10 +132,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
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', () => {
......@@ -152,10 +152,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
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', () => {
......@@ -172,10 +172,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: MAJOR_UPDATED_STUB_LIST,
},
pendingUpdate: MAJOR_UPDATED_STUB_LIST
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
})
......@@ -185,7 +185,7 @@ describe('list reducer', () => {
store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' }))
expect(store.getState()).toEqual({
byUrl: {},
activeListUrls: undefined,
activeListUrls: undefined
})
})
......@@ -196,10 +196,10 @@ describe('list reducer', () => {
error: null,
current: null,
loadingRequestId: 'request-id',
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(fetchTokenList.rejected({ requestId: 'request-id', errorMessage: 'abcd', url: 'fake-url' }))
expect(store.getState()).toEqual({
......@@ -208,10 +208,10 @@ describe('list reducer', () => {
error: 'abcd',
current: null,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
})
......@@ -226,10 +226,10 @@ describe('list reducer', () => {
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
it('no op for existing list', () => {
......@@ -239,10 +239,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(addList('fake-url'))
expect(store.getState()).toEqual({
......@@ -251,10 +251,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
})
......@@ -267,10 +267,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
},
pendingUpdate: PATCHED_STUB_LIST
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(acceptListUpdate('fake-url'))
expect(store.getState()).toEqual({
......@@ -279,10 +279,10 @@ describe('list reducer', () => {
error: null,
current: PATCHED_STUB_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
})
})
......@@ -295,15 +295,15 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
},
pendingUpdate: PATCHED_STUB_LIST
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(removeList('fake-url'))
expect(store.getState()).toEqual({
byUrl: {},
activeListUrls: undefined,
activeListUrls: undefined
})
})
it('Removes from active lists if active list is removed', () => {
......@@ -313,15 +313,15 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
},
pendingUpdate: PATCHED_STUB_LIST
}
},
activeListUrls: ['fake-url'],
activeListUrls: ['fake-url']
})
store.dispatch(removeList('fake-url'))
expect(store.getState()).toEqual({
byUrl: {},
activeListUrls: [],
activeListUrls: []
})
})
})
......@@ -334,10 +334,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
},
pendingUpdate: PATCHED_STUB_LIST
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(enableList('fake-url'))
expect(store.getState()).toEqual({
......@@ -346,10 +346,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
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', () => {
......@@ -359,10 +359,10 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
},
pendingUpdate: PATCHED_STUB_LIST
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(enableList('fake-url-invalid'))
expect(store.getState()).toEqual({
......@@ -371,16 +371,16 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: PATCHED_STUB_LIST,
pendingUpdate: PATCHED_STUB_LIST
},
'fake-url-invalid': {
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: ['fake-url-invalid'],
activeListUrls: ['fake-url-invalid']
})
})
it('enable works if list already added', () => {
......@@ -390,10 +390,10 @@ describe('list reducer', () => {
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(enableList('fake-url'))
expect(store.getState()).toEqual({
......@@ -402,10 +402,10 @@ describe('list reducer', () => {
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: ['fake-url'],
activeListUrls: ['fake-url']
})
})
})
......@@ -419,16 +419,16 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
},
'https://unpkg.com/@uniswap/default-token-list@latest': {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
activeListUrls: undefined
})
store.dispatch(updateVersion())
})
......@@ -445,12 +445,12 @@ describe('list reducer', () => {
})
it('all lists are empty', () => {
const s = store.getState()
Object.keys(s.byUrl).forEach((url) => {
Object.keys(s.byUrl).forEach(url => {
expect(s.byUrl[url]).toEqual({
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
})
})
})
......@@ -469,17 +469,17 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
},
'https://unpkg.com/@uniswap/default-token-list@latest': {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
},
pendingUpdate: null
}
},
activeListUrls: undefined,
lastInitializedDefaultListOfLists: ['https://unpkg.com/@uniswap/default-token-list@latest'],
lastInitializedDefaultListOfLists: ['https://unpkg.com/@uniswap/default-token-list@latest']
})
store.dispatch(updateVersion())
})
......@@ -491,7 +491,7 @@ describe('list reducer', () => {
error: null,
current: STUB_TOKEN_LIST,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
})
})
it('removes lists in the last initialized list of lists', () => {
......@@ -502,13 +502,13 @@ describe('list reducer', () => {
const byUrl = store.getState().byUrl
// note we don't expect the uniswap default list to be prepopulated
// 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') {
expect(byUrl[url]).toEqual({
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
})
}
})
......
......@@ -28,7 +28,7 @@ const NEW_LIST_STATE: ListState = {
error: null,
current: null,
loadingRequestId: null,
pendingUpdate: null,
pendingUpdate: null
}
type Mutable<T> = { -readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? U[] : T[P] }
......@@ -39,12 +39,12 @@ const initialState: ListsState = {
...DEFAULT_LIST_OF_LISTS.reduce<Mutable<ListsState['byUrl']>>((memo, listUrl) => {
memo[listUrl] = NEW_LIST_STATE
return memo
}, {}),
}, {})
},
activeListUrls: DEFAULT_ACTIVE_LIST_URLS,
activeListUrls: DEFAULT_ACTIVE_LIST_URLS
}
export default createReducer(initialState, (builder) =>
export default createReducer(initialState, builder =>
builder
.addCase(fetchTokenList.pending, (state, { payload: { requestId, url } }) => {
state.byUrl[url] = {
......@@ -52,7 +52,7 @@ export default createReducer(initialState, (builder) =>
pendingUpdate: null,
...state.byUrl[url],
loadingRequestId: requestId,
error: null,
error: null
}
})
.addCase(fetchTokenList.fulfilled, (state, { payload: { requestId, tokenList, url } }) => {
......@@ -70,7 +70,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null,
error: null,
current: current,
pendingUpdate: tokenList,
pendingUpdate: tokenList
}
}
} else {
......@@ -84,7 +84,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null,
error: null,
current: tokenList,
pendingUpdate: null,
pendingUpdate: null
}
}
})
......@@ -99,7 +99,7 @@ export default createReducer(initialState, (builder) =>
loadingRequestId: null,
error: errorMessage,
current: null,
pendingUpdate: null,
pendingUpdate: null
}
})
.addCase(addList, (state, { payload: url }) => {
......@@ -113,7 +113,7 @@ export default createReducer(initialState, (builder) =>
}
// remove list from active urls if needed
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 }) => {
......@@ -131,7 +131,7 @@ export default createReducer(initialState, (builder) =>
})
.addCase(disableList, (state, { payload: 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 }) => {
......@@ -141,10 +141,10 @@ export default createReducer(initialState, (builder) =>
state.byUrl[url] = {
...state.byUrl[url],
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
if (!state.lastInitializedDefaultListOfLists) {
state.byUrl = initialState.byUrl
......@@ -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())
DEFAULT_LIST_OF_LISTS.forEach((listUrl) => {
DEFAULT_LIST_OF_LISTS.forEach(listUrl => {
if (!lastInitializedSet.has(listUrl)) {
state.byUrl[listUrl] = NEW_LIST_STATE
}
})
state.lastInitializedDefaultListOfLists.forEach((listUrl) => {
state.lastInitializedDefaultListOfLists.forEach(listUrl => {
if (!newListOfListsSet.has(listUrl)) {
delete state.byUrl[listUrl]
}
......
......@@ -26,8 +26,8 @@ export default function Updater(): null {
const fetchList = useFetchListCallback()
const fetchAllListsCallback = useCallback(() => {
if (!isWindowVisible) return
Object.keys(lists).forEach((url) =>
fetchList(url).catch((error) => console.debug('interval list fetching error', error))
Object.keys(lists).forEach(url =>
fetchList(url).catch(error => console.debug('interval list fetching error', error))
)
}, [fetchList, isWindowVisible, lists])
......@@ -36,17 +36,17 @@ export default function Updater(): null {
// whenever a list is not loaded and not loading, try again to load it
useEffect(() => {
Object.keys(lists).forEach((listUrl) => {
Object.keys(lists).forEach(listUrl => {
const list = lists[listUrl]
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])
// automatically update lists if versions are minor/patch
useEffect(() => {
Object.keys(lists).forEach((listUrl) => {
Object.keys(lists).forEach(listUrl => {
const list = lists[listUrl]
if (list.current && list.pendingUpdate) {
const bump = getVersionUpgrade(list.current.version, list.pendingUpdate.version)
......
......@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit'
export enum Field {
CURRENCY_A = 'CURRENCY_A',
CURRENCY_B = 'CURRENCY_B',
CURRENCY_B = 'CURRENCY_B'
}
export const typeInput = createAction<{ field: Field; typedValue: string; noLiquidity: boolean }>('mint/typeInputMint')
......
......@@ -14,7 +14,7 @@ import { Field, typeInput } from './actions'
const ZERO = JSBI.BigInt(0)
export function useMintState(): AppState['mint'] {
return useSelector<AppState, AppState['mint']>((state) => state.mint)
return useSelector<AppState, AppState['mint']>(state => state.mint)
}
export function useMintActionHandlers(
......@@ -40,7 +40,7 @@ export function useMintActionHandlers(
return {
onFieldAInput,
onFieldBInput,
onFieldBInput
}
}
......@@ -70,7 +70,7 @@ export function useDerivedMintInfo(
const currencies: { [field in Field]?: Currency } = useMemo(
() => ({
[Field.CURRENCY_A]: currencyA ?? undefined,
[Field.CURRENCY_B]: currencyB ?? undefined,
[Field.CURRENCY_B]: currencyB ?? undefined
}),
[currencyA, currencyB]
)
......@@ -85,11 +85,11 @@ export function useDerivedMintInfo(
// balances
const balances = useCurrencyBalances(account ?? undefined, [
currencies[Field.CURRENCY_A],
currencies[Field.CURRENCY_B],
currencies[Field.CURRENCY_B]
])
const currencyBalances: { [field in Field]?: CurrencyAmount } = {
[Field.CURRENCY_A]: balances[0],
[Field.CURRENCY_B]: balances[1],
[Field.CURRENCY_B]: balances[1]
}
// amounts
......@@ -119,7 +119,7 @@ export function useDerivedMintInfo(
}, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, chainId, currencyB, pair])
const parsedAmounts: { [field in Field]: CurrencyAmount | undefined } = {
[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(() => {
......@@ -140,7 +140,7 @@ export function useDerivedMintInfo(
const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts
const [tokenAmountA, tokenAmountB] = [
wrappedCurrencyAmount(currencyAAmount, chainId),
wrappedCurrencyAmount(currencyBAmount, chainId),
wrappedCurrencyAmount(currencyBAmount, chainId)
]
if (pair && totalSupply && tokenAmountA && tokenAmountB) {
return pair.getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB)
......@@ -191,6 +191,6 @@ export function useDerivedMintInfo(
noLiquidity,
liquidityMinted,
poolTokenPercentage,
error,
error
}
}
......@@ -10,7 +10,7 @@ describe('mint reducer', () => {
store = createStore(reducer, {
independentField: Field.CURRENCY_A,
typedValue: '',
otherTypedValue: '',
otherTypedValue: ''
})
})
......
......@@ -10,10 +10,10 @@ export interface MintState {
const initialState: MintState = {
independentField: Field.CURRENCY_A,
typedValue: '',
otherTypedValue: '',
otherTypedValue: ''
}
export default createReducer<MintState>(initialState, (builder) =>
export default createReducer<MintState>(initialState, builder =>
builder
.addCase(resetMintState, () => initialState)
.addCase(typeInput, (state, { payload: { field, typedValue, noLiquidity } }) => {
......@@ -23,7 +23,7 @@ export default createReducer<MintState>(initialState, (builder) =>
return {
...state,
independentField: field,
typedValue,
typedValue
}
}
// they're typing into a new field, store the other value
......@@ -32,7 +32,7 @@ export default createReducer<MintState>(initialState, (builder) =>
...state,
independentField: field,
typedValue,
otherTypedValue: state.typedValue,
otherTypedValue: state.typedValue
}
}
} else {
......@@ -40,7 +40,7 @@ export default createReducer<MintState>(initialState, (builder) =>
...state,
independentField: field,
typedValue,
otherTypedValue: '',
otherTypedValue: ''
}
}
})
......
......@@ -8,7 +8,7 @@ describe('actions', () => {
it('does not throw for invalid calldata', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-abc')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: 'abc',
callData: 'abc'
})
})
it('throws for invalid format', () => {
......@@ -17,13 +17,13 @@ describe('actions', () => {
it('throws for uppercase calldata', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcD')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcD',
callData: '0xabcD'
})
})
it('parses pieces into address', () => {
expect(parseCallKey('0x6b175474e89094c44da98b954eedeac495271d0f-0xabcd')).toEqual({
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcd',
callData: '0xabcd'
})
})
})
......@@ -36,7 +36,7 @@ describe('actions', () => {
expect(() =>
toCallKey({
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: 'abc',
callData: 'abc'
})
).toThrow('Invalid hex: abc')
})
......@@ -44,7 +44,7 @@ describe('actions', () => {
expect(() =>
toCallKey({
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
callData: '0xabcD',
callData: '0xabcD'
})
).toThrow('Invalid hex: 0xabcD')
})
......
......@@ -24,7 +24,7 @@ export function parseCallKey(callKey: string): Call {
}
return {
address: pcs[0],
callData: pcs[1],
callData: pcs[1]
}
}
......
......@@ -12,7 +12,7 @@ import {
removeMulticallListeners,
parseCallKey,
toCallKey,
ListenerOptions,
ListenerOptions
} from './actions'
export interface Result extends ReadonlyArray<any> {
......@@ -31,7 +31,7 @@ function isMethodArg(x: unknown): x is MethodArg {
function isValidMethodArgs(x: unknown): x is MethodArgs | undefined {
return (
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:
// use this options object
export const NEVER_RELOAD: ListenerOptions = {
blocksPerFetch: Infinity,
blocksPerFetch: Infinity
}
// the lowest level call for subscribing to contract data
function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): CallResult[] {
const { chainId } = useActiveWeb3React()
const callResults = useSelector<AppState, AppState['multicall']['callResults']>(
(state) => state.multicall.callResults
)
const callResults = useSelector<AppState, AppState['multicall']['callResults']>(state => state.multicall.callResults)
const dispatch = useDispatch<AppDispatch>()
const serializedCallKeys: string = useMemo(
......@@ -71,12 +69,12 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
useEffect(() => {
const callKeys: string[] = JSON.parse(serializedCallKeys)
if (!chainId || callKeys.length === 0) return undefined
const calls = callKeys.map((key) => parseCallKey(key))
const calls = callKeys.map(key => parseCallKey(key))
dispatch(
addMulticallListeners({
chainId,
calls,
options,
options
})
)
......@@ -85,7 +83,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
removeMulticallListeners({
chainId,
calls,
options,
options
})
)
}
......@@ -93,7 +91,7 @@ function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): C
return useMemo(
() =>
calls.map<CallResult>((call) => {
calls.map<CallResult>(call => {
if (!chainId || !call) return INVALID_RESULT
const result = callResults[chainId]?.[toCallKey(call)]
......@@ -147,7 +145,7 @@ function toCallState(
loading: false,
error: true,
syncing,
result,
result
}
}
}
......@@ -156,7 +154,7 @@ function toCallState(
loading: false,
syncing,
result: result,
error: !success,
error: !success
}
}
......@@ -171,10 +169,10 @@ export function useSingleContractMultipleData(
const calls = useMemo(
() =>
contract && fragment && callInputs && callInputs.length > 0
? callInputs.map<Call>((inputs) => {
? callInputs.map<Call>(inputs => {
return {
address: contract.address,
callData: contract.interface.encodeFunctionData(fragment, inputs),
callData: contract.interface.encodeFunctionData(fragment, inputs)
}
})
: [],
......@@ -186,7 +184,7 @@ export function useSingleContractMultipleData(
const latestBlockNumber = useBlockNumber()
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])
}
......@@ -209,11 +207,11 @@ export function useMultipleContractSingleData(
const calls = useMemo(
() =>
fragment && addresses && addresses.length > 0 && callData
? addresses.map<Call | undefined>((address) => {
? addresses.map<Call | undefined>(address => {
return address && callData
? {
address,
callData,
callData
}
: undefined
})
......@@ -226,7 +224,7 @@ export function useMultipleContractSingleData(
const latestBlockNumber = useBlockNumber()
return useMemo(() => {
return results.map((result) => toCallState(result, contractInterface, fragment, latestBlockNumber))
return results.map(result => toCallState(result, contractInterface, fragment, latestBlockNumber))
}, [fragment, results, contractInterface, latestBlockNumber])
}
......@@ -243,8 +241,8 @@ export function useSingleCallResult(
? [
{
address: contract.address,
callData: contract.interface.encodeFunctionData(fragment, inputs),
},
callData: contract.interface.encodeFunctionData(fragment, inputs)
}
]
: []
}, [contract, fragment, inputs])
......
......@@ -3,7 +3,7 @@ import {
errorFetchingMulticallResults,
fetchingMulticallResults,
removeMulticallListeners,
updateMulticallResults,
updateMulticallResults
} from './actions'
import reducer, { MulticallState } from './reducer'
import { Store, createStore } from '@reduxjs/toolkit'
......@@ -29,20 +29,20 @@ describe('multicall reducer', () => {
calls: [
{
address: DAI_ADDRESS,
callData: '0x',
},
],
callData: '0x'
}
]
})
)
expect(store.getState()).toEqual({
callListeners: {
[1]: {
[`${DAI_ADDRESS}-0x`]: {
[1]: 1,
},
},
[1]: 1
}
}
},
callResults: {},
callResults: {}
})
})
})
......@@ -54,10 +54,10 @@ describe('multicall reducer', () => {
calls: [
{
address: DAI_ADDRESS,
callData: '0x',
},
callData: '0x'
}
],
chainId: 1,
chainId: 1
})
)
expect(store.getState()).toEqual({ callResults: {}, callListeners: {} })
......@@ -69,9 +69,9 @@ describe('multicall reducer', () => {
calls: [
{
address: DAI_ADDRESS,
callData: '0x',
},
],
callData: '0x'
}
]
})
)
store.dispatch(
......@@ -79,15 +79,15 @@ describe('multicall reducer', () => {
calls: [
{
address: DAI_ADDRESS,
callData: '0x',
},
callData: '0x'
}
],
chainId: 1,
chainId: 1
})
)
expect(store.getState()).toEqual({
callResults: {},
callListeners: { [1]: { [`${DAI_ADDRESS}-0x`]: {} } },
callListeners: { [1]: { [`${DAI_ADDRESS}-0x`]: {} } }
})
})
})
......@@ -99,8 +99,8 @@ describe('multicall reducer', () => {
chainId: 1,
blockNumber: 1,
results: {
abc: '0x',
},
abc: '0x'
}
})
)
expect(store.getState()).toEqual({
......@@ -108,10 +108,10 @@ describe('multicall reducer', () => {
[1]: {
abc: {
blockNumber: 1,
data: '0x',
},
},
},
data: '0x'
}
}
}
})
})
it('updates old data', () => {
......@@ -120,8 +120,8 @@ describe('multicall reducer', () => {
chainId: 1,
blockNumber: 1,
results: {
abc: '0x',
},
abc: '0x'
}
})
)
store.dispatch(
......@@ -129,8 +129,8 @@ describe('multicall reducer', () => {
chainId: 1,
blockNumber: 2,
results: {
abc: '0x2',
},
abc: '0x2'
}
})
)
expect(store.getState()).toEqual({
......@@ -138,10 +138,10 @@ describe('multicall reducer', () => {
[1]: {
abc: {
blockNumber: 2,
data: '0x2',
},
},
},
data: '0x2'
}
}
}
})
})
it('ignores late updates', () => {
......@@ -150,8 +150,8 @@ describe('multicall reducer', () => {
chainId: 1,
blockNumber: 2,
results: {
abc: '0x2',
},
abc: '0x2'
}
})
)
store.dispatch(
......@@ -159,8 +159,8 @@ describe('multicall reducer', () => {
chainId: 1,
blockNumber: 1,
results: {
abc: '0x1',
},
abc: '0x1'
}
})
)
expect(store.getState()).toEqual({
......@@ -168,10 +168,10 @@ describe('multicall reducer', () => {
[1]: {
abc: {
blockNumber: 2,
data: '0x2',
},
},
},
data: '0x2'
}
}
}
})
})
})
......@@ -181,15 +181,15 @@ describe('multicall reducer', () => {
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
callResults: {
[1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 },
},
},
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }
}
}
})
})
......@@ -198,22 +198,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
store.dispatch(
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 3,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
callResults: {
[1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 },
},
},
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }
}
}
})
})
......@@ -222,22 +222,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
store.dispatch(
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 1,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
callResults: {
[1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 },
},
},
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 2 }
}
}
})
})
})
......@@ -248,13 +248,13 @@ describe('multicall reducer', () => {
errorFetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 1,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
callResults: {
[1]: {},
},
[1]: {}
}
})
})
it('updates block number if we were fetching', () => {
......@@ -262,14 +262,14 @@ describe('multicall reducer', () => {
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
store.dispatch(
errorFetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
......@@ -278,10 +278,10 @@ describe('multicall reducer', () => {
[`${DAI_ADDRESS}-0x0`]: {
blockNumber: 2,
// null data indicates error
data: null,
},
},
},
data: null
}
}
}
})
})
it('does nothing if not errored on latest block', () => {
......@@ -289,22 +289,22 @@ describe('multicall reducer', () => {
fetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 3,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
store.dispatch(
errorFetchingMulticallResults({
chainId: 1,
fetchingBlockNumber: 2,
calls: [{ address: DAI_ADDRESS, callData: '0x0' }],
calls: [{ address: DAI_ADDRESS, callData: '0x0' }]
})
)
expect(store.getState()).toEqual({
callResults: {
[1]: {
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 },
},
},
[`${DAI_ADDRESS}-0x0`]: { fetchingBlockNumber: 3 }
}
}
})
})
})
......
......@@ -5,7 +5,7 @@ import {
fetchingMulticallResults,
removeMulticallListeners,
toCallKey,
updateMulticallResults,
updateMulticallResults
} from './actions'
export interface MulticallState {
......@@ -32,17 +32,17 @@ export interface MulticallState {
}
const initialState: MulticallState = {
callResults: {},
callResults: {}
}
export default createReducer(initialState, (builder) =>
export default createReducer(initialState, builder =>
builder
.addCase(addMulticallListeners, (state, { payload: { calls, chainId, options: { blocksPerFetch = 1 } = {} } }) => {
const listeners: MulticallState['callListeners'] = state.callListeners
? state.callListeners
: (state.callListeners = {})
listeners[chainId] = listeners[chainId] ?? {}
calls.forEach((call) => {
calls.forEach(call => {
const callKey = toCallKey(call)
listeners[chainId][callKey] = listeners[chainId][callKey] ?? {}
listeners[chainId][callKey][blocksPerFetch] = (listeners[chainId][callKey][blocksPerFetch] ?? 0) + 1
......@@ -56,7 +56,7 @@ export default createReducer(initialState, (builder) =>
: (state.callListeners = {})
if (!listeners[chainId]) return
calls.forEach((call) => {
calls.forEach(call => {
const callKey = toCallKey(call)
if (!listeners[chainId][callKey]) return
if (!listeners[chainId][callKey][blocksPerFetch]) return
......@@ -71,12 +71,12 @@ export default createReducer(initialState, (builder) =>
)
.addCase(fetchingMulticallResults, (state, { payload: { chainId, fetchingBlockNumber, calls } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {}
calls.forEach((call) => {
calls.forEach(call => {
const callKey = toCallKey(call)
const current = state.callResults[chainId][callKey]
if (!current) {
state.callResults[chainId][callKey] = {
fetchingBlockNumber,
fetchingBlockNumber
}
} else {
if ((current.fetchingBlockNumber ?? 0) >= fetchingBlockNumber) return
......@@ -86,7 +86,7 @@ export default createReducer(initialState, (builder) =>
})
.addCase(errorFetchingMulticallResults, (state, { payload: { fetchingBlockNumber, chainId, calls } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {}
calls.forEach((call) => {
calls.forEach(call => {
const callKey = toCallKey(call)
const current = state.callResults[chainId][callKey]
if (!current) return // only should be dispatched if we are already fetching
......@@ -99,12 +99,12 @@ export default createReducer(initialState, (builder) =>
})
.addCase(updateMulticallResults, (state, { payload: { chainId, results, blockNumber } }) => {
state.callResults[chainId] = state.callResults[chainId] ?? {}
Object.keys(results).forEach((callKey) => {
Object.keys(results).forEach(callKey => {
const current = state.callResults[chainId][callKey]
if ((current?.blockNumber ?? 0) > blockNumber) return
state.callResults[chainId][callKey] = {
data: results[callKey],
blockNumber,
blockNumber
}
})
})
......
......@@ -9,14 +9,14 @@ describe('multicall updater', () => {
[1]: {
['abc']: {
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
)
).toEqual({
abc: 4,
abc: 4
})
})
it('applies min', () => {
......@@ -27,14 +27,14 @@ describe('multicall updater', () => {
['abc']: {
4: 2, // 2 listeners care about 4 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
)
).toEqual({
abc: 3,
abc: 3
})
})
it('works for infinity', () => {
......@@ -44,18 +44,18 @@ describe('multicall updater', () => {
[1]: {
['abc']: {
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']: {
Infinity: 2,
},
},
Infinity: 2
}
}
},
1
)
).toEqual({
abc: 4,
def: Infinity,
def: Infinity
})
})
it('multiple keys', () => {
......@@ -65,19 +65,19 @@ describe('multicall updater', () => {
[1]: {
['abc']: {
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']: {
2: 1,
5: 2,
},
},
5: 2
}
}
},
1
)
).toEqual({
abc: 4,
def: 2,
def: 2
})
})
it('ignores negative numbers', () => {
......@@ -88,14 +88,14 @@ describe('multicall updater', () => {
['abc']: {
4: 2,
1: -1,
[-3]: 4,
},
},
[-3]: 4
}
}
},
1
)
).toEqual({
abc: 4,
abc: 4
})
})
it('applies min to infinity', () => {
......@@ -106,14 +106,14 @@ describe('multicall updater', () => {
['abc']: {
Infinity: 2, // 2 listeners care about any 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
)
).toEqual({
abc: 4,
abc: 4
})
})
})
......@@ -136,7 +136,7 @@ describe('multicall updater', () => {
expect(
outdatedListeningKeys(
{
[1]: { abc: { data: '0x', blockNumber: 2 }, def: { fetchingBlockNumber: 2 } },
[1]: { abc: { data: '0x', blockNumber: 2 }, def: { fetchingBlockNumber: 2 } }
},
{ abc: 1, def: 1 },
1,
......
......@@ -13,7 +13,7 @@ import {
errorFetchingMulticallResults,
fetchingMulticallResults,
parseCallKey,
updateMulticallResults,
updateMulticallResults
} from './actions'
// chunk calls so we do not exceed the gas limit
......@@ -33,9 +33,7 @@ async function fetchChunk(
console.debug('Fetching chunk', multicallContract, chunk, minBlockNumber)
let resultsBlockNumber, returnData
try {
;[resultsBlockNumber, returnData] = await multicallContract.aggregate(
chunk.map((obj) => [obj.address, obj.callData])
)
;[resultsBlockNumber, returnData] = await multicallContract.aggregate(chunk.map(obj => [obj.address, obj.callData]))
} catch (error) {
console.debug('Failed to fetch chunk inside retry', error)
throw error
......@@ -65,7 +63,7 @@ export function activeListeningKeys(
const keyListeners = listeners[callKey]
memo[callKey] = Object.keys(keyListeners)
.filter((key) => {
.filter(key => {
const blocksPerFetch = parseInt(key)
if (blocksPerFetch <= 0) return false
return keyListeners[blocksPerFetch] > 0
......@@ -95,7 +93,7 @@ export function outdatedListeningKeys(
// no results at all, load everything
if (!results) return Object.keys(listeningKeys)
return Object.keys(listeningKeys).filter((callKey) => {
return Object.keys(listeningKeys).filter(callKey => {
const blocksPerFetch = listeningKeys[callKey]
const data = callResults[chainId][callKey]
......@@ -114,7 +112,7 @@ export function outdatedListeningKeys(
export default function Updater(): null {
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
const debouncedListeners = useDebounce(state.callListeners, 100)
const latestBlockNumber = useBlockNumber()
......@@ -131,7 +129,7 @@ export default function Updater(): null {
}, [chainId, state.callResults, listeningKeys, latestBlockNumber])
const serializedOutdatedCallKeys = useMemo(() => JSON.stringify(unserializedOutdatedCallKeys.sort()), [
unserializedOutdatedCallKeys,
unserializedOutdatedCallKeys
])
useEffect(() => {
......@@ -139,19 +137,19 @@ export default function Updater(): null {
const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys)
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)
if (cancellations.current?.blockNumber !== latestBlockNumber) {
cancellations.current?.cancellations?.forEach((c) => c())
cancellations.current?.cancellations?.forEach(c => c())
}
dispatch(
fetchingMulticallResults({
calls,
chainId,
fetchingBlockNumber: latestBlockNumber,
fetchingBlockNumber: latestBlockNumber
})
)
......@@ -161,7 +159,7 @@ export default function Updater(): null {
const { cancel, promise } = retry(() => fetchChunk(multicallContract, chunk, latestBlockNumber), {
n: Infinity,
minWait: 2500,
maxWait: 3500,
maxWait: 3500
})
promise
.then(({ results: returnData, blockNumber: fetchBlockNumber }) => {
......@@ -180,7 +178,7 @@ export default function Updater(): null {
memo[callKey] = returnData[i] ?? null
return memo
}, {}),
blockNumber: fetchBlockNumber,
blockNumber: fetchBlockNumber
})
)
})
......@@ -194,12 +192,12 @@ export default function Updater(): null {
errorFetchingMulticallResults({
calls: chunk,
chainId,
fetchingBlockNumber: latestBlockNumber,
fetchingBlockNumber: latestBlockNumber
})
)
})
return cancel
}),
})
}
}, [chainId, multicallContract, dispatch, serializedOutdatedCallKeys, latestBlockNumber])
......
......@@ -21,21 +21,21 @@ export const STAKING_REWARDS_INFO: {
[ChainId.MAINNET]: [
{
tokens: [WETH[ChainId.MAINNET], DAI],
stakingRewardAddress: '0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711',
stakingRewardAddress: '0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711'
},
{
tokens: [WETH[ChainId.MAINNET], USDC],
stakingRewardAddress: '0x7FBa4B8Dc5E7616e59622806932DBea72537A56b',
stakingRewardAddress: '0x7FBa4B8Dc5E7616e59622806932DBea72537A56b'
},
{
tokens: [WETH[ChainId.MAINNET], USDT],
stakingRewardAddress: '0x6C3e4cb2E96B01F4b866965A91ed4437839A121a',
stakingRewardAddress: '0x6C3e4cb2E96B01F4b866965A91ed4437839A121a'
},
{
tokens: [WETH[ChainId.MAINNET], WBTC],
stakingRewardAddress: '0xCA35e32e7926b96A9988f61d510E038108d8068e',
},
],
stakingRewardAddress: '0xCA35e32e7926b96A9988f61d510E038108d8068e'
}
]
}
export interface StakingInfo {
......@@ -76,7 +76,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
const info = useMemo(
() =>
chainId
? STAKING_REWARDS_INFO[chainId]?.filter((stakingRewardInfo) =>
? STAKING_REWARDS_INFO[chainId]?.filter(stakingRewardInfo =>
pairToFilterBy === undefined
? true
: pairToFilterBy === null
......@@ -193,7 +193,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
stakedAmount: stakedAmount,
totalStakedAmount: totalStakedAmount,
getHypotheticalRewardRate,
active,
active
})
}
return memo
......@@ -208,7 +208,7 @@ export function useStakingInfo(pairToFilterBy?: Pair | null): StakingInfo[] {
rewardRates,
rewardsAddresses,
totalSupplies,
uni,
uni
])
}
......@@ -256,7 +256,7 @@ export function useDerivedStakeInfo(
return {
parsedAmount,
error,
error
}
}
......@@ -284,6 +284,6 @@ export function useDerivedUnstakeInfo(
return {
parsedAmount,
error,
error
}
}
......@@ -2,7 +2,7 @@ import { createAction } from '@reduxjs/toolkit'
export enum Field {
INPUT = 'INPUT',
OUTPUT = 'OUTPUT',
OUTPUT = 'OUTPUT'
}
export const selectCurrency = createAction<{ field: Field; currencyId: string }>('swap/selectCurrency')
......
......@@ -17,7 +17,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: 'ETH' },
typedValue: '20.5',
independentField: Field.OUTPUT,
recipient: null,
recipient: null
})
})
......@@ -29,7 +29,7 @@ describe('hooks', () => {
[Field.OUTPUT]: { currencyId: 'ETH' },
typedValue: '',
independentField: Field.INPUT,
recipient: null,
recipient: null
})
})
......@@ -43,7 +43,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '20.5',
independentField: Field.INPUT,
recipient: null,
recipient: null
})
})
......@@ -57,7 +57,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '20.5',
independentField: Field.INPUT,
recipient: null,
recipient: null
})
})
......@@ -66,7 +66,7 @@ describe('hooks', () => {
queryParametersToSwapState(
parse('?outputCurrency=eth&exactAmount=20.5&recipient=0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5', {
parseArrays: false,
ignoreQueryPrefix: true,
ignoreQueryPrefix: true
})
)
).toEqual({
......@@ -74,7 +74,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '20.5',
independentField: Field.INPUT,
recipient: '0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5',
recipient: '0x0fF2D1eFd7A57B7562b2bf27F3f37899dB27F4a5'
})
})
test('accepts any recipient', () => {
......@@ -82,7 +82,7 @@ describe('hooks', () => {
queryParametersToSwapState(
parse('?outputCurrency=eth&exactAmount=20.5&recipient=bob.argent.xyz', {
parseArrays: false,
ignoreQueryPrefix: true,
ignoreQueryPrefix: true
})
)
).toEqual({
......@@ -90,7 +90,7 @@ describe('hooks', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '20.5',
independentField: Field.INPUT,
recipient: 'bob.argent.xyz',
recipient: 'bob.argent.xyz'
})
})
})
......
......@@ -20,7 +20,7 @@ import { useUserSlippageTolerance } from '../user/hooks'
import { computeSlippageAdjustedAmounts } from '../../utils/prices'
export function useSwapState(): AppState['swap'] {
return useSelector<AppState, AppState['swap']>((state) => state.swap)
return useSelector<AppState, AppState['swap']>(state => state.swap)
}
export function useSwapActionHandlers(): {
......@@ -35,7 +35,7 @@ export function useSwapActionHandlers(): {
dispatch(
selectCurrency({
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(): {
onSwitchTokens,
onCurrencySelection,
onUserInput,
onChangeRecipient,
onChangeRecipient
}
}
......@@ -91,7 +91,7 @@ export function tryParseAmount(value?: string, currency?: Currency): CurrencyAmo
const BAD_RECIPIENT_ADDRESSES: string[] = [
'0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f', // v2 factory
'0xf164fC0Ec4E93095b804a4795bBe1e041497b92a', // v2 router 01
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', // v2 router 02
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' // v2 router 02
]
/**
......@@ -101,8 +101,8 @@ const BAD_RECIPIENT_ADDRESSES: string[] = [
*/
function involvesAddress(trade: Trade, checksummedAddress: string): boolean {
return (
trade.route.path.some((token) => token.address === checksummedAddress) ||
trade.route.pairs.some((pair) => pair.liquidityToken.address === checksummedAddress)
trade.route.path.some(token => token.address === checksummedAddress) ||
trade.route.pairs.some(pair => pair.liquidityToken.address === checksummedAddress)
)
}
......@@ -124,7 +124,7 @@ export function useDerivedSwapInfo(): {
typedValue,
[Field.INPUT]: { currencyId: inputCurrencyId },
[Field.OUTPUT]: { currencyId: outputCurrencyId },
recipient,
recipient
} = useSwapState()
const inputCurrency = useCurrency(inputCurrencyId)
......@@ -134,7 +134,7 @@ export function useDerivedSwapInfo(): {
const relevantTokenBalances = useCurrencyBalances(account ?? undefined, [
inputCurrency ?? undefined,
outputCurrency ?? undefined,
outputCurrency ?? undefined
])
const isExactIn: boolean = independentField === Field.INPUT
......@@ -147,12 +147,12 @@ export function useDerivedSwapInfo(): {
const currencyBalances = {
[Field.INPUT]: relevantTokenBalances[0],
[Field.OUTPUT]: relevantTokenBalances[1],
[Field.OUTPUT]: relevantTokenBalances[1]
}
const currencies: { [field in Field]?: Currency } = {
[Field.INPUT]: inputCurrency ?? undefined,
[Field.OUTPUT]: outputCurrency ?? undefined,
[Field.OUTPUT]: outputCurrency ?? undefined
}
// get link to trade on v1, if a better rate exists
......@@ -200,7 +200,7 @@ export function useDerivedSwapInfo(): {
: null
: slippageAdjustedAmounts
? slippageAdjustedAmounts[Field.INPUT]
: null,
: null
]
if (balanceIn && amountIn && balanceIn.lessThan(amountIn)) {
......@@ -213,7 +213,7 @@ export function useDerivedSwapInfo(): {
parsedAmount,
v2Trade: v2Trade ?? undefined,
inputError,
v1Trade,
v1Trade
}
}
......@@ -261,14 +261,14 @@ export function queryParametersToSwapState(parsedQs: ParsedQs): SwapState {
return {
[Field.INPUT]: {
currencyId: inputCurrency,
currencyId: inputCurrency
},
[Field.OUTPUT]: {
currencyId: outputCurrency,
currencyId: outputCurrency
},
typedValue: parseTokenAmountURLParameter(parsedQs.exactAmount),
independentField: parseIndependentFieldURLParameter(parsedQs.exactField),
recipient,
recipient
}
}
......@@ -293,7 +293,7 @@ export function useDefaultsFromURLSearch():
field: parsed.independentField,
inputCurrencyId: parsed[Field.INPUT].currencyId,
outputCurrencyId: parsed[Field.OUTPUT].currencyId,
recipient: parsed.recipient,
recipient: parsed.recipient
})
)
......
......@@ -11,7 +11,7 @@ describe('swap reducer', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '',
independentField: Field.INPUT,
recipient: null,
recipient: null
})
})
......@@ -20,7 +20,7 @@ describe('swap reducer', () => {
store.dispatch(
selectCurrency({
field: Field.OUTPUT,
currencyId: '0x0000',
currencyId: '0x0000'
})
)
......@@ -29,7 +29,7 @@ describe('swap reducer', () => {
[Field.INPUT]: { currencyId: '' },
typedValue: '',
independentField: Field.INPUT,
recipient: null,
recipient: null
})
})
})
......
......@@ -18,29 +18,29 @@ const initialState: SwapState = {
independentField: Field.INPUT,
typedValue: '',
[Field.INPUT]: {
currencyId: '',
currencyId: ''
},
[Field.OUTPUT]: {
currencyId: '',
currencyId: ''
},
recipient: null,
recipient: null
}
export default createReducer<SwapState>(initialState, (builder) =>
export default createReducer<SwapState>(initialState, builder =>
builder
.addCase(
replaceSwapState,
(state, { payload: { typedValue, recipient, field, inputCurrencyId, outputCurrencyId } }) => {
return {
[Field.INPUT]: {
currencyId: inputCurrencyId,
currencyId: inputCurrencyId
},
[Field.OUTPUT]: {
currencyId: outputCurrencyId,
currencyId: outputCurrencyId
},
independentField: field,
typedValue: typedValue,
recipient,
recipient
}
}
)
......@@ -52,29 +52,29 @@ export default createReducer<SwapState>(initialState, (builder) =>
...state,
independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT,
[field]: { currencyId: currencyId },
[otherField]: { currencyId: state[field].currencyId },
[otherField]: { currencyId: state[field].currencyId }
}
} else {
// the normal case
return {
...state,
[field]: { currencyId: currencyId },
[field]: { currencyId: currencyId }
}
}
})
.addCase(switchCurrencies, (state) => {
.addCase(switchCurrencies, state => {
return {
...state,
independentField: state.independentField === Field.INPUT ? Field.OUTPUT : Field.INPUT,
[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 } }) => {
return {
...state,
independentField: field,
typedValue,
typedValue
}
})
.addCase(setRecipient, (state, { payload: { recipient } }) => {
......
......@@ -21,7 +21,7 @@ export function useTransactionAdder(): (
{
summary,
approval,
claim,
claim
}: { summary?: string; claim?: { recipient: string }; approval?: { tokenAddress: string; spender: string } } = {}
) => {
if (!account) return
......@@ -41,7 +41,7 @@ export function useTransactionAdder(): (
export function useAllTransactions(): { [txHash: string]: TransactionDetails } {
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] ?? {} : {}
}
......@@ -69,7 +69,7 @@ export function useHasPendingApproval(tokenAddress: string | undefined, spender:
() =>
typeof tokenAddress === 'string' &&
typeof spender === 'string' &&
Object.keys(allTransactions).some((hash) => {
Object.keys(allTransactions).some(hash => {
const tx = allTransactions[hash]
if (!tx) return false
if (tx.receipt) {
......@@ -93,7 +93,7 @@ export function useUserHasSubmittedClaim(
// get the txn if it has been submitted
const claimTxn = useMemo(() => {
const txnIndex = Object.keys(allTransactions).find((hash) => {
const txnIndex = Object.keys(allTransactions).find(hash => {
const tx = allTransactions[hash]
return tx.claim && tx.claim.recipient === account
})
......
......@@ -19,7 +19,7 @@ describe('transaction reducer', () => {
summary: 'hello world',
hash: '0x0',
approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc',
from: 'abc'
})
)
const txs = store.getState()
......@@ -49,8 +49,8 @@ describe('transaction reducer', () => {
from: '0x0',
contractAddress: '0x0',
blockHash: '0x0',
blockNumber: 1,
},
blockNumber: 1
}
})
)
expect(store.getState()).toEqual({})
......@@ -62,7 +62,7 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world',
from: '0x0',
from: '0x0'
})
)
const beforeTime = new Date().getTime()
......@@ -78,8 +78,8 @@ describe('transaction reducer', () => {
from: '0x0',
contractAddress: '0x0',
blockHash: '0x0',
blockNumber: 1,
},
blockNumber: 1
}
})
)
const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
......@@ -93,7 +93,7 @@ describe('transaction reducer', () => {
from: '0x0',
contractAddress: '0x0',
blockHash: '0x0',
blockNumber: 1,
blockNumber: 1
})
})
})
......@@ -104,7 +104,7 @@ describe('transaction reducer', () => {
checkedTransaction({
chainId: ChainId.RINKEBY,
hash: '0x0',
blockNumber: 1,
blockNumber: 1
})
)
expect(store.getState()).toEqual({})
......@@ -116,14 +116,14 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world',
from: '0x0',
from: '0x0'
})
)
store.dispatch(
checkedTransaction({
chainId: ChainId.RINKEBY,
hash: '0x0',
blockNumber: 1,
blockNumber: 1
})
)
const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
......@@ -136,21 +136,21 @@ describe('transaction reducer', () => {
chainId: ChainId.RINKEBY,
approval: { spender: '0x0', tokenAddress: '0x0' },
summary: 'hello world',
from: '0x0',
from: '0x0'
})
)
store.dispatch(
checkedTransaction({
chainId: ChainId.RINKEBY,
hash: '0x0',
blockNumber: 3,
blockNumber: 3
})
)
store.dispatch(
checkedTransaction({
chainId: ChainId.RINKEBY,
hash: '0x0',
blockNumber: 1,
blockNumber: 1
})
)
const tx = store.getState()[ChainId.RINKEBY]?.['0x0']
......@@ -166,7 +166,7 @@ describe('transaction reducer', () => {
summary: 'hello world',
hash: '0x0',
approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc',
from: 'abc'
})
)
store.dispatch(
......@@ -175,7 +175,7 @@ describe('transaction reducer', () => {
summary: 'hello world',
hash: '0x1',
approval: { tokenAddress: 'abc', spender: 'def' },
from: 'abc',
from: 'abc'
})
)
expect(Object.keys(store.getState())).toHaveLength(2)
......
......@@ -4,7 +4,7 @@ import {
checkedTransaction,
clearAllTransactions,
finalizeTransaction,
SerializableTransactionReceipt,
SerializableTransactionReceipt
} from './actions'
const now = () => new Date().getTime()
......@@ -29,7 +29,7 @@ export interface TransactionState {
export const initialState: TransactionState = {}
export default createReducer(initialState, (builder) =>
export default createReducer(initialState, builder =>
builder
.addCase(addTransaction, (transactions, { payload: { chainId, from, hash, approval, summary, claim } }) => {
if (transactions[chainId]?.[hash]) {
......
......@@ -35,7 +35,7 @@ export default function Updater(): null {
const lastBlockNumber = useBlockNumber()
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] ?? {} : {}
......@@ -46,11 +46,11 @@ export default function Updater(): null {
if (!chainId || !library || !lastBlockNumber) return
Object.keys(transactions)
.filter((hash) => shouldCheck(lastBlockNumber, transactions[hash]))
.forEach((hash) => {
.filter(hash => shouldCheck(lastBlockNumber, transactions[hash]))
.forEach(hash => {
library
.getTransactionReceipt(hash)
.then((receipt) => {
.then(receipt => {
if (receipt) {
dispatch(
finalizeTransaction({
......@@ -64,8 +64,8 @@ export default function Updater(): null {
status: receipt.status,
to: receipt.to,
transactionHash: receipt.transactionHash,
transactionIndex: receipt.transactionIndex,
},
transactionIndex: receipt.transactionIndex
}
})
)
......@@ -74,8 +74,8 @@ export default function Updater(): null {
txn: {
hash,
success: receipt.status === 1,
summary: transactions[hash]?.summary,
},
summary: transactions[hash]?.summary
}
},
hash
)
......@@ -83,7 +83,7 @@ export default function Updater(): null {
dispatch(checkedTransaction({ chainId, hash, blockNumber: lastBlockNumber }))
}
})
.catch((error) => {
.catch(error => {
console.error(`failed to check transaction hash: ${hash}`, error)
})
})
......
......@@ -19,7 +19,7 @@ import {
updateUserExpertMode,
updateUserSlippageTolerance,
toggleURLWarning,
updateUserSingleHopOnly,
updateUserSingleHopOnly
} from './actions'
function serializeToken(token: Token): SerializedToken {
......@@ -28,7 +28,7 @@ function serializeToken(token: Token): SerializedToken {
address: token.address,
decimals: token.decimals,
symbol: token.symbol,
name: token.name,
name: token.name
}
}
......@@ -49,7 +49,7 @@ export function useIsDarkMode(): boolean {
>(
({ user: { matchesDarkMode, userDarkMode } }) => ({
userDarkMode,
matchesDarkMode,
matchesDarkMode
}),
shallowEqual
)
......@@ -69,7 +69,7 @@ export function useDarkModeManager(): [boolean, () => void] {
}
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] {
......@@ -87,14 +87,14 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) =>
const dispatch = useDispatch<AppDispatch>()
const singleHopOnly = useSelector<AppState, AppState['user']['userSingleHopOnly']>(
(state) => state.user.userSingleHopOnly
state => state.user.userSingleHopOnly
)
const setSingleHopOnly = useCallback(
(newSingleHopOnly: boolean) => {
ReactGA.event({
category: 'Routing',
action: newSingleHopOnly ? 'enable single hop' : 'disable single hop',
action: newSingleHopOnly ? 'enable single hop' : 'disable single hop'
})
dispatch(updateUserSingleHopOnly({ userSingleHopOnly: newSingleHopOnly }))
},
......@@ -106,7 +106,7 @@ export function useUserSingleHopOnly(): [boolean, (newSingleHopOnly: boolean) =>
export function useUserSlippageTolerance(): [number, (slippage: number) => void] {
const dispatch = useDispatch<AppDispatch>()
const userSlippageTolerance = useSelector<AppState, AppState['user']['userSlippageTolerance']>((state) => {
const userSlippageTolerance = useSelector<AppState, AppState['user']['userSlippageTolerance']>(state => {
return state.user.userSlippageTolerance
})
......@@ -122,7 +122,7 @@ export function useUserSlippageTolerance(): [number, (slippage: number) => void]
export function useUserTransactionTTL(): [number, (slippage: number) => void] {
const dispatch = useDispatch<AppDispatch>()
const userDeadline = useSelector<AppState, AppState['user']['userDeadline']>((state) => {
const userDeadline = useSelector<AppState, AppState['user']['userDeadline']>(state => {
return state.user.userDeadline
})
......@@ -169,7 +169,7 @@ export function useUserAddedTokens(): Token[] {
function serializePair(pair: Pair): SerializedPair {
return {
token0: serializeToken(pair.token0),
token1: serializeToken(pair.token1),
token1: serializeToken(pair.token1)
}
}
......@@ -216,14 +216,14 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const generatedPairs: [Token, Token][] = useMemo(
() =>
chainId
? flatMap(Object.keys(tokens), (tokenAddress) => {
? flatMap(Object.keys(tokens), tokenAddress => {
const token = tokens[tokenAddress]
// for each token on the current chain,
return (
// loop though all bases on the current chain
(BASES_TO_TRACK_LIQUIDITY_FOR[chainId] ?? [])
// to construct pairs of the given token with each base
.map((base) => {
.map(base => {
if (base.address === token.address) {
return null
} else {
......@@ -245,7 +245,7 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const forChain = savedSerializedPairs[chainId]
if (!forChain) return []
return Object.keys(forChain).map((pairId) => {
return Object.keys(forChain).map(pairId => {
return [deserializeToken(forChain[pairId].token0), deserializeToken(forChain[pairId].token1)]
})
}, [savedSerializedPairs, chainId])
......@@ -253,7 +253,7 @@ export function useTrackedTokenPairs(): [Token, Token][] {
const combinedList = useMemo(() => userPairs.concat(generatedPairs).concat(pinnedPairs), [
generatedPairs,
pinnedPairs,
userPairs,
userPairs
])
return useMemo(() => {
......@@ -266,6 +266,6 @@ export function useTrackedTokenPairs(): [Token, Token][] {
return memo
}, {})
return Object.keys(keyed).map((key) => keyed[key])
return Object.keys(keyed).map(key => keyed[key])
}, [combinedList])
}
......@@ -23,7 +23,7 @@ describe('swap reducer', () => {
store = createStore(reducer, {
...initialState,
userDeadline: undefined,
userSlippageTolerance: undefined,
userSlippageTolerance: undefined
} as any)
store.dispatch(updateVersion())
expect(store.getState().userDeadline).toEqual(DEFAULT_DEADLINE_FROM_NOW)
......
......@@ -14,7 +14,7 @@ import {
updateUserSlippageTolerance,
updateUserDeadline,
toggleURLWarning,
updateUserSingleHopOnly,
updateUserSingleHopOnly
} from './actions'
const currentTimestamp = () => new Date().getTime()
......@@ -67,12 +67,12 @@ export const initialState: UserState = {
tokens: {},
pairs: {},
timestamp: currentTimestamp(),
URLWarningVisible: true,
URLWarningVisible: true
}
export default createReducer(initialState, (builder) =>
export default createReducer(initialState, builder =>
builder
.addCase(updateVersion, (state) => {
.addCase(updateVersion, state => {
// slippage isnt being tracked in local storage, reset to default
// noinspection SuspiciousTypeOfGuard
if (typeof state.userSlippageTolerance !== 'number') {
......@@ -139,7 +139,7 @@ export default createReducer(initialState, (builder) =>
}
state.timestamp = currentTimestamp()
})
.addCase(toggleURLWarning, (state) => {
.addCase(toggleURLWarning, state => {
state.URLWarningVisible = !state.URLWarningVisible
})
)
......@@ -32,7 +32,7 @@ export function useETHBalances(
const results = useSingleContractMultipleData(
multicallContract,
'getEthBalance',
addresses.map((address) => [address])
addresses.map(address => [address])
)
return useMemo(
......@@ -58,11 +58,11 @@ export function useTokenBalancesWithLoadingIndicator(
[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 anyLoading: boolean = useMemo(() => balances.some((callState) => callState.loading), [balances])
const anyLoading: boolean = useMemo(() => balances.some(callState => callState.loading), [balances])
return [
useMemo(
......@@ -79,7 +79,7 @@ export function useTokenBalancesWithLoadingIndicator(
: {},
[address, validatedTokens, balances]
),
anyLoading,
anyLoading
]
}
......@@ -102,16 +102,16 @@ export function useCurrencyBalances(
currencies?: (Currency | undefined)[]
): (CurrencyAmount | undefined)[] {
const tokens = useMemo(() => currencies?.filter((currency): currency is Token => currency instanceof Token) ?? [], [
currencies,
currencies
])
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] : [])
return useMemo(
() =>
currencies?.map((currency) => {
currencies?.map(currency => {
if (!account || !currency) return undefined
if (currency instanceof Token) return tokenBalances[currency.address]
if (currency === ETHER) return ethBalance[account]
......
......@@ -14,7 +14,7 @@ export default function DarkModeQueryParamReader({ location: { search } }: Route
const parsed = parse(search, {
parseArrays: false,
ignoreQueryPrefix: true,
ignoreQueryPrefix: true
})
const theme = parsed.theme
......
......@@ -24,7 +24,7 @@ export const ButtonText = styled.button`
`
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;
border-radius: 3rem;
......
......@@ -4,7 +4,7 @@ import styled, {
ThemeProvider as StyledComponentsThemeProvider,
createGlobalStyle,
css,
DefaultTheme,
DefaultTheme
} from 'styled-components'
import { useIsDarkMode } from '../state/user/hooks'
import { Text, TextProps } from 'rebass'
......@@ -16,7 +16,7 @@ const MEDIA_WIDTHS = {
upToExtraSmall: 500,
upToSmall: 720,
upToMedium: 960,
upToLarge: 1280,
upToLarge: 1280
}
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 {
green1: '#27AE60',
yellow1: '#FFE270',
yellow2: '#F3841E',
blue1: '#2172E5',
blue1: '#2172E5'
// dont wanna forget these blue yet
// blue4: darkMode ? '#153d6f70' : '#C4D9F8',
......@@ -95,7 +95,7 @@ export function theme(darkMode: boolean): DefaultTheme {
grids: {
sm: 8,
md: 12,
lg: 24,
lg: 24
},
//shadows
......@@ -112,7 +112,7 @@ export function theme(darkMode: boolean): DefaultTheme {
flexRowNoWrap: css`
display: flex;
flex-flow: row nowrap;
`,
`
}
}
......@@ -173,7 +173,7 @@ export const TYPE = {
},
error({ error, ...props }: { error: boolean } & TextProps) {
return <TextWrapper fontWeight={500} color={error ? 'red1' : 'text2'} {...props} />
},
}
}
export const FixedGlobalStyle = createGlobalStyle`
......
......@@ -14,7 +14,7 @@ describe('#chunkArray', () => {
it('size exact half', () => {
expect(chunkArray([1, 2, 3, 4], 2)).toEqual([
[1, 2],
[3, 4],
[3, 4]
])
})
it('evenly distributes', () => {
......@@ -22,8 +22,8 @@ describe('#chunkArray', () => {
expect(chunked).toEqual([
[...Array(34).keys()],
[...Array(34).keys()].map((i) => i + 34),
[...Array(32).keys()].map((i) => i + 68),
[...Array(34).keys()].map(i => i + 34),
[...Array(32).keys()].map(i => i + 68)
])
expect(chunked[0][0]).toEqual(0)
......
......@@ -7,5 +7,5 @@ export default function chunkArray<T>(items: T[], maxChunkSize: number): T[][] {
const numChunks: number = Math.ceil(items.length / maxChunkSize)
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 {
isAddress,
shortenAddress,
calculateGasMargin,
basisPointsToPercent,
basisPointsToPercent
} from '.'
describe('utils', () => {
......@@ -37,10 +37,10 @@ describe('utils', () => {
it('bounds are correct', () => {
const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100')
expect(() => calculateSlippageAmount(tokenAmount, -1)).toThrow()
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, 200).map((bound) => bound.toString())).toEqual(['98', '102'])
expect(calculateSlippageAmount(tokenAmount, 10000).map((bound) => bound.toString())).toEqual(['0', '200'])
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, 200).map(bound => bound.toString())).toEqual(['98', '102'])
expect(calculateSlippageAmount(tokenAmount, 10000).map(bound => bound.toString())).toEqual(['0', '200'])
expect(() => calculateSlippageAmount(tokenAmount, 10001)).toThrow()
})
})
......
......@@ -22,7 +22,7 @@ const ETHERSCAN_PREFIXES: { [chainId in ChainId]: string } = {
3: 'ropsten.',
4: 'rinkeby.',
5: 'goerli.',
42: 'kovan.',
42: 'kovan.'
}
export function getEtherscanLink(
......@@ -74,7 +74,7 @@ export function calculateSlippageAmount(value: CurrencyAmount, slippage: number)
}
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))
]
}
......
......@@ -13,7 +13,7 @@ describe('prices', () => {
it('returns undefined for undefined', () => {
expect(computeTradePriceBreakdown(undefined)).toEqual({
priceImpactWithoutFee: undefined,
realizedLPFee: undefined,
realizedLPFee: undefined
})
})
......
......@@ -50,7 +50,7 @@ export function computeSlippageAdjustedAmounts(
const pct = basisPointsToPercent(allowedSlippage)
return {
[Field.INPUT]: trade?.maximumAmountIn(pct),
[Field.OUTPUT]: trade?.minimumAmountOut(pct),
[Field.OUTPUT]: trade?.minimumAmountOut(pct)
}
}
......
......@@ -8,20 +8,20 @@ const REGISTRAR_ABI = [
inputs: [
{
name: 'node',
type: 'bytes32',
},
type: 'bytes32'
}
],
name: 'resolver',
outputs: [
{
name: 'resolverAddress',
type: 'address',
},
type: 'address'
}
],
payable: false,
stateMutability: 'view',
type: 'function',
},
type: 'function'
}
]
const REGISTRAR_ADDRESS = '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e'
......@@ -32,21 +32,21 @@ const RESOLVER_ABI = [
{
internalType: 'bytes32',
name: 'node',
type: 'bytes32',
},
type: 'bytes32'
}
],
name: 'contenthash',
outputs: [
{
internalType: 'bytes',
name: '',
type: 'bytes',
},
type: 'bytes'
}
],
payable: false,
stateMutability: 'view',
type: 'function',
},
type: 'function'
}
]
// cache the resolver contracts since most of them are the public resolver
......
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> {
......@@ -64,6 +64,6 @@ export function retry<T>(
if (completed) return
completed = true
rejectCancelled(new CancelledError())
},
}
}
}
......@@ -13,13 +13,13 @@ describe('uriToHttp', () => {
it('returns ipfs gateways for ipfs:// urls', () => {
expect(uriToHttp('ipfs://QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ')).toEqual([
'https://cloudflare-ipfs.com/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/',
'https://ipfs.io/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/',
'https://ipfs.io/ipfs/QmV8AfDE8GFSGQvt3vck8EwAzsPuNTmtP8VcQJE3qxRPaZ/'
])
})
it('returns ipns gateways for ipns:// urls', () => {
expect(uriToHttp('ipns://app.uniswap.org')).toEqual([
'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', () => {
......
......@@ -16,10 +16,10 @@ export default function useUSDCPrice(currency?: Currency): Price | undefined {
() => [
[
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],
[chainId ? WETH[chainId] : undefined, chainId === ChainId.MAINNET ? USDC : undefined],
[chainId ? WETH[chainId] : undefined, chainId === ChainId.MAINNET ? USDC : undefined]
],
[chainId, currency, wrapped]
)
......
......@@ -15,7 +15,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60,
deadline: 20 * 60
})
expect(result.methodName).toEqual('ethToTokenTransferInput')
expect(result.args).toEqual(['0x62', '0x4b0', TEST_RECIPIENT_ADDRESS])
......@@ -26,7 +26,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 40 * 60,
deadline: 40 * 60
})
expect(result.methodName).toEqual('tokenToEthTransferInput')
expect(result.args[0]).toEqual('0x64')
......@@ -40,7 +40,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60,
deadline: 20 * 60
})
expect(result.methodName).toEqual('tokenToTokenTransferInput')
expect(result.args[0]).toEqual('0x64')
......@@ -56,7 +56,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60,
deadline: 20 * 60
})
expect(result.methodName).toEqual('ethToTokenTransferOutput')
expect(result.args[0]).toEqual('0x64')
......@@ -69,7 +69,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60,
deadline: 20 * 60
})
expect(result.methodName).toEqual('tokenToEthTransferOutput')
expect(result.args[0]).toEqual('0x64')
......@@ -83,7 +83,7 @@ describe('v1SwapArguments', () => {
const result = v1SwapArguments(trade, {
recipient: TEST_RECIPIENT_ADDRESS,
allowedSlippage: new Percent('1', '100'),
deadline: 20 * 60,
deadline: 20 * 60
})
expect(result.methodName).toEqual('tokenToTokenTransferOutput')
expect(result.args[0]).toEqual('0x64')
......
......@@ -34,13 +34,13 @@ export default function v1SwapArguments(
return {
methodName: 'ethToTokenTransferInput',
args: [minimumAmountOut, deadline, options.recipient],
value: maximumAmountIn,
value: maximumAmountIn
}
} else if (outputETH) {
return {
methodName: 'tokenToEthTransferInput',
args: [maximumAmountIn, minimumAmountOut, deadline, options.recipient],
value: '0x0',
value: '0x0'
}
} else {
const outputToken = trade.outputAmount.currency
......@@ -51,7 +51,7 @@ export default function v1SwapArguments(
return {
methodName: 'tokenToTokenTransferInput',
args: [maximumAmountIn, minimumAmountOut, '0x1', deadline, options.recipient, outputToken.address],
value: '0x0',
value: '0x0'
}
}
} else {
......@@ -59,13 +59,13 @@ export default function v1SwapArguments(
return {
methodName: 'ethToTokenTransferOutput',
args: [minimumAmountOut, deadline, options.recipient],
value: maximumAmountIn,
value: maximumAmountIn
}
} else if (outputETH) {
return {
methodName: 'tokenToEthTransferOutput',
args: [minimumAmountOut, maximumAmountIn, deadline, options.recipient],
value: '0x0',
value: '0x0'
}
} else {
const output = trade.outputAmount.currency
......@@ -81,9 +81,9 @@ export default function v1SwapArguments(
MaxUint256.toHexString(),
deadline,
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