import { ActivityStatus as e } from "../../types/activities.types.mjs";
import { StorageKeys as t } from "../../types/cache.types.mjs";
import "../../types/index.mjs";
import { transactionErrorCodes as n } from "../../error-handling/error-codes.constants.mjs";
import { RELAYER_TX_CONFIRMATION_TIMEOUT as r } from "../../constants/tx-confirmation.constants.mjs";
import { Logger as i } from "../../error-handling/logger.mjs";
import "../../error-handling/index.mjs";
import { waitForTransactionConfirmation as a } from "../../functions/utils/tx-confirmation.utils.mjs";
import "../../functions/index.mjs";
import { aggregateTokensBySymbol as o } from "../../functions/utils/aggregateTokenAmounts.mjs";
import { get as s, update as c } from "idb-keyval";
//#region libs/shared/common/src/data-structures/IndexedDB/activity-db.ts
var l = class {
	generateTxId() {
		return `tx_${(/* @__PURE__ */ new Date()).getTime()}_${Math.random().toString(36).substring(2, 15)}`;
	}
	async getTransactionRecord() {
		return await s(t.TX_ACTIVITY) || {};
	}
	async saveTxRequest(n) {
		let { from: r, to: i, gasInDollar: a, extraNativeTokenFee: s, chainId: l, status: u, txHash: d, activityType: f, tokensReceive: p, tokensSpend: m, tokensApprove: h, activityIcon: g, dappUrl: _, dappName: v, integrationProvider: y, knownPartialSignature: b } = n, x = this.generateTxId(), S = m?.length ? o(m) : [], C = p?.length ? o(p) : [], w = {
			id: x,
			from: r,
			to: i,
			gasInDollar: a?.toString(),
			extraNativeTokenFee: s?.toString(),
			chainId: l,
			txHash: d,
			activityType: f,
			status: u ?? e.PENDING,
			timestamp: /* @__PURE__ */ new Date(),
			tokensReceive: C,
			tokensSpend: S,
			tokensApprove: h,
			activityIcon: g,
			dappUrl: _,
			dappName: v,
			integrationProvider: y,
			knownPartialSignature: b
		};
		return await c(t.TX_ACTIVITY, (e = {}) => (e[x] = w, e)), x;
	}
	async getTxRequest(e) {
		return (await this.getTransactionRecord())[e] || null;
	}
	async getAllTxRequests(e) {
		let t = await this.getTransactionRecord();
		return Object.values(t).filter((t) => t.chainId === e).sort((e, t) => new Date(t.timestamp).getTime() - new Date(e.timestamp).getTime());
	}
	async updateTxHash(e, n) {
		let r = await this.getTxRequest(e);
		if (!r) throw Error("Activity not found");
		let i = {
			...r,
			txHash: n
		};
		await c(t.TX_ACTIVITY, (t = {}) => (t[e] = i, t));
	}
	async updateTxStatusAndHash(e, n, r) {
		let i = await this.getTxRequest(e);
		if (!i) throw Error("Transaction not found");
		let a = {
			...i,
			status: n,
			txHash: r,
			timestamp: /* @__PURE__ */ new Date()
		};
		return await c(t.TX_ACTIVITY, (t = {}) => (t[e] = a, t)), a;
	}
	async updateActivity(e, t, n) {
		try {
			await this.updateTxStatusAndHash(e, t, n);
		} catch (e) {
			i.error("error in updating tx request", e);
		}
	}
	async removePendingTransactions(e) {
		try {
			await c(t.TX_ACTIVITY, (t = {}) => (delete t[e], t));
		} catch (e) {
			i.error("error in deleting tx requests", e);
		}
	}
	async updatePendingTransactions(t, o, s, c) {
		try {
			let i = await this.getTxRequest(o);
			if (!i) throw Error("Transaction not found");
			let { chainId: l } = i;
			if (!t.success) {
				c?.(t.error), await this.updateActivity(o, e.FAILED, "erroredTx" in t ? t.erroredTx : void 0);
				return;
			}
			if ("txHash" in t) {
				let { txHash: i } = t;
				try {
					await a(l, i, { evmTimeoutMs: r });
				} catch (t) {
					let r = t instanceof Error ? t : Error(n.UNKNOWN);
					c?.(r), await this.updateActivity(o, e.FAILED, i);
					return;
				}
				s?.(), await this.updateActivity(o, e.SUCCESSFUL, i);
			}
		} catch (e) {
			i.error("error in updating pending transactions", e);
		}
	}
}, u = new l();
//#endregion
export { l as ActivityStorage, u as activityStorage };
