ReentrancyGuardTransient.sol 2.0 KB

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