Skip to content
This repository was archived by the owner on Jun 24, 2022. It is now read-only.

Commit

Permalink
set the validTo in the callback
Browse files Browse the repository at this point in the history
  • Loading branch information
W3stside committed Dec 15, 2021
1 parent 25b0439 commit 8b90b2b
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 34 deletions.
13 changes: 7 additions & 6 deletions src/custom/hooks/usePriceImpact/useFallbackPriceImpact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { calculateFallbackPriceImpact, FeeQuoteParams } from 'utils/price'
import TradeGp from 'state/swap/TradeGp'
import { QuoteInformationObject } from 'state/price/reducer'
import { QuoteError } from 'state/price/actions'
import { useOrderValidTo } from 'state/user/hooks'
import { getAdjustedValidTo } from 'state/price/updater'
import { useQuote } from 'state/price/hooks'
import { useActiveWeb3React } from 'hooks/web3'

type SwapParams = { abTrade?: TradeGp; sellToken?: string | null; buyToken?: string | null }

Expand Down Expand Up @@ -47,7 +47,9 @@ export default function useFallbackPriceImpact({ abTrade, isWrapping }: Fallback
INPUT: { currencyId: sellToken },
OUTPUT: { currencyId: buyToken },
} = useSwapState()
const { validTo, deadline } = useOrderValidTo()

const { chainId } = useActiveWeb3React()
const lastQuote = useQuote({ token: sellToken, chainId })

const [loading, setLoading] = useState(false)

