useGetFinalityTime.tsx
1 import { useQuery } from '@tanstack/react-query'; 2 import dayjs from 'dayjs'; 3 import relativeTime from 'dayjs/plugin/relativeTime'; 4 import { getProvider } from 'src/utils/marketsAndNetworksConfig'; 5 6 dayjs.extend(relativeTime); 7 8 // Used in case there's an error fetching the latest finalized block, it should give a close estimate for Arb or Eth source chains 9 const DEFAULT_FINALITY_TIME = 1080; // 18 minutes 10 11 export const useTimeToDestination = (sourceChainId: number) => { 12 return useQuery({ 13 queryFn: async () => { 14 const provider = getProvider(sourceChainId); 15 try { 16 const block = await provider.send('eth_getBlockByNumber', ['finalized', false]); 17 const timestamp = parseInt(block.timestamp, 16); 18 const now = dayjs().unix(); 19 const estimatedTimeToDestination = dayjs.unix(now + (now - timestamp) + 120).fromNow(); 20 return estimatedTimeToDestination; 21 } catch (error) { 22 console.error('Error fetching finality time', error); 23 return dayjs.unix(dayjs().unix() + DEFAULT_FINALITY_TIME).fromNow(); 24 } 25 }, 26 queryKey: ['getFinalityTime', sourceChainId], 27 staleTime: 0, 28 }); 29 };