"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDepositKey = exports.setDepositInCache = exports.getDepositInCache = exports.shouldCache = void 0;
var tslib_1 = require("tslib");
var constants_1 = require("../constants");
var assert_1 = tslib_1.__importDefault(require("assert"));
var ReviverUtils_1 = require("./ReviverUtils");
var DepositUtils_1 = require("./DepositUtils");
var TimeUtils_1 = require("./TimeUtils");
var TypeGuards_1 = require("./TypeGuards");
function shouldCache(eventTimestamp, latestTime, cachingMaxAge) {
    (0, assert_1.default)(eventTimestamp.toString().length === 10, "eventTimestamp must be in seconds");
    (0, assert_1.default)(latestTime.toString().length === 10, "eventTimestamp must be in seconds");
    return latestTime - eventTimestamp >= cachingMaxAge;
}
exports.shouldCache = shouldCache;
function getDepositInCache(key, cache) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var depositRaw;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4, cache.get(key)];
                case 1:
                    depositRaw = _a.sent();
                    return [2, (0, TypeGuards_1.isDefined)(depositRaw) ? JSON.parse(depositRaw, (0, ReviverUtils_1.composeRevivers)(ReviverUtils_1.objectWithBigNumberReviver)) : undefined];
            }
        });
    });
}
exports.getDepositInCache = getDepositInCache;
function setDepositInCache(deposit, currentChainTime, cache, expirySeconds, timeToCache) {
    if (expirySeconds === void 0) { expirySeconds = constants_1.DEFAULT_CACHING_TTL; }
    if (timeToCache === void 0) { timeToCache = constants_1.DEFAULT_CACHING_SAFE_LAG; }
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var currentTimeInSeconds;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    currentTimeInSeconds = (0, TimeUtils_1.getCurrentTime)();
                    if (deposit.quoteTimestamp > currentTimeInSeconds || currentChainTime > currentTimeInSeconds) {
                        return [2];
                    }
                    if (!shouldCache(deposit.quoteTimestamp, currentChainTime, timeToCache)) return [3, 2];
                    return [4, cache.set(getDepositKey(deposit), JSON.stringify(deposit), expirySeconds)];
                case 1:
                    _a.sent();
                    _a.label = 2;
                case 2: return [2];
            }
        });
    });
}
exports.setDepositInCache = setDepositInCache;
function getDepositKey(bridgeEvent) {
    var relayHash = (0, DepositUtils_1.getRelayEventKey)(bridgeEvent);
    return "deposit_".concat(bridgeEvent.originChainId, "_").concat(bridgeEvent.depositId.toString(), "_").concat(relayHash);
}
exports.getDepositKey = getDepositKey;
//# sourceMappingURL=CachingUtils.js.map