Expand All @@ -64,12 +66,11 @@ export default function useFallbackPriceImpact({ abTrade, isWrapping }: Fallback
// Calculate the necessary params to get the inverse trade impact
const { parsedAmount, outputCurrency, ...swapQuoteParams } = useMemo(
() => ({
parsedAmount: _getBaTradeParsedAmount(abTrade, shouldCalculate),
validTo: getAdjustedValidTo(validTo, deadline),
..._getBaTradeParams({ abTrade, sellToken, buyToken }),
parsedAmount: _getBaTradeParsedAmount(abTrade, shouldCalculate),
validTo: lastQuote?.validTo,
}),
[abTrade, buyToken, deadline, sellToken, shouldCalculate, validTo]
[abTrade, buyToken, lastQuote?.validTo, sellToken, shouldCalculate]
)

const { quote } = useCalculateQuote({
Expand Down
8 changes: 4 additions & 4 deletions src/custom/hooks/usePriceImpact/useQuoteAndSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import { FeeQuoteParams, getBestQuote, QuoteResult } from 'utils/price'

import { ZERO_ADDRESS } from 'constants/misc'
import { SupportedChainId } from 'constants/chains'
import { DEFAULT_DECIMALS } from 'constants/index'
import { DEFAULT_DECIMALS, DEFAULT_GP_PRICE_STRATEGY } from 'constants/index'
import { QuoteError } from 'state/price/actions'
import { isWrappingTrade } from 'state/swap/utils'
import useGetGpPriceStrategy, { DEFAULT_GP_PRICE_STRATEGY } from '../useGetGpPriceStrategy'
import useGetGpPriceStrategy from '../useGetGpPriceStrategy'

type WithLoading = { loading: boolean; setLoading: (state: boolean) => void }

Expand All @@ -33,7 +33,7 @@ type GetQuoteParams = {
buyToken?: string | null
fromDecimals?: number
toDecimals?: number
validTo: number
validTo?: number
} & WithLoading

type FeeQuoteParamsWithError = FeeQuoteParams & { error?: QuoteError }
Expand All @@ -58,7 +58,7 @@ export function useCalculateQuote(params: GetQuoteParams) {
useEffect(() => {
const chainId = supportedChainId(preChain)
// bail out early - amount here is undefined if usd price impact is valid
if (!sellToken || !buyToken || !amount) return
if (!sellToken || !buyToken || !amount || !validTo) return

setLoading(true)

Expand Down
20 changes: 18 additions & 2 deletions src/custom/hooks/useRefetchPriceCallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,20 @@ import { useQuoteDispatchers } from 'state/price/hooks'
import { AddGpUnsupportedTokenParams } from 'state/lists/actions'
import { QuoteError } from 'state/price/actions'
import { onlyResolvesLast } from 'utils/async'
import useGetGpPriceStrategy from '@src/custom/hooks/useGetGpPriceStrategy'
import useGetGpPriceStrategy from 'hooks/useGetGpPriceStrategy'
import { calculateValidTo } from 'hooks/useSwapCallback'
import { useUserTransactionTTL } from 'state/user/hooks'

interface HandleQuoteErrorParams {
quoteData: QuoteInformationObject | FeeQuoteParams
error: unknown
addUnsupportedToken: (params: AddGpUnsupportedTokenParams) => void
}

interface QuoteParamsForFetching extends Omit<QuoteParams, 'quoteParams' | 'strategy'> {
quoteParams: Omit<FeeQuoteParams, 'validTo'>
}

export function handleQuoteError({ quoteData, error, addUnsupportedToken }: HandleQuoteErrorParams): QuoteError {
if (isValidOperatorError(error)) {
switch (error.type) {
Expand Down Expand Up @@ -117,6 +123,7 @@ export function useRefetchQuoteCallback() {
const removeGpUnsupportedToken = useRemoveGpUnsupportedToken()
// check which price strategy to use (COWSWAP/LEGACY)
const priceStrategy = useGetGpPriceStrategy()
const [deadline] = useUserTransactionTTL()

registerOnWindow({
getNewQuote,
Expand All @@ -128,7 +135,15 @@ export function useRefetchQuoteCallback() {
})

return useCallback(
async (params: Omit<QuoteParams, 'strategy'>) => {
async (preParams: QuoteParamsForFetching) => {
// construct params with validTo
const params = {
...preParams,
quoteParams: {
...preParams.quoteParams,
validTo: calculateValidTo(deadline),
},
}
const { quoteParams, isPriceRefresh } = params
let quoteData: FeeQuoteParams | QuoteInformationObject = quoteParams

Expand Down Expand Up @@ -207,6 +222,7 @@ export function useRefetchQuoteCallback() {
}
},
[
deadline,
priceStrategy,
isUnsupportedTokenGp,
updateQuote,
Expand Down
28 changes: 6 additions & 22 deletions src/custom/state/price/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect, useState } from 'react'
import { DEFAULT_DECIMALS } from 'custom/constants'

import { UnsupportedToken } from 'api/gnosisProtocol'
import { FeeQuoteParams } from 'utils/price'
import { FeeQuoteParams as FeeQuoteParamsFull } from 'utils/price'
import { OrderKind } from '@gnosis.pm/gp-v2-contracts'

import { useSwapState, tryParseAmount } from 'state/swap/hooks'
Expand All @@ -24,10 +24,11 @@ import { useOrderValidTo } from 'state/user/hooks'
const DEBOUNCE_TIME = 350
const REFETCH_CHECK_INTERVAL = 10000 // Every 10s
const RENEW_FEE_QUOTES_BEFORE_EXPIRATION_TIME = 30000 // Will renew the quote if there's less than 30 seconds left for the quote to expire
const RENEW_VALIDTO_QUOTES_BEFORE_EXPIRATION_TIME = 1800000
const WAITING_TIME_BETWEEN_EQUAL_REQUESTS = 5000 // Prevents from sending the same request to often (max, every 5s)
const UNSUPPORTED_TOKEN_REFETCH_CHECK_INTERVAL = 10 * 60 * 1000 // if unsupported token was added > 10min ago, re-try

type FeeQuoteParams = Omit<FeeQuoteParamsFull, 'validTo'>

/**
* Returns if the quote has been recently checked
*/
Expand Down Expand Up @@ -115,22 +116,6 @@ function unsupportedTokenNeedsRecheck(
return shouldUpdate
}

export function getAdjustedValidTo(validTo: number, deadline: number) {
const now = Math.floor(Date.now() / 1000)
const validToAsDate = new Date(validTo * 1000).toISOString()
const validToAdjusted = isExpiringSoon(validToAsDate, RENEW_VALIDTO_QUOTES_BEFORE_EXPIRATION_TIME)
? now + deadline
: validTo
console.log(
'🚀 ~ file: updater.ts ~ line 120 ~ _getAdjustedValidTo ~ validToAdjusted',
validToAsDate,
validToAdjusted,
isExpiringSoon(validToAsDate, RENEW_VALIDTO_QUOTES_BEFORE_EXPIRATION_TIME)
)

return validToAdjusted
}

export default function FeesUpdater(): null {
const [lastUnsupportedCheck, setLastUnsupportedCheck] = useState<null | number>(null)
const { chainId, account } = useActiveWeb3React()
Expand Down Expand Up @@ -160,7 +145,7 @@ export default function FeesUpdater(): null {

const windowVisible = useIsWindowVisible()
const isOnline = useIsOnline()
const { validTo, deadline } = useOrderValidTo()
const { validTo } = useOrderValidTo()

// Update if any parameter is changing
useEffect(() => {
Expand Down Expand Up @@ -191,7 +176,7 @@ export default function FeesUpdater(): null {
amount: amount.quotient.toString(),
receiver,
userAddress: account,
validTo: getAdjustedValidTo(validTo, deadline),
validTo,
}

// Don't refetch if offline.
Expand Down Expand Up @@ -269,9 +254,8 @@ export default function FeesUpdater(): null {
setQuoteError,
account,
lastUnsupportedCheck,
validTo,
receiver,
deadline,
validTo,
])

return null
Expand Down

0 comments on commit 8b90b2b

Please sign in to comment.