import { useState as C, useRef as L } from "react";
import { useQuery as M, keepPreviousData as G } from "@tanstack/react-query";
import { G as v } from "../config-BDnHptBC.js";
import { feeServiceApi as x } from "../network.js";
import { getTransactionHistoryQueryKey as H } from "../utils/transactions/getTransactionHistoryQueryKey.js";
import { getTransactionHashes as N } from "../utils/transactions/getTransactionHashes.js";
import { getOptimisticTransactions as I, removeOptimisticTransaction as B } from "../utils/transactions/addOptimisticTransaction.js";
const h = 9, U = h + 1, k = 1e3, q = 5e3, S = [
  "PENDING",
  "PROCESSING",
  "WAITING_FOR_FUNDS"
], J = () => {
  const {
    apiKey: o,
    connectedWallets: { default: e }
  } = v(), [a, P] = C(!1), l = a ? k : U, _ = [
    ...H(e),
    l
  ], { data: r, isLoading: E, isError: i, isFetching: w, isPlaceholderData: p, refetch: f } = M({
    queryKey: _,
    queryFn: () => {
      if (!o)
        throw new Error("An API key is required to fetch transactions");
      return x.get(
        `/api/transactions/${o}`,
        {
          params: {
            numberOfTransactions: l,
            walletAddress: e
          }
        }
      );
    },
    enabled: !!o && !!e,
    // Keep the current list visible while the larger "Show more" request is
    // in flight instead of flashing the loading skeleton.
    placeholderData: G,
    refetchInterval: (t) => (t.state.data?.data ?? []).some((s) => S.includes(s.status)) || !!e && I(e).length > 0 ? q : !1
  }), A = L([]);
  r?.data && (A.current = r.data);
  const c = r?.data ?? A.current, d = a && !p && !i ? c : c.slice(0, h), T = e ? I(e) : [], O = new Set(d.flatMap(N)), y = new Set(
    d.map((t) => t.depositAddress).filter(Boolean)
  );
  T.forEach((t) => {
    const n = N(t).some(
      (s) => O.has(s)
    ), g = !!t.depositAddress && y.has(t.depositAddress);
    if (n || g) {
      const s = t.intentHashes ?? t.originChainTxHashes[0];
      s && B(s);
    }
  });
  const m = [
    ...T,
    ...d
  ].sort(
    (t, n) => new Date(n.createdAt).getTime() - new Date(t.createdAt).getTime()
  ), D = m.filter(
    (t) => S.includes(t.status)
  ).length, F = w && p, u = a && i, R = !a && c.length > h;
  return {
    transactions: m,
    pendingTransactionsCount: D,
    isLoading: E,
    isError: i,
    refetch: f,
    hasNextPage: R,
    fetchNextPage: () => {
      if (u) {
        f();
        return;
      }
      P(!0);
    },
    isFetchingNextPage: F,
    isFetchNextPageError: u
  };
};
export {
  J as useTransactions
};
//# sourceMappingURL=useTransactions.js.map
