Skip to content

Instantly share code, notes, and snippets.

@minute-med
Last active March 14, 2022 12:44
Show Gist options
  • Save minute-med/c0341190af15d711c98ff057b2cdea9f to your computer and use it in GitHub Desktop.
Save minute-med/c0341190af15d711c98ff057b2cdea9f to your computer and use it in GitHub Desktop.
Express verify signed message from metamask

Express verify signed message from metamask

this gist show you how you can verify in express a message signature generated by web3 with the metamask injected provider using the etherjs library

initial setup

cd /tmp && mkdir test-evm-sign && cd test-evm-sign
yarn init -y
yarn add express ethers
touch index.js # copy paste content of below's index.js in this file
touch index.html # copy paste content of below's index.html in this file
node index.js # browse http://localhost:3000/ metamask popup show at page load to sign message 'hello' 

index.js

const path = require('path')
const express = require('express')
const ethers = require('ethers')

const app = express()
const port = 3001

app.use(express.json())

app.get('/', (req,res) => {
	res.sendFile(path.join(__dirname+'/index.html'))
})

app.post('/verify', (req, res) => {

  const { signer, signature, message } = req.body

  const msgHash = ethers.utils.hashMessage(message)
  const msgHashBytes = ethers.utils.arrayify(msgHash)

  const recoveredPubKey = ethers.utils.recoverAddress(msgHashBytes, signature)

  res.json(signer === recoveredPubKey)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

index.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/5.5.4/ethers.umd.min.js" integrity="sha512-xmbPx0riylir51GhTZCFd20yS7NYZNpfDTbEWBjDRzs+UaGb2RyjtASTVtF2ydQWp3xkso9j4sJj39PdSH8/EA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" type="module">
window.addEventListener('DOMContentLoaded',async (event) => {

	const provider = new ethers.providers.Web3Provider(window.ethereum)
	const signer = provider.getSigner()
	const sig = await signer.signMessage('hello')

	const reqBody = {
		signer: await signer.getAddress(),
		signature: sig,
		message: 'hello'
	};

	const rawResponse = await fetch('http://localhost:3000/verify', {
	    method: 'POST',
	    headers: {
	      'Accept': 'application/json',
	      'Content-Type': 'application/json'
	    },
	    body: JSON.stringify(reqBody)
	  });
	  const isVerified = await rawResponse.json();
	  console.log(`isVerified: ${isVerified}`)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment