import JSBI from 'jsbi' ; import { useRef , useCallback , useEffect } from 'react' ; import { EthereumProvider } from '../types' ; import { pollEvery , getBlockNumber } from '../utils' ; export function useWatchBlockNumber ( { ethereum , pollBlockNumberInterval , } ) { const lastBlockNumber = useRef < number | null > ( null ) ; const blockNumberListeners = useRef < Set < ( blockNumber : number ) => void > > ( new Set ( ) ) ; const addBlockNumberListener = useCallback ( ( cb ) => { if ( blockNumberListeners . current . has ( cb ) ) { return ; } cb ( lastBlockNumber . current ) ; blockNumberListeners . current . add ( cb ) ; } , [ ] ) ; const removeBlockNumberListener = useCallback ( ( cb ) => { blockNumberListeners . current . delete ( cb ) ; } , [ ] ) ; const updateBlockNumber = useCallback ( ( blockNumber ) => { if ( lastBlockNumber . current === blockNumber ) { return ; } lastBlockNumber . current = blockNumber ; blockNumberListeners . current . forEach ( ( cb ) => cb ( blockNumber ) ) ; } , [ ] ) ; useEffect ( ( ) => { if ( ! ethereum ) { updateBlockNumber ( null ) ; return ; } let cancel = false ; const pollBlockNumber = pollEvery ( ( ) => { return { request : ( ) => getBlockNumber ( ethereum ) , onResult : ( latestBlockNumber ) => { if ( ! cancel ) { updateBlockNumber ( latestBlockNumber === null ? null : JSBI . BigInt ( latestBlockNumber ) . toString ( ) ) ; } } } ; } , pollBlockNumberInterval ) ; const stopPollingBlockNumber = pollBlockNumber ( ) ; return ( ) => { cancel = true ; stopPollingBlockNumber ( ) ; } ; } , [ ethereum , pollBlockNumberInterval , updateBlockNumber ] ) ; return { addBlockNumberListener , removeBlockNumberListener } ; }