import { Web3Provider } from '@ethersproject/providers' ; import { NetworkContext } from 'contexts/networkContext' ; import { ChildElems } from 'models/child-elems' ; import { NetworkName } from 'models/network-name' ; import { useCallback , useContext , useEffect , useState } from 'react' ; import { initOnboard } from 'utils/onboard' ; import { API , Subscriptions , Wallet } from 'bnc-onboard/dist/src/interfaces' ; import { ThemeContext } from 'contexts/themeContext' ; import { readNetwork } from 'constants/networks' ; import { NETWORKS } from 'constants/networks' ; const KEY_SELECTED_WALLET = 'selectedWallet' ; export default function NetworkProvider ( { children , } ) { const { isDarkMode } = useContext ( ThemeContext ) ; const [ signingProvider , setSigningProvider ] = useState < Web3Provider > ( ) ; const [ network , setNetwork ] = useState < NetworkName > ( ) ; const [ account , setAccount ] = useState < string > ( ) ; const [ onboard , setOnboard ] = useState < API > ( ) ; const resetWallet = useCallback ( ( ) => { onboard ?. walletReset ( ) ; setSigningProvider ( undefined ) ; window . localStorage . setItem ( KEY_SELECTED_WALLET , '' ) ; } , [ onboard ] ) ; const selectWallet = async ( ) => { resetWallet ( ) ; const selectedWallet = await onboard ?. walletSelect ( ) ; if ( ! selectedWallet ) { return ; } await onboard ?. walletCheck ( ) ; } ; const logOut = async ( ) => { resetWallet ( ) ; } ; useEffect ( ( ) => { if ( onboard ) return ; const selectWallet = async ( newWallet ) => { if ( newWallet . provider ) { setAccount ( undefined ) ; window . localStorage . setItem ( KEY_SELECTED_WALLET , newWallet . name || '' ) ; setSigningProvider ( new Web3Provider ( newWallet . provider ) ) ; } else { resetWallet ( ) ; } } ; const config = { address : setAccount , wallet : selectWallet , } ; setOnboard ( initOnboard ( config , isDarkMode ) ) ; } , [ isDarkMode , onboard , resetWallet ] ) ; useEffect ( ( ) => { if ( onboard ) { onboard . config ( { darkMode : isDarkMode } ) ; } } , [ isDarkMode , onboard ] ) ; useEffect ( ( ) => { async function getNetwork ( ) { await signingProvider ?. ready ; const network = signingProvider ?. network ?. chainId ? NETWORKS [ signingProvider . network . chainId ] : undefined ; setNetwork ( network ?. name ) ; } getNetwork ( ) ; } , [ signingProvider ] ) ; useEffect ( ( ) => { const previouslySelectedWallet = window . localStorage . getItem ( KEY_SELECTED_WALLET ) ; if ( previouslySelectedWallet && onboard ) { onboard . walletSelect ( previouslySelectedWallet ) ; } } , [ onboard ] ) ; return ( < NetworkContext . Provider value = { { signerNetwork : network , signingProvider : signingProvider && network === readNetwork . name && account ? signingProvider : undefined , userAddress : account , onSelectWallet : selectWallet , onLogOut : logOut , } } > { children } < /NetworkContext.Provider>); }