ReentrancyGuardTransient.sol 1.9 KB

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