namespaced-storage.js 776 B

12345678910111213141516171819202122232425262728
  1. const { keccak256, id, toBeHex, MaxUint256 } = require('ethers');
  2. const { artifacts } = require('hardhat');
  3. function namespaceId(contractName) {
  4. return `openzeppelin.storage.${contractName}`;
  5. }
  6. function namespaceLocation(value) {
  7. const hashIdBN = BigInt(id(value)) - 1n; // keccak256(id) - 1
  8. const mask = MaxUint256 - 0xffn; // ~0xff
  9. return BigInt(keccak256(toBeHex(hashIdBN, 32))) & mask;
  10. }
  11. function namespaceSlot(contractName, offset) {
  12. try {
  13. // Try to get the artifact paths, will throw if it doesn't exist
  14. artifacts._getArtifactPathSync(`${contractName}Upgradeable`);
  15. return offset + namespaceLocation(namespaceId(contractName));
  16. } catch (_) {
  17. return offset;
  18. }
  19. }
  20. module.exports = {
  21. namespaceSlot,
  22. namespaceLocation,
  23. namespaceId,
  24. };