diff --git a/client/dapp.js b/client/dapp.js index e4b40f8..61795d6 100644 --- a/client/dapp.js +++ b/client/dapp.js @@ -19,7 +19,44 @@ const DApp = { }, initWeb3: async function () { - // TODO implementation code + if (typeof window.ethereum !== 'undefined') { + // New web3 provider + // As per EIP1102 and EIP1193 + // Ref: https://eips.ethereum.org/EIPS/eip-1102 + // Ref: https://eips.ethereum.org/EIPS/eip-1193 + try { + // Request account access if needed + const accounts = await window.ethereum.request({ + method: 'eth_requestAccounts', + }); + // Accounts now exposed, use them + DApp.updateAccounts(accounts); + + // Opt out of refresh page on network change + // Ref: https://docs.metamask.io/guide/ethereum-provider.html#properties + ethereum.autoRefreshOnNetworkChange = false; + + // When user changes to another account, + // trigger necessary updates within DApp + window.ethereum.on('accountsChanged', DApp.updateAccounts); + } catch (error) { + // User denied account access + console.error('User denied web3 access'); + return; + } + DApp.web3 = new Web3(window.ethereum); + } + else if (window.web3) { + // Deprecated web3 provider + DApp.web3 = new Web3(web3.currentProvider); + // no need to ask for permission + } + // No web3 provider + else { + console.error('No web3 provider detected'); + return; + } + return DApp.initContract(); }, updateAccounts: async function(accounts) {