2020-10-28 10:32:56 +01:00
|
|
|
import React, {
|
|
|
|
useState,
|
|
|
|
ReactElement,
|
|
|
|
createContext,
|
|
|
|
useContext,
|
|
|
|
ReactNode
|
|
|
|
} from 'react'
|
|
|
|
import { fetchData } from '../utils'
|
|
|
|
import useSWR from 'swr'
|
|
|
|
import { useSiteMetadata } from '../hooks/useSiteMetadata'
|
|
|
|
import { Logger } from '@oceanprotocol/lib'
|
|
|
|
|
|
|
|
interface PricesValue {
|
2020-10-28 11:00:06 +01:00
|
|
|
[key: string]: number
|
2020-10-28 10:32:56 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const initialData: PricesValue = {
|
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 {
|
|
|
|
const { appConfig } = useSiteMetadata()
|
|
|
|
const tokenId = 'ocean-protocol'
|
|
|
|
const currencies = appConfig.currencies.join(',') // comma-separated list
|
2020-10-28 11:00:06 +01:00
|
|
|
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=${currencies}`
|
2020-10-28 10:32:56 +01:00
|
|
|
|
|
|
|
const [prices, setPrices] = useState(initialData)
|
|
|
|
|
2020-10-28 11:00:06 +01:00
|
|
|
const onSuccess = async (data: { [tokenId]: { [key: string]: number } }) => {
|
2020-10-28 10:32:56 +01:00
|
|
|
if (!data) return
|
2021-03-17 11:44:26 +01:00
|
|
|
Logger.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)
|
|
|
|
|
|
|
|
export { PricesProvider, usePrices, PricesValue }
|