sign.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string legnth
  2. const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length
  3. const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`;
  4. function toEthSignedMessageHash (messageHex) {
  5. const messageBuffer = Buffer.from(messageHex.substring(2), 'hex');
  6. const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`);
  7. return web3.utils.sha3(Buffer.concat([prefix, messageBuffer]));
  8. }
  9. // signs message in node (ganache auto-applies "Ethereum Signed Message" prefix)
  10. const signMessage = (signer, messageHex = '0x') => {
  11. return web3.eth.sign(messageHex, signer);
  12. };
  13. /**
  14. * Create a signer between a contract and a signer for a voucher of method, args, and redeemer
  15. * Note that `method` is the web3 method, not the truffle-contract method
  16. * @param contract TruffleContract
  17. * @param signer address
  18. * @param redeemer address
  19. * @param methodName string
  20. * @param methodArgs any[]
  21. */
  22. const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = []) => {
  23. const parts = [
  24. contract.address,
  25. redeemer,
  26. ];
  27. // if we have a method, add it to the parts that we're signing
  28. if (methodName) {
  29. if (methodArgs.length > 0) {
  30. parts.push(
  31. contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])).encodeABI()
  32. .slice(0, -1 * PADDED_SIGNATURE_SIZE)
  33. );
  34. } else {
  35. const abi = contract.abi.find(abi => abi.name === methodName);
  36. parts.push(abi.signature);
  37. }
  38. }
  39. // return the signature of the "Ethereum Signed Message" hash of the hash of `parts`
  40. const messageHex = web3.utils.soliditySha3(...parts);
  41. return signMessage(signer, messageHex);
  42. };
  43. module.exports = {
  44. signMessage,
  45. toEthSignedMessageHash,
  46. getSignFor,
  47. };