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

Commit

Permalink
create validTo adjuster. return more from useOrderValidTo
Browse files Browse the repository at this point in the history
  • Loading branch information
W3stside committed Dec 9, 2021
1 parent 0041ee6 commit cab6a8c
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 11 deletions.
7 changes: 4 additions & 3 deletions src/custom/hooks/usePriceImpact/useFallbackPriceImpact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ 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'

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

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

// Should we even calc this? Check if fiatPriceImpact exists OR user is wrapping token
const shouldCalculate = !Boolean(fiatPriceImpact) || !isWrapping
Expand All @@ -55,10 +56,10 @@ export default function useFallbackPriceImpact({ abTrade, fiatPriceImpact, isWra
const { parsedAmount, outputCurrency, ...swapQuoteParams } = useMemo(
() => ({
parsedAmount: _getBaTradeParsedAmount(abTrade, shouldCalculate),
validTo,
validTo: getAdjustedValidTo(validTo, deadline),
..._getBaTradeParams({ abTrade, sellToken, buyToken }),
}),
[abTrade, buyToken, sellToken, shouldCalculate, validTo]
[abTrade, buyToken, deadline, sellToken, shouldCalculate, validTo]
)

const { quote, loading } = useCalculateQuote({
Expand Down
2 changes: 1 addition & 1 deletion src/custom/hooks/useUSDCPrice/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function useUSDCPrice(currency?: Currency) {
const [error, setError] = useState<Error | null>(null)

const { chainId, account } = useActiveWeb3React()
const validTo = useOrderValidTo()
const { validTo } = useOrderValidTo()
const blockNumber = useBlockNumber()

const amountOut = chainId ? STABLECOIN_AMOUNT_OUT[chainId] : undefined
Expand Down
29 changes: 24 additions & 5 deletions src/custom/state/price/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ 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

Expand All @@ -36,9 +37,9 @@ function wasQuoteCheckedRecently(lastQuoteCheck: number): boolean {
/**
* Returns true if the fee quote expires soon (in less than RENEW_FEE_QUOTES_BEFORE_EXPIRATION_TIME milliseconds)
*/
function isFeeExpiringSoon(quoteExpirationIsoDate: string): boolean {
function isExpiringSoon(quoteExpirationIsoDate: string, threshold: number): boolean {
const feeExpirationDate = Date.parse(quoteExpirationIsoDate)
const needRefetch = feeExpirationDate <= Date.now() + RENEW_FEE_QUOTES_BEFORE_EXPIRATION_TIME
const needRefetch = feeExpirationDate <= Date.now() + threshold

// const secondsLeft = (feeExpirationDate.valueOf() - Date.now()) / 1000
// console.log(`[state:price:updater] Fee isExpiring in ${secondsLeft}. Refetch?`, needRefetch)
Expand Down Expand Up @@ -96,7 +97,7 @@ function isRefetchQuoteRequired(
return false
} else if (quoteInformation.fee) {
// Re-fetch if the fee is expiring soon
return isFeeExpiringSoon(quoteInformation.fee.expirationDate)
return isExpiringSoon(quoteInformation.fee.expirationDate, RENEW_FEE_QUOTES_BEFORE_EXPIRATION_TIME)
}

return false
Expand All @@ -114,6 +115,22 @@ 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 @@ -143,7 +160,7 @@ export default function FeesUpdater(): null {

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

// Update if any parameter is changing
useEffect(() => {
Expand All @@ -163,6 +180,7 @@ export default function FeesUpdater(): null {

const fromDecimals = sellCurrency?.decimals ?? DEFAULT_DECIMALS
const toDecimals = buyCurrency?.decimals ?? DEFAULT_DECIMALS

const quoteParams = {
chainId,
sellToken,
Expand All @@ -173,7 +191,7 @@ export default function FeesUpdater(): null {
amount: amount.quotient.toString(),
receiver,
userAddress: account,
validTo,
validTo: getAdjustedValidTo(validTo, deadline),
}

// Don't refetch if offline.
Expand Down Expand Up @@ -253,6 +271,7 @@ export default function FeesUpdater(): null {
lastUnsupportedCheck,
validTo,
receiver,
deadline,
])

return null
Expand Down
4 changes: 2 additions & 2 deletions src/custom/state/user/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function useURLWarningToggle(): () => void {
return useCallback(() => dispatch(toggleURLWarning()), [dispatch])
}

export function useOrderValidTo(): number {
export function useOrderValidTo() {
const [deadline] = useUserTransactionTTL()
return useMemo(() => calculateValidTo(deadline), [deadline])
return useMemo(() => ({ validTo: calculateValidTo(deadline), deadline }), [deadline])
}

0 comments on commit cab6a8c

Please sign in to comment.