"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlockCypher = exports.BlockCypherClass = void 0;
const util_1 = __importDefault(require("util"));
const request_1 = __importDefault(require("request"));
const logger_1 = __importDefault(require("../../logger"));
class BlockCypherClass {
    constructor() {
        this.feeUrls = {
            mainnet: 'https://api.blockcypher.com/v1/btc/main',
            testnet3: 'https://api.blockcypher.com/v1/btc/test3'
        };
        this.cache = {
            mainnet: {
                timestamp: 0,
                response: null
            },
            testnet3: {
                timestamp: 0,
                response: null
            }
        };
    }
    async getFee(network, nblocks) {
        try {
            network = network === 'regtest' ? 'testnet3' : network;
            // blockcypher rate limits to 3 req/s or 100 req/hr, so cache for 1.5 minutes
            if (this.cache[network] && this.cache[network].timestamp > Date.now() - 1000 * 90) {
                return this._getFeeLevel(this.cache[network].response, nblocks);
            }
            const res = await util_1.default.promisify(request_1.default.get).call(request_1.default, {
                uri: this.feeUrls[network],
                json: true
            });
            if (res.statusCode !== 200) {
                throw new Error(`Status code: ${res.statusCode}`);
            }
            const fee = res.body;
            this.cache[network] = {
                timestamp: Date.now(),
                response: fee
            };
            return this._getFeeLevel(fee, nblocks);
        }
        catch (err) {
            logger_1.default.warn('Error getting fee from blockcypher: %o', err.message || err);
            throw err;
        }
    }
    ;
    /**
     * Return the appropriate fee level for nblocks per the ref.
     * REF: https://www.blockcypher.com/dev/bitcoin/#blockchain
     * @param response
     * @param nblocks
     * @returns
     */
    _getFeeLevel(response, nblocks) {
        if (nblocks <= 2) {
            return response.high_fee_per_kb / 1000;
        }
        else if (nblocks <= 6) {
            return response.medium_fee_per_kb / 1000;
        }
        else {
            return response.low_fee_per_kb / 1000;
        }
    }
    ;
}
exports.BlockCypherClass = BlockCypherClass;
;
exports.BlockCypher = new BlockCypherClass();
//# sourceMappingURL=blockcypher.js.map