-
Notifications
You must be signed in to change notification settings - Fork 81
/
selectors.ts
507 lines (459 loc) · 16.1 KB
/
selectors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import BigNumber from 'bignumber.js'
import _ from 'lodash'
import deviceInfoModule from 'react-native-device-info'
import { createSelector } from 'reselect'
import {
STABLE_TRANSACTION_MIN_AMOUNT,
TIME_UNTIL_TOKEN_INFO_BECOMES_STALE,
TOKEN_MIN_AMOUNT,
} from 'src/config'
import { usdToLocalCurrencyRateSelector } from 'src/localCurrency/selectors'
import { RootState } from 'src/redux/reducers'
import { getFeatureGate } from 'src/statsig'
import { StatsigFeatureGates } from 'src/statsig/types'
import {
TokenBalance,
TokenBalanceWithAddress,
TokenBalances,
TokenBalancesWithAddress,
} from 'src/tokens/slice'
import { NetworkId } from 'src/transactions/types'
import { Currency } from 'src/utils/currencies'
import { isVersionBelowMinimum } from 'src/utils/versionCheck'
import networkConfig from 'src/web3/networkConfig'
import {
sortByUsdBalance,
sortFirstStableThenCeloThenOthersByUsdBalance,
usdBalance,
} from './utils'
type TokenBalanceWithPriceUsd = TokenBalance & {
priceUsd: BigNumber
}
export type CurrencyTokens = {
[currency in Currency]: TokenBalanceWithAddress | undefined
}
// This is somewhat arbitrary, but appears to reliably prevent recalculation
// for selectors using networkId as a parameter
const DEFAULT_MEMOIZE_MAX_SIZE = 10
function isNetworkIdList(networkIds: any): networkIds is NetworkId[] {
return (
networkIds.constructor === Array &&
networkIds.every((networkId) => Object.values(NetworkId).includes(networkId))
)
}
export const tokenFetchLoadingSelector = (state: RootState) => state.tokens.loading
export const tokenFetchErrorSelector = (state: RootState) => state.tokens.error
export const tokensByIdSelector = createSelector(
[
(state: RootState) => state.tokens.tokenBalances,
(_state: RootState, networkIds: NetworkId[]) => networkIds,
],
(storedBalances, networkIds) => {
const tokenBalances: TokenBalances = {}
for (const storedState of Object.values(storedBalances)) {
if (
!storedState ||
storedState.balance === null ||
!networkIds.includes(storedState.networkId)
) {
continue
}
const priceUsd = new BigNumber(storedState.priceUsd ?? NaN)
const tokenPriceUsdIsStale =
(storedState.priceFetchedAt ?? 0) < Date.now() - TIME_UNTIL_TOKEN_INFO_BECOMES_STALE
tokenBalances[storedState.tokenId] = {
...storedState,
balance: new BigNumber(storedState.balance),
priceUsd: priceUsd.isNaN() || tokenPriceUsdIsStale ? null : priceUsd,
lastKnownPriceUsd: !priceUsd.isNaN() ? priceUsd : null,
}
}
return tokenBalances
},
{
memoizeOptions: {
equalityCheck: (previousValue, currentValue) => {
if (isNetworkIdList(previousValue) && isNetworkIdList(currentValue)) {
return _.isEqual(previousValue, currentValue)
}
return previousValue === currentValue
},
maxSize: DEFAULT_MEMOIZE_MAX_SIZE,
},
}
)
export const networksIconSelector = createSelector(
[
(state: RootState, networkIds: NetworkId[]) => tokensByIdSelector(state, networkIds),
(_state: RootState, networkIds: NetworkId[]) => networkIds,
],
(tokens, networkIds) => {
const result: Partial<Record<NetworkId, string>> = {}
for (const networkId of networkIds) {
// We use as network icon the network icon of any token in that network.
const token = Object.values(tokens).find(
(token) => token?.networkId === networkId && token.networkIconUrl
)
result[networkId] = token?.networkIconUrl
}
return result
}
)
/**
* Get an object mapping token addresses to token metadata, the user's balance, and its price
*
* NOTE: includes only tokens from the default network
*
* @deprecated use tokensByIdSelector instead
*/
export const tokensByAddressSelector = createSelector(
(state: RootState) => tokensByIdSelector(state, [networkConfig.defaultNetworkId]),
(tokens) => {
const output: TokenBalancesWithAddress = {}
for (const token of Object.values(tokens)) {
if (token?.address) {
output[token.address] = {
...token,
address: token.address,
name: token.bridge ? `${token.name} (${token.bridge})` : token.name, // to make sure we show the bridge names even if the old token balances UI (which lacks a "bridge" line) is being used
}
}
}
return output
}
)
export const tokensListSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensByIdSelector(state, networkIds),
(tokens) => {
return Object.values(tokens).map((token) => token!)
}
)
/**
* @deprecated use tokensListSelector instead
*/
export const tokensListWithAddressSelector = createSelector(tokensByAddressSelector, (tokens) => {
return Object.values(tokens).map((token) => token!)
})
/**
* @deprecated
*/
export const tokensBySymbolSelector = createSelector(
tokensListWithAddressSelector,
(
tokens
): {
[symbol: string]: TokenBalanceWithAddress
} => {
return tokens.reduce(
(acc, token) => ({
...acc,
[token.symbol]: token,
}),
{}
)
}
)
export const tokensWithLastKnownUsdValueSelector = createSelector(tokensListSelector, (tokens) => {
return tokens.filter((tokenInfo) =>
tokenInfo.balance
.multipliedBy(tokenInfo.lastKnownPriceUsd ?? 0)
.gt(STABLE_TRANSACTION_MIN_AMOUNT)
)
})
/**
* @deprecated use tokensWithTokenBalanceSelector instead
*/
export const tokensWithTokenBalanceAndAddressSelector = createSelector(
tokensListWithAddressSelector,
(tokens) => {
return tokens.filter((tokenInfo) => tokenInfo.balance.gt(TOKEN_MIN_AMOUNT))
}
)
/**
* @deprecated
*/
export const tokensSortedToShowInSendSelector = createSelector(
tokensWithTokenBalanceAndAddressSelector,
(tokens) => tokens.sort(sortFirstStableThenCeloThenOthersByUsdBalance)
)
// Tokens sorted by usd balance (descending)
/**
* @deprecated
*/
export const tokensByUsdBalanceSelector = createSelector(
tokensListWithAddressSelector,
(tokensList) => tokensList.sort(sortByUsdBalance)
)
/**
* @deprecated
*/
export const coreTokensSelector = createSelector(tokensByUsdBalanceSelector, (tokens) => {
return tokens.filter((tokenInfo) => tokenInfo.isFeeCurrency === true)
})
/**
* @deprecated
*/
export const celoAddressSelector = createSelector(coreTokensSelector, (tokens) => {
return tokens.find((tokenInfo) => tokenInfo.symbol === 'CELO')?.address
})
/**
* @deprecated
*/
export const tokensByCurrencySelector = createSelector(
tokensListWithAddressSelector,
(tokens): CurrencyTokens => {
const cUsdTokenInfo = tokens.find((token) => token?.symbol === Currency.Dollar)
const cEurTokenInfo = tokens.find((token) => token?.symbol === Currency.Euro)
// Currency.Celo === 'cGLD' for legacy reasons, so we just use a hard-coded string.
const celoTokenInfo = tokens.find((token) => token?.symbol === 'CELO')
return {
[Currency.Dollar]: cUsdTokenInfo,
[Currency.Euro]: cEurTokenInfo,
[Currency.Celo]: celoTokenInfo,
}
}
)
export const lastKnownTokenBalancesSelector = createSelector(
[tokensListSelector, tokensWithLastKnownUsdValueSelector, usdToLocalCurrencyRateSelector],
(tokensList, tokensWithLastKnownUsdValue, usdToLocalRate) => {
if (!usdToLocalRate || tokensList.length === 0) {
return null
}
let totalBalance = new BigNumber(0)
for (const token of tokensWithLastKnownUsdValue) {
const tokenAmount = new BigNumber(token.balance)
.multipliedBy(token.lastKnownPriceUsd ?? 0)
.multipliedBy(usdToLocalRate)
totalBalance = totalBalance.plus(tokenAmount)
}
return totalBalance
}
)
export const tokensWithUsdValueSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) => {
return tokens.filter((tokenInfo) =>
tokenInfo.balance.multipliedBy(tokenInfo.priceUsd ?? 0).gt(STABLE_TRANSACTION_MIN_AMOUNT)
) as TokenBalanceWithPriceUsd[]
}
)
export const totalTokenBalanceSelector = createSelector(
[
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(state: RootState, networkIds: NetworkId[]) => tokensWithUsdValueSelector(state, networkIds),
usdToLocalCurrencyRateSelector,
tokenFetchErrorSelector,
tokenFetchLoadingSelector,
(_state: RootState, networkIds: NetworkId[]) => networkIds,
],
(
tokensList,
tokensWithUsdValue,
usdToLocalRate,
tokenFetchError,
tokenFetchLoading,
networkIds
) => {
if (tokenFetchError || tokenFetchLoading) {
return null
}
if (!usdToLocalRate || tokensList.length === 0) {
return null
}
let totalBalance = new BigNumber(0)
for (const token of tokensWithUsdValue.filter((token) =>
networkIds.includes(token.networkId)
)) {
const tokenAmount = new BigNumber(token.balance)
.multipliedBy(token.priceUsd)
.multipliedBy(usdToLocalRate)
totalBalance = totalBalance.plus(tokenAmount)
}
return totalBalance
}
)
export const tokensInfoUnavailableSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => totalTokenBalanceSelector(state, networkIds),
(totalBalance) => {
// The total balance is null if there was an error fetching the tokens
// info and there are no cached values
return totalBalance === null
}
)
export const tokensWithTokenBalanceSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) => {
return tokens.filter((token) => token.balance.gt(TOKEN_MIN_AMOUNT))
}
)
export const swappableFromTokensByNetworkIdSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) => {
const appVersion = deviceInfoModule.getVersion()
return (
tokens
.filter(
(tokenInfo) =>
tokenInfo.isSwappable ||
(tokenInfo.minimumAppVersionToSwap &&
!isVersionBelowMinimum(appVersion, tokenInfo.minimumAppVersionToSwap)) ||
tokenInfo.balance.gt(TOKEN_MIN_AMOUNT)
)
// sort by balance USD (DESC) then name (ASC), tokens without a priceUsd
// are pushed last, sorted by name (ASC)
.sort((token1, token2) => {
// Sort by USD balance first (higher balances first)
const token1UsdBalance = token1.balance.multipliedBy(token1.priceUsd ?? 0)
const token2UsdBalance = token2.balance.multipliedBy(token2.priceUsd ?? 0)
if (token1UsdBalance.gt(token2UsdBalance)) return -1
if (token1UsdBalance.lt(token2UsdBalance)) return 1
// Sort by token balance if there is no priceUsd (higher balances first)
const balanceCompare = token2.balance.comparedTo(token1.balance)
if (balanceCompare) {
return balanceCompare
}
// Sort tokens without priceUsd and balance at bottom of list
if (token1.priceUsd === null || token2.priceUsd === null) {
// If both prices are null, sort alphabetically by name
if (!token1.priceUsd && !token2.priceUsd) {
return token1.name.localeCompare(token2.name)
}
// Otherwise, sort such that the token with a non-null price comes first
return token1.priceUsd === null ? 1 : -1
}
// Lastly, sort by name
return token1.name.localeCompare(token2.name)
})
)
}
)
export const swappableToTokensByNetworkIdSelector = createSelector(
swappableFromTokensByNetworkIdSelector,
(tokens) => {
const appVersion = deviceInfoModule.getVersion()
return tokens.filter(
(tokenInfo) =>
tokenInfo.isSwappable ||
(tokenInfo.minimumAppVersionToSwap &&
!isVersionBelowMinimum(appVersion, tokenInfo.minimumAppVersionToSwap))
)
}
)
export const cashInTokensByNetworkIdSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) => tokens.filter((tokenInfo) => tokenInfo.isCashInEligible)
)
export const cashOutTokensByNetworkIdSelector = createSelector(
[
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(_state: RootState, _networkIds: NetworkId[], showZeroBalanceTokens: boolean) =>
showZeroBalanceTokens,
],
(tokens, showZeroBalanceTokens) =>
tokens.filter(
(tokenInfo) =>
((showZeroBalanceTokens ? tokenInfo.showZeroBalance : false) ||
tokenInfo.balance.gt(TOKEN_MIN_AMOUNT)) &&
tokenInfo.isCashOutEligible
)
)
export const spendTokensByNetworkIdSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) => tokens.filter((tokenInfo) => networkConfig.spendTokenIds.includes(tokenInfo.tokenId))
)
export const tokensWithNonZeroBalanceAndShowZeroBalanceSelector = createSelector(
(state: RootState, networkIds: NetworkId[]) => tokensListSelector(state, networkIds),
(tokens) =>
tokens
.filter((tokenInfo) => tokenInfo.balance.gt(TOKEN_MIN_AMOUNT) || tokenInfo.showZeroBalance)
.sort((token1, token2) => {
// Sorts by usd balance, then token balance, then zero balance natives by
// network id, then zero balance non natives by network id
const usdBalanceCompare = usdBalance(token2).comparedTo(usdBalance(token1))
if (usdBalanceCompare) {
return usdBalanceCompare
}
const balanceCompare = token2.balance.comparedTo(token1.balance)
if (balanceCompare) {
return balanceCompare
}
if (token1.isNative && !token2.isNative) {
return -1
}
if (!token1.isNative && token2.isNative) {
return 1
}
return token1.networkId.localeCompare(token2.networkId)
})
)
const feeCurrenciesByNetworkIdSelector = createSelector(
(state: RootState) => tokensByIdSelector(state, Object.values(NetworkId)),
(tokens) => {
const feeCurrenciesByNetworkId: { [key in NetworkId]?: TokenBalance[] } = {}
// collect fee currencies
Object.values(tokens).forEach((token) => {
if (token?.isNative || token?.isFeeCurrency) {
feeCurrenciesByNetworkId[token.networkId] = [
...(feeCurrenciesByNetworkId[token.networkId] ?? []),
token,
]
}
})
// sort the fee currencies by native currency first, then by USD balance, and balance otherwise
Object.entries(feeCurrenciesByNetworkId).forEach(([networkId, tokens]) => {
feeCurrenciesByNetworkId[networkId as NetworkId] = tokens.sort((a, b) => {
if (a.isNative && !b.isNative) {
return -1
}
if (b.isNative && !a.isNative) {
return 1
}
if (a.priceUsd && b.priceUsd) {
const aBalanceUsd = a.balance.multipliedBy(a.priceUsd)
const bBalanceUsd = b.balance.multipliedBy(b.priceUsd)
return bBalanceUsd.comparedTo(aBalanceUsd)
}
if (a.priceUsd) {
return -1
}
if (b.priceUsd) {
return 1
}
return b.balance.comparedTo(a.balance)
})
})
return feeCurrenciesByNetworkId
}
)
// for testing
export const _feeCurrenciesByNetworkIdSelector = feeCurrenciesByNetworkIdSelector
export const feeCurrenciesSelector = createSelector(
feeCurrenciesByNetworkIdSelector,
(_state: RootState, networkId: NetworkId) => networkId,
(feeCurrencies, networkId) => {
return feeCurrencies[networkId] ?? []
}
)
// Note this takes a networkId as parameter
export const feeCurrenciesWithPositiveBalancesSelector = createSelector(
feeCurrenciesSelector,
(feeCurrencies) => {
return feeCurrencies.filter((token) => token.balance.gt(0))
},
{
memoizeOptions: {
maxSize: DEFAULT_MEMOIZE_MAX_SIZE,
},
}
)
export const visualizeNFTsEnabledInHomeAssetsPageSelector = (state: RootState) =>
state.app.visualizeNFTsEnabledInHomeAssetsPage
export const importedTokensSelector = createSelector(
[tokensListSelector],
(tokenList): TokenBalance[] => {
if (!getFeatureGate(StatsigFeatureGates.SHOW_IMPORT_TOKENS_FLOW)) {
return []
}
return tokenList.filter((token) => token?.isManuallyImported)
}
)