为什么从ethers.js获得的块时间戳不等于在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()

从上面的代码输出:

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 

从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)

我的问题

  1. 我的电脑时钟是准确的时间,为什么这两种方式不同?

  2. 我可以从醚。js API获得准确的块时间,还是可以从其他方式获得?

  1. 区块的时间戳是UTC(因此是@Dmitriy Kashirin提到的时区偏移量),并且不代表区块被开采的确切时间,因为它是由矿工设置的。因此,轻微的偏移是允许的,时间戳不应该被用作敏感合约的随机性来源。点击这里阅读更多内容。

  2. 是的,确切块的时间戳可以相当简单地使用带有RPC提供程序的ethers.js获得:

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;

etherscan。io返回UTC格式的时间。但您当地显示的时间是GMT +8。

最新更新