import { chainIds as e, networkRegistry as t } from "../../constants/chains.constants.mjs";
import { TRON_DEFAULT_FEE_LIMIT_SUN as n, zeroAddress as r } from "../../constants/protocol.constants.mjs";
import { httpClient as i } from "../../data-structures/http/HttpClient.mjs";
import { ENCLAVE_URL as a } from "../snarkjs/constant.mjs";
import { caseInsensitiveEqual as o } from "./caseInsensitive.utils.mjs";
import { ERC20ABI as s } from "../../externalABIs/index.mjs";
import { insufficientResourcesErrorCodes as c } from "../../error-handling/error-codes.constants.mjs";
import { Logger as l } from "../../error-handling/logger.mjs";
import { ethers as u } from "ethers";
import { TronWeb as d } from "tronweb";
//#region libs/shared/common/src/functions/utils/tron.utils.ts
var f = ["https://nile.trongrid.io", "https://api.shasta.trongrid.io"], p = 2000n, m = (t) => {
	let n = t.toLowerCase();
	return f.some((e) => n.includes(e)) ? e.tronNile : e.tronMainnet;
}, h = (e) => {
	let t = e.trim(), n = t.startsWith("0x") ? t.slice(2) : t;
	if (!/^[0-9a-fA-F]{64}$/.test(n)) throw Error("Tron private key must be 32 bytes (64 hex characters), with or without 0x prefix");
	return n;
}, g = (e, n) => {
	let r = t[e].fetchRpcUrl, i = n ? h(n) : void 0, a = i ? new d({
		fullHost: r,
		privateKey: i
	}) : new d({ fullHost: r });
	return n || a.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"), a;
}, _ = (e) => e?.startsWith("T") ? e : d.address.fromHex(e), v = (e) => e.startsWith("0x") ? _(e) : e, y = (e) => {
	if (e.startsWith("0x")) return e;
	if (e.startsWith("41")) return e.replace("41", "0x");
	if (e.startsWith("T")) return y(d.address.toHex(e));
	throw Error("Failed to convert address to hex format");
}, b = (e) => e?.startsWith("T") ? y(e) : e, x = (t) => {
	if (t === e.tronNile) return "https://nile.trongrid.io";
	if (t === e.tronMainnet) return "https://api.trongrid.io";
	throw Error(`Unsupported Tron chain for wallet RPC: ${t}`);
}, S = (e, t) => e.map((e) => Array.isArray(e) ? S(e, t) : t(e)), C = (e, t, n) => {
	let r = new u.Interface(e);
	if (!r.getFunction(t)) throw Error(`${t} ABI is missing for Tron call data creation`);
	let i = S(n, (e) => typeof e == "string" && e.startsWith("T") ? y(e) : e);
	return r.encodeFunctionData(t, i);
}, w = (e, t, n) => e ? BigInt(Math.max((e[t] ?? 0) - (e[n] ?? 0), 0)) : 0n, T = (e, t) => {
	let n = e.find((e) => e.key === t);
	if (!n || typeof n.value != "number") throw Error(`Missing Tron chain parameter: ${t}`);
	return BigInt(n.value);
}, E = async (e) => {
	let t = `${x(e)}/wallet/getchainparameters`, n = await i.post(t, {});
	if (!n?.chainParameter?.length) throw Error("Failed to fetch Tron chain parameters from wallet RPC");
	return n.chainParameter;
}, D = async (e, t) => {
	let n = `${x(e)}/wallet/getaccountresource`, r = y(t), a = r.startsWith("0x") ? `41${r.slice(2)}` : r;
	return await i.post(n, {
		address: a,
		visible: !1
	});
}, O = async (e, t, r, i, a, o) => {
	let s = {
		input: a,
		callValue: Number(o),
		feeLimit: n
	}, [c, l] = await Promise.all([e.transactionBuilder.estimateEnergy(r, "", s, [], i), e.transactionBuilder.triggerConstantContract(r, "", s, [], i)]), u = await E(t), d = T(u, "getEnergyFee"), f = T(u, "getTransactionFee"), m = await D(t, i), h = BigInt(c?.energy_required ?? l?.energy_used ?? 0), g = w(m, "EnergyLimit", "EnergyUsed"), _ = (h > g ? h - g : 0n) * d, v = BigInt(Math.ceil((l?.transaction?.raw_data_hex?.length ?? 0) / 2)), y = w(m, "freeNetLimit", "freeNetUsed") + w(m, "NetLimit", "NetUsed"), b = _ + (v > y ? v - y : 0n) * f, x = b + b * p / 10000n;
	return x > BigInt(1e9) ? BigInt(n) : x;
}, k = (e) => {
	let t = e[0].map(BigInt), n = e[1][0].map(BigInt), r = e[1][1].map(BigInt), i = e[2].map(BigInt), a = e[3].map(BigInt);
	return {
		a: t,
		b: [[n[1], n[0]], [r[1], r[0]]],
		c: i,
		publicSignals: a
	};
}, A = (e, t) => {
	let n = u.AbiCoder.defaultAbiCoder().encode([
		"uint16",
		"uint16",
		"uint16",
		"uint256"
	], [
		e.tokenNumber,
		e.nullifierAmount,
		e.outputAmount,
		t
	]);
	return BigInt(u.keccak256(n));
}, j = async (e, t, n, r, o, s) => {
	let c = A(o, s), l = e.map(String), d = n.map(String), f = r.map(String), p = {
		a: l,
		b: [t[0].map(String), t[1].map(String)],
		c: d,
		inputs: f,
		verifier_id: String(c)
	}, m = await i.post(`${a}/sign-proof`, p), { v: h, r: g, s: _ } = u.Signature.from(m.signature.trim());
	return {
		v: h,
		r: g,
		s: _
	};
}, M = (e) => [
	e.rootHashHinkal,
	e.erc20TokenAddresses,
	e.tokenIds,
	e.amountChanges,
	e.onChainCreation,
	e.slippageValues,
	e.inputNullifiers,
	e.outCommitments,
	e.encryptedOutputs,
	[
		e.feeStructure.feeToken,
		e.feeStructure.flatFee,
		e.feeStructure.variableRate
	],
	e.timeStamp,
	[
		e.stealthAddressStructure.extraRandomization,
		e.stealthAddressStructure.stealthAddress,
		e.stealthAddressStructure.H0,
		e.stealthAddressStructure.H1
	],
	e.rootHashAccessToken,
	e.calldataHash,
	e.publicSignalCount,
	e.relay,
	e.externalAddress,
	e.externalActionId,
	e.externalActionMetadata,
	[
		e.hinkalLogicArgs.hinkalLogicAction,
		e.hinkalLogicArgs.inHinkalAddress,
		e.hinkalLogicArgs.executeApprovalChanges,
		e.hinkalLogicArgs.doPreTxApproval,
		e.hinkalLogicArgs.useApprovalUtxoData.map((e) => [
			e.approvalChanges,
			e.externalApprovalAddresses,
			e.conversionInHinkalAddress
		])
	],
	[
		e.hookData.preHookContract,
		e.hookData.hookContract,
		e.hookData.preHookMetadata,
		e.hookData.postHookMetadata
	],
	[
		e.signatureData.v,
		e.signatureData.r,
		e.signatureData.s,
		e.signatureData.accessKey,
		e.signatureData.nonce,
		e.signatureData.ethereumAddress
	],
	e.originalSender
], N = async (e, t, n, r, i = !0) => {
	if (e) {
		let { a: e, b: a, c: o, publicSignals: s } = k(t), c = await j(e, a, o, s, n, BigInt(r.externalActionId)), l = {
			v: c.v,
			r: c.r,
			s: c.s
		};
		return i && (t[1] = [[t[1][0][1], t[1][0][0]], [t[1][1][1], t[1][1][0]]]), l;
	}
}, P = (e, t) => {
	let n = 0n, i = /* @__PURE__ */ new Map();
	for (let a = 0; a < e.length; a += 1) if (o(e[a].erc20TokenAddress, r)) n += t[a];
	else {
		let n = _(e[a].erc20TokenAddress);
		i.set(n, (i.get(n) ?? 0n) + t[a]);
	}
	return {
		totalTrxValue: n,
		tokensNeedingApproval: i
	};
}, F = async (e, t, r, i, a, o) => {
	let s = BigInt(await e.trx.getBalance(i)), u = BigInt(n);
	try {
		u = await O(e, t, r, i, a, o);
	} catch (e) {
		l.error("Error estimating Tron deposit fee", e);
	}
	if (s < o + u) throw Error(c.INSUFFICIENT_TRON_BALANCE_FOR_FEE);
}, I = async (e, t, r, i) => {
	let a = Array.from(i.entries());
	for (let i = 0; i < a.length; i += 1) {
		let [o, c] = a[i], l = await e.contract(s, o).allowance(t, r).call({ from: t });
		if (BigInt(String(l)) < c) {
			let { transaction: i } = await e.transactionBuilder.triggerSmartContract(o, "approve(address,uint256)", { feeLimit: n }, [{
				type: "address",
				value: r
			}, {
				type: "uint256",
				value: c.toString()
			}], t), a = await e.trx.sign(i), s = await e.trx.sendRawTransaction(a);
			if (!s.result) {
				let e = s.code ?? "UNKNOWN", t = s.message ? Buffer.from(s.message, "hex").toString() : "no message";
				throw Error(`Tron token approval failed: ${e} - ${t}`);
			}
		}
	}
};
//#endregion
export { y as addressToHexFormat, I as approveTronTokens, F as assertTronSufficientBalance, M as circomDataToArray, C as createTronCallData, g as createTronWeb, m as detectTronChainIdFromHost, O as estimateTronFeeSunWithPadding, _ as evmHexToTronBase58Address, D as fetchTronAccountResources, E as fetchTronChainParameters, j as generateProofSignatureRemotely, w as getAvailableResource, T as getChainParameterValue, A as getVerifierId, b as normalizeTronAddr, h as normalizeTronPrivateKey, k as parseZkCalldata, N as reorderZkCallData, P as splitTronTokensByNative, v as toTronBase58IfHex };
