Update Staking DApp scripts

due to MetaMask breaking changes: https://docs.metamask.io/guide/provider-migration.html
pull/3460/head
POA 4 years ago
parent 84741f3db5
commit 0634c259e4
  1. 99
      apps/block_scout_web/assets/js/pages/stakes.js
  2. 4
      apps/block_scout_web/assets/js/pages/stakes/become_candidate.js
  3. 2
      apps/block_scout_web/assets/js/pages/stakes/claim_reward.js
  4. 2
      apps/block_scout_web/assets/js/pages/stakes/make_stake.js
  5. 6
      apps/block_scout_web/assets/js/pages/stakes/utils.js

@ -158,8 +158,6 @@ if ($stakesPage.length) {
} }
updating = true updating = true
const firstMsg = (state.currentBlockNumber === 0)
store.dispatch({ type: 'BLOCK_CREATED', currentBlockNumber: msg.block_number }) store.dispatch({ type: 'BLOCK_CREATED', currentBlockNumber: msg.block_number })
// hide tooltip on tooltip triggering element reloading // hide tooltip on tooltip triggering element reloading
@ -179,13 +177,9 @@ if ($stakesPage.length) {
msg.epoch_number > state.lastEpochNumber || msg.epoch_number > state.lastEpochNumber ||
msg.validator_set_apply_block !== state.validatorSetApplyBlock || msg.validator_set_apply_block !== state.validatorSetApplyBlock ||
(state.refreshInterval && msg.block_number >= state.refreshBlockNumber + state.refreshInterval) || (state.refreshInterval && msg.block_number >= state.refreshBlockNumber + state.refreshInterval) ||
accountChanged(msg.account, state) || msg.by_set_account accountChanged(msg.account, state) ||
msg.by_set_account
) { ) {
if (firstMsg) {
// Don't refresh the page for the first load
// as it is already refreshed by the `initialize` function.
msg.dont_refresh_page = true
}
await reloadPoolList(msg, store) await reloadPoolList(msg, store)
} }
@ -205,7 +199,6 @@ if ($stakesPage.length) {
if (!store.getState().finishRequestResolve) { if (!store.getState().finishRequestResolve) {
$refreshInformer.hide() $refreshInformer.hide()
$stakesPage.fadeTo(0, 0.5) $stakesPage.fadeTo(0, 0.5)
delete msg.dont_refresh_page // refresh anyway
await reloadPoolList(msg, store) await reloadPoolList(msg, store)
} }
}) })
@ -308,6 +301,28 @@ function accountChanged (account, state) {
return account !== state.account return account !== state.account
} }
async function getAccounts () {
let accounts = []
try {
accounts = await window.ethereum.request({ method: 'eth_accounts' })
} catch (e) {
console.error('eth_accounts request failed. Make sure you are using the latest version of MetaMask')
openErrorModal('Get account', 'Cannot get your account address. Make sure you are using the latest version of MetaMask')
}
return accounts
}
async function getNetId (web3) {
let netId = null
if (!window.ethereum.chainId) {
console.error('Cannot get chainId. Make sure you are using the latest MetaMask version')
} else {
const { chainId } = window.ethereum
netId = web3.utils.isHex(chainId) ? web3.utils.hexToNumber(chainId) : chainId
}
return netId
}
function hideCurrentModal () { function hideCurrentModal () {
const $modal = currentModal() const $modal = currentModal()
if ($modal) $modal.modal('hide') if ($modal) $modal.modal('hide')
@ -316,51 +331,63 @@ function hideCurrentModal () {
function initialize (store) { function initialize (store) {
if (window.ethereum) { if (window.ethereum) {
const web3 = new Web3(window.ethereum) const web3 = new Web3(window.ethereum)
window.ethereum.autoRefreshOnNetworkChange = false if (window.ethereum.autoRefreshOnNetworkChange) {
window.ethereum.autoRefreshOnNetworkChange = false
}
store.dispatch({ type: 'WEB3_DETECTED', web3 }) store.dispatch({ type: 'WEB3_DETECTED', web3 })
checkNetworkAndAccount(store, web3) initNetworkAndAccount(store, web3)
window.ethereum.on('chainChanged', async (chainId) => {
const newNetId = web3.utils.isHex(chainId) ? web3.utils.hexToNumber(chainId) : chainId
setNetwork(newNetId, store)
})
window.ethereum.on('accountsChanged', async (accs) => {
const newAccount = accs && accs.length > 0 ? accs[0].toLowerCase() : null
if (accountChanged(newAccount, store.getState())) {
await setAccount(newAccount, store)
}
})
$stakesTop.on('click', '[data-selector="login-button"]', loginByMetamask) $stakesTop.on('click', '[data-selector="login-button"]', loginByMetamask)
} else { } else {
// We do the first load immediately if the latest version of MetaMask is not installed
refreshPageWrapper(store) refreshPageWrapper(store)
} }
} }
async function checkNetworkAndAccount (store, web3) { async function initNetworkAndAccount (store, web3) {
const networkId = await web3.eth.net.getId()
const state = store.getState() const state = store.getState()
let refresh = false const networkId = await getNetId(web3)
if (!state.network || (networkId !== state.network.id)) { if (!state.network || (networkId !== state.network.id)) {
setNetwork(networkId, store) setNetwork(networkId, store)
refresh = true
} }
const accounts = await web3.eth.getAccounts() const accounts = await getAccounts()
const account = accounts[0] ? accounts[0].toLowerCase() : null const account = accounts[0] ? accounts[0].toLowerCase() : null
if (accountChanged(account, state) && await setAccount(account, store)) { if (accountChanged(account, state)) {
refresh = false // because refreshing will be done by `onStakingUpdate` await setAccount(account, store)
} // We don't call `refreshPageWrapper` in this case because it will be called
// by the `onStakingUpdate` function
if (refresh) { } else {
await refreshPageWrapper(store) await refreshPageWrapper(store)
} }
setTimeout(() => {
checkNetworkAndAccount(store, web3)
}, 100)
} }
async function loginByMetamask () { async function loginByMetamask () {
event.stopPropagation() event.stopPropagation()
event.preventDefault() event.preventDefault()
try { try {
await window.ethereum.enable() await window.ethereum.request({ method: 'eth_requestAccounts' })
} catch (e) { } catch (e) {
console.log(e) console.log(e)
console.error('User denied account access') if (e.code !== 4001) {
console.error('eth_requestAccounts failed. Make sure you are using the latest MetaMask version')
openErrorModal('Request account access', 'Cannot request access to your account in MetaMask. Make sure you are using the latest version of MetaMask')
}
} }
} }
@ -394,9 +421,7 @@ async function reloadPoolList (msg, store) {
stakingTokenDefined: msg.staking_token_defined, stakingTokenDefined: msg.staking_token_defined,
validatorSetApplyBlock: msg.validator_set_apply_block validatorSetApplyBlock: msg.validator_set_apply_block
}) })
if (!msg.dont_refresh_page) { await refreshPageWrapper(store)
await refreshPageWrapper(store)
}
} }
function resetFilterMy (store) { function resetFilterMy (store) {
@ -417,11 +442,13 @@ function setAccount (account, store) {
store.getState().channel.push( store.getState().channel.push(
'set_account', account 'set_account', account
).receive('ok', () => { ).receive('ok', () => {
$addressField.html(` if (account) {
<div data-placement="bottom" data-toggle="tooltip" title="${account}"> $addressField.html(`
${account} <div data-placement="bottom" data-toggle="tooltip" title="${account}">
</div> ${account}
`) </div>
`)
}
hideCurrentModal() hideCurrentModal()
resolve(true) resolve(true)
}).receive('error', () => { }).receive('error', () => {
@ -468,7 +495,7 @@ function updateFilters (store, filterType) {
if (filterType === 'my' && !state.account) { if (filterType === 'my' && !state.account) {
filterMy.prop('checked', false) filterMy.prop('checked', false)
openWarningModal('Unauthorized', 'Please login with MetaMask') openWarningModal('Unauthorized', 'You are not logged in. Please login with the latest version of MetaMask')
return return
} }
store.dispatch({ store.dispatch({

@ -10,7 +10,7 @@ export async function openBecomeCandidateModal (event, store) {
const state = store.getState() const state = store.getState()
if (!state.account) { if (!state.account) {
openWarningModal('Unauthorized', 'You haven\'t approved the reading of account list from your MetaMask or MetaMask is not installed.') openWarningModal('Unauthorized', 'You haven\'t approved the reading of account list from your MetaMask or the latest MetaMask is not installed.')
return return
} }
@ -93,6 +93,8 @@ async function becomeCandidate ($modal, store, msg) {
} }
lockModal($modal) lockModal($modal)
console.log(`Call addPool(${stake.toString()}, ${miningAddress})`)
makeContractCall(stakingContract.methods.addPool(stake.toString(), miningAddress), store) makeContractCall(stakingContract.methods.addPool(stake.toString(), miningAddress), store)
} catch (err) { } catch (err) {
openErrorModal('Error', err.message) openErrorModal('Error', err.message)

@ -17,7 +17,7 @@ export function openClaimRewardModal (event, store) {
const state = store.getState() const state = store.getState()
if (!state.account) { if (!state.account) {
openWarningModal('Unauthorized', 'Please login with MetaMask') openWarningModal('Unauthorized', 'You are not logged in. Please login with the latest version of MetaMask')
return return
} }

@ -8,7 +8,7 @@ export function openMakeStakeModal (event, store) {
const state = store.getState() const state = store.getState()
if (!state.account) { if (!state.account) {
openWarningModal('Unauthorized', 'You haven\'t approved the reading of account list from your MetaMask or MetaMask is not installed.') openWarningModal('Unauthorized', 'You haven\'t approved the reading of account list from your MetaMask or the latest MetaMask is not installed.')
return return
} }

@ -19,7 +19,7 @@ export async function makeContractCall (call, store, gasLimit, callbackFunc) {
} }
if (!from) { if (!from) {
return callbackFunc('Your MetaMask account is undefined. Please, contact support.') return callbackFunc('Your MetaMask account is undefined. Please, ensure you are using the latest MetaMask and connected it to the page')
} else if (!web3) { } else if (!web3) {
return callbackFunc('Web3 is undefined. Please, contact support.') return callbackFunc('Web3 is undefined. Please, contact support.')
} }
@ -30,6 +30,8 @@ export async function makeContractCall (call, store, gasLimit, callbackFunc) {
try { try {
gasLimit = await call.estimateGas({ from, gasPrice }) gasLimit = await call.estimateGas({ from, gasPrice })
} catch (e) { } catch (e) {
console.log(`from = ${from}`)
console.error(e)
return callbackFunc('Your transaction cannot be mined at the moment. Please, try again in a few blocks.') return callbackFunc('Your transaction cannot be mined at the moment. Please, try again in a few blocks.')
} }
} }
@ -128,7 +130,7 @@ export function isSupportedNetwork (store) {
if (state.network && state.network.authorized) { if (state.network && state.network.authorized) {
return true return true
} }
openWarningModal('Unauthorized', 'Please, connect to the xDai Chain.<br /><a href="https://xdaichain.com" target="_blank">Instructions</a>') openWarningModal('Unauthorized', 'Please, connect to the xDai Chain.<br /><a href="https://xdaichain.com" target="_blank">Instructions</a>. If you have already connected to, please update MetaMask to the latest version.')
return false return false
} }

Loading…
Cancel
Save