MessageHashUtils.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. const { domainSeparator, hashTypedData } = require('../../helpers/eip712');
  5. async function fixture() {
  6. const mock = await ethers.deployContract('$MessageHashUtils');
  7. return { mock };
  8. }
  9. describe('MessageHashUtils', function () {
  10. beforeEach(async function () {
  11. Object.assign(this, await loadFixture(fixture));
  12. });
  13. describe('toEthSignedMessageHash', function () {
  14. it('prefixes bytes32 data correctly', async function () {
  15. const message = ethers.randomBytes(32);
  16. const expectedHash = ethers.hashMessage(message);
  17. expect(await this.mock.getFunction('$toEthSignedMessageHash(bytes32)')(message)).to.equal(expectedHash);
  18. });
  19. it('prefixes dynamic length data correctly', async function () {
  20. const message = ethers.randomBytes(128);
  21. const expectedHash = ethers.hashMessage(message);
  22. expect(await this.mock.getFunction('$toEthSignedMessageHash(bytes)')(message)).to.equal(expectedHash);
  23. });
  24. it('version match for bytes32', async function () {
  25. const message = ethers.randomBytes(32);
  26. const fixed = await this.mock.getFunction('$toEthSignedMessageHash(bytes32)')(message);
  27. const dynamic = await this.mock.getFunction('$toEthSignedMessageHash(bytes)')(message);
  28. expect(fixed).to.equal(dynamic);
  29. });
  30. });
  31. describe('toDataWithIntendedValidatorHash', function () {
  32. it('returns the digest correctly', async function () {
  33. const verifier = ethers.Wallet.createRandom().address;
  34. const message = ethers.randomBytes(128);
  35. const expectedHash = ethers.solidityPackedKeccak256(
  36. ['string', 'address', 'bytes'],
  37. ['\x19\x00', verifier, message],
  38. );
  39. expect(await this.mock.$toDataWithIntendedValidatorHash(verifier, message)).to.equal(expectedHash);
  40. });
  41. });
  42. describe('toTypedDataHash', function () {
  43. it('returns the digest correctly', async function () {
  44. const domain = {
  45. name: 'Test',
  46. version: '1',
  47. chainId: 1n,
  48. verifyingContract: ethers.Wallet.createRandom().address,
  49. };
  50. const structhash = ethers.randomBytes(32);
  51. const expectedHash = hashTypedData(domain, structhash);
  52. expect(await this.mock.$toTypedDataHash(domainSeparator(domain), structhash)).to.equal(expectedHash);
  53. });
  54. });
  55. });