An efficient and accurate way to search for Ethereum block numbers by date
Support all EVM chains (Polygon, Fantom, Arbitrum, Avalanche, etc...)
Uses an interpolation search algorithm
Current version supports Web3.js and ethers.js providers
Finds blocks 2x faster than ethereum-block-by-date, while using half the RPC calls
Using npm:
npm i eth-date-to-block
Using yarn:
yarn add eth-date-to-block
import EthereumDater from "eth-date-to-block";
import Web3 from "web3";
const web3 = new Web3(new Web3.providers.HttpProvider(process.env.PROVIDER));
const dater = new EthereumDater(
web3.eth, // Web3 eth provider, required.
{
accuracy, // Optional. Returns a block number within an accuracy of n seconds. Default 10.
maxRetries, // Optional. Max amount of RPC calls allowed. Default 15.
},
);
const EthereumDater = require("eth-date-to-block");
const { ethers } = require("ethers");
const ethersProvider = ethers.providers.JsonRpcProvider(process.env.PROVIDER);
const dater = new EthereumDater(
ethersProvider, // Ethers provider, required.
);
// Getting block by date:
const block = await dater.getBlock(
"2016-07-20T13:20:40Z", // Any valid Date() constructor value
);
/* Returns {
block: {
number: number; // Resolved block number
timestamp: number; // Timestamp the resolved block was mined
date: Date; // Date() object of block's timestamp
};
retries: number; // Number of reties (RPC requests made)
secondsFromTarget: number; // Delta between the target timestamp minus the resolved blocks timestamp
} */
Note: if date is out of range (before genesis block or in the future), getBlock() will throw a relevant error
If you need any help, please contact me via GitHub issues page: GitHub
Feel free to open new issues and pull requests!