2018-06-15 00:15:23 +02:00
|
|
|
module.exports = setupDappAutoReload
|
|
|
|
|
|
|
|
function setupDappAutoReload (web3, observable) {
|
|
|
|
// export web3 as a global, checking for usage
|
|
|
|
let reloadInProgress = false
|
|
|
|
let lastTimeUsed
|
|
|
|
let lastSeenNetwork
|
2019-11-01 01:26:02 +01:00
|
|
|
let hasBeenWarned = false
|
2018-06-15 00:15:23 +02:00
|
|
|
|
|
|
|
global.web3 = new Proxy(web3, {
|
|
|
|
get: (_web3, key) => {
|
|
|
|
// get the time of use
|
|
|
|
lastTimeUsed = Date.now()
|
2019-11-01 01:26:02 +01:00
|
|
|
// show warning once on web3 access
|
|
|
|
if (!hasBeenWarned && key !== 'currentProvider') {
|
2019-12-05 21:23:43 +01:00
|
|
|
console.warn('MetaMask: web3 will be deprecated in the near future in favor of the ethereumProvider\nhttps://medium.com/metamask/4a899ad6e59e')
|
2019-11-01 01:26:02 +01:00
|
|
|
hasBeenWarned = true
|
|
|
|
}
|
2018-06-15 00:15:23 +02:00
|
|
|
// return value normally
|
|
|
|
return _web3[key]
|
|
|
|
},
|
|
|
|
set: (_web3, key, value) => {
|
|
|
|
// set value normally
|
|
|
|
_web3[key] = value
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
observable.subscribe(function (state) {
|
2019-03-21 20:42:23 +01:00
|
|
|
// if the auto refresh on network change is false do not
|
|
|
|
// do anything
|
2019-12-05 21:23:43 +01:00
|
|
|
if (!window.ethereum.autoRefreshOnNetworkChange) return
|
2019-03-21 20:42:23 +01:00
|
|
|
|
2018-06-15 00:15:23 +02:00
|
|
|
// if reload in progress, no need to check reload logic
|
2019-12-05 21:23:43 +01:00
|
|
|
if (reloadInProgress) return
|
2018-06-15 00:15:23 +02:00
|
|
|
|
|
|
|
const currentNetwork = state.networkVersion
|
|
|
|
|
|
|
|
// set the initial network
|
|
|
|
if (!lastSeenNetwork) {
|
|
|
|
lastSeenNetwork = currentNetwork
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// skip reload logic if web3 not used
|
2019-12-05 21:23:43 +01:00
|
|
|
if (!lastTimeUsed) return
|
2018-06-15 00:15:23 +02:00
|
|
|
|
|
|
|
// if network did not change, exit
|
2019-12-05 21:23:43 +01:00
|
|
|
if (currentNetwork === lastSeenNetwork) return
|
2018-06-15 00:15:23 +02:00
|
|
|
|
|
|
|
// initiate page reload
|
|
|
|
reloadInProgress = true
|
|
|
|
const timeSinceUse = Date.now() - lastTimeUsed
|
|
|
|
// if web3 was recently used then delay the reloading of the page
|
|
|
|
if (timeSinceUse > 500) {
|
|
|
|
triggerReset()
|
|
|
|
} else {
|
|
|
|
setTimeout(triggerReset, 500)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// reload the page
|
|
|
|
function triggerReset () {
|
|
|
|
global.location.reload()
|
|
|
|
}
|