DEV Community

chandra penugonda
chandra penugonda

Posted on

Learn how to generate and verify signatures using ethers

ethers module provides complete Ethereum wallet implementation and utilities in JavaScript (and TypeScript).

importing ether

import { ethers } from "ethers"

Verify wallet installation

const isWalletInstalled = () => {
  if (!window.ethereum) {
    throw new Error("No crypto wallet found. Please install it.");
  } else {
    return true;
  }
};
Enter fullscreen mode Exit fullscreen mode

Request accounts

const requestAccount = async () => {
  if (!window.ethereum) {
    throw new Error("No crypto wallet found. Please install it.");
  }
  const accounts = await window.ethereum.send("eth_requestAccounts");
  if (accounts.result.length) {
    const account = accounts.result[0];
  }
};
Enter fullscreen mode Exit fullscreen mode

Using wallet to Sign a message

const signMessage = async (message) => {
  try {
    if (isWalletInstalled()) {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const signature = await signer.signMessage(message);
      const address = await signer.getAddress();
      return {
        signature,
        address,
      };
    }
  } catch (err) {
    console.log(err);
  }
};

Enter fullscreen mode Exit fullscreen mode

Verify message

const verifyMessage = async ({ message, address, signature }) => {
  try {
    const signerAddr = await ethers.utils.verifyMessage(message, signature);
    if (signerAddr !== address) {
      return false;
    }
    return true;
  } catch (err) {
    console.log(err);
    return false;
  }
Enter fullscreen mode Exit fullscreen mode

Credits: Artur Chmaro
Video reference

Top comments (0)