time.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  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().then(ethers.toBigInt),
  6. timestamp: () => time.latest().then(ethers.toBigInt),
  7. };
  8. const clockFromReceipt = {
  9. blocknumber: receipt => Promise.resolve(receipt).then(({ blockNumber }) => ethers.toBigInt(blockNumber)),
  10. timestamp: receipt =>
  11. Promise.resolve(receipt)
  12. .then(({ blockNumber }) => ethers.provider.getBlock(blockNumber))
  13. .then(({ timestamp }) => ethers.toBigInt(timestamp)),
  14. };
  15. const increaseBy = {
  16. blockNumber: mine,
  17. timestamp: (delay, mine = true) =>
  18. time.latest().then(clock => increaseTo.timestamp(clock + ethers.toNumber(delay), mine)),
  19. };
  20. const increaseTo = {
  21. blocknumber: mineUpTo,
  22. timestamp: (to, mine = true) => (mine ? time.increaseTo(to) : time.setNextBlockTimestamp(to)),
  23. };
  24. const duration = mapValues(time.duration, fn => n => ethers.toBigInt(fn(ethers.toNumber(n))));
  25. module.exports = {
  26. clock,
  27. clockFromReceipt,
  28. increaseBy,
  29. increaseTo,
  30. duration,
  31. };