Skip to content

Instantly share code, notes, and snippets.

@CQBinh
Last active April 22, 2022 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CQBinh/b35ef09fc499642b623ec1dba2c41e70 to your computer and use it in GitHub Desktop.
Save CQBinh/b35ef09fc499642b623ec1dba2c41e70 to your computer and use it in GitHub Desktop.
Sign the eip-712 message using privateKey with nodejs
const MessageVerifier = artifacts.require('./MessageVerifier.sol')
module.exports = async function (deployer, network, accounts) {
deployer.deploy(MessageVerifier, "BinhCAO", "1")
}
import { ecsign } from 'ethereumjs-util'
import { getMessage } from 'eip-712'
function signMessageFooFunction(verifyingContract, message, privateKey) {
const typedData = {
types: {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' }
],
FooFunction: [
{ name: 'anAddress', type: 'address' },
{ name: 'aString', type: 'string' },
{ name: 'aNumber', type: 'uint256' }
]
},
primaryType: 'FooFunction',
domain: {
name: 'BinhCAO',
version: '1',
chainId: 56, // BSC mainnet (https://chainlist.org)
verifyingContract
},
message
};
const messageFromData = getMessage(typedData, true)
const { r, s, v } = ecsign(messageFromData, Buffer.from(privateKey, 'hex'))
return `0x${r.toString('hex')}${s.toString('hex')}${v.toString(16)}`
}
const signature = signMessageFooFunction(
'0x1D957802B2a85AF834c53F400F9bbf05b5C6B976',
{
anAddress: '0x63C1b5176117b8Cb38A5CCa6a0103A732eb65a9a',
aString: 'nhatky.dev',
aNumber: 69
},
'0xea860da83e80557650f951da0b640438596aa6e5a8ce7a21c4236c97a58375b8'
)
console.log({signature})
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
contract MessageVerifier is EIP712 {
constructor(string memory _name, string memory _version) EIP712(_name, _version) {
}
function validateFooFunction(
string calldata _aString,
uint256 _aNumber,
bytes memory _signature
) external view returns (address){
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("FooFunction(address anAddress,string aString,uint256 aNumber)"),
msg.sender,
keccak256(bytes(_aString)),
_aNumber
)));
address signer = ECDSA.recover(digest, _signature);
require(signer == msg.sender, "MessageVerifier: invalid signature");
require(signer != address(0), "ECDSAUpgradeable: invalid signature");
return signer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment