eip712.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const ethSigUtil = require('eth-sig-util');
  2. const keccak256 = require('keccak256');
  3. const EIP712Domain = [
  4. { name: 'name', type: 'string' },
  5. { name: 'version', type: 'string' },
  6. { name: 'chainId', type: 'uint256' },
  7. { name: 'verifyingContract', type: 'address' },
  8. ];
  9. const Permit = [
  10. { name: 'owner', type: 'address' },
  11. { name: 'spender', type: 'address' },
  12. { name: 'value', type: 'uint256' },
  13. { name: 'nonce', type: 'uint256' },
  14. { name: 'deadline', type: 'uint256' },
  15. ];
  16. function bufferToHexString (buffer) {
  17. return '0x' + buffer.toString('hex');
  18. }
  19. function hexStringToBuffer (hexstr) {
  20. return Buffer.from(hexstr.replace(/^0x/, ''), 'hex');
  21. }
  22. async function domainSeparator ({ name, version, chainId, verifyingContract }) {
  23. return bufferToHexString(
  24. ethSigUtil.TypedDataUtils.hashStruct(
  25. 'EIP712Domain',
  26. { name, version, chainId, verifyingContract },
  27. { EIP712Domain },
  28. ),
  29. );
  30. }
  31. async function hashTypedData (domain, structHash) {
  32. return domainSeparator(domain).then(separator => bufferToHexString(keccak256(Buffer.concat([
  33. '0x1901',
  34. separator,
  35. structHash,
  36. ].map(str => hexStringToBuffer(str))))));
  37. }
  38. module.exports = {
  39. EIP712Domain,
  40. Permit,
  41. domainSeparator,
  42. hashTypedData,
  43. };