"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.redeemTokens = exports.getAuthorization = exports.prepareRedeemTokens = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareRedeemTokens(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context, context: { polymeshApi: { tx }, }, } = this;
        const { ticker, amount } = args;
        const asset = new internal_1.Asset({ ticker }, context);
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const [{ isDivisible }, { did }] = yield Promise.all([
            asset.details(),
            context.getSigningIdentity(),
        ]);
        const defaultPortfolio = new internal_1.DefaultPortfolio({ did }, context);
        const portfolioBalance = yield defaultPortfolio.getAssetBalances({ assets: [ticker] });
        const { free } = portfolioBalance[0];
        if (free.lt(amount)) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.InsufficientBalance,
                message: 'Insufficient free balance',
                data: {
                    free,
                },
            });
        }
        this.addTransaction({
            transaction: tx.asset.redeem,
            args: [rawTicker, conversion_1.bigNumberToBalance(amount, context, isDivisible)],
        });
    });
}
exports.prepareRedeemTokens = prepareRedeemTokens;
/**
 * @hidden
 */
function getAuthorization({ ticker }) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context } = this;
        const { did } = yield context.getSigningIdentity();
        return {
            permissions: {
                transactions: [types_1.TxTags.asset.Redeem],
                assets: [new internal_1.Asset({ ticker }, context)],
                portfolios: [new internal_1.DefaultPortfolio({ did }, context)],
            },
        };
    });
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const redeemTokens = () => new internal_1.Procedure(prepareRedeemTokens, getAuthorization);
exports.redeemTokens = redeemTokens;
//# sourceMappingURL=redeemTokens.js.map