Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Commit

Permalink
Merge caf6d27 into 2e0c015
Browse files Browse the repository at this point in the history
  • Loading branch information
anxolin committed Nov 28, 2020
2 parents 2e0c015 + caf6d27 commit b1d18a2
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 17 deletions.
1 change: 1 addition & 0 deletions src/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Network } from 'types'
import { DisabledTokensMaps, TokenOverride, AddressToOverrideMap } from 'types/config'

export const BATCH_TIME_IN_MS = BATCH_TIME * 1000
export const DEFAULT_TIMEOUT = 5000

export const ZERO_BIG_NUMBER = new BigNumber(0)
export const ONE_BIG_NUMBER = new BigNumber(1)
Expand Down
44 changes: 28 additions & 16 deletions src/hooks/useTokenBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { erc20Api, depositApi } from 'api'
import useSafeState from './useSafeState'
import { useWalletConnection } from './useWalletConnection'

import { formatSmart, logDebug, isTokenEnabled } from 'utils'
import { formatSmart, logDebug, isTokenEnabled, timeout } from 'utils'
import { TokenBalanceDetails, TokenDetails } from 'types'
import { WalletInfo } from 'api/wallet/WalletApi'
import { PendingFlux } from 'api/deposit/DepositApi'
Expand All @@ -34,6 +34,7 @@ async function fetchBalancesForToken(
networkId: number,
): Promise<TokenBalanceDetails> {
const tokenAddress = token.address

const [
exchangeBalance,
pendingDeposit,
Expand Down Expand Up @@ -83,28 +84,39 @@ async function _getBalances(walletInfo: WalletInfo, tokens: TokenDetails[]): Pro
const contractAddress = depositApi.getContractAddress(networkId)
assert(contractAddress, 'No valid contract address found. Stopping.')

const balancePromises: Promise<TokenBalanceDetails | null>[] = tokens.map((token) =>
fetchBalancesForToken(token, userAddress, contractAddress, networkId)
.then((balance) => {
const balancePromises: Promise<TokenBalanceDetails | null>[] = tokens.map((token) => {
const timeoutPromise = timeout<TokenBalanceDetails | null>({
timeoutErrorMsg: 'Timeout fetching balances for ' + token.address,
})

const fetchBalancesPromise = fetchBalancesForToken(token, userAddress, contractAddress, networkId).then(
(balance) => {
const cacheKey = constructCacheKey({ token, userAddress, contractAddress, networkId })
balanceCache[cacheKey] = balance
return balance
})
.catch((e) => {
console.error('[useTokenBalances] Error for', token, userAddress, contractAddress, e)
},
)

const cacheKey = constructCacheKey({ token, userAddress, contractAddress, networkId })
const balancePromise = Promise.race([fetchBalancesPromise, timeoutPromise])

return balancePromise.catch((e) => {
console.error('[useTokenBalances] Error for', token, userAddress, contractAddress, e)

const cachedValue = balanceCache[cacheKey]
if (cachedValue) {
logDebug('Using cached value for', token, userAddress, contractAddress)
return cachedValue
}
const cacheKey = constructCacheKey({ token, userAddress, contractAddress, networkId })

const cachedValue = balanceCache[cacheKey]
if (cachedValue) {
logDebug('Using cached value for', token, userAddress, contractAddress)
return cachedValue
}

return null
})
})

return null
}),
)
const balances = await Promise.all(balancePromises)

// TODO: Would be better to show the errored tokens in error state
return balances.filter(Boolean) as TokenBalanceDetails[]
}

Expand Down
21 changes: 20 additions & 1 deletion src/utils/miscellaneous.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { TokenDetails, Unpromise } from 'types'
import { AssertionError } from 'assert'
import { AuctionElement, Trade, Order } from 'api/exchange/ExchangeApi'
import { batchIdToDate } from './time'
import { ORDER_FILLED_FACTOR, MINIMUM_ALLOWANCE_DECIMALS } from 'const'
import { ORDER_FILLED_FACTOR, MINIMUM_ALLOWANCE_DECIMALS, DEFAULT_TIMEOUT } from 'const'
import { TEN, ZERO } from '@gnosis.pm/dex-js'

export function assertNonNull<T>(val: T, message: string): asserts val is NonNullable<T> {
Expand Down Expand Up @@ -210,3 +210,22 @@ export function notEmpty<TValue>(value: TValue | null | undefined): value is TVa
}

export const isNonZeroNumber = (value?: string | number): boolean => !!value && !!+value

export interface TimeoutParams<T> {
time?: number
result?: T
timeoutErrorMsg?: string
}

export function timeout<T>(params: TimeoutParams<T>): Promise<T> {
const { time = DEFAULT_TIMEOUT, result, timeoutErrorMsg: timeoutMsg = 'Timeout' } = params
return new Promise((resolve, rejects) =>
setTimeout(() => {
if (result) {
resolve(result)
} else {
rejects(new Error(timeoutMsg))
}
}, time),
)
}

0 comments on commit b1d18a2

Please sign in to comment.