"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.redeemToken = exports.getAuthorization = exports.prepareRedeemToken = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareRedeemToken(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context, context: { polymeshApi: { tx }, }, } = this;
        const { ticker, amount } = args;
        const securityToken = new internal_1.SecurityToken({ ticker }, context);
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const [{ isDivisible }, { did }] = yield Promise.all([
            securityToken.details(),
            context.getCurrentIdentity(),
        ]);
        const defaultPortfolio = new internal_1.DefaultPortfolio({ did }, context);
        const portfolioBalance = yield defaultPortfolio.getTokenBalances({ tokens: [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(tx.asset.redeem, {}, rawTicker, conversion_1.numberToBalance(amount, context, isDivisible));
    });
}
exports.prepareRedeemToken = prepareRedeemToken;
/**
 * @hidden
 */
function getAuthorization({ ticker }) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context } = this;
        const { did } = yield context.getCurrentIdentity();
        return {
            permissions: {
                transactions: [types_1.TxTags.asset.Redeem],
                tokens: [new internal_1.SecurityToken({ ticker }, context)],
                portfolios: [new internal_1.DefaultPortfolio({ did }, context)],
            },
        };
    });
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const redeemToken = () => new internal_1.Procedure(prepareRedeemToken, getAuthorization);
exports.redeemToken = redeemToken;
//# sourceMappingURL=redeemToken.js.map