Created
January 18, 2024 02:17
-
-
Save kosso/9a68462cd6f95689f4b933d80e7b3cf9 to your computer and use it in GitHub Desktop.
Get the Ethereum block number at a given date.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios'); | |
const SUBGRAPH_ETH_BLOCKS = 'https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks'; | |
// Run: `node getBlockFromtimeStamp.js` to see the block number at the given date. | |
const date = 'Fri Dec 24 2021 10:22:12 GMT'; // The date you want to get the block number from. | |
const timestamp = Math.round(new Date(date).getTime() / 1000); // Unix timestamp in seconds | |
getBlockFromTimestamp(timestamp).then(block => { | |
// result | |
console.log('BLOCK:', block, 'AT:', new Date(timestamp * 1000).toUTCString()); | |
}) | |
//////////////////////////////////////////////////////////////////////////////////// | |
async function getBlockFromTimestamp(_timestamp) { | |
try { | |
const block_gql = `{ blocks(first: 1, orderBy: timestamp, orderDirection: asc, where: {timestamp_gt: \\"${_timestamp}\\"}) { number }}`; | |
const query = `{ "query":"${block_gql}","variables":null }`; | |
const response = await axios.post(SUBGRAPH_ETH_BLOCKS, query) | |
return response.data.data.blocks[0].number; | |
} catch (error) { | |
console.log('getBlockFromTimestamp ERROR: ', error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment