Learn how to generate and verify signatures using ethers
chandra penugonda
Posted on April 13, 2022
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;
}
};
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];
}
};
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);
}
};
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;
}
Credits: Artur Chmaro
Video reference
💖 💪 🙅 🚩
chandra penugonda
Posted on April 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.