I know that I can sign a message using web3js, but I don't know how I can do that, then how to verify that signature using ecrecover()?
1 Answer
You can use metamask to sign transaction see their example
https://docs.metamask.io/guide/signing-data.html#sign-typed-data-v4
Basically the steps are,
const keep_it_hidden = process.env.Key; // this is a private key
const CHAINID = 1;
const hash_data = web3.utils.soliditySha3(CHAINID, accounts[0] , "some data" ); // any data you want the func to hash
const sign = await web3.eth.accounts.sign(hash_data, keep_it_hidden )['signature'] // sign the hashed data
Now in the smart contract import the Elliptic Curve Digital Signature Algorithm (ECDSA) operations from OpenZeppelin, you have sign as signature
you can run using e.g recover
method and toEthSignedMessageHash
for hash the message in the contract
I hope this is clear