ReentrancyGuard.sol 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // Booleans are more expensive than uint256 or any type that takes up a full
  21. // word because each write operation emits an extra SLOAD to first read the
  22. // slot's contents, replace the bits taken up by the boolean, and then write
  23. // back. This is the compiler's defense against contract upgrades and
  24. // pointer aliasing, and it cannot be disabled.
  25. // The values being non-zero value makes deployment a bit more expensive,
  26. // but in exchange the refund on every call to nonReentrant will be lower in
  27. // amount. Since refunds are capped to a percentage of the total
  28. // transaction's gas, it is best to keep them low in cases like this one, to
  29. // increase the likelihood of the full refund coming into effect.
  30. uint256 private constant _NOT_ENTERED = 1;
  31. uint256 private constant _ENTERED = 2;
  32. uint256 private _status;
  33. constructor () internal {
  34. _status = _NOT_ENTERED;
  35. }
  36. /**
  37. * @dev Prevents a contract from calling itself, directly or indirectly.
  38. * Calling a `nonReentrant` function from another `nonReentrant`
  39. * function is not supported. It is possible to prevent this from happening
  40. * by making the `nonReentrant` function external, and make it call a
  41. * `private` function that does the actual work.
  42. */
  43. modifier nonReentrant() {
  44. // On the first call to nonReentrant, _notEntered will be true
  45. require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
  46. // Any calls to nonReentrant after this point will fail
  47. _status = _ENTERED;
  48. _;
  49. // By storing the original value once again, a refund is triggered (see
  50. // https://eips.ethereum.org/EIPS/eip-2200)
  51. _status = _NOT_ENTERED;
  52. }
  53. }