time.js 1.7 KB

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