Skip to content

Instantly share code, notes, and snippets.

@tatsuyasusukida
Created August 19, 2022 02:23
Show Gist options
  • Save tatsuyasusukida/af5e160fac7b88c151ebca6b653b9135 to your computer and use it in GitHub Desktop.
Save tatsuyasusukida/af5e160fac7b88c151ebca6b653b9135 to your computer and use it in GitHub Desktop.
✍️ How to sign with MetaMask and verify with Node.js using ethers.js
import { useState } from "react"
import { ethers } from "ethers"
export default function Sign() {
const [isVerified, setIsVerified] = useState(false)
const onClick = async () => {
if (!window.ethereum) {
console.error('!window.ethereum')
return
}
const provider = new ethers.providers.Web3Provider(window.ethereum)
await provider.send('eth_requestAccounts', [])
const signer = await provider.getSigner()
const message = 'message'
const address = await signer.getAddress()
const signature = await signer.signMessage(message)
const response = await fetch('/api/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({ message, address, signature }),
})
const body = await response.json()
setIsVerified(body.isVerified)
}
return (
<>
<button onClick={onClick}>Sign</button>
{isVerified && <p>Verified!</p>}
</>
)
}
import { ethers } from "ethers"
export default async function apiVerify (req, res) {
const {message, address: expected, signature} = req.body
const digest = ethers.utils.hashMessage(message)
const actual = ethers.utils.recoverAddress(digest, signature)
const isVerified = actual === expected
res.send({isVerified})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment