2020-03-22 23:51:54 +01:00
|
|
|
import React, { useState, useEffect } from 'react'
|
2020-02-25 04:10:06 +01:00
|
|
|
import PropTypes from 'prop-types'
|
|
|
|
import { PriceContext } from './createContext'
|
|
|
|
import { refreshInterval, conversions } from '../../config'
|
2020-03-22 23:51:54 +01:00
|
|
|
import { fetchData } from '../../utils'
|
|
|
|
import { convertPrices } from './helpers'
|
|
|
|
import useSWR from 'swr'
|
|
|
|
import ms from 'ms'
|
2020-10-10 15:37:05 +02:00
|
|
|
import electron from 'electron'
|
|
|
|
|
|
|
|
const ipcRenderer = electron.ipcRenderer || false
|
2020-02-25 04:10:06 +01:00
|
|
|
|
|
|
|
export default function PriceProvider({ children }) {
|
|
|
|
// construct initial prices Map to get consistent
|
|
|
|
// order for Ticker and Touchbar
|
|
|
|
let pricesMap = new Map()
|
|
|
|
pricesMap.set('ocean', 1)
|
2020-03-22 00:49:10 +01:00
|
|
|
conversions.map((key) => pricesMap.set(key, 0))
|
2020-02-25 04:10:06 +01:00
|
|
|
|
|
|
|
const [prices, setPrices] = useState(pricesMap)
|
|
|
|
const [priceChanges, setPriceChanges] = useState(
|
|
|
|
Object.assign(
|
2020-03-22 00:49:10 +01:00
|
|
|
...conversions.map((key) => ({
|
2020-02-25 04:10:06 +01:00
|
|
|
[key]: 0
|
|
|
|
}))
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2020-03-22 23:51:54 +01:00
|
|
|
// Fetch new prices periodically with swr
|
|
|
|
const currencies = conversions.join(',')
|
|
|
|
const url = `https://api.coingecko.com/api/v3/simple/price?ids=ocean-protocol&vs_currencies=${currencies}&include_24hr_change=true`
|
|
|
|
|
|
|
|
const { data } = useSWR(url, fetchData, {
|
|
|
|
refreshInterval: ms(refreshInterval),
|
|
|
|
onSuccess
|
|
|
|
})
|
|
|
|
|
|
|
|
async function onSuccess() {
|
|
|
|
if (!data) return
|
|
|
|
|
|
|
|
console.log('Got new prices.')
|
|
|
|
const { newPrices, newPriceChanges } = await convertPrices(data, prices)
|
|
|
|
|
|
|
|
setPrices(newPrices)
|
|
|
|
setPriceChanges(newPriceChanges)
|
2020-10-10 15:37:05 +02:00
|
|
|
ipcRenderer && ipcRenderer.send('prices-updated', Array.from(newPrices)) // convert Map to array, ipc messages seem to kill it
|
2020-03-22 23:51:54 +01:00
|
|
|
}
|
|
|
|
|
2020-02-25 04:10:06 +01:00
|
|
|
useEffect(() => {
|
|
|
|
async function init() {
|
2020-03-22 23:51:54 +01:00
|
|
|
await onSuccess()
|
2020-02-25 04:10:06 +01:00
|
|
|
}
|
|
|
|
init()
|
2020-03-22 23:51:54 +01:00
|
|
|
}, [data])
|
2020-02-25 04:10:06 +01:00
|
|
|
|
|
|
|
return (
|
|
|
|
<PriceContext.Provider value={{ prices, priceChanges }}>
|
|
|
|
{children}
|
|
|
|
</PriceContext.Provider>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
PriceProvider.propTypes = {
|
|
|
|
children: PropTypes.any.isRequired
|
|
|
|
}
|