ReentrancyGuard.sol 2.0 KB

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