Skip to content

Commit

Permalink
Add network management to account store and update state handling (#491)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben-Rey authored Oct 14, 2024
1 parent 8eefe89 commit 369b75b
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions src/lib/ConnectMassaWallets/store/accountStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@ export interface AccountStoreState {
unsubscribe: () => void;
};
chainId?: bigint;
network?: string;

setCurrentWallet: (wallet?: Wallet) => void;
setWallets: (wallets: Wallet[]) => void;

setConnectedAccount: (account?: Provider) => void;
setCurrentNetwork: () => void;
}

export const useAccountStore = create<AccountStoreState>((set, get) => ({
Expand All @@ -50,6 +52,7 @@ export const useAccountStore = create<AccountStoreState>((set, get) => ({
wallets: [],
isFetching: false,
chainId: undefined,
network: undefined,

setCurrentWallet: (currentWallet?: Wallet) => {
try {
Expand All @@ -73,9 +76,7 @@ export const useAccountStore = create<AccountStoreState>((set, get) => ({

if (!get().networkObserver) {
const networkObserver = currentWallet.listenNetworkChanges(async () => {
set({
chainId: await currentWallet.networkInfos().then((n) => n.chainId),
});
get().setCurrentNetwork();
});
set({ networkObserver });
}
Expand All @@ -84,21 +85,13 @@ export const useAccountStore = create<AccountStoreState>((set, get) => ({
currentWallet
.connect()
.then(() => {
// get current network
currentWallet
.networkInfos()
.then((infos) => {
set({ chainId: infos.chainId });
})
.catch((error) => {
console.warn('error getting network from bearby', error);
});
// subscribe to network events
const observer = currentWallet.listenAccountChanges(
(newAddress: string) => {
handleBearbyAccountChange(newAddress, get());
},
);

set({ currentWallet, accountObserver: observer });

// get connected account
Expand All @@ -121,6 +114,8 @@ export const useAccountStore = create<AccountStoreState>((set, get) => ({

set({ currentWallet });

get().setCurrentNetwork();

currentWallet
.accounts()
.then((accounts) => {
Expand Down Expand Up @@ -154,4 +149,12 @@ export const useAccountStore = create<AccountStoreState>((set, get) => ({
setConnectedAccount: async (connectedAccount?: Provider) => {
set({ connectedAccount });
},

setCurrentNetwork: () => {
get()
.currentWallet?.networkInfos()
.then((infos) => {
set({ chainId: infos.chainId, network: infos.name });
});
},
}));

0 comments on commit 369b75b

Please sign in to comment.