DayLimit.sol 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. pragma solidity ^0.4.21;
  2. /**
  3. * @title DayLimit
  4. * @dev Base contract that enables methods to be protected by placing a linear limit (specifiable)
  5. * on a particular resource per calendar day. Is multiowned to allow the limit to be altered.
  6. */
  7. contract DayLimit {
  8. uint256 public dailyLimit;
  9. uint256 public spentToday;
  10. uint256 public lastDay;
  11. /**
  12. * @dev Constructor that sets the passed value as a dailyLimit.
  13. * @param _limit uint256 to represent the daily limit.
  14. */
  15. function DayLimit(uint256 _limit) public {
  16. dailyLimit = _limit;
  17. lastDay = today();
  18. }
  19. /**
  20. * @dev sets the daily limit. Does not alter the amount already spent today.
  21. * @param _newLimit uint256 to represent the new limit.
  22. */
  23. function _setDailyLimit(uint256 _newLimit) internal {
  24. dailyLimit = _newLimit;
  25. }
  26. /**
  27. * @dev Resets the amount already spent today.
  28. */
  29. function _resetSpentToday() internal {
  30. spentToday = 0;
  31. }
  32. /**
  33. * @dev Checks to see if there is enough resource to spend today. If true, the resource may be expended.
  34. * @param _value uint256 representing the amount of resource to spend.
  35. * @return A boolean that is True if the resource was spent and false otherwise.
  36. */
  37. function underLimit(uint256 _value) internal returns (bool) {
  38. // reset the spend limit if we're on a different day to last time.
  39. if (today() > lastDay) {
  40. spentToday = 0;
  41. lastDay = today();
  42. }
  43. // check to see if there's enough left - if so, subtract and return true.
  44. // overflow protection // dailyLimit check
  45. if (spentToday + _value >= spentToday && spentToday + _value <= dailyLimit) {
  46. spentToday += _value;
  47. return true;
  48. }
  49. return false;
  50. }
  51. /**
  52. * @dev Private function to determine today's index
  53. * @return uint256 of today's index.
  54. */
  55. function today() private view returns (uint256) {
  56. // solium-disable-next-line security/no-block-members
  57. return block.timestamp / 1 days;
  58. }
  59. /**
  60. * @dev Simple modifier for daily limit.
  61. */
  62. modifier limitedDaily(uint256 _value) {
  63. require(underLimit(_value));
  64. _;
  65. }
  66. }