"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.DefaultReplaceAPI = void 0;
const utils_1 = require("../utils");
class DefaultReplaceAPI {
    constructor(api, btcNetwork, electrsAPI, wrappedCurrency, feeAPI, transactionAPI, assetRegistryAPI, loansAPI) {
        this.api = api;
        this.btcNetwork = btcNetwork;
        this.electrsAPI = electrsAPI;
        this.wrappedCurrency = wrappedCurrency;
        this.feeAPI = feeAPI;
        this.transactionAPI = transactionAPI;
        this.assetRegistryAPI = assetRegistryAPI;
        this.loansAPI = loansAPI;
    }
    buildRequestReplaceExtrinsic(amount, collateralCurrency) {
        const amountAtomicBalance = this.api.createType("Balance", amount.toString(true));
        const vaultCurrencyPair = utils_1.newVaultCurrencyPair(this.api, collateralCurrency, this.wrappedCurrency);
        return this.api.tx.replace.requestReplace(vaultCurrencyPair, amountAtomicBalance);
    }
    request(amount, collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const requestTx = this.buildRequestReplaceExtrinsic(amount, collateralCurrency);
            // When requesting a replace, 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
            yield this.transactionAPI.sendLogged(requestTx, this.api.events.replace.RequestReplace);
        });
    }
    buildWithdrawReplaceExtrinsic(amount, collateralCurrency) {
        const amountAtomicBalance = this.api.createType("Balance", amount.toString(true));
        const vaultCurrencyPair = utils_1.newVaultCurrencyPair(this.api, collateralCurrency, this.wrappedCurrency);
        return this.api.tx.replace.withdrawReplace(vaultCurrencyPair, amountAtomicBalance);
    }
    withdraw(amount, collateralCurrency) {
        return __awaiter(this, void 0, void 0, function* () {
            const requestTx = this.buildWithdrawReplaceExtrinsic(amount, collateralCurrency);
            yield this.transactionAPI.sendLogged(requestTx, this.api.events.replace.WithdrawReplace, true);
        });
    }
    buildAcceptReplaceExtrinsic(oldVault, amount, collateral, btcAddress) {
        const parsedBtcAddress = this.api.createType("BitcoinAddress", btcAddress);
        const amountAtomicUnit = this.api.createType("Balance", amount.toString(true));
        const collateralAtomicUnit = this.api.createType("Balance", collateral.toString(true));
        const vaultCurrencyPair = utils_1.newVaultCurrencyPair(this.api, collateral.currency, this.wrappedCurrency);
        return this.api.tx.replace.acceptReplace(vaultCurrencyPair, oldVault, amountAtomicUnit, collateralAtomicUnit, parsedBtcAddress);
    }
    accept(oldVault, amount, collateral, btcAddress) {
        return __awaiter(this, void 0, void 0, function* () {
            const requestTx = this.buildAcceptReplaceExtrinsic(oldVault, amount, collateral, btcAddress);
            yield this.transactionAPI.sendLogged(requestTx, this.api.events.replace.AcceptReplace, true);
        });
    }
    buildExecuteReplaceExtrinsic(requestId, btcTxId) {
        return __awaiter(this, void 0, void 0, function* () {
            const parsedRequestId = utils_1.ensureHashEncoded(this.api, requestId);
            const txInclusionDetails = yield utils_1.getTxProof(this.electrsAPI, btcTxId);
            return this.api.tx.replace.executeReplace(parsedRequestId, txInclusionDetails.merkleProof, txInclusionDetails.rawTx);
        });
    }
    execute(requestId, btcTxId) {
        return __awaiter(this, void 0, void 0, function* () {
            const tx = yield this.buildExecuteReplaceExtrinsic(requestId, btcTxId);
            yield this.transactionAPI.sendLogged(tx, this.api.events.replace.ExecuteReplace, true);
        });
    }
    getDustValue() {
        return __awaiter(this, void 0, void 0, function* () {
            const dustSatoshi = yield this.api.query.replace.replaceBtcDustValue();
            return utils_1.newMonetaryAmount(dustSatoshi.toString(), this.wrappedCurrency);
        });
    }
    getReplacePeriod() {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.api.query.replace.replacePeriod();
        });
    }
    list() {
        return __awaiter(this, void 0, void 0, function* () {
            const head = yield this.api.rpc.chain.getFinalizedHead();
            const replaceRequests = yield this.api.query.replace.replaceRequests.entriesAt(head);
            return yield Promise.all(replaceRequests
                .filter((v) => v[1].isSome.valueOf)
                // Can be unwrapped because the filter removes `None` values
                .map(([id, req]) => utils_1.parseReplaceRequest(this.assetRegistryAPI, this.loansAPI, req.unwrap(), this.btcNetwork, this.wrappedCurrency, utils_1.storageKeyToNthInner(id))));
        });
    }
    map() {
        return __awaiter(this, void 0, void 0, function* () {
            const head = yield this.api.rpc.chain.getFinalizedHead();
            const replaceRequests = yield this.api.query.replace.replaceRequests.entriesAt(head);
            const replaceRequestMap = new Map();
            yield Promise.all(replaceRequests
                .filter((v) => v[1].isSome.valueOf)
                // Can be unwrapped because the filter removes `None` values
                .map(([id, req]) => new Promise((resolve) => {
                utils_1.parseReplaceRequest(this.assetRegistryAPI, this.loansAPI, req.unwrap(), this.btcNetwork, this.wrappedCurrency, utils_1.storageKeyToNthInner(id)).then((replaceRequest) => {
                    replaceRequestMap.set(utils_1.storageKeyToNthInner(id), replaceRequest);
                    resolve();
                });
            })));
            return replaceRequestMap;
        });
    }
    getRequestById(replaceId) {
        return __awaiter(this, void 0, void 0, function* () {
            const head = yield this.api.rpc.chain.getFinalizedHead();
            return utils_1.parseReplaceRequest(this.assetRegistryAPI, this.loansAPI, yield this.api.query.replace.replaceRequests.at(head, utils_1.ensureHashEncoded(this.api, replaceId)), this.btcNetwork, this.wrappedCurrency, replaceId);
        });
    }
    mapReplaceRequests(vaultAccountId) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const [oldVaultReplaceRequests, newVaultReplaceRequests] = yield Promise.all([
                    this.getOldVaultReplaceRequests(vaultAccountId),
                    this.getNewVaultReplaceRequests(vaultAccountId),
                ]);
                return [...oldVaultReplaceRequests, ...newVaultReplaceRequests];
            }
            catch (err) {
                return Promise.reject(new Error(`Error during replace request retrieval: ${err}`));
            }
        });
    }
    getOldVaultReplaceRequests(vaultAccountId) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.list()).filter((request) => request.oldVault.accountId.toString() === vaultAccountId.toString());
        });
    }
    getNewVaultReplaceRequests(vaultAccountId) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.list()).filter((request) => request.newVault.accountId.toString() === vaultAccountId.toString());
        });
    }
    parseRequestsAsync(requestPairs) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield Promise.all(requestPairs.map(([id, req]) => new Promise((resolve) => {
                utils_1.parseReplaceRequest(this.assetRegistryAPI, this.loansAPI, req, this.btcNetwork, this.wrappedCurrency, id).then((replaceRequest) => {
                    resolve([id, replaceRequest]);
                });
            })));
        });
    }
}
exports.DefaultReplaceAPI = DefaultReplaceAPI;
//# sourceMappingURL=replace.js.map