(Fix) - 772 safe zero balances (#832)

* Refactor currency values:
- Creates middleware to save currency values on actions
- Replaces currency values model to be safeAddress-dependant
-

* - Adds all the safes balances on safe load
- Saves the currency values status to localStorage on the middleware

* Fixs equals comparation used to avoid unnecessary dispatchs

* Update naming

* Fixs rate type

* Fixs wrong variable usage

* Removes currencyBalances from localStorage, just saves currencyRate and currencyValueSelected

* Renames currencyValueSelected to currencyValueSelected

* Refactors currencyValueSelected to selectedCurrencyValue

* Refactors selectedCurrencyValue to selectedCurrency
This commit is contained in:
Agustin Pane 2020-05-06 17:03:59 -03:00 committed by GitHub
parent 377df43168
commit a98652abe4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 177 additions and 80 deletions

View File

@ -7,15 +7,15 @@ import { AVAILABLE_CURRENCIES } from '~/logic/currencyValues/store/model/currenc
import type { GlobalState } from '~/store'
// eslint-disable-next-line max-len
const fetchCurrencySelectedValue = (currencyValueSelected: $Keys<typeof AVAILABLE_CURRENCIES>) => async (
const fetchCurrencyRate = (safeAddress: string, selectedCurrency: $Keys<typeof AVAILABLE_CURRENCIES>) => async (
dispatch: ReduxDispatch<GlobalState>,
) => {
if (AVAILABLE_CURRENCIES.USD === currencyValueSelected) {
return dispatch(setCurrencyRate('1'))
if (AVAILABLE_CURRENCIES.USD === selectedCurrency) {
return dispatch(setCurrencyRate(safeAddress, 1))
}
const selectedCurrencyRateInBaseCurrency = await fetchCurrenciesRates(AVAILABLE_CURRENCIES.USD, currencyValueSelected)
dispatch(setCurrencyRate(selectedCurrencyRateInBaseCurrency))
const selectedCurrencyRateInBaseCurrency = await fetchCurrenciesRates(AVAILABLE_CURRENCIES.USD, selectedCurrency)
dispatch(setCurrencyRate(safeAddress, selectedCurrencyRateInBaseCurrency))
}
export default fetchCurrencySelectedValue
export default fetchCurrencyRate

View File

@ -1,36 +1,42 @@
// @flow
import { List } from 'immutable'
import { batch } from 'react-redux'
import type { Dispatch as ReduxDispatch } from 'redux'
import fetchCurrencySelectedValue from '~/logic/currencyValues/store/actions/fetchCurrencySelectedValue'
import { CURRENCY_SELECTED_KEY } from '~/logic/currencyValues/store/actions/saveCurrencySelected'
import fetchCurrencyRate from '~/logic/currencyValues/store/actions/fetchCurrencyRate'
import { setCurrencyBalances } from '~/logic/currencyValues/store/actions/setCurrencyBalances'
import { setCurrencyRate } from '~/logic/currencyValues/store/actions/setCurrencyRate'
import { setCurrencySelected } from '~/logic/currencyValues/store/actions/setCurrencySelected'
import { setSelectedCurrency } from '~/logic/currencyValues/store/actions/setSelectedCurrency'
import { AVAILABLE_CURRENCIES } from '~/logic/currencyValues/store/model/currencyValues'
import { loadCurrencyValues } from '~/logic/currencyValues/store/utils/currencyValuesStorage'
import fetchSafeTokens from '~/logic/tokens/store/actions/fetchSafeTokens'
import type { GlobalState } from '~/store'
import { loadFromStorage } from '~/utils/storage'
export const fetchCurrencyValues = () => async (dispatch: ReduxDispatch<GlobalState>) => {
export const fetchCurrencyValues = (safeAddress: string) => async (dispatch: ReduxDispatch<GlobalState>) => {
try {
const currencyStored = await loadFromStorage(CURRENCY_SELECTED_KEY)
if (!currencyStored) {
const storedCurrencies = await loadCurrencyValues()
const storedCurrency = storedCurrencies[safeAddress]
if (!storedCurrency) {
return batch(() => {
dispatch(setCurrencySelected(AVAILABLE_CURRENCIES.USD))
dispatch(setCurrencyRate(1))
dispatch(setCurrencyBalances(safeAddress, List([])))
dispatch(setSelectedCurrency(safeAddress, AVAILABLE_CURRENCIES.USD))
dispatch(setCurrencyRate(safeAddress, 1))
})
}
const { currencyValueSelected } = currencyStored
batch(() => {
dispatch(setCurrencySelected(currencyValueSelected))
dispatch(fetchCurrencySelectedValue(currencyValueSelected))
// Loads the stored state on redux
Object.entries(storedCurrencies).forEach((kv) => {
const safeAddr = kv[0]
const value = kv[1]
const { currencyRate, selectedCurrency } = value
batch(() => {
dispatch(setSelectedCurrency(safeAddr, selectedCurrency))
dispatch(setCurrencyRate(safeAddr, currencyRate))
dispatch(fetchCurrencyRate(safeAddr, selectedCurrency))
dispatch(fetchSafeTokens(safeAddress))
})
})
} catch (err) {
console.error('Error fetching tokens price list', err)
console.error('Error fetching currency values', err)
}
return Promise.resolve()
}
export default fetchCurrencyValues

View File

@ -1,19 +0,0 @@
// @flow
import { Dispatch as ReduxDispatch } from 'redux'
import { setCurrencySelected } from '~/logic/currencyValues/store/actions/setCurrencySelected'
import { AVAILABLE_CURRENCIES } from '~/logic/currencyValues/store/model/currencyValues'
import type { GlobalState } from '~/store'
import { saveToStorage } from '~/utils/storage'
export const CURRENCY_SELECTED_KEY = 'CURRENCY_SELECTED_KEY'
const saveCurrencySelected = (currencySelected: AVAILABLE_CURRENCIES) => async (
dispatch: ReduxDispatch<GlobalState>,
) => {
await saveToStorage(CURRENCY_SELECTED_KEY, { currencyValueSelected: currencySelected })
dispatch(setCurrencySelected(currencySelected))
}
export default saveCurrencySelected

View File

@ -1,5 +1,4 @@
// @flow
import { Map } from 'immutable'
import { createAction } from 'redux-actions'
import type { CurrencyValues, CurrencyValuesProps } from '~/logic/currencyValues/store/model/currencyValues'
@ -9,5 +8,8 @@ export const SET_CURRENCY_BALANCES = 'SET_CURRENCY_BALANCES'
// eslint-disable-next-line max-len
export const setCurrencyBalances = createAction<string, *>(
SET_CURRENCY_BALANCES,
(currencyBalances: Map<string, CurrencyValues>): CurrencyValuesProps => ({ currencyBalances }),
(safeAddress: string, currencyBalances: List<CurrencyValues>): CurrencyValuesProps => ({
safeAddress,
currencyBalances,
}),
)

View File

@ -8,5 +8,5 @@ export const SET_CURRENCY_RATE = 'SET_CURRENCY_RATE'
// eslint-disable-next-line max-len
export const setCurrencyRate = createAction<string, *>(
SET_CURRENCY_RATE,
(currencyRate: string): CurrencyValuesProps => ({ currencyRate }),
(safeAddress: string, currencyRate: string): CurrencyValuesProps => ({ safeAddress, currencyRate }),
)

View File

@ -7,7 +7,10 @@ import { AVAILABLE_CURRENCIES } from '~/logic/currencyValues/store/model/currenc
export const SET_CURRENT_CURRENCY = 'SET_CURRENT_CURRENCY'
// eslint-disable-next-line max-len
export const setCurrencySelected = createAction<string, *>(
export const setSelectedCurrency = createAction<string, *>(
SET_CURRENT_CURRENCY,
(currencyValueSelected: $Keys<typeof AVAILABLE_CURRENCIES>): CurrencyValuesProps => ({ currencyValueSelected }),
(safeAddress: string, selectedCurrency: $Keys<typeof AVAILABLE_CURRENCIES>): CurrencyValuesProps => ({
safeAddress,
selectedCurrency,
}),
)

View File

@ -0,0 +1,50 @@
// @flow
import { Action, Store } from 'redux'
import fetchCurrencyRate from '~/logic/currencyValues/store/actions/fetchCurrencyRate'
import { SET_CURRENCY_BALANCES } from '~/logic/currencyValues/store/actions/setCurrencyBalances'
import { SET_CURRENCY_RATE } from '~/logic/currencyValues/store/actions/setCurrencyRate'
import { SET_CURRENT_CURRENCY } from '~/logic/currencyValues/store/actions/setSelectedCurrency'
import { currencyValuesSelector } from '~/logic/currencyValues/store/selectors'
import { saveCurrencyValues } from '~/logic/currencyValues/store/utils/currencyValuesStorage'
import type { GlobalState } from '~/routes/safe/store/middleware/safeStorage'
const watchedActions = [SET_CURRENT_CURRENCY, SET_CURRENCY_RATE, SET_CURRENCY_BALANCES]
const currencyValuesStorageMiddleware = (store: Store<GlobalState>) => (next: Function) => async (
action: Action<*>,
) => {
const handledAction = next(action)
if (watchedActions.includes(action.type)) {
const state: GlobalState = store.getState()
const { dispatch } = store
switch (action.type) {
case SET_CURRENT_CURRENCY: {
const { safeAddress, selectedCurrency } = action.payload
dispatch(fetchCurrencyRate(safeAddress, selectedCurrency))
break
}
case SET_CURRENCY_RATE:
case SET_CURRENCY_BALANCES: {
const currencyValues = currencyValuesSelector(state)
const currencyValuesWithoutBalances = currencyValues.map((currencyValue) => {
const currencyRate = currencyValue.get('currencyRate')
const selectedCurrency = currencyValue.get('selectedCurrency')
return {
currencyRate,
selectedCurrency,
}
})
await saveCurrencyValues(currencyValuesWithoutBalances)
break
}
default:
break
}
}
return handledAction
}
export default currencyValuesStorageMiddleware

View File

@ -1,5 +1,5 @@
// @flow
import type { RecordOf } from 'immutable'
import type { RecordFactory, RecordOf } from 'immutable'
import { Record } from 'immutable'
export const AVAILABLE_CURRENCIES = {
@ -45,17 +45,22 @@ export type BalanceCurrencyType = {
balanceInSelectedCurrency: string,
}
export const makeBalanceCurrency = Record({
export const makeBalanceCurrency: RecordFactory<BalanceCurrencyType> = Record({
currencyName: '',
tokenAddress: '',
balanceInBaseCurrency: '',
balanceInSelectedCurrency: '',
})
export type CurrencyValuesProps = {
currencyValueSelected: $Keys<typeof AVAILABLE_CURRENCIES>,
currencyRate: string,
export type CurrencyValuesEntry = {
selectedCurrency: $Keys<typeof AVAILABLE_CURRENCIES>,
currencyRate: number,
currencyValuesList: BalanceCurrencyType[],
}
export type CurrencyValuesProps = {
// Map safe address to currency values entry
currencyValues: Map<string, CurrencyValuesEntry>,
}
export type CurrencyValues = RecordOf<CurrencyValuesProps>

View File

@ -4,7 +4,7 @@ import { type ActionType, handleActions } from 'redux-actions'
import { SET_CURRENCY_BALANCES } from '~/logic/currencyValues/store/actions/setCurrencyBalances'
import { SET_CURRENCY_RATE } from '~/logic/currencyValues/store/actions/setCurrencyRate'
import { SET_CURRENT_CURRENCY } from '~/logic/currencyValues/store/actions/setCurrencySelected'
import { SET_CURRENT_CURRENCY } from '~/logic/currencyValues/store/actions/setSelectedCurrency'
import type { State } from '~/logic/tokens/store/reducer/tokens'
export const CURRENCY_VALUES_KEY = 'currencyValues'
@ -12,19 +12,19 @@ export const CURRENCY_VALUES_KEY = 'currencyValues'
export default handleActions<State, *>(
{
[SET_CURRENCY_RATE]: (state: State, action: ActionType<Function>): State => {
const { currencyRate } = action.payload
const { currencyRate, safeAddress } = action.payload
return state.set('currencyRate', currencyRate)
return state.setIn([safeAddress, 'currencyRate'], currencyRate)
},
[SET_CURRENCY_BALANCES]: (state: State, action: ActionType<Function>): State => {
const { currencyBalances } = action.payload
const { currencyBalances, safeAddress } = action.payload
return state.set('currencyBalances', currencyBalances)
return state.setIn([safeAddress, 'currencyBalances'], currencyBalances)
},
[SET_CURRENT_CURRENCY]: (state: State, action: ActionType<Function>): State => {
const { currencyValueSelected } = action.payload
const { safeAddress, selectedCurrency } = action.payload
return state.set('currencyValueSelected', currencyValueSelected)
return state.setIn([safeAddress, 'selectedCurrency'], selectedCurrency)
},
},
Map(),

View File

@ -1,13 +1,38 @@
// @flow
import { List } from 'immutable'
import { type OutputSelector, createSelector } from 'reselect'
import type { CurrencyValuesEntry, CurrencyValuesProps } from '~/logic/currencyValues/store/model/currencyValues'
import { CURRENCY_VALUES_KEY } from '~/logic/currencyValues/store/reducer/currencyValues'
import { safeParamAddressFromStateSelector } from '~/routes/safe/store/selectors'
import { type GlobalState } from '~/store'
export const currencyValuesListSelector = (state: GlobalState) =>
state[CURRENCY_VALUES_KEY].get('currencyBalances') ? state[CURRENCY_VALUES_KEY].get('currencyBalances') : List([])
export const currencyValuesSelector = (state: GlobalState): CurrencyValuesEntry => state[CURRENCY_VALUES_KEY]
export const currentCurrencySelector = (state: GlobalState) => state[CURRENCY_VALUES_KEY].get('currencyValueSelected')
export const safeFiatBalancesSelector: OutputSelector<GlobalState> = createSelector(
currencyValuesSelector,
safeParamAddressFromStateSelector,
(currencyValues: CurrencyValuesProps, safeAddress: string) => {
if (!currencyValues) return
return currencyValues.get(safeAddress)
},
)
export const currencyRateSelector = (state: GlobalState) => state[CURRENCY_VALUES_KEY].get('currencyRate')
export const safeFiatBalancesListSelector: OutputSelector<GlobalState> = createSelector(
safeFiatBalancesSelector,
(currencyValuesMap: CurrencyValuesProps) => {
if (!currencyValuesMap) return
return currencyValuesMap.get('currencyBalances') ? currencyValuesMap.get('currencyBalances') : List([])
},
)
export const currentCurrencySelector: OutputSelector<GlobalState> = createSelector(
safeFiatBalancesSelector,
(currencyValuesMap?: CurrencyValuesProps) => (currencyValuesMap ? currencyValuesMap.get('selectedCurrency') : null),
)
export const currencyRateSelector: OutputSelector<GlobalState> = createSelector(
safeFiatBalancesSelector,
(currencyValuesMap: CurrencyValuesProps) => (currencyValuesMap ? currencyValuesMap.get('currencyRate') : null),
)

View File

@ -0,0 +1,18 @@
// @flow
import { Map } from 'immutable'
import type { CurrencyValuesEntry } from '~/logic/currencyValues/store/model/currencyValues'
import { loadFromStorage, saveToStorage } from '~/utils/storage'
const CURRENCY_VALUES_STORAGE_KEY = 'CURRENCY_VALUES_STORAGE_KEY'
export const saveCurrencyValues = async (currencyValues: Map<string, CurrencyValuesEntry>) => {
try {
await saveToStorage(CURRENCY_VALUES_STORAGE_KEY, currencyValues)
} catch (err) {
console.error('Error storing currency values info in localstorage', err)
}
}
export const loadCurrencyValues = async () => {
return (await loadFromStorage(CURRENCY_VALUES_STORAGE_KEY)) || {}
}

View File

@ -35,7 +35,6 @@ const fetchSafeTokens = (safeAddress: string) => async (dispatch: ReduxDispatch<
const alreadyActiveTokens = safe.get('activeTokens')
const blacklistedTokens = safe.get('blacklistedTokens')
const currencyValues = state[CURRENCY_VALUES_KEY]
const storedCurrencyBalances = currencyValues.get('currencyBalances')
const { balances, currencyList, ethBalance, tokens } = result.data.reduce(
(acc, { balance, balanceUsd, token, tokenAddress }) => {
@ -78,8 +77,14 @@ const fetchSafeTokens = (safeAddress: string) => async (dispatch: ReduxDispatch<
const updateActiveTokens = activeTokens.equals(alreadyActiveTokens) ? noFunc : update({ activeTokens })
const updateBalances = balances.equals(safeBalances) ? noFunc : update({ balances })
const updateEthBalance = ethBalance === currentEthBalance ? noFunc : update({ ethBalance })
const storedCurrencyBalances =
currencyValues && currencyValues.get(safeAddress)
? currencyValues.get(safeAddress).get('currencyBalances')
: undefined
const updateCurrencies = currencyList.equals(storedCurrencyBalances) ? noFunc : setCurrencyBalances(currencyList)
const updateCurrencies = currencyList.equals(storedCurrencyBalances)
? noFunc
: setCurrencyBalances(safeAddress, currencyList)
const updateTokens = tokens.size === 0 ? noFunc : addTokens(tokens)

View File

@ -19,8 +19,8 @@ import Button from '~/components/layout/Button'
import Row from '~/components/layout/Row'
import {
currencyRateSelector,
currencyValuesListSelector,
currentCurrencySelector,
safeFiatBalancesListSelector,
} from '~/logic/currencyValues/store/selectors'
import { BALANCE_ROW_TEST_ID } from '~/routes/safe/components/Balances'
import AssetTableCell from '~/routes/safe/components/Balances/AssetTableCell'
@ -46,16 +46,16 @@ const Coins = (props: Props) => {
const classes = useStyles()
const columns = generateColumns()
const autoColumns = columns.filter((c) => !c.custom)
const currencySelected = useSelector(currentCurrencySelector)
const selectedCurrency = useSelector(currentCurrencySelector)
const currencyRate = useSelector(currencyRateSelector)
const activeTokens = useSelector(extendedSafeTokensSelector)
const currencyValues = useSelector(currencyValuesListSelector)
const currencyValues = useSelector(safeFiatBalancesListSelector)
const granted = useSelector(grantedSelector)
const [filteredData, setFilteredData] = React.useState(List())
React.useMemo(() => {
setFilteredData(getBalanceData(activeTokens, currencySelected, currencyValues, currencyRate))
}, [currencySelected, currencyRate, activeTokens.hashCode(), currencyValues.hashCode()])
setFilteredData(getBalanceData(activeTokens, selectedCurrency, currencyValues, currencyRate))
}, [selectedCurrency, currencyRate, activeTokens.hashCode(), currencyValues])
return (
<TableContainer>

View File

@ -13,18 +13,19 @@ import { useDispatch, useSelector } from 'react-redux'
import CheckIcon from './img/check.svg'
import fetchCurrencySelectedValue from '~/logic/currencyValues/store/actions/fetchCurrencySelectedValue'
import saveCurrencySelected from '~/logic/currencyValues/store/actions/saveCurrencySelected'
import { setSelectedCurrency } from '~/logic/currencyValues/store/actions/setSelectedCurrency'
import { AVAILABLE_CURRENCIES } from '~/logic/currencyValues/store/model/currencyValues'
import { currentCurrencySelector } from '~/logic/currencyValues/store/selectors'
import { useDropdownStyles } from '~/routes/safe/components/DropdownCurrency/style'
import { safeParamAddressFromStateSelector } from '~/routes/safe/store/selectors'
import { DropdownListTheme } from '~/theme/mui'
const DropdownCurrency = () => {
const currenciesList = Object.values(AVAILABLE_CURRENCIES)
const safeAddress = useSelector(safeParamAddressFromStateSelector)
const dispatch = useDispatch()
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
const currencyValueSelected = useSelector(currentCurrencySelector)
const selectedCurrency = useSelector(currentCurrencySelector)
const [searchParams, setSearchParams] = useState('')
const classes = useDropdownStyles()
@ -41,17 +42,16 @@ const DropdownCurrency = () => {
}
const onCurrentCurrencyChangedHandler = (newCurrencySelectedName: AVAILABLE_CURRENCIES) => {
dispatch(fetchCurrencySelectedValue(newCurrencySelectedName))
dispatch(saveCurrencySelected(newCurrencySelectedName))
dispatch(setSelectedCurrency(safeAddress, newCurrencySelectedName))
handleClose()
}
return !currencyValueSelected ? null : (
return !selectedCurrency ? null : (
<MuiThemeProvider theme={DropdownListTheme}>
<>
<button className={classes.button} onClick={handleClick} type="button">
<span className={classNames(classes.buttonInner, anchorEl && classes.openMenuButton)}>
{currencyValueSelected}
{selectedCurrency}
</span>
</button>
<Menu
@ -108,7 +108,7 @@ const DropdownCurrency = () => {
/>
</ListItemIcon>
<ListItemText primary={currencyName} />
{currencyName === currencyValueSelected ? (
{currencyName === selectedCurrency ? (
<ListItemIcon className={classes.iconRight}>
<img alt="checked" src={CheckIcon} />
</ListItemIcon>

View File

@ -15,6 +15,7 @@ import {
nftTokensReducer,
} from '~/logic/collectibles/store/reducer/collectibles'
import cookies, { COOKIES_REDUCER_ID } from '~/logic/cookies/store/reducer/cookies'
import currencyValuesStorageMiddleware from '~/logic/currencyValues/store/middleware'
import currencyValues, { CURRENCY_VALUES_KEY } from '~/logic/currencyValues/store/reducer/currencyValues'
import currentSession, {
CURRENT_SESSION_REDUCER_ID,
@ -55,6 +56,7 @@ const finalCreateStore = composeEnhancers(
providerWatcher,
notificationsMiddleware,
addressBookMiddleware,
currencyValuesStorageMiddleware,
),
)