2020-10-28 10:32:56 +01:00
|
|
|
import React, {
|
|
|
|
useState,
|
|
|
|
ReactElement,
|
|
|
|
createContext,
|
|
|
|
useContext,
|
2022-04-22 02:38:35 +02:00
|
|
|
ReactNode,
|
|
|
|
useEffect
|
2020-10-28 10:32:56 +01:00
|
|
|
} from 'react'
|
2021-10-13 18:48:59 +02:00
|
|
|
import { fetchData } from '@utils/fetch'
|
2020-10-28 10:32:56 +01:00
|
|
|
import useSWR from 'swr'
|
2021-12-10 12:33:47 +01:00
|
|
|
import { LoggerInstance } from '@oceanprotocol/lib'
|
2022-04-22 02:38:35 +02:00
|
|
|
import { useMarketMetadata } from './MarketMetadata'
|
2020-10-28 10:32:56 +01:00
|
|
|
|
2022-02-07 15:58:47 +01:00
|
|
|
interface Prices {
|
2020-10-28 11:00:06 +01:00
|
|
|
[key: string]: number
|
2020-10-28 10:32:56 +01:00
|
|
|
}
|
|
|
|
|
2022-02-07 15:58:47 +01:00
|
|
|
interface PricesValue {
|
|
|
|
prices: Prices
|
|
|
|
}
|
|
|
|
|
|
|
|
const initialData: Prices = {
|
2020-10-28 11:00:06 +01:00
|
|
|
eur: 0.0,
|
|
|
|
usd: 0.0,
|
|
|
|
eth: 0.0,
|
|
|
|
btc: 0.0
|
2020-10-28 10:32:56 +01:00
|
|
|
}
|
|
|
|
|
2020-11-17 13:10:12 +01:00
|
|
|
const refreshInterval = 120000 // 120 sec.
|
|
|
|
|
2020-10-28 10:32:56 +01:00
|
|
|
const PricesContext = createContext(null)
|
|
|
|
|
|
|
|
export default function PricesProvider({
|
|
|
|
children
|
|
|
|
}: {
|
|
|
|
children: ReactNode
|
|
|
|
}): ReactElement {
|
2022-04-22 02:38:35 +02:00
|
|
|
const { appConfig } = useMarketMetadata()
|
2020-10-28 10:32:56 +01:00
|
|
|
const tokenId = 'ocean-protocol'
|
|
|
|
|
|
|
|
const [prices, setPrices] = useState(initialData)
|
2022-04-22 02:38:35 +02:00
|
|
|
const [url, setUrl] = useState('')
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!appConfig) return
|
|
|
|
// comma-separated list
|
|
|
|
const currencies = appConfig.currencies.join(',')
|
|
|
|
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=${currencies}`
|
|
|
|
setUrl(url)
|
|
|
|
}, [appConfig])
|
2020-10-28 10:32:56 +01:00
|
|
|
|
2022-02-07 15:58:47 +01:00
|
|
|
const onSuccess = async (data: { [tokenId]: Prices }) => {
|
2020-10-28 10:32:56 +01:00
|
|
|
if (!data) return
|
2021-12-10 12:33:47 +01:00
|
|
|
LoggerInstance.log('[prices] Got new OCEAN spot prices.', data[tokenId])
|
2020-10-28 11:00:06 +01:00
|
|
|
setPrices(data[tokenId])
|
2020-10-28 10:32:56 +01:00
|
|
|
}
|
|
|
|
|
2020-10-28 11:00:06 +01:00
|
|
|
// Fetch new prices periodically with swr
|
|
|
|
useSWR(url, fetchData, {
|
2020-11-17 13:10:12 +01:00
|
|
|
refreshInterval,
|
2020-10-28 11:00:06 +01:00
|
|
|
onSuccess
|
|
|
|
})
|
2020-10-28 10:32:56 +01:00
|
|
|
|
|
|
|
return (
|
|
|
|
<PricesContext.Provider value={{ prices }}>
|
|
|
|
{children}
|
|
|
|
</PricesContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helper hook to access the provider values
|
|
|
|
const usePrices = (): PricesValue => useContext(PricesContext)
|
|
|
|
|
2021-10-27 12:27:14 +02:00
|
|
|
export { PricesProvider, usePrices }
|