"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCachedBlockForTimestamp = getCachedBlockForTimestamp;
const TypeGuards_1 = require("./TypeGuards");
const TimeUtils_1 = require("./TimeUtils");
const CachingUtils_1 = require("./CachingUtils");
const constants_1 = require("../constants");
async function getCachedBlockForTimestamp(chainId, timestamp, blockFinder, cache, hints) {
    const resolver = async () => (await blockFinder.getBlockForTimestamp(timestamp, hints || {})).number;
    if (!(0, TypeGuards_1.isDefined)(cache)) {
        return resolver();
    }
    const key = `${chainId}_block_number_${timestamp}`;
    if ((0, CachingUtils_1.shouldCache)(timestamp, (0, TimeUtils_1.getCurrentTime)(), constants_1.DEFAULT_CACHING_SAFE_LAG)) {
        const result = await cache.get(key);
        if (result !== null) {
            return parseInt(result);
        }
        else {
            const blockNumber = await resolver();
            await cache.set(key, blockNumber.toString(), 60 * 60 * 24 * 90);
            return blockNumber;
        }
    }
    else {
        return resolver();
    }
}
//# sourceMappingURL=BlockUtils.js.map