ReentrancyGuard.sol 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
  3. pragma solidity ^0.8.0;
  4. /**
  5. * @dev Contract module that helps prevent reentrant calls to a function.
  6. *
  7. * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
  8. * available, which can be applied to functions to make sure there are no nested
  9. * (reentrant) calls to them.
  10. *
  11. * Note that because there is a single `nonReentrant` guard, functions marked as
  12. * `nonReentrant` may not call one another. This can be worked around by making
  13. * those functions `private`, and then adding `external` `nonReentrant` entry
  14. * points to them.
  15. *
  16. * TIP: If you would like to learn more about reentrancy and alternative ways
  17. * to protect against it, check out our blog post
  18. * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
  19. */
  20. abstract contract ReentrancyGuard {
  21. // Booleans are more expensive than uint256 or any type that takes up a full
  22. // word because each write operation emits an extra SLOAD to first read the
  23. // slot's contents, replace the bits taken up by the boolean, and then write
  24. // back. This is the compiler's defense against contract upgrades and
  25. // pointer aliasing, and it cannot be disabled.
  26. // The values being non-zero value makes deployment a bit more expensive,
  27. // but in exchange the refund on every call to nonReentrant will be lower in
  28. // amount. Since refunds are capped to a percentage of the total
  29. // transaction's gas, it is best to keep them low in cases like this one, to
  30. // increase the likelihood of the full refund coming into effect.
  31. uint256 private constant _NOT_ENTERED = 1;
  32. uint256 private constant _ENTERED = 2;
  33. uint256 private _status;
  34. constructor() {
  35. _status = _NOT_ENTERED;
  36. }
  37. /**
  38. * @dev Prevents a contract from calling itself, directly or indirectly.
  39. * Calling a `nonReentrant` function from another `nonReentrant`
  40. * function is not supported. It is possible to prevent this from happening
  41. * by making the `nonReentrant` function external, and making it call a
  42. * `private` function that does the actual work.
  43. */
  44. modifier nonReentrant() {
  45. // On the first call to nonReentrant, _notEntered will be true
  46. require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
  47. // Any calls to nonReentrant after this point will fail
  48. _status = _ENTERED;
  49. _;
  50. // By storing the original value once again, a refund is triggered (see
  51. // https://eips.ethereum.org/EIPS/eip-2200)
  52. _status = _NOT_ENTERED;
  53. }
  54. }