Skip to content

Commit

Permalink
Merge pull request #3475 from cowprotocol/release/1.51.0
Browse files Browse the repository at this point in the history
Release/1.51.0
  • Loading branch information
anxolin authored Dec 6, 2023
2 parents 45950a8 + 1d1458c commit 69f92e9
Show file tree
Hide file tree
Showing 150 changed files with 2,383 additions and 1,017 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { CowModal } from 'common/pure/Modal'
import { TransactionErrorContent } from 'common/pure/TransactionErrorContent'

import { useTradeApproveCallback } from './useTradeApproveCallback'
import { useTradeApproveState } from './useTradeApproveState'

import { useApproveState } from '../../hooks/useApproveState'

export interface TradeApproveButtonProps {
amountToApprove: CurrencyAmount<Currency>
Expand All @@ -22,7 +23,7 @@ export function TradeApproveButton(props: TradeApproveButtonProps) {

const currency = amountToApprove.currency

const approvalState = useTradeApproveState(amountToApprove)
const approvalState = useApproveState(amountToApprove)
const tradeApproveCallback = useTradeApproveCallback(amountToApprove)
const shouldZeroApprove = useShouldZeroApprove(amountToApprove)
const zeroApprove = useZeroApprove(amountToApprove.currency)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './TradeApproveButton'
export * from './TradeApproveModal'
export * from './useTradeApproveCallback'
export * from './useTradeApproveState'

This file was deleted.

36 changes: 20 additions & 16 deletions apps/cowswap-frontend/src/common/hooks/useApproveState.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,56 @@
import { useMemo } from 'react'

import { useTokensAllowances } from '@cowprotocol/balances-and-allowances'
import { usePrevious } from '@cowprotocol/common-hooks'
import { FractionUtils, getWrappedToken } from '@cowprotocol/common-utils'
import { useWalletInfo } from '@cowprotocol/wallet'
import { getWrappedToken } from '@cowprotocol/common-utils'
import { BigNumber } from '@ethersproject/bignumber'
import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core'

import { Nullish } from 'types'

import { ApprovalState } from 'legacy/hooks/useApproveCallback/useApproveCallbackMod'
import { useTokenAllowance } from 'legacy/hooks/useTokenAllowance'
import { useHasPendingApproval } from 'legacy/state/enhancedTransactions/hooks'

import { useSafeMemo } from 'common/hooks/useSafeMemo'

import { useTradeSpenderAddress } from './useTradeSpenderAddress'

function getCurrencyToApprove(amountToApprove: Nullish<CurrencyAmount<Currency>>): Token | undefined {
if (!amountToApprove) return undefined

return getWrappedToken(amountToApprove.currency)
}

export function useApproveState(amountToApprove: Nullish<CurrencyAmount<Currency>>, spender?: string): ApprovalState {
const { account } = useWalletInfo()
export function useApproveState(amountToApprove: Nullish<CurrencyAmount<Currency>>): ApprovalState {
const spender = useTradeSpenderAddress()
const token = getCurrencyToApprove(amountToApprove)
const currentAllowance = useTokenAllowance(token, account ?? undefined, spender)
const pendingApproval = useHasPendingApproval(token?.address, spender)
const tokenAddress = token?.address?.toLowerCase()
const allowances = useTokensAllowances()
const pendingApproval = useHasPendingApproval(tokenAddress, spender)

const currentAllowance = tokenAddress ? allowances.values[tokenAddress] : undefined

const approvalStateBase = useSafeMemo(() => {
if (!amountToApprove || !spender || !currentAllowance) {
if (!amountToApprove || !currentAllowance) {
return ApprovalState.UNKNOWN
}

if (FractionUtils.gte(currentAllowance, amountToApprove)) {
const amountToApproveString = amountToApprove.quotient.toString()

if (currentAllowance.gte(amountToApproveString)) {
return ApprovalState.APPROVED
}

if (pendingApproval) {
return ApprovalState.PENDING
}

if (currentAllowance.lessThan(amountToApprove)) {
if (currentAllowance.lt(amountToApproveString)) {
return ApprovalState.NOT_APPROVED
}

return ApprovalState.APPROVED
}, [amountToApprove, currentAllowance, pendingApproval, spender])
}, [amountToApprove, currentAllowance, pendingApproval])

return useAuxApprovalState(approvalStateBase, currentAllowance)
}
Expand All @@ -55,12 +62,9 @@ export function useApproveState(amountToApprove: Nullish<CurrencyAmount<Currency
*
* Solution: we check the prev approval state and also check if the allowance has been updated
*/
function useAuxApprovalState(
approvalStateBase: ApprovalState,
currentAllowance?: CurrencyAmount<Currency>
): ApprovalState {
function useAuxApprovalState(approvalStateBase: ApprovalState, currentAllowance?: BigNumber): ApprovalState {
const previousApprovalState = usePrevious(approvalStateBase)
const currentAllowanceString = currentAllowance?.quotient.toString()
const currentAllowanceString = currentAllowance?.toHexString()
const previousAllowanceString = usePrevious(currentAllowanceString)
// Has allowance actually updated?
const allowanceHasNotChanged = previousAllowanceString === currentAllowanceString
Expand Down
13 changes: 4 additions & 9 deletions apps/cowswap-frontend/src/common/hooks/useNeedsApproval.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { useTokensAllowances } from '@cowprotocol/balances-and-allowances'
import { getWrappedToken, isEnoughAmount } from '@cowprotocol/common-utils'
import { useWalletInfo } from '@cowprotocol/wallet'
import { Currency, CurrencyAmount } from '@uniswap/sdk-core'

import { Nullish } from 'types'

import { useBalancesAndAllowances } from 'modules/tokens'

import { useTradeSpenderAddress } from 'common/hooks/useTradeSpenderAddress'

/**
Expand All @@ -22,19 +20,16 @@ import { useTradeSpenderAddress } from 'common/hooks/useTradeSpenderAddress'
* @returns {boolean}
*/
export function useNeedsApproval(amount: Nullish<CurrencyAmount<Currency>>): boolean {
const { account } = useWalletInfo()
const spender = useTradeSpenderAddress()
const token = amount ? getWrappedToken(amount.currency) : undefined
const tokens = token ? [token] : []
const balancesAndAllowances = useBalancesAndAllowances({ account, spender, tokens })

const { allowances } = balancesAndAllowances
const { values: allowances } = useTokensAllowances()

const allowance = token && allowances[token.address]?.value
const allowance = token && allowances[token.address.toLowerCase()]

if (!allowance) {
return true
}

if (!token || !amount || !spender) {
return false
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useSetAtom } from 'jotai'
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useCallback, useEffect, useRef } from 'react'

import { priceOutOfRangeAnalytics } from '@cowprotocol/analytics'
import { GP_VAULT_RELAYER, NATIVE_CURRENCY_BUY_ADDRESS, WRAPPED_NATIVE_CURRENCY } from '@cowprotocol/common-const'
import { useTokensBalances } from '@cowprotocol/balances-and-allowances'
import { NATIVE_CURRENCY_BUY_ADDRESS, WRAPPED_NATIVE_CURRENCY } from '@cowprotocol/common-const'
import { useIsWindowVisible } from '@cowprotocol/common-hooks'
import { getPromiseFulfilledValue } from '@cowprotocol/common-utils'
import { timestamp } from '@cowprotocol/contracts'
Expand All @@ -26,7 +27,7 @@ import {
import { getBestQuote } from 'legacy/utils/price'

import { updatePendingOrderPricesAtom } from 'modules/orders/state/pendingOrdersPricesAtom'
import { hasEnoughBalanceAndAllowance, useBalancesAndAllowances } from 'modules/tokens'
import { hasEnoughBalanceAndAllowance } from 'modules/tokens'

import { getPriceQuality } from 'api/gnosisProtocol/api'

Expand All @@ -46,15 +47,7 @@ export function UnfillableOrdersUpdater(): null {
const setIsOrderUnfillable = useSetIsOrderUnfillable()
const strategy = useGetGpPriceStrategy()

const tokens = useMemo(() => {
return pending.map((order) => order.inputToken)
}, [pending])

const { balances } = useBalancesAndAllowances({
account,
spender: chainId ? GP_VAULT_RELAYER[chainId] : undefined,
tokens: tokens,
})
const { values: balances } = useTokensBalances()

// Ref, so we don't rerun useEffect
const pendingRef = useRef(pending)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React from 'react'

import { useNativeCurrencyAmount } from '@cowprotocol/balances-and-allowances'
import { NATIVE_CURRENCY_BUY_TOKEN } from '@cowprotocol/common-const'
import { TokenAmount } from '@cowprotocol/ui'
import { useWalletInfo } from '@cowprotocol/wallet'

import { useToggleAccountModal } from 'modules/account'
import { useNativeCurrencyBalances } from 'modules/tokens/hooks/useCurrencyBalance'
import { Web3Status } from 'modules/wallet/containers/Web3Status'

import { useIsProviderNetworkUnsupported } from 'common/hooks/useIsProviderNetworkUnsupported'
Expand All @@ -21,7 +21,7 @@ interface AccountElementProps {
export function AccountElement({ className, isWidgetMode, pendingActivities }: AccountElementProps) {
const { account, chainId } = useWalletInfo()
const isChainIdUnsupported = useIsProviderNetworkUnsupported()
const userEthBalance = useNativeCurrencyBalances(account ? [account] : [])?.[account ?? '']
const userEthBalance = useNativeCurrencyAmount()
const toggleAccountModal = useToggleAccountModal()
const nativeToken = NATIVE_CURRENCY_BUY_TOKEN[chainId].symbol

Expand Down
16 changes: 3 additions & 13 deletions apps/cowswap-frontend/src/legacy/components/Header/Polling.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { useEffect, useState } from 'react'

import { getChainInfo } from '@cowprotocol/common-const'
import { useBlockNumber, useMachineTimeMs, useTheme } from '@cowprotocol/common-hooks'
import { useBlockNumber, useIsOnline, useTheme } from '@cowprotocol/common-hooks'
import { ExplorerDataType, getExplorerLink } from '@cowprotocol/common-utils'
import { RowFixed } from '@cowprotocol/ui'
import { MouseoverTooltip, ExternalLink } from '@cowprotocol/ui'
import { useWalletInfo } from '@cowprotocol/wallet'

import { Trans } from '@lingui/macro'
import JSBI from 'jsbi'
import ms from 'ms.macro'
import styled, { keyframes } from 'styled-components/macro'

import useCurrentBlockTimestamp from 'legacy/hooks/useCurrentBlockTimestamp'
import useGasPrice from 'legacy/hooks/useGasPrice'
import { ThemedText } from 'legacy/theme'

Expand Down Expand Up @@ -157,25 +154,18 @@ const Wrapper = styled.div`
}
`

const DEFAULT_MS_BEFORE_WARNING = ms`10m`
const NETWORK_HEALTH_CHECK_MS = ms`10s`

export function Polling() {
const { chainId } = useWalletInfo()
const blockNumber = useBlockNumber()
const [isMounting, setIsMounting] = useState(false)
const [isHover, setIsHover] = useState(false)
const machineTime = useMachineTimeMs(NETWORK_HEALTH_CHECK_MS)
const blockTime = useCurrentBlockTimestamp()
const isOnline = useIsOnline()
const theme = useTheme()

const ethGasPrice = useGasPrice()
const priceGwei = ethGasPrice ? JSBI.divide(ethGasPrice, JSBI.BigInt(1000000000)) : undefined

const waitMsBeforeWarning =
(chainId ? getChainInfo(chainId)?.blockWaitMsBeforeWarning : DEFAULT_MS_BEFORE_WARNING) ?? DEFAULT_MS_BEFORE_WARNING

const warning = Boolean(!!blockTime && machineTime - blockTime.mul(1000).toNumber() > waitMsBeforeWarning)
const warning = !isOnline

useEffect(
() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'

import { BalancesState } from '@cowprotocol/balances-and-allowances'
import { TokenWithLogo } from '@cowprotocol/common-const'
import { useFilterTokens, usePrevious } from '@cowprotocol/common-hooks'
import { CurrencyAmount } from '@uniswap/sdk-core'

import { Trans } from '@lingui/macro'

Expand All @@ -10,8 +12,6 @@ import useTransactionConfirmationModal from 'legacy/hooks/useTransactionConfirma
import { useToggleWalletModal } from 'legacy/state/application/hooks'
import { ConfirmOperationType } from 'legacy/state/types'

import { TokenAmounts } from 'modules/tokens'

import { balanceComparator, useTokenComparator } from './sorting'
import {
Arrow,
Expand All @@ -36,12 +36,10 @@ enum SORT_FIELD {
BALANCE = 'balance',
}

type BalanceType = [TokenAmounts, boolean]

type TokenTableParams = {
tokensData: TokenWithLogo[] | undefined
maxItems?: number
balances?: BalanceType
balances?: BalancesState['values']
page: number
setPage: (page: number) => void
query: string
Expand Down Expand Up @@ -113,8 +111,8 @@ export default function TokenTable({
// If the sort field is Balance
if (!balances) return 0

const balanceA = balances[0][tokenA.address]?.value
const balanceB = balances[0][tokenB.address]?.value
const balanceA = balances[tokenA.address.toLowerCase()]
const balanceB = balances[tokenB.address.toLowerCase()]
const balanceComp = balanceComparator(balanceA, balanceB)

return applyDirection(balanceComp > 0, sortDirection)
Expand Down Expand Up @@ -202,13 +200,16 @@ export default function TokenTable({

{tokensData && sortedTokens.length !== 0 ? (
sortedTokens.map((data, i) => {
const balanceRaw = balances && balances[data.address.toLowerCase()]
const balance = balanceRaw ? CurrencyAmount.fromRawAmount(data, balanceRaw.toHexString()) : undefined

if (data) {
return (
<Row key={data.address}>
<TokensTableRow
key={data.address}
toggleWalletModal={toggleWalletModal}
balance={balances && balances[0][data.address]?.value}
balance={balance}
openTransactionConfirmationModal={openModal}
closeModals={closeModal}
index={getTokenIndex(i)}
Expand Down
23 changes: 11 additions & 12 deletions apps/cowswap-frontend/src/legacy/components/Tokens/sorting.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import { useMemo } from 'react'

import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core'

import { TokenAmounts } from 'modules/tokens'
import { useAllTokensBalances } from 'modules/tokensList'
import { BalancesState, useTokensBalances } from '@cowprotocol/balances-and-allowances'
import { BigNumber } from '@ethersproject/bignumber'
import { Token } from '@uniswap/sdk-core'

const PRIORITISED_TOKENS = ['COW', 'GNO']

// compare two token amounts with highest one coming first
export function balanceComparator(balanceA?: CurrencyAmount<Currency>, balanceB?: CurrencyAmount<Currency>) {
export function balanceComparator(balanceA: BigNumber | undefined, balanceB: BigNumber | undefined) {
if (balanceA && balanceB) {
return balanceA.greaterThan(balanceB) ? -1 : balanceA.equalTo(balanceB) ? 0 : 1
} else if (balanceA && balanceA.greaterThan('0')) {
return balanceA.gt(balanceB) ? -1 : balanceA.eq(balanceB) ? 0 : 1
} else if (balanceA && balanceA.gt('0')) {
return -1
} else if (balanceB && balanceB.greaterThan('0')) {
} else if (balanceB && balanceB.gt('0')) {
return 1
}
return 0
}

function getTokenComparator(balances: [TokenAmounts, boolean]): (tokenA: Token, tokenB: Token) => number {
function getTokenComparator(balances: BalancesState['values']): (tokenA: Token, tokenB: Token) => number {
return function sortTokens(tokenA: Token, tokenB: Token): number {
// -1 = a is first
// 1 = b is first

// sort by balances
const balanceA = balances[0][tokenA.address]?.value
const balanceB = balances[0][tokenB.address]?.value
const balanceA = balances[tokenA.address.toLowerCase()]
const balanceB = balances[tokenB.address.toLowerCase()]

const balanceComp = balanceComparator(balanceA, balanceB)
if (balanceComp !== 0) return balanceComp
Expand All @@ -51,7 +50,7 @@ function getTokenComparator(balances: [TokenAmounts, boolean]): (tokenA: Token,
}

export function useTokenComparator(inverted: boolean): (tokenA: Token, tokenB: Token) => number {
const balances = useAllTokensBalances()
const { values: balances } = useTokensBalances()

const comparator = useMemo(() => getTokenComparator(balances), [balances])

Expand Down
Loading

2 comments on commit 69f92e9

@vercel
Copy link

@vercel vercel bot commented on 69f92e9 Dec 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on 69f92e9 Dec 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

cosmos – ./

cosmos-cowswap.vercel.app
cowswap-seven.vercel.app
cosmos.cow.fi
cosmos-git-main-cowswap.vercel.app

Please sign in to comment.