"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.messageFee = void 0;
var tslib_1 = require("tslib");
var utils_1 = require("../../utils");
var kit_1 = require("@solana/kit");
function messageFee(provider, opts) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var _unsignedTx, unsignedTx, compiledTransaction, encodedTransactionMessage, baseFeeResponse, instructionAddresses, recentPriorityFees, nonzeroPrioritizationFees, totalPrioritizationFees, flooredPriorityFeePerGas, microLamportsPerComputeUnit;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _unsignedTx = opts.unsignedTx;
                    unsignedTx = _unsignedTx;
                    compiledTransaction = (0, kit_1.compileTransaction)(unsignedTx);
                    encodedTransactionMessage = Buffer.from(compiledTransaction.messageBytes).toString("base64");
                    return [4, provider.getFeeForMessage(encodedTransactionMessage).send()];
                case 1:
                    baseFeeResponse = _a.sent();
                    instructionAddresses = (0, utils_1.dedupArray)(unsignedTx.instructions.map(function (instruction) { return instruction.programAddress; }));
                    return [4, provider.getRecentPrioritizationFees(instructionAddresses).send()];
                case 2:
                    recentPriorityFees = _a.sent();
                    nonzeroPrioritizationFees = recentPriorityFees
                        .slice(125)
                        .map(function (value) { return value.prioritizationFee; })
                        .filter(function (fee) { return fee > 0; });
                    totalPrioritizationFees = nonzeroPrioritizationFees.reduce(function (acc, fee) { return acc + fee; }, BigInt(0));
                    flooredPriorityFeePerGas = (0, utils_1.parseUnits)(process.env["MIN_PRIORITY_FEE_PER_GAS_".concat(opts.chainId)] || "0", 6);
                    microLamportsPerComputeUnit = (0, utils_1.toBN)(totalPrioritizationFees / BigInt(Math.max(nonzeroPrioritizationFees.length, 1)));
                    if (microLamportsPerComputeUnit.lt(flooredPriorityFeePerGas)) {
                        microLamportsPerComputeUnit = flooredPriorityFeePerGas;
                    }
                    return [2, {
                            baseFee: (0, utils_1.toBN)(baseFeeResponse.value),
                            microLamportsPerComputeUnit: microLamportsPerComputeUnit,
                        }];
            }
        });
    });
}
exports.messageFee = messageFee;
//# sourceMappingURL=solana.js.map