35

My main goal is to obtain time spent between two transaction calls inside my smart-contract. I am not sure, should I depend on now or block.timestamp to obtain the most accurate time difference in between transactions.

I have call my contract's start() and end() functions to store now and/or block.timestamp values. getTimeDif() returns the difference.

Contract-1:

contract Now {
   uint start;
   uint end;
   function start(){
      start = now;
   } 
   function end(){
      end = now;
   } 
   function getTimeDif() returns(uint){
      return end - start;
   }     
}

Scnerio:

Now.start(); //Transaction mined on blk.num=100.
Now.end();  //Transaction mined on blk.num=200.
console.log( Timestamp. getTimeDif(); )  //Transaction called on blk.num=201.

Contract-2:

contract Timestamp {
   uint start;
   uint end;
   function start(){
      start = block.timestamp;
   } 
   function end(){
      end = block.timestamp;
   } 
   function getTimeDif() returns(uint){
      return end - start;
   }     
}

Scnerio:

Timestamp.start(); //Transaction mined on blk.num=100.
Timestamp.end();  //Transaction mined on blk.num=200.
console.log( Timestamp. getTimeDif(); )  //Transaction called on blk.num=201.

[Q] On the contracts above, should I assume difference between stored now value and stored block.stamp value to be same? ( Timestamp.getTimeDif() ?= Now.getTimeDif() ) Which one might return me the most accurate time difference between two called transactions?

2 Answers 2

48

What is the difference between now and block.timestamp?

Nothing. They're aliases. From the documentation:

now (uint): current block timestamp (alias for block.timestamp)

Update: (Thanks @ShaneFontaine)

Solidity 0.7.0 deprecated the now keyword.

For contracts ^0.7.0, you must use block.timestamp.

3
  • 1
    Update: Solidity 0.7.0 deprecated the now keyword. For contracts ^0.7.0, you must use block.timestamp. Jul 1, 2020 at 16:51
  • 1
    Thanks for the update! Do you mind if I update my answer (referencing your comment)? :-) Jul 2, 2020 at 18:55
  • 1
    Not at all. Please feel free to update it. Jul 2, 2020 at 23:53
0

Use block.timestamp instead of now.

This is still true for Solidity - 0.8.11. Using Truffle v5.4.32 and VSCode which is where I got the TypeError.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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