import { chainIds as e } from "../../constants/chains.constants.mjs";
import { TokenType as t } from "../../constants/protocol.constants.mjs";
import { ContractType as n } from "../../types/ethereum-network.types.mjs";
import { StorageKeys as r } from "../../types/cache.types.mjs";
import { caseInsensitiveEqual as i, lowerCaseIncludes as a } from "../../functions/utils/caseInsensitive.utils.mjs";
import { API as o } from "../../API/API.mjs";
import { Logger as s } from "../../error-handling/logger.mjs";
import { getStateKey as c } from "../../functions/utils/string.utils.mjs";
import { tokenVisibilityStorage as l } from "./token-visibility-db.mjs";
import { getContractWithFetcherByChainId as u } from "../../functions/web3/getContractMetadata.mjs";
import { get as d, update as f } from "idb-keyval";
import p from "axios";
//#region libs/shared/common/src/data-structures/TokenDBs/ArcPublicTokensDB.ts
var m = class {
	API_BASE = "https://testnet.arcscan.app/api";
	fetchedTokens = {};
	async getPublicTokens(t) {
		let n = c(t, e.arcTestnet);
		return (await d(r.ARC_PUBLIC_TOKENS))?.[n] || [];
	}
	getFetchedTokens(t) {
		let n = c(t, e.arcTestnet);
		return this.fetchedTokens[n] || [];
	}
	async fetchAndUpdatePublicTokens(n) {
		let s = c(n, e.arcTestnet), u = await this.getERC20TokenAddresses(n), d = await this.getNFTTokens(n), p = d.map((e) => e.contractAddress), m = [...u, ...p];
		if (!m.length) return;
		let h = (await o.tokensInfoCall(e.arcTestnet, m)).map((n, r) => {
			if (n) return n;
			let a = m[r], o = d.find((e) => i(e.contractAddress, a));
			return o && o.tokenIds && o.tokenIds.length > 0 ? {
				chainId: e.arcTestnet,
				name: "Unknown NFT",
				symbol: "NFT",
				erc20TokenAddress: a,
				decimals: 0,
				nftTokenType: t.ERC721,
				tokenIds: o.tokenIds
			} : null;
		}).filter((e) => !!e), g = await l.hideSpamsAndFetchHiddenTokensAddresses(e.arcTestnet, h), _ = h.filter((e) => !a(g, e.erc20TokenAddress)).map((e) => ({
			...e,
			tokenIds: d.find((t) => i(t.contractAddress, e.erc20TokenAddress))?.tokenIds
		}));
		await f(r.ARC_PUBLIC_TOKENS, (e = {}) => {
			let t = {
				...e,
				[s]: _
			};
			return this.fetchedTokens = t, t;
		});
	}
	async getERC20TokenAddresses(t) {
		let r = [];
		try {
			let i = (await p.post(`${this.API_BASE}?module=account&action=tokentx&address=${t}`)).data;
			if (i.status === "1" && i.result) {
				let a = [...new Set(i.result.map(({ contractAddress: e }) => e))];
				for (let i of a) try {
					let a = u(e.arcTestnet, n.ERC20Contract, i), o = BigInt(await a.balanceOf(t));
					o > 0n && r.push({
						contractAddress: i,
						tokenBalance: o.toString()
					});
				} catch (e) {
					s.error("Error fetching ARC testnet token balance:", e);
				}
			}
		} catch (e) {
			s.error("Error fetching ARC testnet token transactions:", e);
		}
		return r.filter(({ tokenBalance: e }) => Number(e) !== 0).map(({ contractAddress: e }) => e);
	}
	async getNFTTokens(e) {
		let t = `${this.API_BASE}/v2/addresses/${e}/nft?type=ERC-721,ERC-1155`, n = [], r;
		do {
			let e = r ? `&${new URLSearchParams(r)}` : "", { data: i } = await p.get(`${t}${e}`), { items: a = [], next_page_params: o } = i;
			n.push(...a), r = o ? {
				token_contract_address_hash: o.token_contract_address_hash,
				token_id: o.token_id,
				token_type: o.token_type
			} : void 0;
		} while (r);
		let i = n.reduce((e, t) => {
			let n = t.token.address_hash.toLowerCase(), r = t.id;
			return e.has(n) || e.set(n, []), e.get(n)?.push(r), e;
		}, /* @__PURE__ */ new Map());
		return Array.from(i.entries()).map(([e, t]) => ({
			contractAddress: e,
			tokenIds: t
		}));
	}
}, h = new m();
//#endregion
export { m as ArcPublicTokensDB, h as arcPublicTokensDB };
