erc1967.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const { getStorageAt, setStorageAt } = require('@nomicfoundation/hardhat-network-helpers');
  2. const ImplementationLabel = 'eip1967.proxy.implementation';
  3. const AdminLabel = 'eip1967.proxy.admin';
  4. const BeaconLabel = 'eip1967.proxy.beacon';
  5. function labelToSlot(label) {
  6. return '0x' + web3.utils.toBN(web3.utils.keccak256(label)).subn(1).toString(16);
  7. }
  8. function getSlot(address, slot) {
  9. return getStorageAt(
  10. web3.utils.isAddress(address) ? address : address.address,
  11. web3.utils.isHex(slot) ? slot : labelToSlot(slot),
  12. );
  13. }
  14. function setSlot(address, slot, value) {
  15. const hexValue = web3.utils.isHex(value) ? value : web3.utils.toHex(value);
  16. return setStorageAt(
  17. web3.utils.isAddress(address) ? address : address.address,
  18. web3.utils.isHex(slot) ? slot : labelToSlot(slot),
  19. web3.utils.padLeft(hexValue, 64),
  20. );
  21. }
  22. async function getAddressInSlot(address, slot) {
  23. const slotValue = await getSlot(address, slot);
  24. return web3.utils.toChecksumAddress(slotValue.substring(slotValue.length - 40));
  25. }
  26. module.exports = {
  27. ImplementationLabel,
  28. AdminLabel,
  29. BeaconLabel,
  30. ImplementationSlot: labelToSlot(ImplementationLabel),
  31. AdminSlot: labelToSlot(AdminLabel),
  32. BeaconSlot: labelToSlot(BeaconLabel),
  33. setSlot,
  34. getSlot,
  35. getAddressInSlot,
  36. };