ethers-io / ethers.js

Complete Ethereum library and wallet implementation in JavaScript.
https://ethers.org/
MIT License
7.96k stars 1.85k forks source link

Get Block closest to a timestampt #3672

Open sebastiantf opened 1 year ago

sebastiantf commented 1 year ago

Describe the Feature

I was looking for an API that fetches you the block thats closest to a given timestamp. This feature is available in Foundry's cast CLI: cast find-block. There's also the ethereum-block-by-date package

Edit: There's also Etherscan's API: https://docs.etherscan.io/api-endpoints/blocks#get-block-number-by-timestamp

Code Example

provider.getBlockByTimestamp(1674193355)
ricmoo commented 1 year ago

There is no API that I know of that provides this sort of service. How do they do that? By guessing based on block time and extrapolating/interpolating?

What networks does it work with?

sebastiantf commented 1 year ago

There's also Etherscan's API: https://docs.etherscan.io/api-endpoints/blocks#get-block-number-by-timestamp

ricmoo commented 1 year ago

Any API added to the Provider Interface must be present in all (or at least almost all) backends.

It is possible to add a method to just the EtherscanProvider though, similar to getHistory.

sebastiantf commented 1 year ago

cast find-block seem to be doing a binary search, I think.

ethereum-block-by-date seem to be doing some form of extrapolation / heuristics.

Haven't really dug into either of them

ricmoo commented 1 year ago

For now, I'll prolly leave it as an option for someone to provide a utility library for then, some function that looks like getBlockByTimestamp(provider: Provider). But if it becomes popular, useful and (generally) efficient, I can add it to the internal API.

I'll likely include it in the EtherscanProvider though, since it is just coming from an index.