"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.transferPolyx = exports.getAuthorization = exports.prepareTransferPolyx = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareTransferPolyx(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { to, amount, memo } = args;
        let toAccount;
        if (to instanceof internal_1.Account) {
            toAccount = to;
        }
        else {
            toAccount = new internal_1.Account({ address: to }, context);
        }
        const rawAccountId = conversion_1.stringToAccountId(conversion_1.signerToString(to), context);
        const [{ free: freeBalance }, receiverIdentity] = yield Promise.all([context.accountBalance(), toAccount.getIdentity()]);
        if (amount.isGreaterThan(freeBalance)) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.InsufficientBalance,
                message: 'Insufficient free balance',
                data: {
                    freeBalance,
                },
            });
        }
        if (!receiverIdentity) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: "The destination Account doesn't have an associated Identity",
            });
        }
        const senderIdentity = yield context.getCurrentIdentity();
        const [senderCdd, receiverCdd] = yield Promise.all([
            senderIdentity.hasValidCdd(),
            receiverIdentity.hasValidCdd(),
        ]);
        if (!senderCdd) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'The sender Identity has an invalid CDD claim',
            });
        }
        if (!receiverCdd) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'The receiver Identity has an invalid CDD claim',
            });
        }
        const rawAmount = conversion_1.bigNumberToBalance(amount, context);
        if (memo) {
            this.addTransaction({
                transaction: tx.balances.transferWithMemo,
                args: [rawAccountId, rawAmount, conversion_1.stringToMemo(memo, context)],
            });
        }
        else {
            this.addTransaction({
                transaction: tx.balances.transfer,
                args: [rawAccountId, rawAmount],
            });
        }
    });
}
exports.prepareTransferPolyx = prepareTransferPolyx;
/**
 * @hidden
 */
function getAuthorization({ memo }) {
    return {
        permissions: {
            transactions: [memo ? types_1.TxTags.balances.TransferWithMemo : types_1.TxTags.balances.Transfer],
            assets: [],
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const transferPolyx = () => new internal_1.Procedure(prepareTransferPolyx, getAuthorization);
exports.transferPolyx = transferPolyx;
//# sourceMappingURL=transferPolyx.js.map