import { z as e } from "zod";
import { alchemyApi as P } from "../../network.js";
import { isEvmAddress as O } from "../../utils/chains/isEvmAddress.js";
import { isTonAddress as _ } from "../../utils/chains/isTonAddress.js";
import { CHAINS_MAP as c, isAlchemySupportedChain as M } from "./types.js";
const R = e.object({
  network: e.string(),
  tokenAddress: e.string().nullable(),
  tokenBalance: e.string()
}), T = e.object({
  pageKey: e.string().nullable(),
  tokens: e.array(R)
}), v = e.object({
  data: T
}), $ = e.object({
  code: e.number(),
  message: e.string()
}), K = e.object({
  result: e.string().optional(),
  error: $.optional()
}), I = e.object({
  portfolioPageKey: e.string().nullable(),
  monadPageKeys: e.record(e.string(), e.string())
}), A = "alchemy-composite:", S = (t) => `https://${c.monad}.g.alchemy.com/v2/${t}`, b = [
  // USDC on Monad
  "0x754704Bc059F8C67012fEd69BC8A327a5aafb603",
  // USDT0 on Monad
  "0xe7cd86e13AC4309349F30B3435a9d337750fC82D"
], L = (t) => {
  const o = "70a08231", s = t.toLowerCase().replace(/^0x/, "").padStart(64, "0");
  return `0x${o}${s}`;
}, D = (t) => `${A}${encodeURIComponent(JSON.stringify(t))}`, F = (t) => {
  if (!t.startsWith(A))
    return null;
  try {
    const o = t.slice(A.length), d = JSON.parse(decodeURIComponent(o)), s = I.safeParse(d);
    return s.success ? s.data : null;
  } catch {
    return null;
  }
}, U = (t) => t.map((o) => M(o) ? c[o] ?? null : null).filter((o) => !!o), q = ({ alchemyApiKey: t }) => async ({
  supportedChains: o,
  connectedWallets: d,
  pageParam: s
}) => {
  const u = U(o), N = u.includes(c.monad), w = u, g = Object.values(d).filter(
    (r) => !!r && !_(r)
  );
  if (!u.length || !g.length)
    return {
      pageKey: null,
      data: []
    };
  const x = (s ? F(s) : null)?.portfolioPageKey ?? null, f = [];
  let h = null;
  if (w.length > 0) {
    const r = await P.post(
      `/${t}/assets/tokens/balances/by-address`,
      {
        includeErc20Tokens: !0,
        includeNativeTokens: !0,
        addresses: g.map((a) => ({
          address: a,
          networks: w
        })),
        pageKey: x
      }
    ), { data: C } = v.parse(r.data), { tokens: n, pageKey: y } = C, i = n.filter((a) => {
      const l = a.network === c.monad, p = l && a.tokenAddress === null, k = l && a.tokenAddress != null && b.some(
        (m) => m.toLowerCase() === a.tokenAddress?.toLowerCase()
      );
      return !(p || k);
    });
    f.push(...i), h = y;
  }
  const E = s == null;
  if (N && E) {
    const r = g.filter(O);
    (await Promise.allSettled(
      r.map(async (n) => {
        const y = await P.post(
          S(t),
          {
            jsonrpc: "2.0",
            id: 1,
            method: "eth_getBalance",
            params: [n, "latest"]
          }
        ), i = K.parse(y.data), a = i.error ? "0x0" : i.result ?? "0x0", l = [];
        for (const p of b)
          try {
            const k = await P.post(
              S(t),
              {
                jsonrpc: "2.0",
                id: 1,
                method: "eth_call",
                params: [
                  {
                    to: p,
                    data: L(n)
                  },
                  "latest"
                ]
              }
            ), m = K.parse(
              k.data
            ), j = m.error ? "0x0" : m.result ?? "0x0";
            l.push({
              network: c.monad,
              tokenAddress: p,
              tokenBalance: j
            });
          } catch {
          }
        return {
          address: n,
          tokens: [
            {
              network: c.monad,
              tokenAddress: null,
              tokenBalance: a
            },
            ...l
          ]
        };
      })
    )).forEach((n) => {
      n.status === "fulfilled" && f.push(...n.value.tokens);
    });
  }
  const B = !!h ? D({
    portfolioPageKey: h,
    monadPageKeys: {}
  }) : null;
  return {
    data: f,
    pageKey: B
  };
};
export {
  q as createLoader
};
//# sourceMappingURL=load.js.map
