import { networkRegistry as e } from "../../constants/chains.constants.mjs";
import { solanaNativeAddress as t } from "../../constants/protocol.constants.mjs";
import { getStorageAccountPublicKey as n, getStorageVaultPublicKey as r, getSwapperAccountPublicKeyFromSalt as i } from "../../functions/pre-transaction/solana.mjs";
import { ExternalActionId as a } from "../../types/external-action.types.mjs";
import { AdminTransactionType as o } from "../../types/admin.types.mjs";
import { StorageKeys as s } from "../../types/cache.types.mjs";
import "../../types/index.mjs";
import { transactionErrorCodes as c } from "../../error-handling/error-codes.constants.mjs";
import { getAmountInToken as l, getAmountInWei as ee, randomBigInt as te } from "../../functions/web3/etherFunctions.mjs";
import { getCurrentTimeInSeconds as u } from "../../functions/utils/time.utils.mjs";
import { Utxo as d } from "../utxo/Utxo.mjs";
import { validateAndGetChainId as f } from "../../functions/utils/token-check.utils.mjs";
import { addPaddingToUtxos as p } from "../../functions/web3/events/getShieldedBalance.mjs";
import { outputUtxoProcessing as m } from "../../functions/pre-transaction/outputUtxoProcessing.mjs";
import { calcEncryptedOutputs as h } from "../../functions/snarkjs/common.snarkjs.mjs";
import { constructAdminData as g } from "../../functions/pre-transaction/constructAdminData.mjs";
import { convertOKXToHinkalInstructions as _ } from "../../functions/pre-transaction/convert-okx-instructions.mjs";
import { ensureAmountChanges as ne } from "../../functions/pre-transaction/ensureAmountChanges.mjs";
import { getFeeStructure as re } from "../../functions/pre-transaction/getFeeStructure.mjs";
import { shouldPatchAccessTokenMerkleTree as ie } from "../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.mjs";
import { buildCommitmentValidationData as v } from "../../functions/pre-transaction/buildCommitmentValidationData.mjs";
import { constructSolanaZkProof as y } from "../../functions/snarkjs/constructSolanaZkProof.mjs";
import { solanaTransactCallRelayer as b } from "../../functions/web3/functionCalls/transactCallRelayer.mjs";
import { ethers as x } from "ethers";
import { PublicKey as S } from "@solana/web3.js";
//#region libs/shared/common/src/data-structures/Hinkal/hinkalSolanaSwap.ts
var C = async (e, t, n, r) => {
	let i = [...await p(e, t, n, r, 6)], a = u().toString(), o = [];
	for (let t = 0; t < n.length; t += 1) {
		let { outputUtxos: n } = m(e.userKeys, i[t], r[t], a);
		o.push([n[0]]);
	}
	return {
		inputUtxosArray: i,
		outputUtxosArray: o
	};
}, w = async (u, p, m, w, ae, oe, se, ce) => {
	let T = f(p), E = new S(t), { hinkalAddress: D, originalDeployer: O, hinkalIdl: k } = e[T].contractData;
	if (!O || !k) throw Error("No IDL configured for Solana program on this network");
	let A = new S(O), j = new S(D), M = p.map((e) => e.erc20TokenAddress), { userKeys: N, merkleTreeAccessTokenByChain: P, merkleTreeHinkalByChain: F } = u, I = u.getSolanaProgram(k), L = ce ?? await re(T, se, M, a.Transact), R = m[1], z = Number(u.cacheDevice.get(s.SLIPPAGE_PERCENTAGE) ?? 0), B = p[1], V = l(B, R), H = Number(V) * z / 100;
	m[1] -= ee(B, H.toFixed(B.decimals));
	let U = R * BigInt(L.variableRate ?? 0) / 10000n + L.flatFee;
	if (m[1] -= U, m[1] < 0) throw Error(c.LOW_OUTPUT_AMOUNT);
	let W = L.variableRate.toString(), [{ patchAccessTokenMerkleTree: le, kycRequired: ue, hasAccessToken: de }, G, K, { inputUtxosArray: q, outputUtxosArray: J }] = await Promise.all([
		ie(u, T, M, m),
		u.getRandomRelay(T, !0),
		u.getEthereumAddressByChain(T),
		C(u, T, M, m)
	]);
	if (!G) throw Error(c.RELAYER_NOT_AVAILABLE);
	let fe = u.userKeys.getShieldedPrivateKey(), pe = d.findCorrectRandomization(te(31), fe), Y = {
		tokenNumber: 2,
		nullifierAmount: q[0].length,
		outputAmount: 1
	}, X = h(J).map((e) => [...x.getBytes(e[0])]), Z = i(j, A, w), { remainingAccounts: Q, hinkalInstructions: $ } = _(ae, Z);
	ne(q, J, m);
	let [{ proofAArr: me, proofBArr: he, proofCArr: ge, publicInputsArr: _e }, ve] = await Promise.all([y(u.generateProofRemotely, O, F[T], P[T], N, I, M, q, J, pe, L.flatFee, L.variableRate, E.toString(), G, Y, X, T, le, w, $, Q), v(T, N, M, q)]), ye = n(j, A), be = r(j, A), xe = p[0].erc20TokenAddress === "11111111111111111111111111111111" ? null : new S(p[0].erc20TokenAddress), Se = p[1].erc20TokenAddress === "11111111111111111111111111111111" ? null : new S(p[1].erc20TokenAddress), Ce = {
		recipient: E.toString(),
		storageAccount: ye.toString(),
		storageVault: be.toString(),
		swapperAccount: Z.toString(),
		mintFrom: xe?.toString() ?? null,
		mintTo: Se?.toString() ?? null,
		remainingAccounts: Q.map((e) => ({
			pubkey: e.pubkey.toString(),
			isSigner: e.isSigner,
			isWritable: e.isWritable
		})),
		addressLookupTableAccount: oe
	}, we = {
		encryptedOutputs: X,
		proofAArr: me,
		proofBArr: he,
		proofCArr: ge,
		publicInputsArr: _e,
		relayerFee: L.flatFee.toString(),
		variableRate: W,
		dimensions: Y,
		hinkalInstructions: $.map((e) => ({
			accountIndexes: [...e.accountIndexes],
			data: [...e.data],
			programIndex: e.programIndex
		}))
	}, Te = g(o.PrivateSwap, T, M, m, K, p);
	return b({
		chainId: T,
		relayAddress: G,
		functionName: "swap",
		args: we,
		accounts: Ce,
		commitmentValidationData: ve,
		solanaAccessTokenData: !de && ue ? {
			ethereumAddress: K,
			accessKey: N.getAccessKey()
		} : void 0,
		adminData: Te
	});
};
//#endregion
export { w as hinkalSolanaSwap };
