ReentrancyGuardTransient.sol 2.0 KB

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