diff --git a/src/contexts/ActiveAccounts/index.tsx b/src/contexts/ActiveAccounts/index.tsx index 120116d9d1..29059a9dbf 100644 --- a/src/contexts/ActiveAccounts/index.tsx +++ b/src/contexts/ActiveAccounts/index.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only import type { ReactNode } from 'react'; -import { createContext, useContext, useEffect, useRef, useState } from 'react'; +import { createContext, useContext, useRef, useState } from 'react'; import type { MaybeAddress } from 'types'; import { setStateWithRef } from '@w3ux/utils'; import { useNetwork } from 'contexts/Network'; @@ -63,12 +63,6 @@ export const ActiveAccountsProvider = ({ // Getter for the active account. const getActiveAccount = () => activeAccountRef.current; - // Disconnect from the active account on network change, but don't remove local record. - useEffect(() => { - setActiveAccount(null, false); - setActiveProxy(null, false); - }, [network]); - return ( ( @@ -32,10 +34,12 @@ export const ImportedAccountsProvider = ({ }) => { const { isReady, api } = useApi(); const { + network, networkData: { ss58 }, } = useNetwork(); const { otherAccounts } = useOtherAccounts(); const { getExtensionAccounts } = useExtensionAccounts(); + const { setActiveAccount, setActiveProxy } = useActiveAccounts(); // Get the imported extension accounts formatted with the current network's ss58 prefix. const extensionAccounts = getExtensionAccounts(ss58); @@ -120,6 +124,24 @@ export const ImportedAccountsProvider = ({ } }, [isReady, allAccountsStringified]); + // Re-sync the active account and active proxy on network change. + useEffectIgnoreInitial(() => { + const localActiveAccount = getActiveAccountLocal(network, ss58); + + if (getAccount(localActiveAccount) !== null) { + setActiveAccount(getActiveAccountLocal(network, ss58), false); + } else { + setActiveAccount(null, false); + } + + const localActiveProxy = getActiveProxyLocal(network, ss58); + if (getAccount(localActiveProxy?.address || null)) { + setActiveProxy(getActiveProxyLocal(network, ss58), false); + } else { + setActiveProxy(null, false); + } + }, [network]); + return ( { } return account; }; + +// Gets local `activeProxy` for a network. +export const getActiveProxyLocal = (network: NetworkName, ss58: number) => { + const keyring = new Keyring(); + keyring.setSS58Format(ss58); + const localActiveProxy = localStorageOrDefault( + `${network}_active_proxy`, + null + ) as ActiveProxy | null; + + if (localActiveProxy !== null && localActiveProxy?.address) { + localActiveProxy.address = keyring.addFromAddress( + localActiveProxy.address + ).address; + } + + return localActiveProxy; +};