classic-ui/store/price.js

64 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2022-04-22 06:05:56 +03:00
/* eslint-disable no-console */
import { TokenPriceOracle } from '@tornado/tornado-oracles'
2022-04-22 06:05:56 +03:00
export const state = () => {
return {
prices: {
torn: '1607657994944809',
dai: '604623353553108',
cdai: '13524059864784',
usdc: '600920027684692',
usdt: '600764414690498',
wbtc: '15636492243151834302'
2022-04-22 06:05:56 +03:00
}
}
}
export const getters = {
priceOracle: (state, getters, rootState, rootGetters) => {
const netId = Number(rootGetters['metamask/netId'])
const { url: rpcUrl } = rootState.settings[`netId${netId}`].rpc
return new TokenPriceOracle(rpcUrl)
2022-04-22 06:05:56 +03:00
},
tokenRate: (state, getters, rootState) => {
return state.prices[rootState.application.selectedStatistic.currency]
2022-04-22 06:05:56 +03:00
},
getTokenPrice: (state) => (currency) => {
2022-04-22 06:05:56 +03:00
return state.prices[currency]
},
isPriceWatcherDisabled: (state, getters, rootState, rootGetters) => {
const nativeCurrency = rootGetters['metamask/nativeCurrency']
const tokens = Object.keys(rootGetters['metamask/networkConfig'].tokens)
return tokens.includes(nativeCurrency) && tokens.length === 1
}
}
export const mutations = {
SAVE_TOKEN_PRICES(state, prices) {
state.prices = {
...state.prices,
...prices
}
}
}
export const actions = {
async fetchTokenPrice({ getters, commit, dispatch, rootState }) {
if (getters.isPriceWatcherDisabled) {
return
}
try {
const prices = await getters.priceOracle.fetchPrices()
2022-04-22 06:05:56 +03:00
console.log('prices', prices)
commit('SAVE_TOKEN_PRICES', prices)
setTimeout(() => dispatch('fetchTokenPrice'), 1000 * 30)
} catch (e) {
console.error(e)
setTimeout(() => dispatch('fetchTokenPrice'), 1000 * 30)
}
}
}