import { safeJsonStringify as e } from "../utils/serialize.utils.mjs";
import { COMPUTE_UNIT_PADDING_PERCENTAGE as t, MAX_COMPUTE_UNIT_LIMIT as n, MIN_COMPUTE_UNIT_LIMIT as r } from "../../constants/protocol.constants.mjs";
import { AccountActions as i } from "../../data-structures/AccountActions/AccountActions.mjs";
import { SolanaPriorityFeeMode as a } from "../../types/fee.types.mjs";
import { getSolanaPriorityFee as o } from "../web3/getSolanaPriorityFee.mjs";
import { pollForValue as s } from "../utils/process.utils.mjs";
import { shouldRetryForSolanaError as c } from "../../error-handling/retrySolanaError.mjs";
import { ComputeBudgetProgram as l, PublicKey as u, TransactionMessage as d, VersionedTransaction as f } from "@solana/web3.js";
import { ASSOCIATED_TOKEN_PROGRAM_ID as p, TOKEN_PROGRAM_ID as m, createAssociatedTokenAccountInstruction as h, getAssociatedTokenAddress as g } from "@solana/spl-token";
//#region libs/shared/common/src/functions/pre-transaction/sendV0Transaction.ts
var _ = 5e3, v = 6e4, y = 7, b = async (e, t, n = "confirmed") => await s(() => e.getTransaction(t, {
	commitment: n,
	maxSupportedTransactionVersion: 0
}), {
	timeoutMs: v,
	intervalMs: _
}) ?? null, x = async (e, i, a, o) => {
	try {
		let { blockhash: s } = await e.getLatestBlockhash(), c = new f(new d({
			payerKey: i,
			recentBlockhash: s,
			instructions: [l.setComputeUnitLimit({ units: n }), ...a]
		}).compileToV0Message(o)), { unitsConsumed: u } = (await e.simulateTransaction(c, {
			sigVerify: !1,
			replaceRecentBlockhash: !0
		})).value;
		if (!u) return n;
		let p = Math.ceil(u * (1 + t));
		return Math.max(r, Math.min(p, n));
	} catch {
		return n;
	}
}, S = (e, t, n, r) => {
	let i = /* @__PURE__ */ new Set();
	return t && i.add(t.toBase58()), n?.forEach((e) => i.add(e.toBase58())), e.forEach((e) => {
		i.add(e.programId.toBase58()), e.keys.forEach((e) => {
			i.add(e.pubkey.toBase58());
		});
	}), r && r.forEach((e) => {
		i.add(e.key.toBase58()), e.state.addresses.forEach((e) => {
			i.add(e.toBase58());
		});
	}), [...i].map((e) => new u(e));
}, C = (t) => {
	if (!t) throw Error("Failed to fetch Solana transaction details for signature");
	if (t.meta?.err) {
		let n = e(t.meta.err);
		throw Error(`Solana transaction failed on-chain: ${n}`);
	}
}, w = async (e, t, r, i, a) => {
	if (r.some((e) => e.programId.equals(l.programId))) return r.map((e) => e.programId.equals(l.programId) && e.data[0] === 2 ? l.setComputeUnitLimit({ units: n }) : e);
	let s = r.filter((e) => !e.programId.equals(l.programId)), c = await x(e, t, s, i), u = l.setComputeUnitLimit({ units: c }), d = e.rpcEndpoint.includes("helius") ? await o(S(s, t, [l.programId], i), a) : 0;
	return [
		u,
		l.setComputeUnitPrice({ microLamports: d }),
		...s
	];
}, T = async (e, t, n, r, i) => {
	if (t.length === 0) return "";
	for (let o = 0; o < 10; o += 1) {
		let s = o === 9;
		try {
			let s = await w(e, n.publicKey, t, i, o >= y ? a.HIGH : a.RECOMMENDED), { blockhash: c, lastValidBlockHeight: l } = await e.getLatestBlockhash(), u = new f(new d({
				payerKey: n.publicKey,
				instructions: s,
				recentBlockhash: c
			}).compileToV0Message(i));
			u.sign(r);
			let p = await e.sendTransaction(u);
			return await e.confirmTransaction({
				signature: p,
				blockhash: c,
				lastValidBlockHeight: l
			}, "confirmed"), C(await b(e, p)), p;
		} catch (e) {
			if (c(e) && !s) continue;
			throw e;
		}
	}
	return "";
}, E = async (e, t, n, r) => {
	if (!n) return null;
	let i = await g(n, r, !0, m, p);
	return await e.getAccountInfo(i) || await T(e, [h(t.publicKey, i, r, n, m, p)], t, [t]), i;
}, D = async ({ connection: e, chainId: t, subAccount: n, payerPublicKey: r, instructions: o, lookupTableAccounts: s }) => {
	let l = i.getPrivateKeyFromSubAccount(t, n);
	if (!l) throw Error("Private key is not available");
	for (let t = 0; t < 10; t += 1) {
		let n = t === 9;
		try {
			let t = await w(e, r, o, s, n ? a.HIGH : a.RECOMMENDED), { blockhash: c, lastValidBlockHeight: u } = await e.getLatestBlockhash(), p = new f(new d({
				payerKey: r,
				recentBlockhash: c,
				instructions: t
			}).compileToV0Message(s)), m = await i.sendAndSignSolanaTransactionFromPrivateKey(e, l, p, !0);
			return await e.confirmTransaction({
				signature: m,
				blockhash: c,
				lastValidBlockHeight: u
			}, "confirmed"), C(await b(e, m)), m;
		} catch (e) {
			if (c(e) && !n) continue;
			throw e;
		}
	}
	throw Error("Failed to send proxy v0 transaction due to expired blockheight after all retries");
}, O = async (e, t, n, r) => {
	let { blockhash: i } = await e.getLatestBlockhash(), a = new f(new d({
		payerKey: t,
		recentBlockhash: i,
		instructions: await w(e, t, n, r)
	}).compileToV0Message(r));
	return Buffer.from(a.serialize()).toString("base64");
};
//#endregion
export { E as ensureAtaExists, x as estimateComputeUnitLimit, b as fetchSolanaTransaction, S as getAccountsFromInstructions, D as sendProxyV0Transaction, T as sendV0Transaction, O as serializeProxyV0Transaction };
