classic-ui/store/settings.js

97 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2022-04-22 06:05:56 +03:00
/* eslint-disable no-console */
import Web3 from 'web3'
import networkConfig from '@/networkConfig'
const getFirstRpcs = (acc, [netId, { rpcUrls }]) => {
const [rpc] = Object.values(rpcUrls)
acc[netId] = {
rpc
}
return acc
}
const rpcData = Object.entries(networkConfig).reduce(getFirstRpcs, {})
export const state = () => {
return {
...rpcData,
isActiveNotification: {
first: true,
2022-06-06 17:26:00 +03:00
second: true,
third: true
2022-04-22 06:05:56 +03:00
}
}
}
export const getters = {
getRpc: (state) => (netId) => {
return state[`netId${netId}`].rpc
},
currentRpc: (state, getters, rootState) => {
const netId = rootState.metamask.netId
return state[`netId${netId}`].rpc
}
}
export const mutations = {
SAVE_RPC(state, { netId, name, url }) {
this._vm.$set(state[`netId${netId}`], 'rpc', { name, url })
},
DISABLE_NOTIFICATION(state, { key }) {
this._vm.$set(state, 'isActiveNotification', { ...state.isActiveNotification, [key]: false })
}
}
export const actions = {
disableNotification({ commit }, params) {
commit('DISABLE_NOTIFICATION', params)
},
async checkCurrentRpc({ dispatch, getters, rootGetters }) {
const netId = rootGetters['metamask/netId']
2022-12-03 19:02:03 +03:00
if (netId !== 1) {
await dispatch('preselectRpc', { netId: 1, isEthRpc: true })
}
2022-04-22 06:05:56 +03:00
await dispatch('preselectRpc', { netId })
},
2022-12-03 19:02:03 +03:00
async preselectRpc({ getters, commit, dispatch }, { netId, isEthRpc = false }) {
2022-04-22 06:05:56 +03:00
const savedRpc = getters.getRpc(netId)
2022-12-03 19:02:03 +03:00
const { isValid } = await dispatch('checkRpc', { ...savedRpc, netId, isEthRpc })
2022-04-22 06:05:56 +03:00
if (isValid) {
return
}
const { rpcUrls } = networkConfig[`netId${netId}`]
for (const [, { name, url }] of Object.entries(rpcUrls)) {
2022-12-03 19:02:03 +03:00
const { isValid, error } = await dispatch('checkRpc', { url, netId, isEthRpc })
2022-04-22 06:05:56 +03:00
if (isValid) {
commit('SAVE_RPC', { netId, name, url })
return
} else {
console.error('preselectRpc', url, error)
}
}
throw new Error(this.app.i18n.t('rpcSelectError'))
},
2022-12-03 19:02:03 +03:00
async checkRpc(_, { url, netId, isEthRpc = false }) {
2022-04-22 06:05:56 +03:00
try {
const web3 = new Web3(url)
const chainId = await web3.eth.getChainId()
const isCurrent = Number(chainId) === Number(netId)
2022-12-03 19:02:03 +03:00
if (isEthRpc || isCurrent) {
2022-04-22 06:05:56 +03:00
return { isValid: true }
} else {
return { isValid: false, error: this.app.i18n.t('thisRpcIsForDifferentNetwork') }
}
} catch (e) {
console.error('checkRpc', e)
return { isValid: false, error: this.app.i18n.t('rpcIsDown') }
}
}
}