-
Notifications
You must be signed in to change notification settings - Fork 101
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'develop' into feat/limit-ui-upgrade
- Loading branch information
Showing
5 changed files
with
148 additions
and
168 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
82 changes: 18 additions & 64 deletions
82
apps/cowswap-frontend/src/modules/limitOrders/hooks/useGetInitialPrice.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,90 +1,44 @@ | ||
import { useEffect, useState } from 'react' | ||
|
||
import { useIsWindowVisible } from '@cowprotocol/common-hooks' | ||
import { getWrappedToken } from '@cowprotocol/common-utils' | ||
import { useWalletInfo } from '@cowprotocol/wallet' | ||
import { Currency, Fraction } from '@uniswap/sdk-core' | ||
import { FractionUtils, getWrappedToken } from '@cowprotocol/common-utils' | ||
import { Fraction } from '@uniswap/sdk-core' | ||
|
||
import ms from 'ms.macro' | ||
import { useAsyncMemo } from 'use-async-memo' | ||
|
||
import { useLimitOrdersDerivedState } from 'modules/limitOrders/hooks/useLimitOrdersDerivedState' | ||
|
||
import { useSafeMemo } from 'common/hooks/useSafeMemo' | ||
|
||
import { fetchCurrencyUsdPrice, usdcPriceLoader } from '../../usdAmount' | ||
|
||
const PRICE_UPDATE_INTERVAL = ms`10sec` | ||
|
||
export async function requestPrice( | ||
chainId: number | undefined, | ||
inputCurrency: Currency | null, | ||
outputCurrency: Currency | null, | ||
): Promise<Fraction | null> { | ||
if (!chainId || !inputCurrency || !outputCurrency) { | ||
return null | ||
} | ||
|
||
const inputToken = getWrappedToken(inputCurrency) | ||
const outputToken = getWrappedToken(outputCurrency) | ||
|
||
// Only needed for the fallback CoW price, which needs to know the USDC price | ||
const getUsdPrice = usdcPriceLoader(chainId) | ||
|
||
return Promise.all([ | ||
fetchCurrencyUsdPrice(inputToken, getUsdPrice), | ||
fetchCurrencyUsdPrice(outputToken, getUsdPrice), | ||
]).then(([inputPrice, outputPrice]) => { | ||
if (!inputPrice || !outputPrice) { | ||
return null | ||
} | ||
|
||
const result = inputPrice.divide(outputPrice) | ||
|
||
console.debug('Updated limit orders initial price: ', result.toSignificant(18)) | ||
|
||
return result | ||
}) | ||
} | ||
import { useUsdPrice } from '../../usdAmount' | ||
|
||
// Fetches the INPUT and OUTPUT price and calculates initial Active rate | ||
// When return null it means we failed on price loading | ||
export function useGetInitialPrice(): { price: Fraction | null; isLoading: boolean } { | ||
const { chainId } = useWalletInfo() | ||
const { inputCurrency, outputCurrency } = useLimitOrdersDerivedState() | ||
const [isLoading, setIsLoading] = useState(false) | ||
const [updateTimestamp, setUpdateTimestamp] = useState(Date.now()) | ||
const isWindowVisible = useIsWindowVisible() | ||
|
||
const inputToken = inputCurrency && getWrappedToken(inputCurrency) | ||
const outputToken = outputCurrency && getWrappedToken(outputCurrency) | ||
const inputUsdPrice = useUsdPrice(inputToken) | ||
const outputUsdPrice = useUsdPrice(outputToken) | ||
|
||
useEffect(() => { | ||
setIsLoading(!!inputUsdPrice?.isLoading || !!outputUsdPrice?.isLoading) | ||
}, [inputUsdPrice?.isLoading, outputUsdPrice?.isLoading]) | ||
|
||
const price = useAsyncMemo( | ||
async () => { | ||
setIsLoading(true) | ||
|
||
console.debug('[useGetInitialPrice] Fetching price') | ||
try { | ||
return await requestPrice(chainId, inputCurrency, outputCurrency) | ||
} finally { | ||
setIsLoading(false) | ||
if (!inputUsdPrice?.price || !outputUsdPrice?.price) { | ||
return null | ||
} | ||
const inputFraction = FractionUtils.fractionLikeToFraction(inputUsdPrice.price) | ||
const outputFraction = FractionUtils.fractionLikeToFraction(outputUsdPrice.price) | ||
return inputFraction.divide(outputFraction) | ||
}, | ||
[chainId, inputCurrency, outputCurrency, updateTimestamp], | ||
[inputUsdPrice?.price, outputUsdPrice?.price], | ||
null, | ||
) | ||
|
||
// Update initial price every 10 seconds | ||
useEffect(() => { | ||
if (!isWindowVisible) { | ||
console.debug('[useGetInitialPrice] No need to fetch quotes') | ||
return | ||
} | ||
|
||
console.debug('[useGetInitialPrice] Periodically fetch price') | ||
const interval = setInterval(() => { | ||
setUpdateTimestamp(Date.now()) | ||
}, PRICE_UPDATE_INTERVAL) | ||
|
||
return () => clearInterval(interval) | ||
}, [isWindowVisible]) | ||
|
||
return useSafeMemo(() => ({ price, isLoading }), [price, isLoading]) | ||
} |
63 changes: 35 additions & 28 deletions
63
apps/cowswap-frontend/src/modules/limitOrders/updaters/QuoteObserverUpdater/index.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,49 +1,56 @@ | ||
import { useSetAtom } from 'jotai' | ||
import { useEffect } from 'react' | ||
import { useEffect, useMemo } from 'react' | ||
|
||
import { FractionUtils } from '@cowprotocol/common-utils' | ||
import { CurrencyAmount, Percent, Price } from '@uniswap/sdk-core' | ||
import { FractionUtils, getWrappedToken } from '@cowprotocol/common-utils' | ||
import { Fraction, Token } from '@uniswap/sdk-core' | ||
|
||
import { Nullish } from 'types' | ||
|
||
import { updateLimitRateAtom } from 'modules/limitOrders/state/limitRateAtom' | ||
import { useDerivedTradeState } from 'modules/trade/hooks/useDerivedTradeState' | ||
import { useTradeQuote } from 'modules/tradeQuote' | ||
|
||
const LIMIT_ORDERS_PRICE_SLIPPAGE = new Percent(1, 10) // 0.1% | ||
import { useUsdPrice } from 'modules/usdAmount/hooks/useUsdPrice' | ||
|
||
export function QuoteObserverUpdater() { | ||
const { response } = useTradeQuote() | ||
const state = useDerivedTradeState() | ||
|
||
const updateLimitRateState = useSetAtom(updateLimitRateAtom) | ||
|
||
const inputCurrency = state?.inputCurrency | ||
const outputCurrency = state?.outputCurrency | ||
|
||
useEffect(() => { | ||
if (!outputCurrency || !inputCurrency || !response) { | ||
return | ||
} | ||
|
||
const { buyAmount: buyAmountRaw, sellAmount: sellAmountRaw, feeAmount: feeAmountRaw } = response.quote | ||
const inputToken = inputCurrency && getWrappedToken(inputCurrency) | ||
const outputToken = outputCurrency && getWrappedToken(outputCurrency) | ||
|
||
const feeAmount = CurrencyAmount.fromRawAmount(inputCurrency, feeAmountRaw) | ||
const sellAmount = CurrencyAmount.fromRawAmount(inputCurrency, sellAmountRaw) | ||
const buyAmount = CurrencyAmount.fromRawAmount(outputCurrency, buyAmountRaw) | ||
const { price, isLoading } = useSpotPrice(inputToken, outputToken) | ||
|
||
if (sellAmount.equalTo(0) || buyAmount.equalTo(0)) return | ||
useEffect(() => { | ||
updateLimitRateState({ marketRate: price, isLoadingMarketRate: isLoading }) | ||
}, [price, isLoading, updateLimitRateState]) | ||
|
||
const price = FractionUtils.fractionLikeToFraction(new Price({ baseAmount: sellAmount, quoteAmount: buyAmount })) | ||
const marketRate = price.subtract(price.multiply(LIMIT_ORDERS_PRICE_SLIPPAGE.divide(100))) | ||
return null | ||
} | ||
|
||
const biggestDecimal = Math.max(sellAmount.currency.decimals, buyAmount.currency.decimals) | ||
/** | ||
* In case when inputted sell amount is enormously big and the price is very small | ||
* App crashes with "Invariant failed" | ||
*/ | ||
const isPriceInvalid = +marketRate.toFixed(biggestDecimal) === 0 | ||
function useSpotPrice( | ||
inputCurrency: Nullish<Token>, | ||
outputCurrency: Nullish<Token>, | ||
): { | ||
price: Fraction | null | ||
isLoading: boolean | ||
} { | ||
const inputUsdPrice = useUsdPrice(inputCurrency) | ||
const outputUsdPrice = useUsdPrice(outputCurrency) | ||
|
||
return useMemo(() => { | ||
const isLoading = !!inputUsdPrice?.isLoading || !!outputUsdPrice?.isLoading | ||
|
||
if (!inputUsdPrice?.price || !outputUsdPrice?.price) { | ||
return { price: null, isLoading } | ||
} | ||
const inputFraction = FractionUtils.fractionLikeToFraction(inputUsdPrice.price) | ||
const outputFraction = FractionUtils.fractionLikeToFraction(outputUsdPrice.price) | ||
|
||
updateLimitRateState({ marketRate: isPriceInvalid ? null : marketRate, feeAmount }) | ||
}, [response, inputCurrency, outputCurrency, updateLimitRateState]) | ||
const price = inputFraction.divide(outputFraction) | ||
|
||
return null | ||
return { price, isLoading } | ||
}, [inputUsdPrice?.price, inputUsdPrice?.isLoading, outputUsdPrice?.price, outputUsdPrice?.isLoading]) | ||
} |
Oops, something went wrong.