Fix #381: notification shown after loading safe (#402)

* Prevent notifications from showing after loading safe

* Make a safe-based sessionStorage control

* Show notifications for new Safes and prevent displaying oldest incoming tx for newly loaded Safe

* Create `currentSession` state

* Add `currentSession` to the Store

* Initialize `currentSession`

* Use `currentSession` to handle notifications for incoming Transactions

* Remove `updateUserStatus`

* Move the load of the current session from storage to app startup

* Fix duplicated reducer id

* Adapt notificationsMiddleware
This commit is contained in:
Fernando 2020-01-16 14:28:28 -03:00 committed by Germán Martínez
parent 36166cd86d
commit f64ebf99a1
14 changed files with 138 additions and 36 deletions

View File

@ -7,8 +7,8 @@ import Root from '~/components/Root'
import loadActiveTokens from '~/logic/tokens/store/actions/loadActiveTokens' import loadActiveTokens from '~/logic/tokens/store/actions/loadActiveTokens'
import loadDefaultSafe from '~/routes/safe/store/actions/loadDefaultSafe' import loadDefaultSafe from '~/routes/safe/store/actions/loadDefaultSafe'
import loadSafesFromStorage from '~/routes/safe/store/actions/loadSafesFromStorage' import loadSafesFromStorage from '~/routes/safe/store/actions/loadSafesFromStorage'
import loadCurrentSessionFromStorage from '~/logic/currentSession/store/actions/loadCurrentSessionFromStorage'
import { store } from '~/store' import { store } from '~/store'
import verifyRecurringUser from '~/utils/verifyRecurringUser'
BigNumber.set({ EXPONENTIAL_AT: [-7, 255] }) BigNumber.set({ EXPONENTIAL_AT: [-7, 255] })
@ -20,9 +20,12 @@ if (process.env.NODE_ENV !== 'production') {
// $FlowFixMe // $FlowFixMe
store.dispatch(loadActiveTokens()) store.dispatch(loadActiveTokens())
// $FlowFixMe
store.dispatch(loadSafesFromStorage()) store.dispatch(loadSafesFromStorage())
// $FlowFixMe
store.dispatch(loadDefaultSafe()) store.dispatch(loadDefaultSafe())
verifyRecurringUser() // $FlowFixMe
store.dispatch(loadCurrentSessionFromStorage())
const root = document.getElementById('root') const root = document.getElementById('root')

View File

@ -0,0 +1,10 @@
// @flow
import { type Dispatch as ReduxDispatch } from 'redux'
import { type GlobalState } from '~/store'
import updateViewedSafes from '~/logic/currentSession/store/actions/updateViewedSafes'
const addViewedSafe = (safeAddress: string) => (dispatch: ReduxDispatch<GlobalState>) => {
dispatch(updateViewedSafes(safeAddress))
}
export default addViewedSafe

View File

@ -0,0 +1,8 @@
// @flow
import { createAction } from 'redux-actions'
export const LOAD_CURRENT_SESSION = 'LOAD_CURRENT_SESSION'
const loadCurrentSession = createAction<string, *>(LOAD_CURRENT_SESSION)
export default loadCurrentSession

View File

@ -0,0 +1,14 @@
// @flow
import { type Dispatch as ReduxDispatch } from 'redux'
import { type GlobalState } from '~/store'
import { getCurrentSessionFromStorage } from '~/logic/currentSession/utils'
import loadCurrentSession from '~/logic/currentSession/store/actions/loadCurrentSession'
import { makeCurrentSession } from '~/logic/currentSession/store/model/currentSession'
const loadCurrentSessionFromStorage = () => async (dispatch: ReduxDispatch<GlobalState>) => {
const currentSession = (await getCurrentSessionFromStorage())
dispatch(loadCurrentSession(makeCurrentSession(currentSession ? currentSession : {})))
}
export default loadCurrentSessionFromStorage

View File

@ -0,0 +1,8 @@
// @flow
import { createAction } from 'redux-actions'
export const UPDATE_VIEWED_SAFES = 'UPDATE_VIEWED_SAFES'
const updateViewedSafes = createAction<string, *>(UPDATE_VIEWED_SAFES)
export default updateViewedSafes

View File

@ -0,0 +1,14 @@
// @flow
import {
Record, type RecordFactory, type RecordOf,
} from 'immutable'
export type CurrentSessionProps = {
viewedSafes: Array<string>,
}
export const makeCurrentSession: RecordFactory<CurrentSessionProps> = Record({
viewedSafes: [],
})
export type CurrentSession = RecordOf<CurrentSessionProps>

View File

@ -0,0 +1,32 @@
// @flow
import { Map } from 'immutable'
import { handleActions, type ActionType } from 'redux-actions'
import { LOAD_CURRENT_SESSION } from '~/logic/currentSession/store/actions/loadCurrentSession'
import { UPDATE_VIEWED_SAFES } from '~/logic/currentSession/store/actions/updateViewedSafes'
import { saveCurrentSessionToStorage } from '~/logic/currentSession/utils'
export const CURRENT_SESSION_REDUCER_ID = 'currentSession'
export type State = Map<string, *>
export default handleActions<State, *>(
{
[LOAD_CURRENT_SESSION]: (
state: State,
action: ActionType<Function>,
): State => state.merge(Map(action.payload)),
[UPDATE_VIEWED_SAFES]: (state: State, action: ActionType<Function>): State => {
const safeAddress = action.payload
const newState = state.updateIn(
['viewedSafes'],
(prev) => (prev.includes(safeAddress) ? prev : [...prev, safeAddress]),
)
saveCurrentSessionToStorage(newState)
return newState
},
},
Map(),
)

View File

@ -0,0 +1,15 @@
// @flow
import type { CurrentSession, CurrentSessionProps } from '~/logic/currentSession/store/model/currentSession'
import { loadFromStorage, saveToStorage } from '~/utils/storage'
const CURRENT_SESSION_STORAGE_KEY = 'CURRENT_SESSION'
export const getCurrentSessionFromStorage = async (): Promise<CurrentSessionProps | *> => loadFromStorage(CURRENT_SESSION_STORAGE_KEY)
export const saveCurrentSessionToStorage = async (currentSession: CurrentSession): Promise<*> => {
try {
await saveToStorage(CURRENT_SESSION_STORAGE_KEY, currentSession.toJSON())
} catch (err) {
console.error('Error storing currentSession in localStorage', err)
}
}

View File

@ -11,6 +11,7 @@ import fetchCurrencyValues from '~/logic/currencyValues/store/actions/fetchCurre
import activateTokensByBalance from '~/logic/tokens/store/actions/activateTokensByBalance' import activateTokensByBalance from '~/logic/tokens/store/actions/activateTokensByBalance'
import loadAddressBookFromStorage from '~/logic/addressBook/store/actions/loadAddressBookFromStorage' import loadAddressBookFromStorage from '~/logic/addressBook/store/actions/loadAddressBookFromStorage'
import { updateAddressBookEntry } from '~/logic/addressBook/store/actions/updateAddressBookEntry' import { updateAddressBookEntry } from '~/logic/addressBook/store/actions/updateAddressBookEntry'
import addViewedSafe from '~/logic/currentSession/store/actions/addViewedSafe'
export type Actions = { export type Actions = {
fetchSafe: typeof fetchSafe, fetchSafe: typeof fetchSafe,
@ -26,6 +27,7 @@ export type Actions = {
fetchCurrencyValues: typeof fetchCurrencyValues, fetchCurrencyValues: typeof fetchCurrencyValues,
loadAddressBook: typeof loadAddressBookFromStorage, loadAddressBook: typeof loadAddressBookFromStorage,
updateAddressBookEntry: typeof updateAddressBookEntry, updateAddressBookEntry: typeof updateAddressBookEntry,
addViewedSafe: typeof addViewedSafe,
} }
export default { export default {
@ -42,4 +44,5 @@ export default {
checkAndUpdateSafeOwners: checkAndUpdateSafe, checkAndUpdateSafeOwners: checkAndUpdateSafe,
loadAddressBook: loadAddressBookFromStorage, loadAddressBook: loadAddressBookFromStorage,
updateAddressBookEntry, updateAddressBookEntry,
addViewedSafe,
} }

View File

@ -34,12 +34,22 @@ class SafeView extends React.Component<Props, State> {
componentDidMount() { componentDidMount() {
const { const {
fetchSafe, activeTokens, safeUrl, fetchTokenBalances, fetchTokens, fetchTransactions, fetchCurrencyValues, loadAddressBook, fetchSafe,
activeTokens,
safeUrl,
fetchTokenBalances,
fetchTokens,
fetchTransactions,
fetchCurrencyValues,
loadAddressBook,
addViewedSafe,
} = this.props } = this.props
fetchSafe(safeUrl).then(() => { fetchSafe(safeUrl)
.then(() => {
// The safe needs to be loaded before fetching the transactions // The safe needs to be loaded before fetching the transactions
fetchTransactions(safeUrl) fetchTransactions(safeUrl)
addViewedSafe(safeUrl)
}) })
fetchTokenBalances(safeUrl, activeTokens) fetchTokenBalances(safeUrl, activeTokens)
// fetch tokens there to get symbols for tokens in TXs list // fetch tokens there to get symbols for tokens in TXs list

View File

@ -12,9 +12,6 @@ import { enhanceSnackbarForAction, NOTIFICATIONS } from '~/logic/notifications'
import closeSnackbarAction from '~/logic/notifications/store/actions/closeSnackbar' import closeSnackbarAction from '~/logic/notifications/store/actions/closeSnackbar'
import { getIncomingTxAmount } from '~/routes/safe/components/Transactions/TxsTable/columns' import { getIncomingTxAmount } from '~/routes/safe/components/Transactions/TxsTable/columns'
import updateSafe from '~/routes/safe/store/actions/updateSafe' import updateSafe from '~/routes/safe/store/actions/updateSafe'
import { loadFromStorage } from '~/utils/storage'
import { SAFES_KEY } from '~/logic/safe/utils'
import { RECURRING_USER_KEY } from '~/utils/verifyRecurringUser'
import { safesMapSelector } from '~/routes/safe/store/selectors' import { safesMapSelector } from '~/routes/safe/store/selectors'
import { isUserOwner } from '~/logic/wallets/ethAddresses' import { isUserOwner } from '~/logic/wallets/ethAddresses'
@ -69,17 +66,16 @@ const notificationsMiddleware = (store: Store<GlobalState>) => (
break break
} }
case ADD_INCOMING_TRANSACTIONS: { case ADD_INCOMING_TRANSACTIONS: {
action.payload.forEach(async (incomingTransactions, safeAddress) => { action.payload.forEach((incomingTransactions, safeAddress) => {
const storedSafes = await loadFromStorage(SAFES_KEY) const { latestIncomingTxBlock } = state.safes.get('safes').get(safeAddress)
const latestIncomingTxBlock = storedSafes const viewedSafes = state.currentSession ? state.currentSession.get('viewedSafes') : []
? storedSafes[safeAddress].latestIncomingTxBlock const recurringUser = viewedSafes.includes(safeAddress)
: 0
const newIncomingTransactions = incomingTransactions.filter( const newIncomingTransactions = incomingTransactions.filter(
(tx) => tx.blockNumber > latestIncomingTxBlock, (tx) => tx.blockNumber > latestIncomingTxBlock,
) )
const { message, ...TX_INCOMING_MSG } = NOTIFICATIONS.TX_INCOMING_MSG const { message, ...TX_INCOMING_MSG } = NOTIFICATIONS.TX_INCOMING_MSG
const recurringUser = await loadFromStorage(RECURRING_USER_KEY)
if (recurringUser) { if (recurringUser) {
if (newIncomingTransactions.size > 3) { if (newIncomingTransactions.size > 3) {
@ -109,7 +105,7 @@ const notificationsMiddleware = (store: Store<GlobalState>) => (
updateSafe({ updateSafe({
address: safeAddress, address: safeAddress,
latestIncomingTxBlock: newIncomingTransactions.size latestIncomingTxBlock: newIncomingTransactions.size
? newIncomingTransactions.last().blockNumber ? newIncomingTransactions.first().blockNumber
: latestIncomingTxBlock, : latestIncomingTxBlock,
}), }),
) )

View File

@ -16,6 +16,7 @@ export type SafeProps = {
ethBalance?: string, ethBalance?: string,
nonce: number, nonce: number,
latestIncomingTxBlock: number, latestIncomingTxBlock: number,
recurringUser?: boolean,
} }
const SafeRecord: RecordFactory<SafeProps> = Record({ const SafeRecord: RecordFactory<SafeProps> = Record({
@ -29,6 +30,7 @@ const SafeRecord: RecordFactory<SafeProps> = Record({
balances: Map({}), balances: Map({}),
nonce: 0, nonce: 0,
latestIncomingTxBlock: 0, latestIncomingTxBlock: 0,
recurringUser: undefined,
}) })
export type Safe = RecordOf<SafeProps> export type Safe = RecordOf<SafeProps>

View File

@ -27,7 +27,10 @@ import cookies, { COOKIES_REDUCER_ID } from '~/logic/cookies/store/reducer/cooki
import notificationsMiddleware from '~/routes/safe/store/middleware/notificationsMiddleware' import notificationsMiddleware from '~/routes/safe/store/middleware/notificationsMiddleware'
import addressBook, { ADDRESS_BOOK_REDUCER_ID } from '~/logic/addressBook/store/reducer/addressBook' import addressBook, { ADDRESS_BOOK_REDUCER_ID } from '~/logic/addressBook/store/reducer/addressBook'
import addressBookMiddleware from '~/logic/addressBook/store/middleware/addressBookMiddleware' import addressBookMiddleware from '~/logic/addressBook/store/middleware/addressBookMiddleware'
import currentSession, {
CURRENT_SESSION_REDUCER_ID,
type State as CurrentSessionState,
} from '~/logic/currentSession/store/reducer/currentSession'
export const history = createBrowserHistory() export const history = createBrowserHistory()
@ -44,6 +47,7 @@ export type GlobalState = {
transactions: TransactionsState, transactions: TransactionsState,
incomingTransactions: IncomingTransactionsState, incomingTransactions: IncomingTransactionsState,
notifications: NotificationsState, notifications: NotificationsState,
currentSession: CurrentSessionState,
} }
export type GetState = () => GlobalState export type GetState = () => GlobalState
@ -59,6 +63,7 @@ const reducers: Reducer<GlobalState> = combineReducers({
[CURRENCY_VALUES_KEY]: currencyValues, [CURRENCY_VALUES_KEY]: currencyValues,
[COOKIES_REDUCER_ID]: cookies, [COOKIES_REDUCER_ID]: cookies,
[ADDRESS_BOOK_REDUCER_ID]: addressBook, [ADDRESS_BOOK_REDUCER_ID]: addressBook,
[CURRENT_SESSION_REDUCER_ID]: currentSession,
}) })
export const store: Store<GlobalState> = createStore(reducers, finalCreateStore) export const store: Store<GlobalState> = createStore(reducers, finalCreateStore)

View File

@ -1,18 +0,0 @@
// @flow
import { loadFromStorage, saveToStorage } from '~/utils/storage'
export const RECURRING_USER_KEY = 'RECURRING_USER'
const verifyRecurringUser = async () => {
const recurringUser = await loadFromStorage(RECURRING_USER_KEY)
if (recurringUser === undefined) {
await saveToStorage(RECURRING_USER_KEY, false)
}
if (recurringUser === false) {
await saveToStorage(RECURRING_USER_KEY, true)
}
}
export default verifyRecurringUser