import { __awaiter, __generator } from "tslib";
import { toBN, dedupArray, parseUnits } from "../../utils";
import { compileTransaction } from "@solana/kit";
/**
 * @notice Returns result of getFeeForMessage and getRecentPrioritizationFees RPC calls.
 * @returns GasPriceEstimate
 */
export function messageFee(provider, opts) {
    return __awaiter(this, void 0, void 0, function () {
        var _unsignedTx, unsignedTx, compiledTransaction, encodedTransactionMessage, baseFeeResponse, instructionAddresses, recentPriorityFees, nonzeroPrioritizationFees, totalPrioritizationFees, flooredPriorityFeePerGas, microLamportsPerComputeUnit;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _unsignedTx = opts.unsignedTx;
                    unsignedTx = _unsignedTx;
                    compiledTransaction = compileTransaction(unsignedTx);
                    encodedTransactionMessage = Buffer.from(compiledTransaction.messageBytes).toString("base64");
                    return [4 /*yield*/, provider.getFeeForMessage(encodedTransactionMessage).send()];
                case 1:
                    baseFeeResponse = _a.sent();
                    instructionAddresses = dedupArray(unsignedTx.instructions.map(function (instruction) { return instruction.programAddress; }));
                    return [4 /*yield*/, 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 = parseUnits(process.env["MIN_PRIORITY_FEE_PER_GAS_".concat(opts.chainId)] || "0", 6);
                    microLamportsPerComputeUnit = toBN(totalPrioritizationFees / BigInt(Math.max(nonzeroPrioritizationFees.length, 1)));
                    if (microLamportsPerComputeUnit.lt(flooredPriorityFeePerGas)) {
                        microLamportsPerComputeUnit = flooredPriorityFeePerGas;
                    }
                    return [2 /*return*/, {
                            baseFee: toBN(baseFeeResponse.value),
                            microLamportsPerComputeUnit: microLamportsPerComputeUnit,
                        }];
            }
        });
    });
}
//# sourceMappingURL=solana.js.map