DayLimit.sol 2.0 KB

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