eip712.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 =>
  33. bufferToHexString(keccak256(Buffer.concat(['0x1901', separator, structHash].map(str => hexStringToBuffer(str))))),
  34. );
  35. }
  36. module.exports = {
  37. EIP712Domain,
  38. Permit,
  39. domainSeparator,
  40. hashTypedData,
  41. };