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