import { FC , useEffect } from "react" ; import { Web3ReactProvider , useWeb3React } from "@web3-react/core" ; import { useSelector } from "react-redux" ; import { Web3Provider } from "@ethersproject/providers" ; import { useRouter } from "next/router" ; import { useAppDispatch } from "v2/store" ; import { updateBlockNumber } from "v2/store/connection" ; import { useEagerConnect , useInactiveListener , } from "v2/features/connection/hooks" ; import { injected } from "v2/features/connection/connectors" ; import { ConnectionSelectors } from "v2/store/connection" ; const getLibrary = ( provider ) => new Web3Provider ( provider ) ; const AppWeb3Provider = ( { children } ) => { const { active , error , activate , library } = useWeb3React < Web3Provider > ( ) ; const isManuallyDeactivated = useSelector ( ConnectionSelectors . selectIsManuallyDeactivated ) ; const router = useRouter ( ) ; const dispatch = useAppDispatch ( ) ; const triedEager = useEagerConnect ( ) ; useEffect ( ( ) => { if ( triedEager && ! error && ! active && ! isManuallyDeactivated ) { activate ( injected ) ; } } , [ triedEager , error , active ] ) ; useInactiveListener ( ! triedEager ) ; useEffect ( ( ) => { if ( library ) { const { ethereum } = window ; library . on ( "block" , ( blockNumber ) => dispatch ( updateBlockNumber ( blockNumber ) ) ) ; if ( ethereum ?. on ) { ethereum . on ( "chainChanged" , router . reload ) ; } return ( ) => { if ( ethereum ?. removeListener ) { ethereum . removeListener ( "chainChanged" , router . reload ) ; } library . removeAllListeners ( "block" ) ; } ; } } , [ library ] ) ; return < > { children } < />; } ; const Provider = ( { children } ) => ( < Web3ReactProvider getLibrary = { getLibrary } > < AppWeb3Provider > { children } < /AppWeb3Provider> < /Web3ReactProvider>); export default Provider ;