time.js 1.8 KB

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