2025-05-30 19:59:02 +00:00
|
|
|
import { ethers } from "ethers"
|
2023-07-02 20:23:22 +03:00
|
|
|
|
2025-05-30 19:59:02 +00:00
|
|
|
const URL = "https://eth-mainnet.public.blastapi.io"
|
2023-07-02 20:23:22 +03:00
|
|
|
|
|
|
|
|
const provider = await ethers.getDefaultProvider(URL)
|
|
|
|
|
|
2025-05-30 19:59:02 +00:00
|
|
|
const latest = await provider.getBlock("latest")
|
2023-07-02 20:23:22 +03:00
|
|
|
|
2023-07-07 15:43:35 +03:00
|
|
|
/*
|
|
|
|
|
Find ethereum block by timestamp using binary search
|
|
|
|
|
*/
|
2025-05-30 19:59:02 +00:00
|
|
|
async function getBlockNumberByTimestamp(
|
|
|
|
|
timestamp,
|
|
|
|
|
low = 0,
|
|
|
|
|
high = latest.number,
|
|
|
|
|
) {
|
|
|
|
|
if (low + 1 == high) {
|
2023-07-02 20:23:22 +03:00
|
|
|
return low
|
|
|
|
|
} else {
|
|
|
|
|
const mid = Math.floor((low + high) / 2)
|
|
|
|
|
const midBlock = await provider.getBlock(mid)
|
2025-05-30 19:59:02 +00:00
|
|
|
if (midBlock.timestamp > timestamp) {
|
2023-07-02 20:23:22 +03:00
|
|
|
return getBlockNumberByTimestamp(timestamp, low, mid)
|
|
|
|
|
} else {
|
|
|
|
|
return getBlockNumberByTimestamp(timestamp, mid, high)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-30 19:59:02 +00:00
|
|
|
const timestamp = new Date("2019-06-01").getTime() / 1000
|
2023-07-02 20:23:22 +03:00
|
|
|
const blockNumber = await getBlockNumberByTimestamp(timestamp)
|
|
|
|
|
const block = await provider.getBlock(blockNumber)
|