"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeRedeem = exports.initializeIssue = exports.initializeVaultNomination = exports.initializeBtcTxFees = exports.initializeExchangeRate = exports.initializeStableConfirmations = void 0;
/* eslint @typescript-eslint/no-var-requires: "off" */
const monetary_js_1 = require("@interlay/monetary-js");
const big_js_1 = require("big.js");
const bn_js_1 = __importDefault(require("bn.js"));
const api_1 = require("@polkadot/api");
const factory_1 = require("../factory");
const issueRedeem_1 = require("./issueRedeem");
const storage_1 = require("./storage");
const bitcoin_core_client_1 = require("./bitcoin-core-client");
const util_crypto_1 = require("@polkadot/util-crypto");
const config_1 = require("../../test/config");
const encoding_1 = require("./encoding");
const __1 = require("..");
// Command line arguments of the initialization script
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const argv = yargs(hideBin(process.argv))
    .option("initialize", {
    type: "boolean",
    description: "Flag that decides whether this script should be run or not",
    default: false,
})
    .option("set-stable-confirmations", {
    type: "boolean",
    description: "Set the required bitcoin and parachain confirmations to zero",
    default: true,
})
    .option("set-exchange-rate", {
    type: "boolean",
    description: "Set the BTC/DOT exchange rate to 3855.23187",
    default: true,
})
    .option("enable-nomination", {
    type: "boolean",
    description: "Enable vault nomination",
    default: true,
})
    .option("issue", {
    type: "boolean",
    description: "Issue 0.1 InterBtc",
    default: true,
})
    .option("redeem", {
    type: "boolean",
    description: "Redeem 0.05 InterBtc",
    default: true,
}).argv;
main(argv).catch((err) => {
    console.log("Error during setup:");
    console.log(err);
});
function getDefaultInitializationParams(keyring, vaultAddress, wrappedCurrency, collateralCurrency) {
    return {
        setStableConfirmations: {
            bitcoinConfirmations: 0,
            parachainConfirmations: 0,
        },
        setExchangeRate: new monetary_js_1.ExchangeRate(monetary_js_1.Bitcoin, collateralCurrency, new big_js_1.Big("3855.23187")),
        btcTxFees: new big_js_1.Big(1),
        enableNomination: true,
        issue: {
            amount: (0, __1.newMonetaryAmount)(0.00007, wrappedCurrency),
            issuingAccount: keyring.addFromUri(config_1.USER_1_URI),
            vaultAddress,
        },
        redeem: {
            amount: (0, __1.newMonetaryAmount)(0.00005, wrappedCurrency),
            redeemingAccount: keyring.addFromUri(config_1.USER_1_URI),
            redeemingBTCAddress: config_1.REDEEM_ADDRESS,
        },
        delayMs: 0,
    };
}
function initializeStableConfirmations(api, stableConfirmationsToSet, account, bitcoinCoreClient) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing stable block confirmations...");
        yield (0, storage_1.setNumericStorage)(api, "BTCRelay", "StableBitcoinConfirmations", new bn_js_1.default(stableConfirmationsToSet.bitcoinConfirmations), account);
        yield (0, storage_1.setNumericStorage)(api, "BTCRelay", "StableParachainConfirmations", new bn_js_1.default(stableConfirmationsToSet.parachainConfirmations), account);
        yield bitcoinCoreClient.mineBlocks(3);
    });
}
exports.initializeStableConfirmations = initializeStableConfirmations;
function initializeExchangeRate(exchangeRateToSet, oracleAPI) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing the exchange rate...");
        yield oracleAPI.setExchangeRate(exchangeRateToSet);
    });
}
exports.initializeExchangeRate = initializeExchangeRate;
function initializeBtcTxFees(fees, oracleAPI) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing BTC tx fees...");
        yield oracleAPI.setBitcoinFees(fees);
        yield oracleAPI.waitForFeeEstimateUpdate();
    });
}
exports.initializeBtcTxFees = initializeBtcTxFees;
function initializeVaultNomination(enabled, nominationAPI) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing vault nomination...");
        yield nominationAPI.setNominationEnabled(enabled);
    });
}
exports.initializeVaultNomination = initializeVaultNomination;
function initializeIssue(InterBtcApi, bitcoinCoreClient, issuingAccount, amountToIssue, vaultAccountId) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing an issue...");
        yield (0, issueRedeem_1.issueSingle)(InterBtcApi, bitcoinCoreClient, issuingAccount, amountToIssue, vaultAccountId);
    });
}
exports.initializeIssue = initializeIssue;
function initializeRedeem(redeemAPI, amountToRedeem, redeemBTCAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        console.log("Initializing a redeem...");
        yield redeemAPI.request(amountToRedeem, redeemBTCAddress);
    });
}
exports.initializeRedeem = initializeRedeem;
function main(params) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!params.initialize) {
            return Promise.resolve();
        }
        yield (0, util_crypto_1.cryptoWaitReady)();
        console.log("Running initialization script...");
        const keyring = new api_1.Keyring({ type: "sr25519" });
        const vault_1 = keyring.addFromUri(config_1.VAULT_1_URI);
        const api = yield (0, factory_1.createSubstrateAPI)(config_1.PARACHAIN_ENDPOINT);
        const sudoAccount = keyring.addFromUri(config_1.SUDO_URI);
        const oracleAccount = keyring.addFromUri(config_1.ORACLE_URI);
        const oracleAccountInterBtcApi = new __1.DefaultInterBtcApi(api, "regtest", oracleAccount, config_1.ESPLORA_BASE_PATH);
        const sudoAccountInterBtcApi = new __1.DefaultInterBtcApi(api, "regtest", sudoAccount, config_1.ESPLORA_BASE_PATH);
        const wrappedCurrency = sudoAccountInterBtcApi.getWrappedCurrency();
        const collateralCurrency = (0, __1.getCorrespondingCollateralCurrency)(sudoAccountInterBtcApi.getGovernanceCurrency());
        const defaultInitializationParams = getDefaultInitializationParams(keyring, vault_1.address, wrappedCurrency, collateralCurrency);
        const bitcoinCoreClient = new bitcoin_core_client_1.BitcoinCoreClient(config_1.BITCOIN_CORE_NETWORK, config_1.BITCOIN_CORE_HOST, config_1.BITCOIN_CORE_USERNAME, config_1.BITCOIN_CORE_PASSWORD, config_1.BITCOIN_CORE_PORT, config_1.BITCOIN_CORE_WALLET);
        if (params.setStableConfirmations !== undefined) {
            const stableConfirmationsToSet = params.setStableConfirmations === true
                ? defaultInitializationParams.setStableConfirmations
                : params.setStableConfirmations;
            yield initializeStableConfirmations(api, stableConfirmationsToSet, sudoAccount, bitcoinCoreClient);
        }
        if (params.setExchangeRate !== undefined) {
            const exchangeRateToSet = params.setExchangeRate === true
                ? defaultInitializationParams.setExchangeRate
                : params.setExchangeRate;
            yield initializeExchangeRate(exchangeRateToSet, oracleAccountInterBtcApi.oracle);
        }
        if (params.btcTxFees !== undefined) {
            const btcTxFees = params.btcTxFees === true ? defaultInitializationParams.btcTxFees : params.btcTxFees;
            yield initializeBtcTxFees(btcTxFees, oracleAccountInterBtcApi.oracle);
        }
        if (params.enableNomination === true) {
            initializeVaultNomination(params.enableNomination, sudoAccountInterBtcApi.nomination);
        }
        if (params.issue !== undefined) {
            const issueParams = params.issue === true
                ? defaultInitializationParams.issue
                : params.issue;
            const vaultId = (0, encoding_1.newVaultId)(api, issueParams.vaultAddress, collateralCurrency, wrappedCurrency);
            yield initializeIssue(sudoAccountInterBtcApi, bitcoinCoreClient, issueParams.issuingAccount, issueParams.amount, vaultId);
        }
        if (params.redeem !== undefined) {
            const redeemParams = params.redeem === true
                ? defaultInitializationParams.redeem
                : params.redeem;
            const redeemingAccountInterBtcApi = new __1.DefaultInterBtcApi(api, "regtest", sudoAccount);
            yield initializeRedeem(redeemingAccountInterBtcApi.redeem, redeemParams.amount, redeemParams.redeemingBTCAddress);
        }
        api.disconnect();
    });
}
//# sourceMappingURL=setup.js.map