SlotDerivation.test.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const { ethers } = require('hardhat');
  2. const { expect } = require('chai');
  3. const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
  4. const { erc7201Slot } = require('../helpers/storage');
  5. const { generators } = require('../helpers/random');
  6. async function fixture() {
  7. const [account] = await ethers.getSigners();
  8. const mock = await ethers.deployContract('$SlotDerivation');
  9. return { mock, account };
  10. }
  11. describe('SlotDerivation', function () {
  12. beforeEach(async function () {
  13. Object.assign(this, await loadFixture(fixture));
  14. });
  15. describe('namespaces', function () {
  16. const namespace = 'example.main';
  17. it('erc-7201', async function () {
  18. expect(await this.mock.$erc7201Slot(namespace)).to.equal(erc7201Slot(namespace));
  19. });
  20. });
  21. describe('derivation', function () {
  22. it('offset', async function () {
  23. const base = generators.bytes32();
  24. const offset = generators.uint256();
  25. expect(await this.mock.$offset(base, offset)).to.equal((ethers.toBigInt(base) + offset) & ethers.MaxUint256);
  26. });
  27. it('array', async function () {
  28. const base = generators.bytes32();
  29. expect(await this.mock.$deriveArray(base)).to.equal(ethers.keccak256(base));
  30. });
  31. describe('mapping', function () {
  32. for (const { type, key, isValueType } of [
  33. { type: 'bool', key: true, isValueType: true },
  34. { type: 'address', key: generators.address(), isValueType: true },
  35. { type: 'bytes32', key: generators.bytes32(), isValueType: true },
  36. { type: 'uint256', key: generators.uint256(), isValueType: true },
  37. { type: 'int256', key: generators.int256(), isValueType: true },
  38. { type: 'bytes', key: generators.hexBytes(128), isValueType: false },
  39. { type: 'string', key: 'lorem ipsum', isValueType: false },
  40. ]) {
  41. it(type, async function () {
  42. const base = generators.bytes32();
  43. const expected = isValueType
  44. ? ethers.keccak256(ethers.AbiCoder.defaultAbiCoder().encode([type, 'bytes32'], [key, base]))
  45. : ethers.solidityPackedKeccak256([type, 'bytes32'], [key, base]);
  46. expect(await this.mock[`$deriveMapping(bytes32,${type})`](base, key)).to.equal(expected);
  47. });
  48. }
  49. });
  50. });
  51. });