eip712.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const { ethers } = require('ethers');
  2. const types = require('./eip712-types');
  3. async function getDomain(contract) {
  4. const { fields, name, version, chainId, verifyingContract, salt, extensions } = await contract.eip712Domain();
  5. if (extensions.length > 0) {
  6. throw Error('Extensions not implemented');
  7. }
  8. const domain = {
  9. name,
  10. version,
  11. // TODO: remove check when contracts are all migrated to ethers
  12. chainId: web3.utils.isBN(chainId) ? chainId.toNumber() : chainId,
  13. verifyingContract,
  14. salt,
  15. };
  16. for (const [i, { name }] of types.EIP712Domain.entries()) {
  17. if (!(fields & (1 << i))) {
  18. delete domain[name];
  19. }
  20. }
  21. return domain;
  22. }
  23. function domainType(domain) {
  24. return types.EIP712Domain.filter(({ name }) => domain[name] !== undefined);
  25. }
  26. function hashTypedData(domain, structHash) {
  27. return ethers.solidityPackedKeccak256(
  28. ['bytes', 'bytes32', 'bytes32'],
  29. ['0x1901', ethers.TypedDataEncoder.hashDomain(domain), structHash],
  30. );
  31. }
  32. module.exports = {
  33. types,
  34. getDomain,
  35. domainType,
  36. domainSeparator: ethers.TypedDataEncoder.hashDomain,
  37. hashTypedData,
  38. };