import { networkRegistry as e } from "../../../constants/chains.constants.mjs";
import { TRON_DEFAULT_FEE_LIMIT_SUN as t, zeroAddress as n } from "../../../constants/protocol.constants.mjs";
import { caseInsensitiveEqual as r } from "../../utils/caseInsensitive.utils.mjs";
import { ERC20ABI as i } from "../../../externalABIs/index.mjs";
import { insufficientResourcesErrorCodes as a } from "../../../error-handling/error-codes.constants.mjs";
import { Logger as o } from "../../../error-handling/logger.mjs";
import { circomDataToArray as s, createTronCallData as c, estimateTronFeeSunWithPadding as l, evmHexToTronBase58Address as u, parseZkCalldata as d, reorderZkCallData as f } from "../../utils/tron.utils.mjs";
import { simulateTronTransaction as p } from "../../utils/tronSimulation.utils.mjs";
import { waitForTronErc20Approvals as m } from "./waitForErc20Approvals.mjs";
//#region libs/shared/common/src/functions/web3/functionCalls/transactCallDirectTron.ts
var h = async (h, g, _, v, y, b, x, S, C, w = !0) => {
	let T = Array.isArray(_) ? _ : [_], E = Array.isArray(v) ? v : [v];
	if (T.length !== E.length) throw Error("token and amount length mismatch");
	let D = h.getTronWeb(), O = await h.getEthereumAddressByChain(g), { hinkalAddress: k, hinkalABI: A } = e[g].contractData, j = D.contract(A, u(k)), M = S ?? j, N = C ?? j;
	if (!M.address) throw Error("contractForApproval address not set");
	if (!N.address) throw Error("contractForTransaction address not set");
	let P = E.findIndex(({ erc20TokenAddress: e }) => r(e, n)), F = P === -1 ? 0n : T[P], I = F > 0n ? F : 0n;
	if (E.some(({ erc20TokenAddress: e }, t) => !r(e, n) && T[t] > 0n)) {
		let e = M.address;
		if (!e) throw Error("token approval spender not set");
		let a = [];
		for (let o = 0; o < E.length; o += 1) {
			let s = E[o], c = T[o];
			if (c > 0n && !r(s.erc20TokenAddress, n)) {
				let n = u(s.erc20TokenAddress), r = await D.contract(i, n).allowance(O, e).call({ from: O });
				if (BigInt(String(r)) < c) {
					let { transaction: r } = await D.transactionBuilder.triggerSmartContract(n, "approve(address,uint256)", { feeLimit: t }, [{
						type: "address",
						value: e
					}, {
						type: "uint256",
						value: c.toString()
					}], O), i = await D.trx.sign(r), o = await D.trx.sendRawTransaction(i);
					if (!o.result) {
						let e = o.code ?? "UNKNOWN", t = o.message ? Buffer.from(o.message, "hex").toString() : "no message";
						throw Error(`Tron token approval failed: ${e} - ${t}`);
					}
					a.push({
						tokenAddress: n,
						requiredAmount: c
					});
				}
			}
		}
		a.length > 0 && await m(D, O, e, a);
	}
	let { a: L, b: R, c: z } = d(y), B = await f(!0, y, x, b, !1);
	if (!B) throw Error("Tron proof signature not found");
	let V = [
		B.v,
		B.r,
		B.s
	], H = [
		x.tokenNumber,
		x.nullifierAmount,
		x.outputAmount
	], U = s(b);
	if (w) {
		await p(g, N.address, "transact", N.abi, [
			V,
			L,
			R,
			z,
			H,
			U
		], O, I);
		let e = BigInt(await D.trx.getBalance(O)), n = BigInt(t);
		try {
			let e = c(N.abi, "transact", [
				V,
				L,
				R,
				z,
				H,
				U
			]);
			n = await l(D, g, N.address, O, e, I);
		} catch (e) {
			o.error("Error estimating Tron transact fee", e);
		}
		if (e < I + n) throw Error(a.INSUFFICIENT_TRON_BALANCE_FOR_FEE);
	}
	let W = await N.transact(V, L, R, z, H, U).send({
		feeLimit: t,
		callValue: Number(I)
	}), G = typeof W == "string" ? W : W?.txid ?? W?.transaction?.txID ?? W?.transaction?.txid;
	if (!G) throw Error("Tron transact failed (missing txid)");
	return G;
}, g = async (e, i, a, o, l, p, m, h, g) => {
	let _ = e.getTronWeb(), v = await e.getEthereumAddressByChain(i), y = r(o.erc20TokenAddress, n), { a: b, b: x, c: S } = d(l), C = await f(!0, l, m, p, !1);
	if (!C) throw Error("Tron proof signature not found");
	let w = c(g, "transact", [
		[
			C.v,
			C.r,
			C.s
		],
		b,
		x,
		S,
		[
			m.tokenNumber,
			m.nullifierAmount,
			m.outputAmount
		],
		s(p)
	]), { transaction: T } = await _.transactionBuilder.triggerSmartContract(u(h), "", {
		feeLimit: t,
		callValue: y ? Number(a) : 0,
		input: w
	}, [], v);
	return T;
};
//#endregion
export { g as buildTronUnsignedTransactTransaction, h as transactCallDirectTron };
