Skip to content

Instantly share code, notes, and snippets.

@kosso
Created January 18, 2024 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosso/9a68462cd6f95689f4b933d80e7b3cf9 to your computer and use it in GitHub Desktop.
Save kosso/9a68462cd6f95689f4b933d80e7b3cf9 to your computer and use it in GitHub Desktop.
Get the Ethereum block number at a given date.
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