forge-std icon indicating copy to clipboard operation
forge-std copied to clipboard

Invariant tests: what is the best way of managing blockchain-timestamp?

Open JacoboLansac opened this issue 2 years ago • 2 comments

When doing invariant tests on a staking protocol, it is important to be able to simulate the pass of time. I tried two approaches:

  1. Adding a function to a handler contract that internally uses skip(time). However, blockchain timestamp was reverted to the original point after executing the function. Time advancement was not preserved outside that function.

  2. In the handler contract, declare a state variable called timestamp and add a modifier to all functions in the handler contract, which would add some time to that variable before using vm.warp(timestamp). This worked.

Is there a better way of doing it?

JacoboLansac avatar May 10 '23 08:05 JacoboLansac

Invariants are still a relatively new feature in Forge Std, so there are few best practices for them. In our code base, we went with your 2nd suggested solution, but we made sure to bound each warp so that the overall invariant campaign doesn't get chaotic (our protocol assumes that time flows linearly 😅)

/// @dev Simulate the passage of time. The time warp is upper bounded so streams don't settle too quickly.
function warp(uint256 timeWarp) external instrument("warp") {
    uint256 lowerBound = 24 hours;
    uint256 currentTime = getLatestTimestamp();
    uint256 upperBound = (MAX_UNIX_TIMESTAMP - currentTime) / MAX_STREAM_COUNT;
    timeWarp = _bound(timeWarp, lowerBound, upperBound);
    uint256 newTime = currentTime + timeWarp;
    vm.warp({ timestamp: newTime });
    setLatestTimestamp(newTime);
}

getLatestTimestamp and setLatestTimestamp do what your state variable timestamp does; block.timestamp is returned on the first run.

PaulRBerg avatar May 15 '23 12:05 PaulRBerg

Also, I think this issue should have opened in the Foundry Book repo:

https://github.com/foundry-rs/book/issues

PaulRBerg avatar May 15 '23 13:05 PaulRBerg