Trying out the new stacks-block-time in Clarity 4.
$ clarinet --version
clarinet 3.10.0
$ clarinet new asdf && cd asdf
$ clarinet contract new asdf
;; asdf.clar
(define-read-only (get-time) stacks-block-time)
// asdf.test.ts
import { describe, expect, it } from "vitest";
const accounts = simnet.getAccounts();
const address1 = accounts.get("wallet_1")!;
describe("get-time", () => {
it("gets the current time", () => {
simnet.mineEmptyBlock();
const { result } = simnet.callReadOnlyFn("asdf", "get-time", [], address1);
const expected = Math.floor(Date.now() / 1000);
const actual = Number((result as any).value);
expect(Math.abs(expected - actual)).toBeLessThan(10);
});
});
$ npm install
$ npm test
FAIL tests/asdf.test.ts > get-time > gets the current time
AssertionError: expected 1809 to be less than 15
❯ tests/asdf.test.ts:13:41
11| const expected = Math.floor(Date.now() / 1000);
12| const actual = Number((result as any).value);
13| expect(Math.abs(expected - actual)).toBeLessThan(15);
| ^
14| });
15| });
I also tried making sure the time was captured in the contract:
;; asdf.clar
(define-data-var t uint u0)
(define-read-only (asdf-get) (var-get t))
(define-public (asdf-set) (begin (var-set t stacks-block-time) (ok true)))
// asdf.test.ts
import { Cl } from "@stacks/transactions";
import { describe, expect, it } from "vitest";
const accounts = simnet.getAccounts();
const address1 = accounts.get("wallet_1")!;
describe("asdf", () => {
it("gets what it sets", () => {
simnet.mineEmptyBlock();
expect(simnet.callPublicFn("asdf", "asdf-set", [], address1).result).toBeOk(Cl.bool(true));
const { result } = simnet.callReadOnlyFn("asdf", "asdf-get", [], address1);
const expected = Math.floor(Date.now() / 1000);
const actual = Number((result as any).value);
expect(Math.abs(expected - actual)).toBeLessThan(15);
});
});
And observed a similar result. Taking a closer look, the simnet time is consistently around 1819s to 1820s ahead for this case. (1800s is 30 minutes.) I assume it has to do with moving the clock forward while network setup and contract deployment occurs. Removing the mineEmptyBlock drops this diff by 600s (10m).