"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) {
        this.api = api;
        this.btcNetwork = btcNetwork;
        this.electrsAPI = electrsAPI;
        this.wrappedCurrency = wrappedCurrency;
        this.vaultsAPI = vaultsAPI;
        this.oracleAPI = oracleAPI;
        this.transactionAPI = transactionAPI;
    }
    getRedeemIdsFromEvents(events, event) {
        return (0, 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 = (0, issueRedeem_1.allocateAmountsToVaults)(availableVaults, amount);
                const result = yield this.requestAdvanced(amountsPerVault, btcAddressEnc, atomic);
                const successfulSum = result.reduce((sum, req) => sum.add(req.amountBTC), (0, 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);
            }
        });
    }
    requestAdvanced(amountsPerVault, btcAddressEnc, atomic) {
        return __awaiter(this, void 0, void 0, function* () {
            const btcAddress = this.api.createType("BitcoinAddress", (0, utils_1.decodeBtcAddress)(btcAddressEnc, this.btcNetwork));
            const txes = new Array();
            for (const [vaultId, amount] of amountsPerVault) {
                txes.push(this.api.tx.redeem.requestRedeem(amount.str.Satoshi(), btcAddress, vaultId));
            }
            // batchAll fails atomically, batch allows partial successes
            const batch = (atomic ? this.api.tx.utility.batchAll : this.api.tx.utility.batch)(txes);
            try {
                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);
            }
        });
    }
    execute(requestId, btcTxId) {
        return __awaiter(this, void 0, void 0, function* () {
            const parsedRequestId = (0, utils_1.ensureHashEncoded)(this.api, requestId);
            const txInclusionDetails = yield (0, utils_1.getTxProof)(this.electrsAPI, btcTxId);
            const tx = this.api.tx.redeem.executeRedeem(parsedRequestId, txInclusionDetails.merkleProof, txInclusionDetails.rawTx);
            yield this.transactionAPI.sendLogged(tx, this.api.events.redeem.ExecuteRedeem, true);
        });
    }
    cancel(requestId, reimburse = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const parsedRequestId = (0, utils_1.ensureHashEncoded)(this.api, requestId);
            const cancelRedeemTx = this.api.tx.redeem.cancelRedeem(parsedRequestId, reimburse);
            yield this.transactionAPI.sendLogged(cancelRedeemTx, this.api.events.redeem.CancelRedeem, true);
        });
    }
    burn(amount, collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const vaultCurrencyPair = (0, utils_1.newVaultCurrencyPair)(this.api, collateralCurrency, this.wrappedCurrency);
            const amountAtomicUnit = this.api.createType("Balance", amount.str.Satoshi());
            const burnRedeemTx = this.api.tx.redeem.liquidationRedeem(vaultCurrencyPair, amountAtomicUnit);
            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 issuedAmount = liquidationVault.issuedTokens.add(liquidationVault.toBeIssuedTokens);
            if (issuedAmount.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(collateralAmount.currency.base)
                .div(issuedAmount.toBig(monetary_js_1.Bitcoin.units.BTC));
            return new monetary_js_1.ExchangeRate(monetary_js_1.Bitcoin, collateralCurrency, exchangeRate, monetary_js_1.Bitcoin.units.BTC, collateralCurrency.base);
        });
    }
    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 = (0, 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 = yield this.api.query.redeem.redeemRequests.entriesAt(head);
            return yield Promise.all(redeemRequests
                .filter(([_, req]) => req.isSome.valueOf())
                // Can be unwrapped because the filter removes `None` values
                .map(([id, req]) => {
                return (0, utils_1.parseRedeemRequest)(this.vaultsAPI, req.unwrap(), this.btcNetwork, (0, utils_1.storageKeyToNthInner)(id));
            }));
        });
    }
    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 (0, utils_1.decodeFixedPointType)(redeemFee);
        });
    }
    getDustValue() {
        return __awaiter(this, void 0, void 0, function* () {
            const dustValueSat = yield this.api.query.redeem.redeemBtcDustValue();
            return (0, 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 (0, utils_1.decodeFixedPointType)(premiumRedeemFee);
        });
    }
    getRequestById(redeemId) {
        return __awaiter(this, void 0, void 0, function* () {
            const id = (0, 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((0, utils_1.ensureHashEncoded)(this.api, redeemId))
                        .then((request) => resolve([request, redeemId]))
                        .catch(reject);
                });
            })));
            return Promise.all(redeemRequestData
                .filter(([option, _]) => option.isSome)
                .map(([redeemRequest, redeemId]) => (0, utils_1.parseRedeemRequest)(this.vaultsAPI, redeemRequest.unwrap(), this.btcNetwork, redeemId)));
        });
    }
}
exports.DefaultRedeemAPI = DefaultRedeemAPI;
//# sourceMappingURL=redeem.js.map