Skip to content

Instantly share code, notes, and snippets.

@AlbertLin0327
Created February 21, 2022 07:03
Show Gist options
  • Save AlbertLin0327/ddc47c25f047d3fd54fe41459bbbd654 to your computer and use it in GitHub Desktop.
Save AlbertLin0327/ddc47c25f047d3fd54fe41459bbbd654 to your computer and use it in GitHub Desktop.
Sign the message at backend
import Web3 from "web3";
import dotenv from "dotenv";
// Establish web3 provider
dotenv.config();
const web3 = new Web3(process.env.MAINNET_RPC_URL);
const generateNonce = () => {
return crypto.randomBytes(16).toString("hex");
};
// Hash message
const mintMsgHash = (recipient, amount, newNonce, contract) => {
return (
web3.utils.soliditySha3(
{ t: "address", v: recipient },
{ t: "uint256", v: amount },
{ t: "string", v: newNonce },
{ t: "address", v: contract }
) || ""
);
};
const signMessage = (msgHash, privateKey) => {
return web3.eth.accounts.sign(msgHash, privateKey);
};
// Signing the message at backend.
// You can store the data at database or check for Nonce conflict
export const Signing = (address, amount) => {
const newNonce = generateNonce();
const hash = mintMsgHash(
address,
amount,
newNonce,
config.ContractAddress
);
const signner = signMessage(hash, config.PrivateKey);
return {
amount: amount,
nonce: newNonce,
hash: signner.message,
signature: signner.signature,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment