StorageSlot.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 ${
  41. name.toLowerCase().startsWith('a') ? 'an' : 'a'
  42. } \`${name}Slot\` with member \`value\` located at \`slot\`.
  43. */
  44. function get${name}Slot(bytes32 slot) internal pure returns (${name}Slot storage r) {
  45. assembly ("memory-safe") {
  46. r.slot := slot
  47. }
  48. }
  49. `;
  50. const getStorage = ({ type, name }) => `\
  51. /**
  52. * @dev Returns an \`${name}Slot\` representation of the ${type} storage pointer \`store\`.
  53. */
  54. function get${name}Slot(${type} storage store) internal pure returns (${name}Slot storage r) {
  55. assembly ("memory-safe") {
  56. r.slot := store.slot
  57. }
  58. }
  59. `;
  60. // GENERATE
  61. module.exports = format(
  62. header.trimEnd(),
  63. 'library StorageSlot {',
  64. format(
  65. [].concat(
  66. TYPES.map(type => struct(type)),
  67. TYPES.flatMap(type => [get(type), !type.isValueType && getStorage(type)].filter(Boolean)),
  68. ),
  69. ).trimEnd(),
  70. '}',
  71. );