StorageSlot.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const format = require('../format-lines');
  2. const { TYPES } = require('./Slot.opts');
  3. const header = `\
  4. pragma solidity ^0.8.20;
  5. /**
  6. * @dev Library for reading and writing primitive types to specific storage slots.
  7. *
  8. * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
  9. * This library helps with reading and writing to such slots without the need for inline assembly.
  10. *
  11. * The functions in this library return Slot structs that contain a \`value\` member that can be used to read or write.
  12. *
  13. * Example usage to set ERC-1967 implementation slot:
  14. * \`\`\`solidity
  15. * contract ERC1967 {
  16. * // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
  17. * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
  18. *
  19. * function _getImplementation() internal view returns (address) {
  20. * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
  21. * }
  22. *
  23. * function _setImplementation(address newImplementation) internal {
  24. * require(newImplementation.code.length > 0);
  25. * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
  26. * }
  27. * }
  28. * \`\`\`
  29. *
  30. * TIP: Consider using this library along with {SlotDerivation}.
  31. */
  32. `;
  33. const struct = ({ type, name }) => `\
  34. struct ${name}Slot {
  35. ${type} value;
  36. }
  37. `;
  38. const get = ({ name }) => `\
  39. /**
  40. * @dev Returns an \`${name}Slot\` with member \`value\` located at \`slot\`.
  41. */
  42. function get${name}Slot(bytes32 slot) internal pure returns (${name}Slot storage r) {
  43. /// @solidity memory-safe-assembly
  44. assembly {
  45. r.slot := slot
  46. }
  47. }
  48. `;
  49. const getStorage = ({ type, name }) => `\
  50. /**
  51. * @dev Returns an \`${name}Slot\` representation of the ${type} storage pointer \`store\`.
  52. */
  53. function get${name}Slot(${type} storage store) internal pure returns (${name}Slot storage r) {
  54. /// @solidity memory-safe-assembly
  55. assembly {
  56. r.slot := store.slot
  57. }
  58. }
  59. `;
  60. // GENERATE
  61. module.exports = format(
  62. header.trimEnd(),
  63. 'library StorageSlot {',
  64. TYPES.map(type => struct(type)),
  65. TYPES.flatMap(type => [get(type), type.isValueType ? '' : getStorage(type)]),
  66. '}',
  67. );