1

I have a trouble with comparing timestamp parameter(in test) and now in smart contract.

Here is my smart contract:

function create(uint created_at) public {
    require(now > created_at, "The created_at should be less than now .");
}

And test function:

it("...should store the created_at", async () => {
    const storageInstance = await Storage.deployed();
    let created_at = new Date().getTime();//create utc now timestamp 
    await storageInstance.create(created_at);
 }

The test doesn't pass. Error:

The created_at should be less than now .

  • 1
    It's not supposed to pass. Even if you take a pair of "regular" machines and compare the JS time on each one of them, they will almost certainly not be the same every time you run the test. Let alone, comparing the JS time on your machine with the current block's timestamp of whatever network you are working with. Also, note that the current block timestamp is updated on average every 15-17 seconds, so even the best you could possibly hope for would give you about 5% success. – goodvibration Mar 11 at 14:06
  • Actually even if i try require((now + 1 days) > created_at, "The created_at should be less than now ."); in smart contracts, the error is same. – adem caglin Mar 11 at 14:11
3

now in Solidity is the amount of seconds since the Epoch, (see Is the block.timestamp value in Solidity seconds or milliseconds?). Javascript's new Date().getTime() / Date.now() returns the amount of milliseconds since the Epoch (see Date.prototype.getTime & Date.now).

This means that Javascript's timestamp is always a factor 1000 larger than the one used by Solidity. You could change your JS code to divide the timestamp by 1000.

let created_at = Math.floor(Date.now() / 1000)

Also be mindful of goodvibration's comment in your design.

UPDATE: new Date().getTime() --> Date.now() (goodvibration's comment)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.