EIP712.test.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const ethSigUtil = require('eth-sig-util');
  2. const Wallet = require('ethereumjs-wallet').default;
  3. const { EIP712Domain, domainSeparator, hashTypedData } = require('../../helpers/eip712');
  4. const { getChainId } = require('../../helpers/chainid');
  5. const EIP712Verifier = artifacts.require('$EIP712Verifier');
  6. contract('EIP712', function (accounts) {
  7. const [mailTo] = accounts;
  8. const name = 'A Name';
  9. const version = '1';
  10. beforeEach('deploying', async function () {
  11. this.eip712 = await EIP712Verifier.new(name, version);
  12. this.domain = {
  13. name,
  14. version,
  15. chainId: await getChainId(),
  16. verifyingContract: this.eip712.address,
  17. };
  18. });
  19. it('domain separator', async function () {
  20. const expected = await domainSeparator(this.domain);
  21. expect(await this.eip712.$_domainSeparatorV4()).to.equal(expected);
  22. });
  23. it('hash digest', async function () {
  24. const structhash = web3.utils.randomHex(32);
  25. const expected = await hashTypedData(this.domain, structhash);
  26. expect(await this.eip712.$_hashTypedDataV4(structhash)).to.be.equal(expected);
  27. });
  28. it('digest', async function () {
  29. const message = {
  30. to: mailTo,
  31. contents: 'very interesting',
  32. };
  33. const data = {
  34. types: {
  35. EIP712Domain,
  36. Mail: [
  37. { name: 'to', type: 'address' },
  38. { name: 'contents', type: 'string' },
  39. ],
  40. },
  41. domain: this.domain,
  42. primaryType: 'Mail',
  43. message,
  44. };
  45. const wallet = Wallet.generate();
  46. const signature = ethSigUtil.signTypedMessage(wallet.getPrivateKey(), { data });
  47. await this.eip712.verify(signature, wallet.getAddressString(), message.to, message.contents);
  48. });
  49. });