"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFeeItems = exports.defaultBlockCount = exports.speeds = void 0;
const errors_1 = require("@ledgerhq/errors");
const cache_1 = require("@ledgerhq/live-network/cache");
const live_network_1 = __importDefault(require("@ledgerhq/live-network"));
const bignumber_js_1 = require("bignumber.js");
const invariant_1 = __importDefault(require("invariant"));
const explorer_1 = require("@ledgerhq/coin-bitcoin/explorer");
const getEstimatedFees = (0, cache_1.makeLRUCache)(async (currency) => {
    const baseURL = (0, explorer_1.blockchainBaseURL)(currency);
    (0, invariant_1.default)(baseURL, `Fees for ${currency.id} are not supported`);
    const { data, status } = await (0, live_network_1.default)({
        method: "GET",
        url: `${baseURL}/fees`,
    });
    if (data) {
        return data;
    }
    throw new errors_1.FeeEstimationFailed(`FeeEstimationFailed ${status}`, {
        httpStatus: status,
    });
}, c => c.id);
exports.speeds = new Map([
    [1, "fast"],
    [3, "medium"],
    [6, "slow"],
]);
exports.defaultBlockCount = 3;
/**
 * Returns the current network fee rate(fast, medium, slow) from our backend for a given currency
 */
const getFeeItems = async (currency) => {
    const all = [];
    const fees = await getEstimatedFees(currency);
    let defaultFeePerByte = new bignumber_js_1.BigNumber(0);
    for (const key of Object.keys(fees)) {
        const feePerByte = new bignumber_js_1.BigNumber(Math.ceil(fees[key] / 1000));
        const blockCount = parseInt(key, 10);
        if (blockCount === exports.defaultBlockCount)
            defaultFeePerByte = feePerByte;
        if (!Number.isNaN(blockCount) && !feePerByte.isNaN() && exports.speeds.has(blockCount)) {
            all.push({
                key,
                speed: exports.speeds.get(blockCount),
                blockCount,
                feePerByte,
            });
        }
    }
    const items = all
        .sort((a, b) => a.blockCount - b.blockCount)
        .map(({ key, speed, feePerByte }) => ({
        key,
        speed,
        feePerByte,
    }));
    return {
        items,
        defaultFeePerByte,
    };
};
exports.getFeeItems = getFeeItems;
//# sourceMappingURL=api.js.map