ReentrancyGuard.sol 2.1 KB

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