namespaced-storage.js 838 B

123456789101112131415161718192021222324252627282930
  1. const { artifacts } = require('hardhat');
  2. function namespaceId(contractName) {
  3. return `openzeppelin.storage.${contractName}`;
  4. }
  5. function namespaceLocation(id) {
  6. const hashIdBN = web3.utils.toBN(web3.utils.keccak256(id)).subn(1); // keccak256(id) - 1
  7. const hashIdHex = web3.utils.padLeft(web3.utils.numberToHex(hashIdBN), 64);
  8. const mask = BigInt(web3.utils.padLeft('0x00', 64, 'f')); // ~0xff
  9. return BigInt(web3.utils.keccak256(hashIdHex)) & 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. };