"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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolymeshTransactionBatch = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const bluebird_1 = __importDefault(require("bluebird"));
const internal_1 = require("../internal");
const conversion_1 = require("../utils/conversion");
const internal_2 = require("../utils/internal");
/**
 * Wrapper class for a batch of Polymesh Transactions
 */
class PolymeshTransactionBatch extends internal_1.PolymeshTransactionBase {
    /**
     * @hidden
     */
    constructor(transactionSpec, context) {
        const { transactions } = transactionSpec, rest = __rest(transactionSpec, ["transactions"]);
        super(rest, context);
        this.inputTransactions = transactions;
    }
    /**
     * @hidden
     */
    getUnwrappedTransactions() {
        if (!this.unwrappedTransactions) {
            this.unwrappedTransactions = this.inputTransactions.map(({ transaction, args, feeMultiplier }) => ({
                tag: conversion_1.transactionToTxTag(transaction),
                args: internal_2.unwrapValues(args),
                feeMultiplier,
                transaction,
            }));
        }
        return this.unwrappedTransactions;
    }
    /**
     * transactions in the batch with their respective arguments
     */
    get transactions() {
        return this.getUnwrappedTransactions().map(({ tag, args }) => ({
            tag,
            args,
        }));
    }
    /**
     * @hidden
     */
    composeTx() {
        const { context: { polymeshApi: { tx: { utility }, }, }, } = this;
        return utility.batchAtomic(this.getUnwrappedTransactions().map(({ transaction, args }) => transaction(...args)));
    }
    /**
     * @hidden
     */
    getProtocolFees() {
        return bluebird_1.default.reduce(this.getUnwrappedTransactions(), (total, { tag, feeMultiplier = 1 }) => __awaiter(this, void 0, void 0, function* () {
            const fee = yield this.context.getProtocolFees({ tag });
            return total.plus(fee.multipliedBy(feeMultiplier));
        }), new bignumber_js_1.default(0));
    }
    /**
     * @note batches can't be subsidized
     */
    supportsSubsidy() {
        return false;
    }
    /**
     * @hidden
     */
    handleExtrinsicSuccess(resolve, reject, receipt) {
        // If one of the transactions in the batch fails, this event gets emitted
        const failed = receipt.findRecord('utility', 'BatchInterrupted');
        if (failed) {
            const { event: { data: failedData }, } = failed;
            const failedIndex = conversion_1.u32ToBigNumber(failedData[0]).toNumber();
            const dispatchError = failedData[1];
            this.handleExtrinsicFailure(resolve, reject, dispatchError, { failedIndex });
        }
        else {
            resolve(receipt);
        }
    }
}
exports.PolymeshTransactionBatch = PolymeshTransactionBatch;
//# sourceMappingURL=PolymeshTransactionBatch.js.map