Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the timestamp of block get from ethers.js not equals to display in etherscan.io?

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?

like image 223
cruelcage Avatar asked Oct 27 '25 15:10

cruelcage


1 Answers

  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;
like image 71
Peter Slaný Avatar answered Oct 29 '25 18:10

Peter Slaný



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!