ReentrancyGuard.sol 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // counter to allow mutex lock with only one SSTORE operation
  19. uint256 private _guardCounter;
  20. constructor () internal {
  21. // The counter starts at one to prevent changing it from zero to a non-zero
  22. // value, which is a more expensive operation.
  23. _guardCounter = 1;
  24. }
  25. /**
  26. * @dev Prevents a contract from calling itself, directly or indirectly.
  27. * Calling a `nonReentrant` function from another `nonReentrant`
  28. * function is not supported. It is possible to prevent this from happening
  29. * by making the `nonReentrant` function external, and make it call a
  30. * `private` function that does the actual work.
  31. */
  32. modifier nonReentrant() {
  33. _guardCounter += 1;
  34. uint256 localCounter = _guardCounter;
  35. _;
  36. require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
  37. _guardCounter = 1;
  38. }
  39. }