Created
June 8, 2023 10:35
-
-
Save reaperes/74930fb3983e759b1dab98452b30f5fc to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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