increaseTime.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import latestTime from './latestTime';
  2. // Increases testrpc time by the passed duration in seconds
  3. export default function increaseTime (duration) {
  4. const id = Date.now();
  5. return new Promise((resolve, reject) => {
  6. web3.currentProvider.sendAsync({
  7. jsonrpc: '2.0',
  8. method: 'evm_increaseTime',
  9. params: [duration],
  10. id: id,
  11. }, err1 => {
  12. if (err1) return reject(err1);
  13. web3.currentProvider.sendAsync({
  14. jsonrpc: '2.0',
  15. method: 'evm_mine',
  16. id: id + 1,
  17. }, (err2, res) => {
  18. return err2 ? reject(err2) : resolve(res);
  19. });
  20. });
  21. });
  22. }
  23. /**
  24. * Beware that due to the need of calling two separate testrpc methods and rpc calls overhead
  25. * it's hard to increase time precisely to a target point so design your test to tolerate
  26. * small fluctuations from time to time.
  27. *
  28. * @param target time in seconds
  29. */
  30. export function increaseTimeTo (target) {
  31. let now = latestTime();
  32. if (target < now) throw Error(`Cannot increase current time(${now}) to a moment in the past(${target})`);
  33. let diff = target - now;
  34. return increaseTime(diff);
  35. }
  36. export const duration = {
  37. seconds: function (val) { return val; },
  38. minutes: function (val) { return val * this.seconds(60); },
  39. hours: function (val) { return val * this.minutes(60); },
  40. days: function (val) { return val * this.hours(24); },
  41. weeks: function (val) { return val * this.days(7); },
  42. years: function (val) { return val * this.days(365); },
  43. };