0

It seems to be recommended to use block.number over block.timestamp for time-based operations (see Block Timestamp Manipulation: Preventative Techniques)

OpenZeppelin provides some APIs to simulate passing time. However, time.advaneBlockTo(target) is extremely slow, so unit testing a contract that uses block.number to simulate any large amount of time (say, 1 month) with this API will be prohibitively slow for the purpose of unit tests.

Are there any faster alternatives to simulate increasing block.number as a means of simulating the passage of time?

0

You can use:

  • Hardhat's evm_mine where your test.js file would look like this:

     const hre = require("hardhat") 
     ...
     //Do operation on block #N
    
     await hre.network.provider.send("evm_mine");
    
     //Do operation on block #N+1
     //Test
    
  • Use OpenZeppelin's test helper advanceBlock where your test.js file would look like this:

     const { time } = 
     require('@openzeppelin/test-helpers');
     ...
     //Do something on block #N
    
     await time.advanceBlock();
    
     //Do something on block #N+1
     //Test
    
1
  • Hi, Thanks for your response. Yes, you can use those APIs, however the issue is that they are very slow. For example, if a contract assumes average block time is 3s and wants to check if 30 days have passed, then it needs to check block #N+864000 (30 days * 24 hours * 60 minutes * 60 seconds / 3 seconds-per-block). Looping 864,000 and calling advanceBlock or evm_mine is not feasible for a unit test, so I am looking for alternatives.
    – EEE
    Dec 2 '21 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.