ReentrancyGuardTransient.sol 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.24;
  3. import {TransientSlot} from "./TransientSlot.sol";
  4. /**
  5. * @dev Variant of {ReentrancyGuard} that uses transient storage.
  6. *
  7. * NOTE: This variant only works on networks where EIP-1153 is available.
  8. *
  9. * _Available since v5.1._
  10. */
  11. abstract contract ReentrancyGuardTransient {
  12. using TransientSlot for *;
  13. // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
  14. bytes32 private constant REENTRANCY_GUARD_STORAGE =
  15. 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
  16. /**
  17. * @dev Unauthorized reentrant call.
  18. */
  19. error ReentrancyGuardReentrantCall();
  20. /**
  21. * @dev Prevents a contract from calling itself, directly or indirectly.
  22. * Calling a `nonReentrant` function from another `nonReentrant`
  23. * function is not supported. It is possible to prevent this from happening
  24. * by making the `nonReentrant` function external, and making it call a
  25. * `private` function that does the actual work.
  26. */
  27. modifier nonReentrant() {
  28. _nonReentrantBefore();
  29. _;
  30. _nonReentrantAfter();
  31. }
  32. function _nonReentrantBefore() private {
  33. // On the first call to nonReentrant, _status will be NOT_ENTERED
  34. if (_reentrancyGuardEntered()) {
  35. revert ReentrancyGuardReentrantCall();
  36. }
  37. // Any calls to nonReentrant after this point will fail
  38. REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
  39. }
  40. function _nonReentrantAfter() private {
  41. REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
  42. }
  43. /**
  44. * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
  45. * `nonReentrant` function in the call stack.
  46. */
  47. function _reentrancyGuardEntered() internal view returns (bool) {
  48. return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
  49. }
  50. }