Skip to content

Instantly share code, notes, and snippets.

@enricobottazzi
Created May 30, 2023 15:02
Show Gist options
  • Save enricobottazzi/58c52754cabd8dd8e7ee9ed5d7591814 to your computer and use it in GitHub Desktop.
Save enricobottazzi/58c52754cabd8dd8e7ee9ed5d7591814 to your computer and use it in GitHub Desktop.
const { ethers } = require("ethers");
async function sign(privKey, message) {
// Create a Wallet instance
const wallet = new ethers.Wallet(privKey);
// Sign the message
const signature = await wallet.signMessage(message);
// Parse the signature and get r and s
// r is "0x" + sig.slice(2, 2 + 64))
// s is "0x" + sig.slice(66, 66 + 64)
const rHex = "0x" + signature.slice(2, 2 + 64);
const sHex = "0x" + signature.slice(66, 66 + 64);
const r = ethers.utils.arrayify(rHex).reverse();
const s = ethers.utils.arrayify(sHex).reverse();
// Compute the hash of the message
const messageHashHex = ethers.utils.hashMessage(message);
// Convert message hash from hex to byte array
const messageHash = ethers.utils.arrayify(messageHashHex).reverse();
// add 0x to the private key and convert to byte array
const privKeyHex = "0x" + privKey;
const privKeyBytes = ethers.utils.arrayify(privKeyHex).reverse();
return {
privKeyHex,
privKeyBytes,
signature,
rHex,
r,
sHex,
s,
messageHashHex,
messageHash,
};
}
signAndCompute('[YOUR PRIVATE KEY]', 'helloworld!')
.then(console.log)
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment