|
1 |
| -import { getLatestBlock as getLatestBlockSdk } from "@defillama/sdk/build/util"; |
| 1 | +import { getLatestBlock as getLatestBlockSdk, lookupBlock } from "@defillama/sdk/build/util"; |
2 | 2 | // import { getClient } from "../helpers/sui";
|
3 | 3 | import { tronGetLatestBlock } from "../helpers/tron";
|
4 | 4 | import { getConnection } from "../helpers/solana";
|
| 5 | +import { Chain } from "@defillama/sdk/build/general"; |
5 | 6 |
|
6 | 7 | export async function getLatestBlockNumber(chain: string): Promise<number> {
|
7 | 8 | if (chain === "sui") {
|
@@ -35,3 +36,27 @@ export async function getLatestBlock(chain: string): Promise<{ number: number; t
|
35 | 36 | }
|
36 | 37 | return await getLatestBlockSdk(chain);
|
37 | 38 | }
|
| 39 | + |
| 40 | +export async function getBlockByTimestamp(timestamp: number, chain: Chain) { |
| 41 | + if (chain === "solana") { |
| 42 | + const { timestamp: latestTimestamp, number } = await getLatestBlock(chain); |
| 43 | + // There is not an easy way to get the slot number from a timestamp on Solana |
| 44 | + // without hammering the RPC node with requests. |
| 45 | + // So we estimate it by assuming that a slot is produced every 400ms. |
| 46 | + if (timestamp <= latestTimestamp) { |
| 47 | + const slot = number - Math.floor(((latestTimestamp - timestamp) * 1000) / 400); |
| 48 | + return { block: slot, timestamp }; |
| 49 | + } |
| 50 | + } else { |
| 51 | + return await lookupBlock(timestamp, { chain }); |
| 52 | + } |
| 53 | + throw new Error(`Could not find block for timestamp ${timestamp} on chain ${chain}`); |
| 54 | +} |
| 55 | + |
| 56 | +export async function getTimestampBySolanaSlot(slot: number) { |
| 57 | + const { timestamp: latestTimestamp, number } = await getLatestBlock("solana"); |
| 58 | + |
| 59 | + const timestamp = latestTimestamp - ((number - slot) * 400) / 1000; |
| 60 | + |
| 61 | + return timestamp; |
| 62 | +} |
0 commit comments