import { ExternalActionId as e } from "../../types/external-action.types.mjs";
import { chainIds as t, networkRegistry as n } from "../../constants/chains.constants.mjs";
import { TransactionStatus as r } from "../../types/transactions.types.mjs";
import { AdminTransactionType as i } from "../../types/admin.types.mjs";
import { ActivityTypes as a } from "../../types/activities.types.mjs";
import { TransactionRequestType as o } from "../../types/transaction.types.mjs";
import { MessagesFromOffscreen as s } from "../../types/offscreen.types.mjs";
import "../../types/index.mjs";
import { caseInsensitiveEqual as c } from "../../functions/utils/caseInsensitive.utils.mjs";
import { API as l } from "../../API/API.mjs";
import { gasErrorCodes as u, transactionErrorCodes as d } from "../../error-handling/error-codes.constants.mjs";
import { getAmountInToken as f } from "../../functions/web3/etherFunctions.mjs";
import { getERC20Token as p, getERC20TokenBySymbol as m } from "../../functions/utils/erc20tokenFunctions.mjs";
import { waitLittle as h } from "../../functions/utils/time.utils.mjs";
import { ErrorWithRelayerTransaction as g } from "../../error-handling/customErrors/ErrorWithTx.mjs";
import { Logger as _ } from "../../error-handling/logger.mjs";
import { createJsonRpcProvider as ee } from "../../functions/utils/create-provider.mjs";
import { getErrorMessageFromTransactionRequest as v } from "../../error-handling/get-error.message.mjs";
import "../../error-handling/index.mjs";
import { modifyVolatileTokenAmountChanges as y } from "../../functions/pre-transaction/getVolatileTransferAmount.mjs";
import { getFeeStructure as b } from "../../functions/pre-transaction/getFeeStructure.mjs";
import { convertEmporiumOpToCallInfo as x } from "../../functions/utils/convertEmporiumOpToCallInfo.mjs";
import { postToOffscreen as S } from "../../functions/utils/postToOffscreen.mjs";
import { getGasTokenSymbols as C } from "../../functions/utils/fees.utils.mjs";
import { createTransaferEmporiumOpsBatch as w } from "../../functions/private-wallet/emporium.helpers.mjs";
import { getTokensToDepositBack as T } from "../../functions/auto-deposit-back-helpers/get-tokens-to-deposit-back.mjs";
import { getGasTokenRecords as E } from "../../functions/auto-deposit-back-helpers/get-gas-token-records.mjs";
import { selectGasToken as D } from "../../functions/auto-deposit-back-helpers/select-gas-token.mjs";
import { updateHinkal as O } from "../../functions/auto-deposit-back-helpers/update-hinkal.mjs";
import "../../functions/index.mjs";
import { activityStorage as k } from "../IndexedDB/activity-db.mjs";
import "../IndexedDB/index.mjs";
//#region libs/shared/common/src/data-structures/Hinkal/handleAutoDepositBack.ts
var te = 3 * 1e3, ne = 13 * 1e3, A = async (A, j, M, N, P, F, I, L) => {
	if (!M || I.length === 0) return;
	let R;
	try {
		let o = ee(j);
		await h(j === t.ethMainnet ? ne : te);
		let g = await T(I, P, M, o);
		if (!g.length) {
			S(s.AutoShieldTxStatus, { message: d.AUTO_SHIELD_SKIPPED });
			return;
		}
		let _ = C(j).map((e) => m(e, j)).filter((e) => e !== void 0), { prices: v } = await l.getTokenPrices(j, _.map((e) => e.erc20TokenAddress)), z = new Map(v.map((e, t) => [_[t].erc20TokenAddress.toLowerCase(), e])), B = g.map(({ token: e }) => e), V = g.map(({ balance: e }) => e), H = B.map(({ erc20TokenAddress: e }) => e), U = w(A, j, H, await y(j, B, V, M)), W = await b(j, P, H, e.Emporium, U.map((e) => x(e, M, j))), { flatFee: G } = W ?? {}, K = p(W.feeToken, j);
		if (!K) return;
		let q = f(K, G), J = (z.get(K.erc20TokenAddress.toLowerCase()) ?? 0) * Number(q), Y = await D(P, J, j, B, U, await E(_, j, A, M, o, z), W, H, M);
		if (!Y) return;
		let { feeToken: X, feeStructure: Z } = Y ?? {};
		if (F && Number(F) < J) {
			S(s.AutoShieldTxStatus, { message: u.GAS_PRICE_EXCEEDS_AUTOSHIELD_LIMIT });
			return;
		}
		let Q = B.findIndex((e) => c(e.erc20TokenAddress, X));
		Q !== -1 && (V[Q] -= Z?.flatFee ?? 0n);
		let { hinkalAddress: re } = n[j].contractData, $ = {
			activityType: a.AUTO_SHIELD,
			chainId: j,
			from: M,
			to: re,
			gasInDollar: J.toString(),
			tokensReceive: B.map((e, t) => ({
				amount: f(e, V[t]),
				token: e
			}))
		};
		R = await k.saveTxRequest($), S(s.AutoShieldTxStatus, { status: r.Loading }), O(L, j, A);
		let ie = {
			id: 0,
			success: !0,
			txHash: await A.actionReceive(B, V, X, Z, N, i.AutoShield)
		};
		await k.updatePendingTransactions(ie, R), S(s.AutoShieldTxStatus, {
			status: r.Confirmed,
			activityRequest: $
		});
	} catch (e) {
		let t;
		e instanceof g && (t = e.txHash);
		let n = {
			error: e,
			id: 0,
			success: !1,
			...t ? { erroredTx: t } : {}
		};
		R && await k.updatePendingTransactions(n, R), S(s.AutoShieldTxStatus, {
			status: r.Failed,
			error: v(e, o.ReceiveFromShieldedAccount)
		}), _.error("Error in auto deposit back:", e);
	}
};
//#endregion
export { A as handleAutoDepositBack };
