ReentrancyGuard.sol 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. bool private _notEntered;
  20. constructor () internal {
  21. // Storing an initial non-zero value makes deployment a bit more
  22. // expensive, but in exchange the refund on every call to nonReentrant
  23. // will be lower in amount. Since refunds are capped to a percetange of
  24. // the total transaction's gas, it is best to keep them low in cases
  25. // like this one, to increase the likelihood of the full refund coming
  26. // into effect.
  27. _notEntered = true;
  28. }
  29. /**
  30. * @dev Prevents a contract from calling itself, directly or indirectly.
  31. * Calling a `nonReentrant` function from another `nonReentrant`
  32. * function is not supported. It is possible to prevent this from happening
  33. * by making the `nonReentrant` function external, and make it call a
  34. * `private` function that does the actual work.
  35. */
  36. modifier nonReentrant() {
  37. // On the first call to nonReentrant, _notEntered will be true
  38. require(_notEntered, "ReentrancyGuard: reentrant call");
  39. // Any calls to nonReentrant after this point will fail
  40. _notEntered = false;
  41. _;
  42. // By storing the original value once again, a refund is triggered (see
  43. // https://eips.ethereum.org/EIPS/eip-2200)
  44. _notEntered = true;
  45. }
  46. }