4
import {providers} from "ethers";

const provider = new providers.InfuraProvider("homestead")

async function main() {
    provider.on("block", (blockNum)=> {
        console.log(blockNum+ ": " +new Date(Date.now()))
    })
}

main()

From code above output:

13261128: Mon Sep 20 2021 14:57:42 GMT+0800 
13261129: Mon Sep 20 2021 14:58:14 GMT+0800 
13261130: Mon Sep 20 2021 14:58:42 GMT+0800 
13261131: Mon Sep 20 2021 14:58:58 GMT+0800 

From etherscan.io:

Sep-20-2021 06:57:12 AM +UTC (https://etherscan.io/block/13261028)
Sep-20-2021 06:57:23 AM +UTC (https://etherscan.io/block/13261129)
Sep-20-2021 06:58:07 AM +UTC (https://etherscan.io/block/13261130)
Sep-20-2021 06:58:38 AM +UTC (https://etherscan.io/block/13261131)

My question

  1. My computer's clock is exact what the time is, why the difference between this two way?

  2. Can I get the accurate block time from ethers.js API or can get it from the other way?

cruelcage
  • 2,044
  • 6
  • 19
  • 19

2 Answers2

7
  1. Timestamp of the block is in UTC (hence the timezone offset as mentioned by @Dmitriy Kashirin) and does not represent exact time the block has been mined as it is set by the miner. Therefore, slight offsets are allowed and timestamp shouldn't be used as the source of randomness for sensitive contracts. Read more here.

  2. Yes, the timestamp of the exact block can be obtained fairly simple using ethers.js with RPC provider:

const RPC = "RPC_OF_THE_NETWORK";
const blockNumber = 1; // number of the block you want to get timestamp of
const provider = new ethers.providers.JsonRpcProvider(RPC)

const timestamp = (await provider.getBlock(blockNumber)).timestamp;
Peter Slaný
  • 193
  • 12
  • 1
    This answer is correct. OP must understand that block timestamp is generated by the miner. Trying to use the local Date and assume that each block will have the exact same date as the Date.now() function is wrong. Thats where the difference is seconds comes from. – Juanu Dec 25 '21 at 09:43
0

etherscan.io returns time in UTC. But your local shown time is GMT +8.

  • That doesn't explain the difference from the examples. Even after accounting for the timezone, the given example times are still (slightly) different. – Bastian Blankenburg Dec 22 '21 at 07:40
  • @peter-slaný 's answer is correct. Also, look at the comment. You are assuming that the when the event is raised, the block will have the time of your computer. The actual timestamp of a block is defined by the miner so there can always be a difference in seconds between when the block is mined and when the event is called. – Juanu Dec 25 '21 at 09:45