import { chainIds as e, networkRegistry as t } from "../../constants/chains.constants.mjs";
import { ExternalActionId as n } from "../../types/external-action.types.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 { gasErrorCodes as c, transactionErrorCodes as l } from "../../error-handling/error-codes.constants.mjs";
import { getAmountInToken as u } from "../../functions/web3/etherFunctions.mjs";
import { getERC20Token as d, getERC20TokenBySymbol as f } from "../../functions/utils/erc20tokenFunctions.mjs";
import { caseInsensitiveEqual as p } from "../../functions/utils/caseInsensitive.utils.mjs";
import { waitLittle as m } from "../../functions/utils/time.utils.mjs";
import { ErrorWithRelayerTransaction as h } from "../../error-handling/customErrors/ErrorWithTx.mjs";
import { API as g } from "../../API/API.mjs";
import { Logger as _ } from "../../error-handling/logger.mjs";
import { getGasTokenSymbols as ee } from "../../functions/utils/fees.utils.mjs";
import { createJsonRpcProvider as v } from "../../functions/utils/create-provider.mjs";
import { getErrorMessageFromTransactionRequest as y } from "../../error-handling/get-error.message.mjs";
import "../../error-handling/index.mjs";
import { modifyVolatileTokenAmountChanges as b } from "../../functions/pre-transaction/getVolatileTransferAmount.mjs";
import { getFeeStructure as x } from "../../functions/pre-transaction/getFeeStructure.mjs";
import { convertEmporiumOpToCallInfo as S } from "../../functions/utils/convertEmporiumOpToCallInfo.mjs";
import { postToOffscreen as C } from "../../functions/utils/postToOffscreen.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 = v(j);
		await m(j === e.ethMainnet ? ne : te);
		let h = await T(I, P, M, o);
		if (!h.length) {
			C(s.AutoShieldTxStatus, { message: l.AUTO_SHIELD_SKIPPED });
			return;
		}
		let _ = ee(j).map((e) => f(e, j)).filter((e) => e !== void 0), { prices: y } = await g.getTokenPrices(j, _.map((e) => e.erc20TokenAddress)), z = new Map(y.map((e, t) => [_[t].erc20TokenAddress.toLowerCase(), e])), B = h.map(({ token: e }) => e), V = h.map(({ balance: e }) => e), H = B.map(({ erc20TokenAddress: e }) => e), U = w(A, j, H, await b(j, B, V, M)), W = await x(j, P, H, n.Emporium, U.map((e) => S(e, M, j))), { flatFee: G } = W ?? {}, K = d(W.feeToken, j);
		if (!K) return;
		let q = u(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) {
			C(s.AutoShieldTxStatus, { message: c.GAS_PRICE_EXCEEDS_AUTOSHIELD_LIMIT });
			return;
		}
		let Q = B.findIndex((e) => p(e.erc20TokenAddress, X));
		Q !== -1 && (V[Q] -= Z?.flatFee ?? 0n);
		let { hinkalAddress: re } = t[j].contractData, $ = {
			activityType: a.AUTO_SHIELD,
			chainId: j,
			from: M,
			to: re,
			gasInDollar: J.toString(),
			tokensReceive: B.map((e, t) => ({
				amount: u(e, V[t]),
				token: e
			}))
		};
		R = await k.saveTxRequest($), C(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), C(s.AutoShieldTxStatus, {
			status: r.Confirmed,
			activityRequest: $
		});
	} catch (e) {
		let t;
		e instanceof h && (t = e.txHash);
		let n = {
			error: e,
			id: 0,
			success: !1,
			...t ? { erroredTx: t } : {}
		};
		R && await k.updatePendingTransactions(n, R), C(s.AutoShieldTxStatus, {
			status: r.Failed,
			error: y(e, o.ReceiveFromShieldedAccount)
		}), _.error("Error in auto deposit back:", e);
	}
};
//#endregion
export { A as handleAutoDepositBack };
