sign.js 897 B

12345678910111213141516171819202122
  1. import utils from 'ethereumjs-util';
  2. /**
  3. * Hash and add same prefix to the hash that ganache use.
  4. * @param {string} message the plaintext/ascii/original message
  5. * @return {string} the hash of the message, prefixed, and then hashed again
  6. */
  7. export const hashMessage = (message) => {
  8. const messageHex = Buffer.from(utils.sha3(message).toString('hex'), 'hex');
  9. const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString());
  10. return utils.bufferToHex(utils.sha3(Buffer.concat([prefix, messageHex])));
  11. };
  12. // signs message using web3 (auto-applies prefix)
  13. export const signMessage = (signer, message = '', options = {}) => {
  14. return web3.eth.sign(signer, web3.sha3(message, options));
  15. };
  16. // signs hex string using web3 (auto-applies prefix)
  17. export const signHex = (signer, message = '') => {
  18. return signMessage(signer, message, { encoding: 'hex' });
  19. };