time.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const { ethers } = require('hardhat');
  2. const { time, mine, mineUpTo } = require('@nomicfoundation/hardhat-network-helpers');
  3. const { mapValues } = require('./iterate');
  4. const clock = {
  5. blocknumber: () => time.latestBlock(),
  6. timestamp: () => time.latest(),
  7. };
  8. const clockFromReceipt = {
  9. blocknumber: receipt => Promise.resolve(receipt.blockNumber),
  10. timestamp: receipt => ethers.provider.getBlock(receipt.blockNumber).then(block => block.timestamp),
  11. };
  12. const increaseBy = {
  13. blockNumber: mine,
  14. timestamp: (delay, mine = true) =>
  15. time.latest().then(clock => increaseTo.timestamp(clock + ethers.toNumber(delay), mine)),
  16. };
  17. const increaseTo = {
  18. blocknumber: mineUpTo,
  19. timestamp: (to, mine = true) => (mine ? time.increaseTo(to) : time.setNextBlockTimestamp(to)),
  20. };
  21. const duration = time.duration;
  22. module.exports = {
  23. clock,
  24. clockFromReceipt,
  25. increaseBy,
  26. increaseTo,
  27. duration,
  28. };
  29. // TODO: deprecate the old version in favor of this one
  30. module.exports.bigint = {
  31. clock: mapValues(clock, fn => () => fn().then(ethers.toBigInt)),
  32. clockFromReceipt: mapValues(clockFromReceipt, fn => receipt => fn(receipt).then(ethers.toBigInt)),
  33. increaseBy: increaseBy,
  34. increaseTo: increaseTo,
  35. duration: mapValues(duration, fn => n => ethers.toBigInt(fn(ethers.toNumber(n)))),
  36. };