time.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const { ethGetBlock } = require('./web3');
  2. const pify = require('pify');
  3. function advanceBlock () {
  4. return pify(web3.currentProvider.sendAsync)({
  5. jsonrpc: '2.0',
  6. method: 'evm_mine',
  7. });
  8. }
  9. // Returns the time of the last mined block in seconds
  10. async function latest () {
  11. const block = await ethGetBlock('latest');
  12. return block.timestamp;
  13. }
  14. // Increases ganache time by the passed duration in seconds
  15. async function increase (duration) {
  16. if (duration < 0) throw Error(`Cannot increase time by a negative amount (${duration})`);
  17. await pify(web3.currentProvider.sendAsync)({
  18. jsonrpc: '2.0',
  19. method: 'evm_increaseTime',
  20. params: [duration],
  21. });
  22. await advanceBlock();
  23. }
  24. /**
  25. * Beware that due to the need of calling two separate ganache methods and rpc calls overhead
  26. * it's hard to increase time precisely to a target point so design your test to tolerate
  27. * small fluctuations from time to time.
  28. *
  29. * @param target time in seconds
  30. */
  31. async function increaseTo (target) {
  32. const now = (await latest());
  33. if (target < now) throw Error(`Cannot increase current time (${now}) to a moment in the past (${target})`);
  34. const diff = target - now;
  35. return increase(diff);
  36. }
  37. const duration = {
  38. seconds: function (val) { return val; },
  39. minutes: function (val) { return val * this.seconds(60); },
  40. hours: function (val) { return val * this.minutes(60); },
  41. days: function (val) { return val * this.hours(24); },
  42. weeks: function (val) { return val * this.days(7); },
  43. years: function (val) { return val * this.days(365); },
  44. };
  45. module.exports = {
  46. advanceBlock,
  47. latest,
  48. increase,
  49. increaseTo,
  50. duration,
  51. };