Last active
February 7, 2022 17:01
-
-
Save ReidWilliams/5abcd51270395f2d66aca7bcb6c3f4a4 to your computer and use it in GitHub Desktop.
Skeleton for signing a message with Metamask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<script type="module"> | |
// Use a simple local http server like 'python3 -m http.server' | |
// Needs to liston on port 8000 | |
// Janky, but I use a local copy of the Ethers libray to avoid CORS headaches | |
// https://cdn.ethers.io/lib/ethers-5.2.esm.min.js | |
// Ethers docs: | |
// https://docs.ethers.io/v5/getting-started/ | |
// Another helpful resource is: | |
// https://docs.metamask.io/guide/ethereum-provider.html#using-the-provider | |
// The way this all works is Metamask (and any compliant wallet) injects | |
// an object into every page at window.ethereum which provides an API for | |
// interacting with Metamask and the Ethereum network. Ethers is a convenient | |
// wrapper libary for this interface. | |
import { ethers } from "http://localhost:8000/ethers-5.2.esm.min.js"; | |
// Most of this is grabbed straight from: | |
// https://docs.ethers.io/v5/getting-started/#getting-started--connecting | |
// A Web3Provider wraps a standard Web3 provider, which is | |
// what MetaMask injects as window.ethereum into each page | |
const provider = new ethers.providers.Web3Provider(window.ethereum); | |
// MetaMask requires requesting permission to connect users accounts | |
// If Metamask is locked, this will open the window to provide the MM password | |
await provider.send("eth_requestAccounts", []); | |
// The MetaMask plugin also allows signing transactions to | |
// send ether and pay to change state within the blockchain. | |
// For this, you need the account signer... | |
const signer = provider.getSigner(); | |
const address = await signer.getAddress(); | |
console.log(`Connected as ${address}`); | |
const msg = "Come on Teenage Engineering. Do it!!!"; | |
// This will open a Metamask window and ask user to sign the message | |
const signedMessage = await signer.signMessage(msg); | |
console.log(`"${msg}" was signed by ${address}:`); | |
console.log(signedMessage); | |
console.log(`You can verify at https://etherscan.io/verifySig`); | |
// debugger | |
</script> | |
Hello Web3 World | |
<br> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment