EIP712.test.js 2.1 KB

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