import { I as v, i as E, m as C, ah as x, J as T, W as s, l as Q, V as I, aK as b, aV as u, N as d, dc as V, aL as l, L as H, E as B, at as M, H as _, dd as z, X as G, aM as j, au as J, aN as K } from "./platform-Cil_UtAQ.mjs";
import { EvmWormholeCore as X } from "./index-BKgliEPZ.mjs";
import { EvmTokenBridge as Y } from "./index-BCKX-m7h.mjs";
const F = new v([
  "function start((bytes32,address,address,address,address,address,uint256,uint256,uint256,uint256)) returns (address,uint16,uint64)",
  "function receiveMessageAndSwap(bytes)"
]), Z = new v([
  "function quoteExactInputSingle((address,address,uint256,uint24,uint160)) public view returns (uint256,uint160,uint32,uint256)"
]), tt = "https://gfx.relayers.xlabs.xyz/api/v1/swap/quote";
class et {
  static async quoteRelayer(e, t, o) {
    if (E(t) || E(o))
      throw new Error("how did you get here tho?");
    const n = C.encode(t.toUniversalAddress().toUint8Array(), !1), r = C.encode(o.toUniversalAddress().toUint8Array(), !1), i = { targetChain: x(e), sourceToken: n, targetToken: r };
    try {
      const a = await T.post(tt, i);
      return BigInt(a.data.fee);
    } catch (a) {
      throw T.isAxiosError(a) ? new Error(`Error getting relayer fee: ${a.response?.statusText}`) : a;
    }
  }
}
const w = 100, y = {
  ETH: [
    s.tokenId("Arbitrum", "native"),
    s.tokenId("Base", "native"),
    s.tokenId("Ethereum", "native"),
    s.tokenId("Optimism", "native")
  ],
  WETH: [
    s.tokenId("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
    s.tokenId("Avalanche", "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB"),
    s.tokenId("Base", "0x4200000000000000000000000000000000000006"),
    s.tokenId("Bsc", "0x2170Ed0880ac9A755fd29B2688956BD959F933F8"),
    s.tokenId("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
    s.tokenId("Optimism", "0x4200000000000000000000000000000000000006"),
    s.tokenId("Polygon", "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619")
  ],
  wstETH: [
    s.tokenId("Arbitrum", "0x5979D7b546E38E414F7E9822514be443A4800529"),
    s.tokenId("Base", "0xc1CBa3fCea344f92D9239c08C0568f6F2F0ee452"),
    s.tokenId("Ethereum", "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
    s.tokenId("Optimism", "0x1F32b1c2345538c0c6f582fCB022739c4A194Ebb"),
    s.tokenId("Polygon", "0x03b54A6e9a984069379fae1a4fC4dBAE93B3bCCD")
  ],
  USDT: [
    s.tokenId("Arbitrum", "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"),
    s.tokenId("Avalanche", "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7"),
    s.tokenId("Base", "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2"),
    s.tokenId("Bsc", "0x55d398326f99059fF775485246999027B3197955"),
    s.tokenId("Ethereum", "0xdAC17F958D2ee523a2206206994597C13D831ec7"),
    s.tokenId("Optimism", "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"),
    s.tokenId("Polygon", "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"),
    s.tokenId("Celo", "0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e")
  ]
};
class g {
  network;
  chain;
  provider;
  contracts;
  chainId;
  core;
  tokenBridge;
  constructor(e, t, o, n) {
    if (this.network = e, this.chain = t, this.provider = o, this.contracts = n, !n.portico)
      throw new Error("Unsupported chain, no contract addresses for: " + t);
    this.core = new X(e, t, o, n), this.tokenBridge = new Y(e, t, o, n), this.chainId = Q.get(e, t);
  }
  static async fromRpc(e, t) {
    const [o, n] = await I.chainFromRpc(e), r = t[n];
    if (r.network !== o)
      throw new Error(`Network mismatch: ${r.network} != ${o}`);
    return new g(o, n, e, r.contracts);
  }
  async *transfer(e, t, o, n, r, c, i) {
    const { minAmountStart: a, minAmountFinish: h } = i.swapAmounts;
    if (a === 0n)
      throw new Error("Invalid min swap amount");
    if (h === 0n)
      throw new Error("Invalid min swap amount");
    const f = new b(e).toString(), [p, A] = u(this.network, this.chain, o), [D, S] = u(this.network, t.chain, r), k = d(A), U = d(await this.getTransferrableToken(k)), P = d(t), q = d(S), N = (/* @__PURE__ */ new Date()).valueOf() % 2 ** 4, R = V.serializeFlagSet({
      flags: {
        shouldWrapNative: p,
        shouldUnwrapNative: D
      },
      recipientChain: x(t.chain),
      bridgeNonce: N,
      feeTierStart: w,
      feeTierFinish: w,
      padding: new Uint8Array(19)
    }), O = F.encodeFunctionData("start", [
      [
        R,
        k.toLowerCase(),
        U,
        q.toLowerCase(),
        P,
        c,
        n.toString(),
        a.toString(),
        h.toString(),
        i.relayerFee.toString()
      ]
    ]), W = this.getTokenGroup(A.address.toString()), m = this.getPorticoAddress(W);
    p || (yield* this.approve(k, f, n, m));
    const $ = await this.core.getMessageFee(), L = {
      to: m,
      data: O,
      value: $ + (p ? n : 0n)
    };
    yield this.createUnsignedTransaction(l(L, f), "PorticoBridge.Transfer");
  }
  async *redeem(e, t) {
    const o = H(t.payload.payload.flagSet.recipientChain), n = t.payload.payload.finalTokenAddress.toNative(o).toString(), r = this.getTokenGroup(n), c = this.getPorticoAddress(r), a = await new B(c, F.fragments, this.provider).getFunction("receiveMessageAndSwap").populateTransaction(M(t)), h = new b(e).toString();
    yield this.createUnsignedTransaction(l(a, h), "PorticoBridge.Redeem");
  }
  async isTransferCompleted(e) {
    return await this.tokenBridge.tokenBridge.isTransferCompleted(_(e.hash));
  }
  async quoteSwap(e, t, o, n) {
    const [, r] = u(this.network, this.chain, e), [, c] = u(this.network, this.chain, t), i = d(r), a = d(c);
    if (z(i, a))
      return n;
    const h = this.getQuoterAddress(o);
    return (await new B(h, Z.fragments, this.provider).getFunction("quoteExactInputSingle").staticCall([i, a, n, w, 0]))[0];
  }
  async quoteRelay(e, t) {
    return await et.quoteRelayer(this.chain, e, t);
  }
  // For a given token, return the Wormhole-wrapped/highway token
  // that actually gets bridged from this chain
  async getTransferrableToken(e) {
    const t = s.tokenId(this.chain, e), [, o] = u(this.network, this.chain, t);
    if (this.chain === "Ethereum")
      return o;
    const n = Object.values(y).find((i) => i.find((a) => a.chain === this.chain && d(a) === d(o)));
    if (!n)
      throw new Error(`No token group found for ${e} on ${this.chain}`);
    const r = n.find((i) => i.chain === "Ethereum");
    if (!r)
      throw new Error(`No Ethereum origin token found for ${e} on ${this.chain}`);
    const c = await this.tokenBridge.getWrappedAsset(r);
    return s.tokenId(this.chain, c.toString());
  }
  supportedTokens() {
    const e = [];
    for (const [t, o] of Object.entries(y))
      for (const n of o)
        n.chain === this.chain && e.push({ group: t, token: n });
    return e;
  }
  getTokenGroup(e) {
    const o = this.supportedTokens().find((n) => d(n.token) === e);
    if (!o)
      throw new Error("Token not found");
    return o.group;
  }
  async *approve(e, t, o, n) {
    const r = I.getTokenImplementation(this.provider, e);
    if (await r.allowance(t, n) < o) {
      const i = await r.approve.populateTransaction(n, o);
      yield this.createUnsignedTransaction(l(i, t), "PorticoBridge.Approve");
    }
  }
  createUnsignedTransaction(e, t) {
    return new G(j(e, this.chainId), this.network, this.chain, t, !1);
  }
  getPorticoAddress(e) {
    const t = this.contracts.portico;
    return e === "USDT" && t.porticoPancakeSwap || t.porticoUniswap;
  }
  getQuoterAddress(e) {
    const t = this.contracts.portico;
    return e === "USDT" && t.pancakeSwapQuoterV2 || t.uniswapQuoterV2;
  }
}
J(K, "PorticoBridge", g);
export {
  g as EvmPorticoBridge
};
