Last active
September 21, 2024 01:23
-
-
Save daltyboy11/5a5a38ea8353164238d945c6d61e8c99 to your computer and use it in GitHub Desktop.
Client side signing + smart contract verification is tricky to get right and difficult to debug. Here's a working example with ethers v6 and OpenZeppelin to save you some time.
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
import { ethers, getBytes } from 'ethers'; | |
export async function signMessage(wallet: ethers.Wallet, msg: string) { | |
const messageHash = ethers.solidityPackedKeccak256(["string"], [msg]) | |
const messageHashBytes = getBytes(messageHash) | |
const flatSig = await wallet.signMessage(messageHashBytes); | |
const sig = ethers.Signature.from(flatSig); | |
return { | |
v: sig.v, | |
r: sig.r, | |
s: sig.s, | |
} | |
} | |
// Example usage | |
const seed = ethers.sha256(ethers.toUtf8Bytes("this is my private key :)")) | |
const dummyWallet = new ethers.Wallet(seed) | |
const message = "Hello World!" | |
const sig = await signMessage(dummyWallet, message) | |
// dummyWallet.address "0x83C5fCE9Fc6bf33F8eE0Bfa9F1e7D7359500EbFf" | |
// sig.v 28 | |
// sig.r "0x2e6d7805bb039c743dedf0b3bdd508d1a5a9520d5f6354116f7f3ca489950946" | |
// sig.s "0x387de5ed5a65e025e652d21d1a62582a986c8ec6e500f5ec590e6d7d8430c6ca" |
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
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; | |
address expectedSigner = 0x83C5fCE9Fc6bf33F8eE0Bfa9F1e7D7359500EbFf; // dummyWallet address from sign-message.ts | |
function verify(string memory message, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { | |
bytes32 messageHash = keccak256(abi.encodePacked(message)); | |
bytes32 ethSignedMessageHash = MessageHashUtils.toEthSignedMessageHash(messageHash); | |
address signer = ecrecover(ethSignedMessageHash, v, r, s); | |
return signer == expectedSigner; | |
} | |
// Example usage | |
verify( | |
"Hello World!", | |
28, | |
0x2e6d7805bb039c743dedf0b3bdd508d1a5a9520d5f6354116f7f3ca489950946, | |
0x387de5ed5a65e025e652d21d1a62582a986c8ec6e500f5ec590e6d7d8430c6ca | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment