"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.submitTransaction = submitTransaction;
exports.simulateTransaction = simulateTransaction;
const utils_1 = require("../../utils");
async function submitTransaction(tronWeb, populatedTx, feeLimit, callValue = 0) {
    const { to, data } = populatedTx;
    if (!to || !data) {
        throw new Error("submitTransaction: populatedTx must have both 'to' and 'data' fields");
    }
    const tronAddress = utils_1.TvmAddress.from(to).toNative();
    const ownerAddress = tronWeb.defaultAddress?.base58;
    if (!ownerAddress) {
        throw new Error("submitTransaction: TronWeb instance must have a default address configured");
    }
    const input = data.startsWith("0x") ? data.slice(2) : data;
    const txWrapper = await tronWeb.transactionBuilder.triggerSmartContract(tronAddress, "", { feeLimit, input, callValue }, [], ownerAddress);
    if (!txWrapper?.result?.result) {
        const message = txWrapper?.result?.message ?? "Unknown error";
        throw new Error(`submitTransaction: triggerSmartContract failed: ${message}`);
    }
    const signedTx = await tronWeb.trx.sign(txWrapper.transaction);
    const broadcast = await tronWeb.trx.sendRawTransaction(signedTx);
    return {
        txid: broadcast.txid ?? signedTx.txID,
        result: broadcast.result ?? false,
    };
}
async function simulateTransaction(tronWeb, populatedTx, feeLimit, callValue = 0) {
    const { to, data } = populatedTx;
    if (!to || !data) {
        throw new Error("simulateTransaction: populatedTx must have both 'to' and 'data' fields");
    }
    const tronAddress = utils_1.TvmAddress.from(to).toNative();
    const ownerAddress = tronWeb.defaultAddress?.base58;
    if (!ownerAddress) {
        throw new Error("simulateTransaction: TronWeb instance must have a default address configured");
    }
    const input = data.startsWith("0x") ? data.slice(2) : data;
    const txWrapper = await tronWeb.transactionBuilder.triggerConstantContract(tronAddress, "", { feeLimit, input, callValue }, [], ownerAddress);
    const success = txWrapper?.result?.result === true;
    return {
        success,
        message: txWrapper?.result?.message,
        constantResult: txWrapper?.constant_result,
        energyUsed: txWrapper?.energy_used,
        energyRequired: txWrapper?.energy_required,
        energyPenalty: txWrapper?.energy_penalty,
    };
}
//# sourceMappingURL=TransactionUtils.js.map