November 19, 2026

Writing Accurate Time-Dependent Truffle Tests – Sablier

Writing Accurate Time-Dependent Truffle Tests – Sablier

Writing Accurate Time-Dependent Truffle Tests – Sablier

Writing Accurate Time-Dependent Truffle Tests – Sablier

Code itself takes time to execute. Specifically, javascript promises take a non-negligible amount of time to resolve.

This is obvious, no? Things get delicate when writing time-dependent tests for Ethereum smart contracts.

Consider the following:

  1. The time it takes for the test case to execute
  2. The amount of seconds you want to jump in the future
  3. The unix timestamp for the moment when you submit yarn run test in your console

Contingent on these variables, your test block could get caught in between the passage of one or more seconds, hence your assertions could break.

For instance:

What this does is that it calls the Sablier contract to withdraw a previously deposited wad of money. The rules that dictate how much the caller can withdraw are specified in ERC-1620.

I expected the test to pass consistently, but I was wrong. So wrong. It started to break ~1 in 8 times and the thing I feared most happened, that is, non-deterministic variance.

I logged the unix timestamp in mocha’s before block and I measured how long it takes for the test to run using node’s performance timing API:

If you add 115 to 1565455128964, you end up with a number that ends with 9079, thus the number of seconds increases from 8 to 9. This is what broke the assertion, because I was expecting a balance of 5, when I was actually getting 6 (more seconds passed = more money allocated).

While it is impossible to write a program P1 that can generally compute how long it will take for another program P2 to finish (see Turing’s Halting Problem), we could safely assume that no more than 1 second should pass between your beforeEach and it blocks. This is assuming the back and forth communication between your node instance and ganache is almost instantaneous.

Here’s the fix:

Where ONE_UNIT is one monetary unit paid every second, as per the Sablier model. It is imperfect, but way better than using a “greater than” or “less than” equality check.

Finally, just like OpenZeppelin recommends here, you might not need your tests to be so fine grained. This is not the case for Sablier, but if your dapp doesn’t involve timestamps or block numbers directly, you may be doing fine by tolerating more chronological offsets in your tests.

Published at Sun, 11 Aug 2019 00:33:52 +0000

Bitcoin Pic Of The Moment
May 2014
Photos by Alissa Millenson
By KnowledgeCommonsDC on 2014-05-17 17:32:55
tags

Previous Article

Writing Accurate Time-Dependent Truffle Tests – Sablier

Next Article

U.S. Department of Energy Awards Grant for Development of Blockchain-Based Energy Platform