@moonwell-fi/moonwell-sdk
Version:
TypeScript Interface for Moonwell
42 lines • 1.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBlockNumberAtTimestamp = getBlockNumberAtTimestamp;
const MAX_ITERATIONS = 8;
async function getBlockNumberAtTimestamp(publicClient, targetTimestamp) {
const latest = await publicClient.getBlock({ blockTag: "latest" });
if (targetTimestamp >= latest.timestamp)
return latest.number;
if (latest.number === 0n)
return latest.number;
const first = await publicClient.getBlock({ blockNumber: 1n });
if (targetTimestamp <= first.timestamp)
return first.number;
let lo = first.number;
let loTs = first.timestamp;
let hi = latest.number;
let hiTs = latest.timestamp;
for (let i = 0; i < MAX_ITERATIONS; i += 1) {
if (hi - lo <= 1n)
break;
const tsRange = hiTs - loTs;
if (tsRange <= 0n)
break;
const offset = ((targetTimestamp - loTs) * (hi - lo)) / tsRange;
let mid = lo + offset;
if (mid <= lo)
mid = lo + 1n;
if (mid >= hi)
mid = hi - 1n;
const block = await publicClient.getBlock({ blockNumber: mid });
if (block.timestamp <= targetTimestamp) {
lo = mid;
loTs = block.timestamp;
}
else {
hi = mid;
hiTs = block.timestamp;
}
}
return lo;
}
//# sourceMappingURL=getBlockNumberAtTimestamp.js.map