|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | + |
| 3 | +enum TimePeriod { |
| 4 | + hour = 'hour', |
| 5 | + day = 'day', |
| 6 | + week = 'week', |
| 7 | + month = 'month', |
| 8 | + year = 'year', |
| 9 | +} |
| 10 | + |
| 11 | +type Dictionary<K extends keyof any, T> = Partial<Record<K, T>> |
| 12 | + |
| 13 | +type TokenData = { |
| 14 | + [address: string]: { |
| 15 | + price: number |
| 16 | + delta: Dictionary<TimePeriod, number> |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +interface UseTokenPriceResult { |
| 21 | + data: TokenData | null |
| 22 | + error: string | null |
| 23 | + loading: boolean |
| 24 | +} |
| 25 | + |
| 26 | +const FAKE_TOKEN_PRICE_RESULT = { |
| 27 | + '0x03ab458634910aad20ef5f1c8ee96f1d6ac54919': { |
| 28 | + price: 3.05, |
| 29 | + delta: { |
| 30 | + [TimePeriod.hour]: 25_000, |
| 31 | + [TimePeriod.day]: 619_000, |
| 32 | + [TimePeriod.week]: 16_800_000, |
| 33 | + [TimePeriod.month]: 58_920_000, |
| 34 | + }, |
| 35 | + }, |
| 36 | + '0x0cec1a9154ff802e7934fc916ed7ca50bde6844e': { |
| 37 | + price: 0.66543, |
| 38 | + delta: { |
| 39 | + [TimePeriod.hour]: 5_000, |
| 40 | + [TimePeriod.day]: 100_000, |
| 41 | + [TimePeriod.week]: 800_000, |
| 42 | + [TimePeriod.month]: 4_920_000, |
| 43 | + }, |
| 44 | + }, |
| 45 | +} |
| 46 | + |
| 47 | +const useTokenPrice = (tokenAddresses: Set<string>): UseTokenPriceResult => { |
| 48 | + const [data, setData] = useState<TokenData | null>(null) |
| 49 | + const [error, setError] = useState<string | null>(null) |
| 50 | + const [loading, setLoading] = useState(false) |
| 51 | + |
| 52 | + const fetchTokenPrices = async (addresses: Set<string>): Promise<TokenData | void> => { |
| 53 | + const waitRandom = (min: number, max: number): Promise<void> => |
| 54 | + new Promise((resolve) => setTimeout(resolve, min + Math.round(Math.random() * Math.max(0, max - min)))) |
| 55 | + try { |
| 56 | + setLoading(true) |
| 57 | + setError(null) |
| 58 | + await waitRandom(250, 2000) |
| 59 | + if (Math.random() < 0.05) { |
| 60 | + throw new Error('fake error') |
| 61 | + } |
| 62 | + console.log('fetchTokenPrices', addresses) |
| 63 | + return FAKE_TOKEN_PRICE_RESULT |
| 64 | + } catch (e) { |
| 65 | + setError('something went wrong') |
| 66 | + } finally { |
| 67 | + setLoading(false) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + useEffect(() => { |
| 72 | + setLoading(true) |
| 73 | + setError(null) |
| 74 | + fetchTokenPrices(tokenAddresses) |
| 75 | + .then((data) => { |
| 76 | + if (data) setData(data) |
| 77 | + }) |
| 78 | + .catch((e) => setError(e)) |
| 79 | + .finally(() => setLoading(false)) |
| 80 | + }, [tokenAddresses]) |
| 81 | + |
| 82 | + return { data, error, loading } |
| 83 | +} |
| 84 | + |
| 85 | +export default useTokenPrice |
0 commit comments