How to check for a fortnight (two weeks)

A user on reddit asked about checking for 14 days or two weeks.

For an OpenZeppelin example using time there is TokenTimelock.sol and TokenTimelock.test.js.

I wrote my own example (borrowing heavily from TokenTimelock) to show using time units and openzeppelin-test-helpers and because I like saying fortnight.

I recommend that code be appropriately tested (Test smart contracts like a rockstar) and audited.

Fortnight.sol

The constructor sets that a fortnight is in two weeks from when the contract is deployed. You can only call the doStuff function after a fortnight has passed.

pragma solidity ^0.5.0;

contract Fortnight {
    uint256 private _fortnightTime;

    constructor () public {
        // solhint-disable-next-line not-rely-on-time
        _fortnightTime = block.timestamp + 2 weeks;
    }

    function doStuff() public {
        // solhint-disable-next-line not-rely-on-time
        require(block.timestamp >= _fortnightTime, "Fortnight: current time is before fortnight");
    }
}

Fortnight.test.js

Tests check that you cannot doStuff before a fortnight and that you can doStuff after a fortnight.

const { expectRevert, time } = require('openzeppelin-test-helpers');
const { expect } = require('chai');

const Fortnight = artifacts.require('Fortnight');

contract('Fortnight', function ([_, creator, other]) {

    beforeEach(async function () {
        this.fortnightTime = (await time.latest()).add(time.duration.weeks(2));
        this.fortnight = await Fortnight.new({from: creator});
    });

    it('cannot do stuff before fortnight', async function () {
        await expectRevert(this.fortnight.doStuff(), 'Fortnight: current time is before fortnight');
    });

    it('cannot do stuff just before fortnight', async function () {
        await time.increaseTo(this.fortnightTime.sub(time.duration.seconds(3)));
        await expectRevert(this.fortnight.doStuff(), 'Fortnight: current time is before fortnight');
    });

    it('can do stuff just after fortnight', async function () {
        await time.increaseTo(this.fortnightTime.add(time.duration.seconds(1)));
        await this.fortnight.doStuff();
    });

    it('can do stuff after fortnight', async function () {
        await time.increaseTo(this.fortnightTime.add(time.duration.years(1)));
        await this.fortnight.doStuff();
    });
});
3 Likes