|
| 1 | +import { useCallback, useEffect, useRef } from 'react'; |
| 2 | +import { useAccountStore } from '@massalabs/react-ui-kit/src/lib/ConnectMassaWallets'; |
| 3 | +import { useLocalStorage } from '@massalabs/react-ui-kit/src/lib/util/hooks/useLocalStorage'; |
| 4 | +import { getWallets } from '@massalabs/wallet-provider'; |
| 5 | + |
| 6 | +type SavedAccount = { |
| 7 | + address: string; |
| 8 | + providerName: string; |
| 9 | +}; |
| 10 | + |
| 11 | +const EMPTY_ACCOUNT: SavedAccount = { |
| 12 | + address: '', |
| 13 | + providerName: '', |
| 14 | +}; |
| 15 | + |
| 16 | +const useAccountSync = () => { |
| 17 | + const initializedRef = useRef(false); |
| 18 | + const { connectedAccount, setCurrentWallet } = useAccountStore(); |
| 19 | + const [savedAccount, setSavedAccount] = useLocalStorage<SavedAccount>( |
| 20 | + 'saved-account', |
| 21 | + EMPTY_ACCOUNT, |
| 22 | + ); |
| 23 | + |
| 24 | + const findAccountInWallets = useCallback(async (address: string) => { |
| 25 | + const wallets = await getWallets(); |
| 26 | + for (const wallet of wallets) { |
| 27 | + const accounts = await wallet.accounts(); |
| 28 | + const matchingAccount = accounts.find((acc) => acc.address === address); |
| 29 | + if (matchingAccount) { |
| 30 | + return { account: matchingAccount, wallet }; |
| 31 | + } |
| 32 | + } |
| 33 | + return null; |
| 34 | + }, []); |
| 35 | + |
| 36 | + const restoreSavedAccount = useCallback(async () => { |
| 37 | + if (!savedAccount.address) return; |
| 38 | + |
| 39 | + const storedAccount = await findAccountInWallets(savedAccount.address); |
| 40 | + if (storedAccount) { |
| 41 | + const { wallet, account } = storedAccount; |
| 42 | + setCurrentWallet(wallet, account); |
| 43 | + } |
| 44 | + }, [savedAccount.address, findAccountInWallets, setCurrentWallet]); |
| 45 | + |
| 46 | + useEffect(() => { |
| 47 | + const isNewAccount = |
| 48 | + connectedAccount && connectedAccount.address !== savedAccount.address; |
| 49 | + |
| 50 | + if (isNewAccount) { |
| 51 | + const { address, providerName } = connectedAccount; |
| 52 | + setSavedAccount({ address, providerName }); |
| 53 | + } |
| 54 | + }, [connectedAccount, savedAccount.address, setSavedAccount]); |
| 55 | + |
| 56 | + useEffect(() => { |
| 57 | + if (!initializedRef.current) { |
| 58 | + initializedRef.current = true; |
| 59 | + restoreSavedAccount(); |
| 60 | + } |
| 61 | + }, [restoreSavedAccount]); |
| 62 | + |
| 63 | + return { setSavedAccount }; |
| 64 | +}; |
| 65 | + |
| 66 | +export default useAccountSync; |
0 commit comments