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?

alper
  • 8,395
  • 11
  • 63
  • 152

2 Answers2

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.

Richard Horrocks
  • 37,835
  • 13
  • 87
  • 144
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.

yaach
  • 121
  • 1