var L = Object.defineProperty;
var _ = (p, e, t) => e in p ? L(p, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : p[e] = t;
var u = (p, e, t) => _(p, typeof e != "symbol" ? e + "" : e, t);
import { I as D, C as T } from "./contract-BVaUamai.mjs";
import { k as I, a3 as b, aP as S, az as F, W as r, aF as G, aR as B, r as f, v as h, cs as H, aU as g, aA as M, N as j, ay as Y, ct as J, aV as K, aW as X } from "./address-CBux52Na.mjs";
import { EvmWormholeCore as Z } from "./index-B5XhLD_L.mjs";
import { EvmTokenBridge as tt } from "./index-CKaF7Gzs.mjs";
import { E as y } from "./platform-CUeBR_i4.mjs";
import { E as et } from "./unsignedTransaction-C0V0UbsS.mjs";
import { r as nt } from "./chain-sKZNJgPZ.mjs";
const v = new D([
  "function start((bytes32,address,address,address,address,address,uint256,uint256,uint256,uint256)) returns (address,uint16,uint64)",
  "function receiveMessageAndSwap(bytes)"
]), ot = new D([
  "function quoteExactInputSingle((address,address,uint256,uint24,uint160)) public view returns (uint256,uint160,uint32,uint256)"
]), rt = "https://gfx.relayers.xlabs.xyz/api/v1/swap/quote";
class st {
  static async quoteRelayer(e, t, o) {
    var i;
    if (I(t) || I(o))
      throw new Error("how did you get here tho?");
    const n = b.encode(t.toUniversalAddress().toUint8Array(), !1), s = b.encode(o.toUniversalAddress().toUint8Array(), !1), a = { targetChain: S(e), sourceToken: n, targetToken: s };
    try {
      const c = await F.post(rt, a);
      return BigInt(c.data.fee);
    } catch (c) {
      throw F.isAxiosError(c) ? new Error(`Error getting relayer fee: ${(i = c.response) == null ? void 0 : i.statusText}`) : c;
    }
  }
}
const m = 100, x = {
  ETH: [
    r.tokenId("Arbitrum", "native"),
    r.tokenId("Base", "native"),
    r.tokenId("Ethereum", "native"),
    r.tokenId("Optimism", "native")
  ],
  WETH: [
    r.tokenId("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"),
    r.tokenId("Avalanche", "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB"),
    r.tokenId("Base", "0x4200000000000000000000000000000000000006"),
    r.tokenId("Bsc", "0x2170Ed0880ac9A755fd29B2688956BD959F933F8"),
    r.tokenId("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
    r.tokenId("Optimism", "0x4200000000000000000000000000000000000006"),
    r.tokenId("Polygon", "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619")
  ],
  wstETH: [
    r.tokenId("Arbitrum", "0x5979D7b546E38E414F7E9822514be443A4800529"),
    r.tokenId("Base", "0xc1CBa3fCea344f92D9239c08C0568f6F2F0ee452"),
    r.tokenId("Ethereum", "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0"),
    r.tokenId("Optimism", "0x1F32b1c2345538c0c6f582fCB022739c4A194Ebb"),
    r.tokenId("Polygon", "0x03b54A6e9a984069379fae1a4fC4dBAE93B3bCCD")
  ],
  USDT: [
    r.tokenId("Arbitrum", "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"),
    r.tokenId("Avalanche", "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7"),
    r.tokenId("Base", "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2"),
    r.tokenId("Bsc", "0x55d398326f99059fF775485246999027B3197955"),
    r.tokenId("Ethereum", "0xdAC17F958D2ee523a2206206994597C13D831ec7"),
    r.tokenId("Optimism", "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"),
    r.tokenId("Polygon", "0xc2132D05D31c914a87C6611C10748AEb04B58e8F"),
    r.tokenId("Celo", "0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e")
  ]
};
class A {
  constructor(e, t, o, n) {
    u(this, "network");
    u(this, "chain");
    u(this, "provider");
    u(this, "contracts");
    u(this, "chainId");
    u(this, "core");
    u(this, "tokenBridge");
    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 Z(e, t, o, n), this.tokenBridge = new tt(e, t, o, n), this.chainId = G.get(e, t);
  }
  static async fromRpc(e, t) {
    const [o, n] = await y.chainFromRpc(e), s = t[n];
    if (s.network !== o)
      throw new Error(`Network mismatch: ${s.network} != ${o}`);
    return new A(o, n, e, s.contracts);
  }
  async *transfer(e, t, o, n, s, d, a) {
    const { minAmountStart: i, minAmountFinish: c } = a.swapAmounts;
    if (i === 0n)
      throw new Error("Invalid min swap amount");
    if (c === 0n)
      throw new Error("Invalid min swap amount");
    const w = new B(e).toString(), [k, E] = f(this.network, this.chain, o), [U, P] = f(this.network, t.chain, s), l = h(E), q = h(await this.getTransferrableToken(l)), R = h(t), N = h(P), O = (/* @__PURE__ */ new Date()).valueOf() % 2 ** 4, W = H.serializeFlagSet({
      flags: {
        shouldWrapNative: k,
        shouldUnwrapNative: U
      },
      recipientChain: S(t.chain),
      bridgeNonce: O,
      feeTierStart: m,
      feeTierFinish: m,
      padding: new Uint8Array(19)
    }), $ = v.encodeFunctionData("start", [
      [
        W,
        l.toLowerCase(),
        q,
        N.toLowerCase(),
        R,
        d,
        n.toString(),
        i.toString(),
        c.toString(),
        a.relayerFee.toString()
      ]
    ]), Q = this.getTokenGroup(E.address.toString()), C = this.getPorticoAddress(Q);
    k || (yield* this.approve(l, w, n, C));
    const V = await this.core.getMessageFee(), z = {
      to: C,
      data: $,
      value: V + (k ? n : 0n)
    };
    yield this.createUnsignedTransaction(g(z, w), "PorticoBridge.Transfer");
  }
  async *redeem(e, t) {
    const o = M(t.payload.payload.flagSet.recipientChain), n = t.payload.payload.finalTokenAddress.toNative(o).toString(), s = this.getTokenGroup(n), d = this.getPorticoAddress(s), i = await new T(d, v.fragments, this.provider).getFunction("receiveMessageAndSwap").populateTransaction(j(t)), c = new B(e).toString();
    yield this.createUnsignedTransaction(g(i, c), "PorticoBridge.Redeem");
  }
  async isTransferCompleted(e) {
    return await this.tokenBridge.tokenBridge.isTransferCompleted(Y(e.hash));
  }
  async quoteSwap(e, t, o, n) {
    const [, s] = f(this.network, this.chain, e), [, d] = f(this.network, this.chain, t), a = h(s), i = h(d);
    if (J(a, i))
      return n;
    const c = this.getQuoterAddress(o);
    return (await new T(c, ot.fragments, this.provider).getFunction("quoteExactInputSingle").staticCall([a, i, n, m, 0]))[0];
  }
  async quoteRelay(e, t) {
    return await st.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 = r.tokenId(this.chain, e), [, o] = f(this.network, this.chain, t);
    if (this.chain === "Ethereum")
      return o;
    const n = Object.values(x).find((a) => a.find((i) => i.chain === this.chain && h(i) === h(o)));
    if (!n)
      throw new Error(`No token group found for ${e} on ${this.chain}`);
    const s = n.find((a) => a.chain === "Ethereum");
    if (!s)
      throw new Error(`No Ethereum origin token found for ${e} on ${this.chain}`);
    const d = await this.tokenBridge.getWrappedAsset(s);
    return r.tokenId(this.chain, d.toString());
  }
  supportedTokens() {
    const e = [];
    for (const [t, o] of Object.entries(x))
      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) => h(n.token) === e);
    if (!o)
      throw new Error("Token not found");
    return o.group;
  }
  async *approve(e, t, o, n) {
    const s = y.getTokenImplementation(this.provider, e);
    if (await s.allowance(t, n) < o) {
      const a = await s.approve.populateTransaction(n, o);
      yield this.createUnsignedTransaction(g(a, t), "PorticoBridge.Approve");
    }
  }
  createUnsignedTransaction(e, t) {
    return new et(K(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;
  }
}
nt(X, "PorticoBridge", A);
export {
  A as EvmPorticoBridge
};
