Skip to content

Commit

Permalink
feat(synapse-interface): refresh stale quotes (#2607)
Browse files Browse the repository at this point in the history
* Track BridgeQuote by initiated timestamp

* useStaleQuoteRefresher to manage refreshing stale bridge quotes

* Prevent stack overflow when invalid quote

* Prevent quote refetch is one is already loading

* Fix build

* Prevent b2b callbacks if time difference is too great

* Pause formatAmount error logging, only retrigger useEffect for stale quote refresher when currentTime changes

* Wrap refresh quote callback with mousedown event to reduce resource usage for idle pages

* Clean

* Prevent refresh quote if browser wallet prompts are open as async callback has already initiated

* Listen to stale timeout value
  • Loading branch information
bigboydiamonds authored Jun 17, 2024
1 parent bc813b7 commit c0de3ca
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 4 deletions.
2 changes: 2 additions & 0 deletions packages/synapse-interface/constants/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const EMPTY_BRIDGE_QUOTE = {
estimatedTime: null,
bridgeModuleName: null,
gasDropAmount: 0n,
timestamp: null,
}

export const EMPTY_BRIDGE_QUOTE_ZERO = {
Expand All @@ -31,6 +32,7 @@ export const EMPTY_BRIDGE_QUOTE_ZERO = {
estimatedTime: null,
bridgeModuleName: null,
gasDropAmount: 0n,
timestamp: null,
}
/**
* ETH Only Bridge Config used to calculate swap fees
Expand Down
19 changes: 16 additions & 3 deletions packages/synapse-interface/pages/state-managed-bridge/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
getPublicClient,
waitForTransactionReceipt,
} from '@wagmi/core'

import { InputContainer } from '@/components/StateManagedBridge/InputContainer'
import { OutputContainer } from '@/components/StateManagedBridge/OutputContainer'
import { BridgeExchangeRateInfo } from '@/components/StateManagedBridge/BridgeExchangeRateInfo'
Expand Down Expand Up @@ -54,7 +53,6 @@ import { Token } from '@/utils/types'
import { txErrorHandler } from '@/utils/txErrorHandler'
import { approveToken } from '@/utils/approveToken'
import { stringToBigInt } from '@/utils/bigint/format'

import { fetchAndStoreSingleNetworkPortfolioBalances } from '@/slices/portfolio/hooks'
import {
updatePendingBridgeTransaction,
Expand All @@ -74,6 +72,7 @@ import {
getBridgeModuleNames,
} from '@/components/Maintenance/Maintenance'
import { wagmiConfig } from '@/wagmiConfig'
import { useStaleQuoteRefresher } from '@/utils/hooks/useStaleQuoteRefresher'

const StateManagedBridge = () => {
const { address } = useAccount()
Expand All @@ -93,12 +92,14 @@ const StateManagedBridge = () => {
bridgeQuote,
debouncedFromValue,
destinationAddress,
isLoading: isQuoteLoading,
}: BridgeState = useBridgeState()
const { showSettingsSlideOver, showDestinationAddress } = useSelector(
(state: RootState) => state.bridgeDisplay
)

const [isApproved, setIsApproved] = useState(false)
const [isWalletPending, setIsWalletPending] = useState<boolean>(false)
const [isApproved, setIsApproved] = useState<boolean>(false)

const dispatch = useAppDispatch()

Expand Down Expand Up @@ -153,6 +154,7 @@ const StateManagedBridge = () => {

try {
dispatch(setIsLoading(true))
const currentTimestamp: number = getTimeMinutesFromNow(0)

const allQuotes = await synapseSDK.allBridgeQuotes(
fromChainId,
Expand Down Expand Up @@ -273,6 +275,7 @@ const StateManagedBridge = () => {
estimatedTime: estimatedTime,
bridgeModuleName: bridgeModuleName,
gasDropAmount: BigInt(gasDropAmount.toString()),
timestamp: currentTimestamp,
})
)

Expand Down Expand Up @@ -314,6 +317,13 @@ const StateManagedBridge = () => {
}
}

useStaleQuoteRefresher(
bridgeQuote,
getAndSetBridgeQuote,
isQuoteLoading,
isWalletPending
)

const approveTxn = async () => {
try {
const tx = approveToken(
Expand Down Expand Up @@ -366,6 +376,7 @@ const StateManagedBridge = () => {
})
)
try {
setIsWalletPending(true)
const wallet = await getWalletClient(wagmiConfig, {
chainId: fromChainId,
})
Expand Down Expand Up @@ -507,6 +518,8 @@ const StateManagedBridge = () => {
}

return txErrorHandler(error)
} finally {
setIsWalletPending(false)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BridgeQuote, Token } from '@/utils/types'
import { formatBigIntToString } from '../bigint/format'
import { commify } from '@ethersproject/units'
import { calculateExchangeRate } from '../calculateExchangeRate'
import { getTimeMinutesFromNow } from '../time'

export interface BridgeQuoteResponse extends BridgeQuote {
destinationToken: Token
Expand All @@ -23,6 +24,7 @@ export async function fetchBridgeQuote(
synapseSDK: any
): Promise<BridgeQuoteResponse> {
if (request && synapseSDK) {
const currentTimestamp: number = getTimeMinutesFromNow(0)
try {
const {
originChainId,
Expand Down Expand Up @@ -93,6 +95,7 @@ export async function fetchBridgeQuote(
estimatedTime: estimatedTime,
bridgeModuleName: bridgeModuleName,
gasDropAmount: BigInt(gasDropAmount.toString()),
timestamp: currentTimestamp,
}
} catch (error) {
console.error('Error fetching bridge quote:', error)
Expand Down
2 changes: 1 addition & 1 deletion packages/synapse-interface/utils/formatAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const formatAmount = (
throw new TypeError(`"${amount}" is not a finite number`)
}
} catch ({ name, message }) {
console.error(name, message)
// console.error(name, message)
return amount
}

Expand Down
34 changes: 34 additions & 0 deletions packages/synapse-interface/utils/hooks/useStaleQuoteRefresher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { isNull, isNumber } from 'lodash'
import { useEffect } from 'react'

import { BridgeQuote } from '@/utils/types'
import { calculateTimeBetween } from '@/utils/time'
import { useIntervalTimer } from '@/utils/hooks/useIntervalTimer'

/**
* Refreshes quotes based on selected stale timeout duration.
* Will refresh quote when browser is active and wallet prompt is not pending.
*/
export const useStaleQuoteRefresher = (
quote: BridgeQuote,
refreshQuoteCallback: () => Promise<void>,
isQuoteLoading: boolean,
isWalletPending: boolean,
staleTimeout: number = 15000 // 15_000ms or 15s
) => {
const quoteTime = quote?.timestamp
const isValidQuote = isNumber(quoteTime) && !isNull(quoteTime)
const currentTime = useIntervalTimer(staleTimeout, !isValidQuote)

useEffect(() => {
if (isValidQuote && !isQuoteLoading && !isWalletPending) {
const timeDifference = calculateTimeBetween(currentTime, quoteTime)
const isStaleQuote = timeDifference >= staleTimeout
if (isStaleQuote) {
document.addEventListener('mousemove', refreshQuoteCallback, {
once: true,
})
}
}
}, [currentTime, staleTimeout])
}
7 changes: 7 additions & 0 deletions packages/synapse-interface/utils/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ export const getTimeMinutesBeforeNow = (minutesBeforeNow) => {
return Math.round(currentTimeSeconds - 60 * minutesBeforeNow)
}

export const calculateTimeBetween = (
timeBefore: number,
timeAfter: number
): number => {
return Math.abs(timeBefore - timeAfter) * 1000
}

export const formatDate = (date) => {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric',
Expand Down
1 change: 1 addition & 0 deletions packages/synapse-interface/utils/types/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export type BridgeQuote = {
estimatedTime: number
bridgeModuleName: string
gasDropAmount: bigint
timestamp: number
}

interface TokensByChain {
Expand Down

0 comments on commit c0de3ca

Please sign in to comment.