Skip to content

Instantly share code, notes, and snippets.

@reaperes
Created June 8, 2023 10:35
Show Gist options
  • Save reaperes/74930fb3983e759b1dab98452b30f5fc to your computer and use it in GitHub Desktop.
Save reaperes/74930fb3983e759b1dab98452b30f5fc to your computer and use it in GitHub Desktop.
/**
* Not working itself. only shows how to get block number from timestamp for example
**/
export async function findBlockNumberFromTimestamp(timestamp) {
invariant(timestamp <= new Date().getTime(), `timestamp: ${timestamp} should be less than or equal current timestamp`)
const targetTimestamp = convertToTimestampSeconds(timestamp)
const latestBlockNumber = await jsonRpcProvider.getBlockNumber()
const latestTimestamp = await blockTimestampFetcher.fetch(latestBlockNumber) as number
let timestampGap = targetTimestamp - latestTimestamp
if (timestampGap === 0) {
return latestBlockNumber
}
let blockGap = Math.floor(timestampGap / BSC_BLOCK_INTERVAL_SECONDS)
let estimatedBlockNumber = latestBlockNumber + blockGap
let estimatedBlockTimestamp = await blockTimestampFetcher.fetch(estimatedBlockNumber) as number
while (true) {
timestampGap = targetTimestamp - estimatedBlockTimestamp
if (timestampGap === 0) {
return estimatedBlockNumber
}
blockGap = Math.floor(timestampGap / BSC_BLOCK_INTERVAL_SECONDS)
if (blockGap === 0) {
let nextEstimatedBlockNumber
let nextEstimatedBlockTimestamp
if (timestampGap > 0) {
while (true) {
nextEstimatedBlockNumber = estimatedBlockNumber + 1
nextEstimatedBlockTimestamp = await blockTimestampFetcher.fetch(nextEstimatedBlockNumber) as number
timestampGap = targetTimestamp - nextEstimatedBlockTimestamp
if (timestampGap < 0) {
return estimatedBlockNumber
}
estimatedBlockNumber = nextEstimatedBlockNumber
}
} else {
while (true) {
nextEstimatedBlockNumber = estimatedBlockNumber - 1
nextEstimatedBlockTimestamp = await blockTimestampFetcher.fetch(nextEstimatedBlockNumber) as number
timestampGap = targetTimestamp - nextEstimatedBlockTimestamp
if (timestampGap > 0) {
return estimatedBlockNumber
}
estimatedBlockNumber = nextEstimatedBlockNumber
}
}
}
estimatedBlockNumber = estimatedBlockNumber + blockGap
estimatedBlockTimestamp = await blockTimestampFetcher.fetch(estimatedBlockNumber) as number
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment