How to test time-based smart contracts with Truffle

Testing Ethereum smart contracts that depend on real-world time is essential to ensure your smart contract works as designed. In this tutorial, we take a closer look at building the test infrastructure to support time-sensitive tests for smart contracts using Solidity, Ganache, and Truffle.

Download the NPM package

The OpenZepplein test helpers package comes bundled with a variety of tools to test your smart contract. A link to the documentation can be found here.

npm install --save-dev @openzeppelin/test-helpers

How to use the package

1) Import the time at the top of your test file in the test folder

const { time } = require('openzeppelin-test-helpers');

2) Use the time library to jump ahead in time or block numbers

Increase: Increases the time of the blockchain by duration (in seconds), and mines a new block with that timestamp.

async function time.increase(duration)

AdvanceBlock: Forces a block to be mined, incrementing the block height.

async function time.advanceBlock()

Example:

contract("ERC20", async (accounts) => {
describe("Example of testing time", () => {
it("These two transactions are 100 seconds apart", async () => {
await myToken.transfer(personOne, 1000000);
//=============================
await time.increase(100) // Increases the time by 100 seconds
await time.advanceBlock() // Increases the block
//=============================
await myToken.transfer(personOne, 1000000);
});
});
});

This is all you need to test time in your smart contract! If you need help with getting started with truffle and testing smart contracts, below is a good blog post on how to do that.

Cabal Labs

Cabal Labs is on a mission to enhance human freedoms and rights through technological innovation. We have grown a network of companies that serve under our banner. These developers and researchers have made it their life’s goal to break the status quo and deliver revolutionary solutions to age-old problems.

We would love to hear from you: caballabs@gmail.com

date published

Nov 16, 2022

reading time

2 min read

.say hello

i'm open for freelance projects, feel free to email me to see how can we collaborate

.say hello

i'm open for freelance projects, feel free to email me to see how can we collaborate