"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.feeRoute = void 0;
const express_1 = __importDefault(require("express"));
const config_1 = __importDefault(require("../../config"));
const logger_1 = __importDefault(require("../../logger"));
const chain_state_1 = require("../../providers/chain-state");
const middleware_1 = require("../middleware");
const middleware_2 = require("../middleware");
const router = express_1.default.Router({ mergeParams: true });
const feeCache = {};
const feeModes = {
    BTC: ['CONSERVATIVE', 'ECONOMICAL'],
    LTC: ['CONSERVATIVE', 'ECONOMICAL']
};
router.get('/:target', (0, middleware_2.CacheMiddleware)(middleware_1.CacheTimes.Second), async (req, res) => {
    let { chain, network } = req.params;
    const { target } = req.params;
    let { mode } = req.query;
    const { txType, signatures } = req.query;
    if (!chain || !network) {
        return res.status(400).send('Missing required param');
    }
    chain = chain.toUpperCase();
    network = network.toLowerCase();
    mode = mode?.toUpperCase();
    const numSignatures = Number(signatures) || 1;
    const targetNum = Number(target);
    if (targetNum < 0 || targetNum > 100) {
        return res.status(400).send('invalid target specified');
    }
    if (!mode) {
        mode = config_1.default.chains[chain]?.[network]?.defaultFeeMode;
    }
    else if (!feeModes[chain]) {
        mode = undefined;
    }
    else if (!feeModes[chain]?.includes(mode)) {
        return res.status(400).send('invalid mode specified');
    }
    if (txType && txType.toString() != '2') {
        return res.status(400).send('invalid txType specified');
    }
    let feeCacheKey = `${chain}:${network}:${target}`;
    feeCacheKey += `${mode ? ':' + mode : ''}`;
    feeCacheKey += `${txType ? ':type' + txType : ''}`;
    feeCacheKey += `${signatures ? ':' + numSignatures : ''}`;
    const cachedFee = feeCache[feeCacheKey];
    if (cachedFee && cachedFee.date > Date.now() - 10 * 1000) {
        return res.json(cachedFee.fee);
    }
    try {
        const fee = await chain_state_1.ChainStateProvider.getFee({ chain, network, target: targetNum, mode, txType, signatures: numSignatures });
        if (!fee) {
            return res.status(404).send('not available right now');
        }
        // As of v0.21.2.2, Litecoin Core has a bug where it returns a fee rate of 0.00000999 which is below the min relay fee (0.00001).
        // TODO: remove this if statement once https://github.com/litecoin-project/litecoin/issues/908 is fixed.
        if (chain === 'LTC' && fee.feerate && fee.feerate < 0.00001) {
            fee.feerate = 0.00001;
        }
        feeCache[feeCacheKey] = { fee, date: Date.now() };
        return res.json(fee);
    }
    catch (err) {
        logger_1.default.error('Fee Error: %o', err?.stack || err?.message || err || '(unknown)');
        return res.status(500).send('Error getting fee from RPC');
    }
});
exports.feeRoute = {
    router,
    path: '/fee'
};
//# sourceMappingURL=fee.js.map