I use this code to connect ui with smart contract

  window.addEventListener('load', () => {
     // Wait for loading completion to avoid race conditions with web3 injection timing.
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          currentAddress = web3js.eth.accounts[0]
          // Acccounts now exposed
          return web3;
        } catch (error) {
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log('Injected web3 detected.');
        return web3;
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/abikeygoeshere');
        const web3 = new Web3(provider);
        console.log('No web3 instance injected, using Local web3.');
        return web3;

but in my console i get this error

exchange.js:41 Uncaught SyntaxError: await is only valid in async function

this is in line 41

await window.ethereum.enable();

how can i fix this?


Change line:

window.addEventListener('load', () => {


window.addEventListener('load', async () => {
  • now i get even more errors – yappy twan Jan 17 '20 at 9:03
  • List them here so we can inspect. Errors are something daily in this job, so get used to them :) – Miroslav Nedelchev Jan 17 '20 at 9:08
  • these are the errors im getting now Uncaught Error: Invalid JSON RPC response: undefined at Object.InvalidResponse (inpage.js:1) at a.send (inpage.js:1) at w.e [as getBalance] (inpage.js:1) at exchange.js:43 InvalidResponse @ inpage.js:1 a.send @ inpage.js:1 e @ inpage.js:1 (anonymous) @ exchange.js:43 – yappy twan Jan 17 '20 at 9:09
  • Start with debugging your provider and web3. Are you sure you initiated your infura application correctly? DId you place your infura api key correctly at this row: const provider = new Web3.providers.HttpProvider('ropsten.infura.io/v3/abikeygoeshere'); – Miroslav Nedelchev Jan 17 '20 at 9:18
  • the error came from those 2 lines: let contract = web3.eth.getBalance('0xE462CbEE0cd420f6c199B0194B1D8D93Fb5e7720'); //document.getElementById('agiContractBalance').value =contract; console.log(contract); – yappy twan Jan 17 '20 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.