import { Q as q, S as $, i as D, V as O, u as H, X as B, C as W, d as k, l as G } from "./platform-Cil_UtAQ.mjs";
import { W as j } from "./wallet-CMTEE6Oa.mjs";
import { V as X, l as y, K as Y, j as F, e as Z, p as z, m as Q, k as J } from "./unsignedTransaction-DCDxTFq8.mjs";
import { E as K } from "./keypair-CP7syX9B.mjs";
var M;
(function(t) {
  t.ETH = "eth", t.POL = "pol", t.BSC = "bsc", t.DAI = "dai", t.FTM = "ftm", t.AVA = "ava", t.ARB = "arb", t.OPT = "opt", t.ONE = "one", t.FSN = "fsn", t.MOR = "mor", t.CEL = "cel", t.FUS = "fus", t.TLO = "tlo", t.CRO = "cro", t.BOB = "bob", t.RSK = "rsk", t.VEL = "vel", t.MOO = "moo", t.MAM = "mam", t.AUR = "aur", t.EVM = "evm", t.ARN = "arn", t.ERA = "era", t.PZE = "pze", t.LNA = "lna", t.BAS = "bas", t.SCL = "scl", t.MOD = "mod", t.MNT = "mnt", t.BLS = "bls", t.SEI = "sei", t.FRA = "fra", t.TAI = "tai", t.GRA = "gra", t.IMX = "imx", t.KAI = "kai", t.XLY = "xly", t.OPB = "opb", t.WCC = "wcc", t.LSK = "lsk", t.ABS = "abs", t.BER = "ber", t.SON = "son", t.UNI = "uni", t.APE = "ape", t.SOE = "soe", t.INK = "ink", t.LNS = "lns", t.SWL = "swl", t.CRN = "crn", t.ETL = "etl", t.SUP = "sup", t.HYP = "hyp", t.XDC = "xdc", t.BOC = "boc", t.VIC = "vic", t.FLR = "flr", t.KAT = "kat", t.VAN = "van", t.RON = "ron", t.PLU = "plu", t.NIB = "nib", t.HPL = "hpl", t.SOP = "sop", t.PLA = "pla", t.FLW = "flw", t.HMI = "hmi", t.MON = "mon", t.SOL = "sol", t.TER = "ter", t.OAS = "oas", t.SUI = "sui", t.BTC = "btc", t.BCH = "bch", t.LTC = "ltc", t.DGE = "dge", t.TRN = "trn";
})(M || (M = {}));
var c;
(function(t) {
  t[t.ETH = 1] = "ETH", t[t.POL = 137] = "POL", t[t.BSC = 56] = "BSC", t[t.DAI = 100] = "DAI", t[t.FTM = 250] = "FTM", t[t.AVA = 43114] = "AVA", t[t.ARB = 42161] = "ARB", t[t.OPT = 10] = "OPT", t[t.ONE = 16666e5] = "ONE", t[t.FSN = 32659] = "FSN", t[t.MOR = 1285] = "MOR", t[t.CEL = 42220] = "CEL", t[t.FUS = 122] = "FUS", t[t.TLO = 40] = "TLO", t[t.CRO = 25] = "CRO", t[t.BOB = 288] = "BOB", t[t.RSK = 30] = "RSK", t[t.VEL = 106] = "VEL", t[t.MOO = 1284] = "MOO", t[t.MAM = 1088] = "MAM", t[t.AUR = 1313161554] = "AUR", t[t.EVM = 9001] = "EVM", t[t.ARN = 42170] = "ARN", t[t.ERA = 324] = "ERA", t[t.PZE = 1101] = "PZE", t[t.LNA = 59144] = "LNA", t[t.BAS = 8453] = "BAS", t[t.SCL = 534352] = "SCL", t[t.MOD = 34443] = "MOD", t[t.MNT = 5e3] = "MNT", t[t.BLS = 81457] = "BLS", t[t.SEI = 1329] = "SEI", t[t.FRA = 252] = "FRA", t[t.TAI = 167e3] = "TAI", t[t.GRA = 1625] = "GRA", t[t.IMX = 13371] = "IMX", t[t.KAI = 8217] = "KAI", t[t.XLY = 196] = "XLY", t[t.OPB = 204] = "OPB", t[t.WCC = 480] = "WCC", t[t.LSK = 1135] = "LSK", t[t.ABS = 2741] = "ABS", t[t.BER = 80094] = "BER", t[t.SON = 146] = "SON", t[t.UNI = 130] = "UNI", t[t.APE = 33139] = "APE", t[t.SOE = 1868] = "SOE", t[t.INK = 57073] = "INK", t[t.LNS = 232] = "LNS", t[t.SWL = 1923] = "SWL", t[t.CRN = 21e6] = "CRN", t[t.ETL = 42793] = "ETL", t[t.SUP = 55244] = "SUP", t[t.HYP = 999] = "HYP", t[t.XDC = 50] = "XDC", t[t.BOC = 60808] = "BOC", t[t.VIC = 88] = "VIC", t[t.FLR = 14] = "FLR", t[t.KAT = 747474] = "KAT", t[t.VAN = 1480] = "VAN", t[t.RON = 2020] = "RON", t[t.PLU = 98866] = "PLU", t[t.NIB = 6900] = "NIB", t[t.HPL = 1337] = "HPL", t[t.SOP = 50104] = "SOP", t[t.PLA = 9745] = "PLA", t[t.FLW = 747] = "FLW", t[t.HMI = 43111] = "HMI", t[t.MON = 143] = "MON", t[t.SOL = 1151111081099710] = "SOL", t[t.TER = 1161011141099710] = "TER", t[t.OAS = 111971151099710] = "OAS", t[t.SUI = 927e13] = "SUI", t[t.BTC = 20000000000001] = "BTC", t[t.BCH = 20000000000002] = "BCH", t[t.LTC = 20000000000003] = "LTC", t[t.DGE = 20000000000004] = "DGE", t[t.TRN = 728126428] = "TRN";
})(c || (c = {}));
const w = /* @__PURE__ */ (() => {
  const t = {
    integrator: "lifi-sdk",
    apiUrl: "https://li.quest/v1",
    rpcUrls: {},
    chains: [],
    providers: [],
    preloadChains: !0,
    debug: !1
  };
  let e;
  return {
    set loading(s) {
      e = s;
    },
    get() {
      return t;
    },
    set(s) {
      const { chains: o, providers: n, rpcUrls: r, ...a } = s;
      return Object.assign(t, a), o && this.setChains(o), n && this.setProviders(n), r && this.setRPCUrls(r), t;
    },
    getProvider(s) {
      return t.providers.find((o) => o.type === s);
    },
    setProviders(s) {
      const o = new Map(t.providers.map((n) => [n.type, n]));
      for (const n of s)
        o.set(n.type, n);
      t.providers = Array.from(o.values());
    },
    setChains(s) {
      const o = s.reduce((n, r) => (r.metamask?.rpcUrls?.length && (n[r.id] = r.metamask.rpcUrls), n), {});
      this.setRPCUrls(o, [c.SOL]), t.chains = s, e = void 0;
    },
    async getChains() {
      return e && await e, t.chains;
    },
    async getChainById(s) {
      e && await e;
      const o = t.chains?.find((n) => n.id === s);
      if (!o)
        throw new Error(`ChainId ${s} not found`);
      return o;
    },
    setRPCUrls(s, o) {
      for (const n in s) {
        const r = Number(n), a = s[r];
        if (a?.length) {
          if (!t.rpcUrls[r]?.length)
            t.rpcUrls[r] = Array.from(a);
          else if (!o?.includes(r)) {
            const u = a.filter((i) => !t.rpcUrls[r]?.includes(i));
            t.rpcUrls[r].push(...u);
          }
        }
      }
    },
    async getRPCUrls() {
      return e && await e, t.rpcUrls;
    }
  };
})();
var l;
(function(t) {
  t.RPCError = "RPCError", t.ProviderError = "ProviderError", t.ServerError = "ServerError", t.TransactionError = "TransactionError", t.ValidationError = "ValidationError", t.BalanceError = "BalanceError", t.NotFoundError = "NotFoundError", t.UnknownError = "UnknownError", t.SlippageError = "SlippageError", t.HTTPError = "HTTPError";
})(l || (l = {}));
var S;
(function(t) {
  t[t.InternalError = 1e3] = "InternalError", t[t.ValidationError = 1001] = "ValidationError", t[t.TransactionUnderpriced = 1002] = "TransactionUnderpriced", t[t.TransactionFailed = 1003] = "TransactionFailed", t[t.Timeout = 1004] = "Timeout", t[t.ProviderUnavailable = 1005] = "ProviderUnavailable", t[t.NotFound = 1006] = "NotFound", t[t.ChainSwitchError = 1007] = "ChainSwitchError", t[t.TransactionUnprepared = 1008] = "TransactionUnprepared", t[t.GasLimitError = 1009] = "GasLimitError", t[t.TransactionCanceled = 1010] = "TransactionCanceled", t[t.SlippageError = 1011] = "SlippageError", t[t.SignatureRejected = 1012] = "SignatureRejected", t[t.BalanceError = 1013] = "BalanceError", t[t.AllowanceRequired = 1014] = "AllowanceRequired", t[t.InsufficientFunds = 1015] = "InsufficientFunds", t[t.ExchangeRateUpdateCanceled = 1016] = "ExchangeRateUpdateCanceled", t[t.WalletChangedDuringExecution = 1017] = "WalletChangedDuringExecution", t[t.TransactionExpired = 1018] = "TransactionExpired", t[t.TransactionSimulationFailed = 1019] = "TransactionSimulationFailed", t[t.TransactionConflict = 1020] = "TransactionConflict", t[t.TransactionNotFound = 1021] = "TransactionNotFound", t[t.TransactionRejected = 1022] = "TransactionRejected", t[t.RateLimitExceeded = 1023] = "RateLimitExceeded", t[t.ThirdPartyError = 1024] = "ThirdPartyError", t[t.InsufficientGas = 1025] = "InsufficientGas";
})(S || (S = {}));
var d;
(function(t) {
  t.UnknownError = "Unknown error occurred.", t.SlippageError = "The slippage is larger than the defined threshold. Please request a new route to get a fresh quote.", t.GasLimitLow = "Gas limit is too low.", t.TransactionUnderpriced = "Transaction is underpriced.", t.TransactionReverted = "Transaction was reverted.";
})(d || (d = {}));
const h = (t) => {
  let e = t;
  for (; e?.cause; )
    e = e.cause;
  return e;
};
class V extends Error {
  code;
  cause;
  constructor(e, s, o, n) {
    super(o), this.name = e, this.code = s, this.cause = n;
    const r = h(this.cause);
    r?.stack && (this.stack = r.stack);
  }
}
class m extends V {
  constructor(e) {
    super(l.ValidationError, S.ValidationError, e);
  }
}
const P = "3.12.14";
class T extends Error {
  step;
  process;
  code;
  name = "SDKError";
  cause;
  constructor(e, s, o) {
    const n = `${e.message ? `[${e.name}] ${e.message}` : "Unknown error occurred"}
LI.FI SDK version: ${P}`;
    super(n), this.name = "SDKError", this.step = s, this.process = o, this.cause = e, this.stack = this.cause.stack, this.code = e.code;
  }
}
const I = /* @__PURE__ */ new Map([
  [
    400,
    { type: l.ValidationError, code: S.ValidationError }
  ],
  [404, { type: l.NotFoundError, code: S.NotFound }],
  [
    409,
    {
      type: l.SlippageError,
      code: S.SlippageError,
      message: d.SlippageError
    }
  ],
  [424, { type: l.ServerError, code: S.ThirdPartyError }],
  [429, { type: l.ServerError, code: S.RateLimitExceeded }],
  [500, { type: l.ServerError, code: S.InternalError }]
]), C = (t) => I.get(t) ?? {
  type: l.ServerError,
  code: S.InternalError
}, tt = (t) => {
  const e = t.status || t.status === 0 ? t.status : "", s = t.statusText || "", o = `${e} ${s}`.trim();
  return `Request failed with ${o ? `status code ${o}` : "an unknown error"}`;
};
class et extends V {
  response;
  status;
  url;
  fetchOptions;
  type;
  responseBody;
  constructor(e, s, o) {
    const n = C(e.status), r = n?.message ? `
${n.message}` : "", a = tt(e) + r;
    super(l.HTTPError, n.code, a), this.type = n.type, this.response = e, this.status = e.status, this.message = a, this.url = s, this.fetchOptions = o;
  }
  async buildAdditionalDetails() {
    this.type && (this.message = `[${this.type}] ${this.message}`);
    try {
      this.responseBody = await this.response.json(), this.responseBody && (this.message += this.message.endsWith(".") ? ` ${this.responseBody?.message.toString()}` : `. ${this.responseBody?.message.toString()}`);
    } catch {
    }
    return this;
  }
}
function st(t) {
  return new Promise((e) => {
    setTimeout(() => e(null), t);
  });
}
const L = {
  retries: 1
}, rt = ({ retries: t, ...e }) => ({
  ...e
}), E = async (t, e = {
  retries: L.retries
}) => {
  const { userId: s, integrator: o, widgetVersion: n, apiKey: r } = w.get();
  if (!o)
    throw new T(new m("You need to provide the Integrator property. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk"));
  e.retries = e.retries ?? L.retries;
  try {
    r && (e.headers = {
      ...e.headers,
      "x-lifi-api-key": r
    }), s && (e.headers = {
      ...e.headers,
      "x-lifi-userid": s
    }), n && (e.headers = {
      ...e.headers,
      "x-lifi-widget": n
    }), P && (e.headers = {
      ...e.headers,
      "x-lifi-sdk": P
    }), e.headers = {
      ...e.headers,
      "x-lifi-integrator": o
    };
    const a = await fetch(t, rt(e));
    if (!a.ok)
      throw new et(a, t, e);
    return await a.json();
  } catch (a) {
    if (e.retries > 0 && a.status === 500)
      return await st(500), E(t, { ...e, retries: e.retries - 1 });
    throw await a.buildAdditionalDetails?.(), new T(a);
  }
}, ot = (t) => {
  const { id: e, type: s, tool: o, action: n, estimate: r } = t;
  return typeof e == "string" && ["swap", "cross", "lifi"].includes(s) && typeof o == "string" && nt(n) && at(r);
}, nt = (t) => {
  const { fromChainId: e, fromAmount: s, fromToken: o, toChainId: n, toToken: r } = t;
  return typeof e == "number" && typeof s == "string" && s !== "" && x(o) && typeof n == "number" && x(r);
}, at = (t) => {
  const { fromAmount: e, toAmount: s, toAmountMin: o, approvalAddress: n } = t;
  return typeof e == "string" && e !== "" && typeof s == "string" && s !== "" && typeof o == "string" && o !== "" && (typeof n == "string" || n === null);
}, x = (t) => {
  const { address: e, decimals: s, chainId: o } = t;
  return typeof e == "string" && typeof s == "number" && typeof o == "number";
};
async function Ot(t, e) {
  const s = [
    "fromChain",
    "fromToken",
    "fromAddress",
    "toChain",
    "toToken"
  ];
  for (const a of s)
    if (!t[a])
      throw new T(new m(`Required parameter "${a}" is missing.`));
  const o = "fromAmount" in t && t.fromAmount !== void 0, n = "toAmount" in t && t.toAmount !== void 0;
  if (!o && !n)
    throw new T(new m('Required parameter "fromAmount" or "toAmount" is missing.'));
  if (o && n)
    throw new T(new m('Cannot provide both "fromAmount" and "toAmount" parameters.'));
  const r = w.get();
  t.integrator ??= r.integrator, t.order ??= r.routeOptions?.order, t.slippage ??= r.routeOptions?.slippage, t.referrer ??= r.routeOptions?.referrer, t.fee ??= r.routeOptions?.fee, t.allowBridges ??= r.routeOptions?.bridges?.allow, t.denyBridges ??= r.routeOptions?.bridges?.deny, t.preferBridges ??= r.routeOptions?.bridges?.prefer, t.allowExchanges ??= r.routeOptions?.exchanges?.allow, t.denyExchanges ??= r.routeOptions?.exchanges?.deny, t.preferExchanges ??= r.routeOptions?.exchanges?.prefer;
  for (const a of Object.keys(t))
    t[a] || delete t[a];
  return await E(`${r.apiUrl}/${o ? "quote" : "quote/toAmount"}?${new URLSearchParams(t)}`, {
    signal: e?.signal
  });
}
const N = async (t, e) => (ot(t) || console.warn("SDK Validation: Invalid Step", t), await E(`${w.get().apiUrl}/advanced/stepTransaction`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(t),
  signal: e?.signal
})), ct = async (t, e) => {
  if (!t.txHash)
    throw new T(new m('Required parameter "txHash" is missing.'));
  const s = new URLSearchParams(t);
  return await E(`${w.get().apiUrl}/status?${s}`, {
    signal: e?.signal
  });
}, dt = 5e-3, Pt = 0.2, Nt = 60, Ut = 3600 * 1e3, vt = {
  deny: ["mayan", "mayanWH", "mayanMCTP", "mayanFastMCTP"]
}, Bt = {}, Mt = 1e3, Lt = 5e3, it = "0x0000000000000000000000000000000000000000", ut = "11111111111111111111111111111111", lt = "0x2::sui::SUI", U = {
  Ethereum: c.ETH,
  Bsc: c.BSC,
  Polygon: c.POL,
  Avalanche: c.AVA,
  Arbitrum: c.ARB,
  Optimism: c.OPT,
  Base: c.BAS,
  Solana: c.SOL,
  Sui: c.SUI,
  Celo: c.CEL,
  Unichain: c.UNI,
  Berachain: c.BER,
  Mantle: c.MNT,
  Scroll: c.SCL,
  Worldchain: c.WCC,
  Moonbeam: c.MOO,
  Linea: c.LNA,
  Sonic: c.SON,
  HyperEVM: c.HYP,
  Seievm: c.SEI,
  Monad: c.MON
}, ft = Object.entries(
  U
).reduce((t, [e, s]) => (t[s] = e, t), {}), xt = "lifi-sdk", Dt = "https://li.quest/v1";
async function A(t, e, s, o, n, r) {
  if (q(e)) {
    const a = await e.signAndSend([t]);
    r.push(...a.map((u) => ({ chain: o, txid: u })));
  } else if ($(e)) {
    const a = await e.sign([t]), u = await n.sendWait(o, s, a);
    r.push(...u.map((i) => ({ chain: o, txid: i })));
  }
}
function pt() {
  return j.createRandom().address;
}
async function kt(t, e, s, o, n) {
  const { request: r, signer: a, rpc: u, txs: i } = e;
  if (!D(r.source.id.address)) {
    const f = O.getTokenImplementation(
      u,
      n(r.source.id)
    ), p = t.steps[0]?.estimate?.approvalAddress;
    if (p) {
      const R = await f.allowance(
        a.address(),
        p
      ), v = H(s.sourceToken.amount);
      if (R < v) {
        const b = await f.approve.populateTransaction(
          p,
          v
        ), _ = new B(
          {
            from: a.address(),
            chainId: o,
            ...b
          },
          r.fromChain.network,
          r.fromChain.chain,
          "Approve Allowance"
        );
        await A(
          _,
          a,
          u,
          r.fromChain.chain,
          O,
          i
        );
      }
    }
  }
  for (const f of t.steps) {
    const p = (await N(f)).transactionRequest;
    if (!p)
      throw new Error(`No transaction data in LiFi step: ${f.tool}`);
    const R = new B(
      {
        from: a.address(),
        chainId: o,
        to: p.to,
        data: p.data,
        value: p.value || "0x0",
        gasLimit: p.gasLimit,
        gasPrice: p.gasPrice
      },
      r.fromChain.network,
      r.fromChain.chain,
      `LiFi Step: ${f.tool}`
    );
    await A(
      R,
      a,
      u,
      r.fromChain.chain,
      O,
      i
    );
  }
}
function St() {
  return Y.generate().publicKey.toString();
}
async function Vt(t, e) {
  const { request: s, signer: o, rpc: n, txs: r } = e;
  for (const a of t.steps) {
    const i = (await N(a)).transactionRequest?.data;
    if (!i)
      throw new Error("No transaction data in LiFi step");
    if (!s.sender)
      throw new Error("Sender is required");
    const f = X.deserialize(
      W.from(i, "base64")
    ), g = new y(
      {
        transaction: f,
        signers: void 0
      },
      s.fromChain.network,
      "Solana",
      `LiFi Step: ${a.tool}`
    );
    await A(
      g,
      o,
      n,
      s.fromChain.chain,
      F,
      r
    );
  }
}
function Tt() {
  return K.generate().toSuiAddress();
}
async function bt(t, e) {
  const { request: s, signer: o, rpc: n, txs: r } = e;
  for (const a of t.steps) {
    const i = (await N(a)).transactionRequest;
    if (!i || !i.data)
      throw new Error("No transaction data in LiFi step");
    const f = Z.from(z(i.data)), g = new Q(
      f,
      s.fromChain.network,
      "Sui",
      `LiFi Step: ${a.tool}`
    );
    await A(
      g,
      o,
      n,
      s.fromChain.chain,
      J,
      r
    );
  }
}
function gt(t) {
  return mt({ chain: t, address: "native" });
}
function _t(t) {
  return D(t.address) ? gt(t.chain) : t.address.toString();
}
function qt(t) {
  const e = k(t);
  if (e === "Solana")
    return St();
  if (e === "Sui")
    return Tt();
  if (e === "Evm")
    return pt();
  throw new Error("Unsupported platform");
}
async function $t(t) {
  const e = G.get(
    t.network,
    t.chain
  );
  if (!e)
    throw new Error(
      `No native chain ID found for ${t.chain} on ${t.network}`
    );
  return e;
}
function Ht(t) {
  const e = U[t];
  if (!e) throw new Error(`Unsupported LiFi chain: ${t}`);
  return e;
}
function Wt(t) {
  const e = ft[t];
  if (!e) throw new Error(`Unsupported LiFi chainId: ${t}`);
  return e;
}
function Gt(t) {
  return t === "Mainnet" ? Object.keys(U).map((e) => e) : [];
}
function mt(t) {
  if (t.address === "native") {
    const e = k(t.chain);
    if (e === "Evm")
      return it;
    if (e === "Solana")
      return ut;
    if (e === "Sui")
      return lt;
    throw new Error(`Unsupported platform for native token: ${e}`);
  }
  return t.address.toString();
}
async function jt(t, e, s, o, n) {
  const r = {
    txHash: e.txid,
    fromChain: s,
    toChain: o,
    bridge: n
  }, a = await ct(r);
  return a.status === "NOT_FOUND" ? null : a;
}
export {
  Pt as D,
  Mt as M,
  Lt as P,
  T as S,
  m as V,
  dt as a,
  vt as b,
  Bt as c,
  _t as d,
  Ot as e,
  xt as f,
  qt as g,
  Nt as h,
  Vt as i,
  bt as j,
  $t as k,
  Wt as l,
  kt as m,
  Ut as n,
  jt as o,
  w as p,
  Dt as q,
  Gt as s,
  Ht as t
};
