0

I'm trying to connect to Metamask using ethers.js.

However, all the solution I found keep returning this error

"await is only valid in async function"

Was there a recent change in Javascript syntax that affects await?

How to connect ethers.js with metamask?

const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
// Prompt user for account connections
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
console.log("Account:", await signer.getAddress());

how to connect metamask with ethers.js and fetch balance?

await window.ethereum.enable();
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(smartContractAddress, abi, provider);
balance = await contract.getBalance("0x7C76C63DB86bfB5437f7426F4C37b15098Bb81da");
Curio
  • 33
  • 1
  • 6
  • Since `await` was introduced, it has only been allowed in `async` functions, except much more recently in the top level of a module. – Pointy Sep 10 '21 at 04:32
  • This error has nothing to do with ethers... promises, async, and await are core to how all of javascript works... – Jim Dec 13 '21 at 00:48

1 Answers1

0

You should put await in async function to work, like this:

async function connectToMetamask(){
   const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
   // Prompt user for account connections
   await provider.send("eth_requestAccounts", []);
   const signer = provider.getSigner();
   console.log("Account:", await signer.getAddress());
}
Ahmad Gorji
  • 424
  • 3
  • 10