diff --git a/src/logic/wallets/store/middlewares/providerWatcher.js b/src/logic/wallets/store/middlewares/providerWatcher.js index 1990ad5c..dbb04a98 100644 --- a/src/logic/wallets/store/middlewares/providerWatcher.js +++ b/src/logic/wallets/store/middlewares/providerWatcher.js @@ -2,19 +2,42 @@ import type { Store, AnyAction } from 'redux' import { type GlobalState } from '~/store/' import { ADD_PROVIDER, REMOVE_PROVIDER } from '../actions' +import { getWeb3, getProviderInfo } from '~/logic/wallets/getWeb3' +import { fetchProvider } from '~/logic/wallets/store/actions' -const watchedActions = [ - ADD_PROVIDER, - REMOVE_PROVIDER, -] +const watchedActions = [ADD_PROVIDER, REMOVE_PROVIDER] + +let watcherInterval = null const providerWatcherMware = (store: Store) => (next: Function) => async (action: AnyAction) => { const handledAction = next(action) if (watchedActions.includes(action.type)) { - const state: GlobalState = store.getState() - switch (action.type) { + case ADD_PROVIDER: { + const currentProviderProps = action.payload.toJS() + + if (watcherInterval) { + clearInterval(watcherInterval) + } + + watcherInterval = setInterval(async () => { + const web3 = getWeb3() + const providerInfo = await getProviderInfo(web3) + + if ( + currentProviderProps.account !== providerInfo.account + || currentProviderProps.network !== providerInfo.network + ) { + store.dispatch(fetchProvider(web3, () => {}, () => {})) + } + }, 2000) + + break + } + case REMOVE_PROVIDER: + clearInterval(watcherInterval) + break default: break } diff --git a/src/store/index.js b/src/store/index.js index d40f5b96..b2dae643 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -7,6 +7,7 @@ import { import thunk from 'redux-thunk' import safe, { SAFE_REDUCER_ID, type SafeReducerState as SafeState } from '~/routes/safe/store/reducer/safe' import safeStorage from '~/routes/safe/store/middleware/safeStorage' +import providerWatcher from '~/logic/wallets/store/middlewares/providerWatcher' import transactions, { type State as TransactionsState, TRANSACTIONS_REDUCER_ID, @@ -22,7 +23,9 @@ export const history = createBrowserHistory() // eslint-disable-next-line const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose -const finalCreateStore = composeEnhancers(applyMiddleware(thunk, routerMiddleware(history), safeStorage)) +const finalCreateStore = composeEnhancers( + applyMiddleware(thunk, routerMiddleware(history), safeStorage, providerWatcher), +) export type GlobalState = { providers: ProviderState, @@ -45,8 +48,4 @@ const reducers: Reducer = combineReducers({ export const store: Store = createStore(reducers, finalCreateStore) -export const aNewStore = (localState?: Object): Store => createStore( - reducers, - localState, - finalCreateStore, -) +export const aNewStore = (localState?: Object): Store => createStore(reducers, localState, finalCreateStore)