Skip to content

Instantly share code, notes, and snippets.

@manumonti
Last active May 16, 2024 10:24
Show Gist options
  • Save manumonti/3014fdda62c5149002e1518e4658c8d7 to your computer and use it in GitHub Desktop.
Save manumonti/3014fdda62c5149002e1518e4658c8d7 to your computer and use it in GitHub Desktop.
Off-chain generation of signature using Ethers.js and on-chain verification
import { ethers } from 'ethers';
const signerPrivateKey = "0x900edb9e8214b2353f82aa195e915128f419a92cfb8bbc0f4784f10ef4112b86";
const signer = new ethers.Wallet(signerPrivateKey);
const nonce = 'hello';
const signature = await signer.signMessage(nonce);
// The recovered address should be the same than the signer address
console.log('Address:', signer.address);
console.log(
'Recovered address:',
ethers.utils.recoverAddress(ethers.utils.hashMessage(nonce), signature),
);
const nonceHex = ethers.utils.hexlify(ethers.utils.toUtf8Bytes(nonce);
// These are the arguments of verifySignature smart-contract method
console.log('nonce:', noceHex);
console.log('signature:', signature);
console.log('signer:', signer.address);

This is an example about how to generate a Ethereum signature using Ethers.js functions.

This also includes smart-contract code to verify the signature.

Deployed on Sepolia: 0xd6da38bf53801f1c7707ed2c5f9eba15e80e33ae.

The generated signature is EIP-191 compliant.

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
contract SignatureVerification {
using ECDSA for bytes32;
using MessageHashUtils for bytes;
function verifySignature(
bytes memory message,
bytes memory signature,
address signer
) public pure returns (bool) {
return message.toEthSignedMessageHash().recover(signature) == signer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment