Skip to content

Commit

Permalink
fix bug switch chain in wagmi on app open (#2554)
Browse files Browse the repository at this point in the history
* fix bug switch chain in wagmi on app open

* fix bug chain does not sync if wallet is not connected
  • Loading branch information
tienkane authored Oct 29, 2024
1 parent cf21c13 commit e6323d5
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions src/hooks/web3/useSyncNetworkParamWithStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom'

import { NETWORKS_INFO } from 'constants/networks'
import { useActiveWeb3React } from 'hooks'
import { useAccount } from 'hooks/useAccount'
import { getChainIdFromSlug } from 'utils/string'

import { useChangeNetwork } from './useChangeNetwork'
Expand All @@ -16,30 +17,46 @@ export function useSyncNetworkParamWithStore() {
const location = useLocation()
const [requestingNetwork, setRequestingNetwork] = useState<string>()
const triedSync = useRef(false)
const chainIdKeeper = useRef<number>(0)
const networkParamKeeper = useRef<string>('')
const { connector, isConnected } = useAccount()

useEffect(() => {
if (!networkParam || !paramChainId || isWrongNetwork) {
triedSync.current = true
return
}
if (!chainIdKeeper.current) chainIdKeeper.current = paramChainId
if (!networkParamKeeper.current)
networkParamKeeper.current = networkParam

/**
* Try to change to network on route param on init. Exp: /swap/ethereum => try to connect to ethereum on init
* @param isOnInit.current: make sure only run 1 time after init
* @param triedEager: only run after tried to connect injected wallet
*/
/**
* Try to change to network on route param on init. Exp: /swap/ethereum => try to connect to ethereum on init
* @param isOnInit.current: make sure only run 1 time after init
* @param triedEager: only run after tried to connect injected wallet
*/
;(async () => {
if (triedSync.current) return
setRequestingNetwork(networkParam)
await changeNetwork(paramChainId, undefined, () => {
if (triedSync.current || (isConnected && !connector?.switchChain)) return
setRequestingNetwork(networkParamKeeper.current)
await changeNetwork(chainIdKeeper.current, undefined, () => {
navigate(
{ ...location, pathname: location.pathname.replace(networkParam, networkInfo.route) },
{ ...location, pathname: location.pathname.replace(networkParamKeeper.current, networkInfo.route) },
{ replace: true },
)
})
triedSync.current = true
})()
}, [changeNetwork, location, navigate, networkInfo.route, networkParam, paramChainId, isWrongNetwork])
}, [
changeNetwork,
location,
navigate,
networkInfo.route,
networkParam,
paramChainId,
isWrongNetwork,
connector?.switchChain,
isConnected,
])

useEffect(() => {
if (NETWORKS_INFO[chainId].route === requestingNetwork) setRequestingNetwork(undefined)
Expand Down

0 comments on commit e6323d5

Please sign in to comment.