"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultRedeemAPI = void 0;
const monetary_js_1 = require("@interlay/monetary-js");
const utils_1 = require("../utils");
const issueRedeem_1 = require("../utils/issueRedeem");
class DefaultRedeemAPI {
    constructor(api, btcNetwork, electrsAPI, wrappedCurrency, vaultsAPI, oracleAPI, transactionAPI, assetRgistryAPI, systemAPI, loansAPI) {
        this.api = api;
        this.btcNetwork = btcNetwork;
        this.electrsAPI = electrsAPI;
        this.wrappedCurrency = wrappedCurrency;
        this.vaultsAPI = vaultsAPI;
        this.oracleAPI = oracleAPI;
        this.transactionAPI = transactionAPI;
        this.assetRgistryAPI = assetRgistryAPI;
        this.systemAPI = systemAPI;
        this.loansAPI = loansAPI;
    }
    getRedeemIdsFromEvents(events, event) {
        return issueRedeem_1.getRequestIdsFromEvents(events, event, this.api);
    }
    request(amount, btcAddressEnc, vaultId, atomic = true, retries = 0, cachedVaults) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                if (vaultId) {
                    // If a vault account id is defined, request to issue with that vault only.
                    // Initialize the `amountsPerVault` map with a single entry, the (vaultId, amount) pair
                    const amountsPerVault = new Map([
                        [vaultId, amount],
                    ]);
                    return yield this.requestAdvanced(amountsPerVault, btcAddressEnc, atomic);
                }
                const availableVaults = cachedVaults || (yield this.vaultsAPI.getVaultsWithRedeemableTokens());
                const amountsPerVault = issueRedeem_1.allocateAmountsToVaults(availableVaults, amount);
                const result = yield this.requestAdvanced(amountsPerVault, btcAddressEnc, atomic);
                const successfulSum = result.reduce((sum, req) => sum.add(req.amountBTC), utils_1.newMonetaryAmount(0, this.wrappedCurrency));
                const remainder = amount.sub(successfulSum);
                if (remainder.isZero() || retries === 0)
                    return result;
                else {
                    return (yield this.request(remainder, btcAddressEnc, vaultId, atomic, retries - 1, availableVaults)).concat(result);
                }
            }
            catch (e) {
                return Promise.reject(e);
            }
        });
    }
    buildRequestRedeemExtrinsic(vaultId, amount, btcAddressEnc) {
        const btcAddress = this.api.createType("BitcoinAddress", utils_1.decodeBtcAddress(btcAddressEnc, this.btcNetwork));
        const amountInAtomicUnits = amount.toString(true);
        return this.api.tx.redeem.requestRedeem(amountInAtomicUnits, btcAddress, vaultId);
    }
    requestAdvanced(amountsPerVault, btcAddressEnc, atomic) {
        return __awaiter(this, void 0, void 0, function* () {
            const txes = Array.from(amountsPerVault).map(([vaultId, amount]) => this.buildRequestRedeemExtrinsic(vaultId, amount, btcAddressEnc));
            const batch = this.transactionAPI.buildBatchExtrinsic(txes, atomic);
            try {
                // When requesting a redeem, wait for the finalized event because we cannot revert BTC transactions.
                // For more details see: https://github.com/interlay/interbtc-api/pull/373#issuecomment-1058949000
                const result = yield this.transactionAPI.sendLogged(batch, this.api.events.issue.RequestRedeem);
                const ids = this.getRedeemIdsFromEvents(result.events, this.api.events.redeem.RequestRedeem);
                const redeemRequests = yield this.getRequestsByIds(ids);
                return redeemRequests;
            }
            catch (e) {
                return Promise.reject(e);
            }
        });
    }
    buildExecuteRedeemExtrinsic(redeemId, btcTxId) {
        return __awaiter(this, void 0, void 0, function* () {
            const parsedRequestId = utils_1.ensureHashEncoded(this.api, redeemId);
            const txInclusionDetails = yield utils_1.getTxProof(this.electrsAPI, btcTxId);
            return this.api.tx.redeem.executeRedeem(parsedRequestId, txInclusionDetails.merkleProof, txInclusionDetails.rawTx);
        });
    }
    execute(requestId, btcTxId) {
        return __awaiter(this, void 0, void 0, function* () {
            const tx = yield this.buildExecuteRedeemExtrinsic(requestId, btcTxId);
            yield this.transactionAPI.sendLogged(tx, this.api.events.redeem.ExecuteRedeem, true);
        });
    }
    buildCancelRedeemExtrinsic(redeemId, reimburse) {
        const parsedRequestId = utils_1.ensureHashEncoded(this.api, redeemId);
        return this.api.tx.redeem.cancelRedeem(parsedRequestId, reimburse);
    }
    cancel(requestId, reimburse = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const cancelRedeemTx = this.buildCancelRedeemExtrinsic(requestId, reimburse);
            yield this.transactionAPI.sendLogged(cancelRedeemTx, this.api.events.redeem.CancelRedeem, true);
        });
    }
    buildLiquidationRedeemExtrinsic(amount, collateralCurrency) {
        const vaultCurrencyPair = utils_1.newVaultCurrencyPair(this.api, collateralCurrency, this.wrappedCurrency);
        const amountAtomicUnit = this.api.createType("Balance", amount.toString(true));
        return this.api.tx.redeem.liquidationRedeem(vaultCurrencyPair, amountAtomicUnit);
    }
    burn(amount, collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const burnRedeemTx = this.buildLiquidationRedeemExtrinsic(amount, collateralCurrency);
            yield this.transactionAPI.sendLogged(burnRedeemTx, this.api.events.redeem.LiquidationRedeem, true);
        });
    }
    setRedeemPeriod(blocks) {
        return __awaiter(this, void 0, void 0, function* () {
            const period = this.api.createType("BlockNumber", blocks);
            const tx = this.api.tx.sudo.sudo(this.api.tx.redeem.setRedeemPeriod(period));
            yield this.transactionAPI.sendLogged(tx, undefined, true);
        });
    }
    getRedeemPeriod() {
        return __awaiter(this, void 0, void 0, function* () {
            const blockNumber = yield this.api.query.redeem.redeemPeriod();
            return blockNumber.toNumber();
        });
    }
    getMaxBurnableTokens(collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const liquidationVault = yield this.vaultsAPI.getLiquidationVault(collateralCurrency);
            // This should never be below 0, but still...
            const burnableTokens = liquidationVault.issuedTokens.sub(liquidationVault.toBeRedeemedTokens);
            if (burnableTokens.lte(monetary_js_1.BitcoinAmount.zero())) {
                return monetary_js_1.BitcoinAmount.zero();
            }
            else {
                return burnableTokens;
            }
        });
    }
    getBurnExchangeRate(collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const liquidationVault = yield this.vaultsAPI.getLiquidationVault(collateralCurrency);
            const burnableAmount = liquidationVault.issuedTokens
                .add(liquidationVault.toBeIssuedTokens)
                .sub(liquidationVault.toBeRedeemedTokens);
            if (burnableAmount.isZero()) {
                return Promise.reject(new Error("There are no burnable tokens. The burn exchange rate is undefined"));
            }
            const collateralAmount = liquidationVault.collateral;
            const exchangeRate = collateralAmount.toBig().div(burnableAmount.toBig());
            return new monetary_js_1.ExchangeRate(monetary_js_1.Bitcoin, collateralCurrency, exchangeRate);
        });
    }
    getCurrentInclusionFee() {
        return __awaiter(this, void 0, void 0, function* () {
            const [size, satoshiFees] = yield Promise.all([
                this.api.query.redeem.redeemTransactionSize(),
                this.oracleAPI.getBitcoinFees(),
            ]);
            const btcFees = utils_1.newMonetaryAmount(satoshiFees, this.wrappedCurrency);
            return btcFees.mul(size.toString());
        });
    }
    list() {
        return __awaiter(this, void 0, void 0, function* () {
            const head = yield this.api.rpc.chain.getFinalizedHead();
            const [redeemRequests, redeemPeriod, activeBlockNumber] = yield Promise.all([
                this.api.query.redeem.redeemRequests.entriesAt(head),
                this.getRedeemPeriod(),
                this.systemAPI.getCurrentActiveBlockNumber(head),
            ]);
            return yield Promise.all(redeemRequests
                .filter(([_, req]) => req.isSome.valueOf())
                // Can be unwrapped because the filter removes `None` values
                .map(([id, req]) => {
                return utils_1.parseRedeemRequest(this.vaultsAPI, this.assetRgistryAPI, this.loansAPI, req.unwrap(), this.btcNetwork, utils_1.storageKeyToNthInner(id), redeemPeriod, activeBlockNumber);
            }));
        });
    }
    getFeesToPay(amount) {
        return __awaiter(this, void 0, void 0, function* () {
            const feePercentage = yield this.getFeeRate();
            return amount.mul(feePercentage);
        });
    }
    getFeeRate() {
        return __awaiter(this, void 0, void 0, function* () {
            const redeemFee = yield this.api.query.fee.redeemFee();
            return utils_1.decodeFixedPointType(redeemFee);
        });
    }
    getDustValue() {
        return __awaiter(this, void 0, void 0, function* () {
            const dustValueSat = yield this.api.query.redeem.redeemBtcDustValue();
            return utils_1.newMonetaryAmount(dustValueSat.toString(), this.wrappedCurrency);
        });
    }
    getPremiumRedeemFeeRate() {
        return __awaiter(this, void 0, void 0, function* () {
            const premiumRedeemFee = yield this.api.query.fee.premiumRedeemFee();
            return utils_1.decodeFixedPointType(premiumRedeemFee);
        });
    }
    getRequestById(redeemId) {
        return __awaiter(this, void 0, void 0, function* () {
            const id = utils_1.ensureHashEncoded(this.api, redeemId);
            return (yield this.getRequestsByIds([id]))[0];
        });
    }
    getRequestsByIds(redeemIds) {
        return __awaiter(this, void 0, void 0, function* () {
            const redeemRequestData = yield Promise.all(redeemIds.map((redeemId) => __awaiter(this, void 0, void 0, function* () {
                return new Promise((resolve, reject) => {
                    this.api.query.redeem
                        .redeemRequests(utils_1.ensureHashEncoded(this.api, redeemId))
                        .then((request) => resolve([request, redeemId]))
                        .catch(reject);
                });
            })));
            const [redeemPeriod, activeBlockCount] = yield Promise.all([
                this.getRedeemPeriod(),
                this.systemAPI.getCurrentActiveBlockNumber(),
            ]);
            return Promise.all(redeemRequestData
                .filter(([option, _]) => option.isSome)
                .map(([redeemRequest, redeemId]) => utils_1.parseRedeemRequest(this.vaultsAPI, this.assetRgistryAPI, this.loansAPI, redeemRequest.unwrap(), this.btcNetwork, redeemId, redeemPeriod, activeBlockCount)));
        });
    }
}
exports.DefaultRedeemAPI = DefaultRedeemAPI;
//# sourceMappingURL=redeem.js.map