ReentrancyGuard.sol 1.4 KB

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