ReentrancyGuard.sol 2.5 KB

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