Skip to content

Commit 1f811b1

Browse files
committed
Add useAccountSync hook
1 parent df92e64 commit 1f811b1

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

frontend/src/App.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ import { Card } from './components/Card';
22
import { FAQ } from './components/FAQ';
33
import { ConnectMassaWallet, Button, Toast } from '@massalabs/react-ui-kit';
44
import { MNSManagement } from './components/MnsManagement';
5+
import useAccountSync from './hooks/useAccountSync';
56

67
function App() {
8+
useAccountSync();
9+
710
return (
811
<>
912
<Toast />

frontend/src/hooks/useAccountSync.tsx

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)