var Me = Object.defineProperty;
var Ie = (e, n, t) => n in e ? Me(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
var c = (e, n, t) => Ie(e, typeof n != "symbol" ? n + "" : n, t);
import { az as O, aP as C, aJ as Be, E as w, b4 as P, aF as ze, aR as Te, aU as te, aV as Ue, aW as Re, v as _e, ae as p, ar as be, aG as re, au as we, d as D, an as Ne, as as Ce, b1 as N, b2 as $e, ao as ke, a_ as $, aX as Oe, b3 as Ge, A as Le, D as se, F as Qe, W as S, u as qe, _ as We, aN as je, a3 as ne, y as Ve, f as R, af as Ke, z as Xe, T as _, i as ae, aj as ie, B as Je, C as He, e as Ze } from "./address-CBux52Na.mjs";
import { r as M } from "./chain-sKZNJgPZ.mjs";
import { l as oe } from "./chunk-IMTC3J2M-DKLPKqnP.mjs";
import { A as Ye } from "./platform-Czq0KkFa.mjs";
import { A as et, _ as tt } from "./address-BWXkejmE.mjs";
import { A as rt } from "./unsignedTransaction-BDOQhqcZ.mjs";
import { E as ce } from "./platform-CUeBR_i4.mjs";
import { C as st } from "./contract-BVaUamai.mjs";
import { E as nt } from "./unsignedTransaction-C0V0UbsS.mjs";
import { b as de, T as at, a as it, _ as ot } from "./platform-Droe0nZu.mjs";
import { suiCircleObjects as ct } from "./index-Cry2AYTm.mjs";
import { S as dt, R as ut } from "./address-DKHa7TFU.mjs";
import { S as ft } from "./unsignedTransaction-BD81leu1.mjs";
import { createDepositForBurnInstruction as mt } from "./index-B9hin5U8.mjs";
import { P as ht } from "./index-DRleG63r.mjs";
import { p as ue, u as Ae, b as lt } from "./web3-B3Usc-Qj.mjs";
import { a as gt, S as pt } from "./unsignedTransaction-C0WXQMmv.mjs";
import { d as bt } from "./account-BK8xMTUI.mjs";
const G = {
  Testnet: "https://executor-testnet.labsapis.com",
  Mainnet: "https://executor.labsapis.com"
}, L = {
  Testnet: {
    Aptos: "0x14a12d1fd6ef371b70c2113155534ec152ec7f779e281b54866c796c9a4a58d3",
    Avalanche: "0x2cfEC91B50f657Cc86Ec693542527ac3e03bF742",
    BaseSepolia: "0x4983C6bD3bB7DA9EECe71cfa7AE4C67CAbf362F0",
    Sepolia: "0x0F78904c750801391EbBf308181e9d6fc892B0f3",
    Solana: "CXGRA5SCc8jxDbaQPZrmmZNu2JV34DP7gFW4m31uC1zs"
  },
  Mainnet: {
    Aptos: "0x9f5ad7d5c2d067ca4abb6d8d6aba44c15596b71a1def8eb4596089b527bb2eb1",
    Arbitrum: "0x55Dd4466BFec29527C54A72fd306efb54e5F7027",
    Avalanche: "0xd331819478b74d8a7B8EA631118B4a4e50F6EbD1",
    Base: "0x08FEB1838C3d7F8509DA1EBb9a11a94c1f006cb2",
    Ethereum: "0xeEFb36c4458dA7798742cf038C5c27E07aB9c51E",
    Optimism: "0xBC6f9d1CBa49DB365728478cefa02F6743617637",
    Polygon: "0x007995f2AEcfBC745f20a7AE8D3a02c0EbF46264",
    Unichain: "0xA7aBDb8f2108901c586543BD5e10E4fA263F4A47",
    Solana: "CXGRA5SCc8jxDbaQPZrmmZNu2JV34DP7gFW4m31uC1zs"
  }
}, fe = {
  Testnet: {
    executorId: "0x4000cfe2955d8355b3d3cf186f854fea9f787a457257056926fde1ec977670eb",
    executorRequestsId: "0x2d9ccf3cce3f7dce408e5455e90b80a8161ad9673d1366c2a5def60ad93657a8"
  },
  Mainnet: {
    executorId: "0xdb0fe8bb1e2b5be628adbea0636063325073e1070ee11e4281457dfd7f158235",
    executorRequestsId: "0xc030df7a3eed1494fa4b64aa8ab63a79041cf1114f4ff2b7ab5aca1c684a21a7"
  }
}, wt = {
  Testnet: "execXUrAsMnqMmTHj5m7N1YQgsDz3cwGLYCYyuDRciV",
  Mainnet: "execXUrAsMnqMmTHj5m7N1YQgsDz3cwGLYCYyuDRciV"
}, Ct = 5001n, At = {
  Testnet: {
    Aptos: 5000n,
    Avalanche: 200000n,
    BaseSepolia: 200000n,
    Sepolia: 200000n,
    Solana: 250000n,
    Sui: 8000000n
  },
  Mainnet: {
    Aptos: 5000n,
    Arbitrum: 400000n,
    Avalanche: 250000n,
    Base: 250000n,
    Ethereum: 250000n,
    Optimism: 250000n,
    Polygon: 250000n,
    Unichain: 250000n,
    Solana: 250000n,
    Sui: 8000000n
  }
}, yt = {
  Testnet: {
    Aptos: "0x23b54f6e29bba7f4123d088f4cfcd83f5e23a049de15895b119ce5a6cb5faa91",
    Avalanche: "0x8F26A0025dcCc6Cfc07A7d38756280a10E295ad7",
    BaseSepolia: "0x8F26A0025dcCc6Cfc07A7d38756280a10E295ad7",
    Sepolia: "0x8F26A0025dcCc6Cfc07A7d38756280a10E295ad7",
    Solana: "9r6q2iEg4MBevjC8reaLmQUDxueF3vabUoqDkZ2LoAYe",
    Sui: "0x30bd9b3d5ad00f38fd0c314139ba47ccb3c78353d99880d81125ca0c370b415e"
  },
  Mainnet: {
    Aptos: "0x1f177e724a874ab6267172a3049291c480fc665883e6a3ac95d0909492c09dc8",
    Solana: "JB3rmygUVuVZzgkxvMdV8mSKLJeQAkSXEK284Dqsziah",
    Sui: "0xbfa1240e48c622d97881473953be730091161b7931d89bd6afe667841cf69ef4",
    Arbitrum: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Avalanche: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Base: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Ethereum: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Optimism: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Polygon: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E",
    Unichain: "0xF11e0efF8b11Ce382645dd75352fC16b3aB3551E"
  }
};
var A;
(function(e) {
  e.Pending = "pending", e.Failed = "failed", e.Unsupported = "unsupported", e.Submitted = "submitted", e.Underpaid = "underpaid", e.Aborted = "aborted";
})(A || (A = {}));
async function xt(e) {
  const n = `${G[e]}/v0/capabilities`;
  try {
    return (await O.get(n)).data;
  } catch {
    throw new Error(`Failed to fetch capabilities for network: ${e}.`);
  }
}
async function Et(e, n, t, r) {
  const s = `${G[e]}/v0/quote`;
  try {
    return (await O.post(s, {
      srcChain: C(n),
      dstChain: C(t),
      relayInstructions: r
    })).data;
  } catch {
    throw new Error("Failed to fetch signed quote.");
  }
}
async function me(e, n, t) {
  const r = `${G[e]}/v0/status/tx`;
  try {
    return (await O.post(r, {
      txHash: n,
      chainId: C(t)
    })).data;
  } catch {
    throw new Error(`Failed to fetch status for txHash: ${n}.`);
  }
}
const St = 65535n;
function vt(e, n) {
  if (n > St)
    throw new Error("dBps exceeds max u16");
  if (n > 0) {
    const t = e * n / 100000n, r = e - t;
    return { referrerFee: t, remainingAmount: r };
  }
  return { referrerFee: 0n, remainingAmount: e };
}
function Ft(e) {
  return new Promise((n) => setTimeout(n, e));
}
const Dt = [
  { name: "gasLimit", binary: "uint", size: 16 },
  { name: "msgValue", binary: "uint", size: 16 }
], Pt = [
  { name: "dropOff", binary: "uint", size: 16 },
  { name: "recipient", ...Be }
], Mt = [
  {
    name: "request",
    binary: "switch",
    idSize: 1,
    idTag: "type",
    layouts: [
      [[1, "GasInstruction"], Dt],
      [[2, "GasDropOffInstruction"], Pt]
    ]
  }
], he = [
  {
    name: "requests",
    binary: "array",
    layout: Mt
  }
];
var le;
(function(e) {
  e.ERM1 = "ERM1", e.ERV1 = "ERV1", e.ERN1 = "ERN1", e.ERC1 = "ERC1";
})(le || (le = {}));
const It = {
  to: (e) => new Date(Number(e * 1000n)),
  from: (e) => BigInt(e.getTime()) / 1000n
}, Bt = [
  {
    name: "quote",
    binary: "switch",
    idSize: 4,
    idTag: "prefix",
    layouts: [
      [
        [1162948657, "EQ01"],
        [
          {
            name: "quoterAddress",
            binary: "bytes",
            size: 20
          },
          {
            name: "payeeAddress",
            binary: "bytes",
            size: 32
          },
          { name: "srcChain", binary: "uint", size: 2 },
          { name: "dstChain", binary: "uint", size: 2 },
          {
            name: "expiryTime",
            binary: "uint",
            size: 8,
            custom: It
          },
          { name: "baseFee", binary: "uint", size: 8 },
          { name: "dstGasPrice", binary: "uint", size: 8 },
          { name: "srcPrice", binary: "uint", size: 8 },
          { name: "dstPrice", binary: "uint", size: 8 }
        ]
      ]
    ]
  }
], ye = [
  ...Bt,
  { name: "signature", binary: "bytes", size: 65 }
];
class Q {
  constructor(n, t, r, s) {
    c(this, "network");
    c(this, "chain");
    c(this, "provider");
    c(this, "contracts");
    c(this, "usdcId");
    c(this, "shimContract");
    var o;
    if (this.network = n, this.chain = t, this.provider = r, this.contracts = s, n === "Devnet")
      throw new Error("CCTPExecutor not supported on Devnet");
    const a = w.get(this.network, this.chain);
    if (!a)
      throw new Error(`No USDC contract configured for network=${this.network} chain=${this.chain}`);
    this.usdcId = a;
    const i = (o = L[n]) == null ? void 0 : o[t];
    if (!i)
      throw new Error(`Shim contract for ${t} not found`);
    this.shimContract = i;
  }
  static async fromRpc(n, t) {
    const [r, s] = await Ye.chainFromRpc(n), a = t[s];
    if (!a)
      throw new Error(`No config found for ${s}`);
    if (a.network !== r)
      throw new Error(`Network mismatch: ${a.network} != ${r}`);
    return new Q(r, s, n, a.contracts);
  }
  async *transfer(n, t, r) {
    const s = new et(n).unwrap(), a = oe.from(t.address.toUniversalAddress().toUint8Array()), i = oe.from(this.usdcId), o = r.remainingAmount + r.referrerFee, d = P.get(this.network, t.chain), u = s, m = s, l = [
      o,
      d,
      a.toString(),
      i.toString(),
      r.estimatedCost,
      C(t.chain),
      u,
      r.signedQuote,
      r.relayInstructions,
      r.referrerFeeDbps,
      m
    ], f = {
      function: `${this.shimContract}::cctp_v1_with_executor::deposit_for_burn_entry`,
      functionArguments: l
    };
    yield this.createUnsignedTx(f, "AtposCCTPExecutor.Transfer");
  }
  createUnsignedTx(n, t, r = !1) {
    return new rt(n, this.network, this.chain, t, r);
  }
}
M(tt, "CCTPExecutor", Q);
class q {
  constructor(n, t, r, s) {
    c(this, "network");
    c(this, "chain");
    c(this, "provider");
    c(this, "contracts");
    c(this, "chainId");
    c(this, "shimContract");
    var i;
    if (this.network = n, this.chain = t, this.provider = r, this.contracts = s, n === "Devnet")
      throw new Error("CCTPExecutor not supported on Devnet");
    this.chainId = ze.get(n, t);
    const a = (i = L[n]) == null ? void 0 : i[t];
    if (!a)
      throw new Error(`Shim contract for ${t} not found`);
    this.shimContract = a;
  }
  static async fromRpc(n, t) {
    const [r, s] = await ce.chainFromRpc(n), a = t[s];
    if (a.network !== r)
      throw new Error(`Network mismatch: ${a.network} != ${r}`);
    return new q(r, s, n, a.contracts);
  }
  async *transfer(n, t, r) {
    const s = new Te(n).toString(), a = t.address.toUniversalAddress().toUint8Array(), i = r.remainingAmount + r.referrerFee, o = w.get(this.network, this.chain), d = ce.getTokenImplementation(this.provider, o);
    if (await d.allowance(s, this.shimContract) < i) {
      const g = await d.approve.populateTransaction(this.shimContract, i);
      yield this.createUnsignedTx(te(g, s), "ERC20.approve of EvmCCTPExecutor", !1);
    }
    const m = [
      "function depositForBurn(uint256 amount, uint16 destinationChain, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, (address refundAddress, bytes signedQuote, bytes instructions) executorArgs, (uint16 dbps, address payee) feeArgs) external payable returns (uint64 nonce)"
    ], f = await new st(this.shimContract, m, this.provider).getFunction("depositForBurn").populateTransaction(i, C(t.chain), P.get(this.network, t.chain), a, o, {
      refundAddress: s,
      signedQuote: r.signedQuote,
      instructions: r.relayInstructions
    }, {
      dbps: r.referrerFeeDbps,
      payee: r.referrer.address.toString()
    });
    f.value = r.estimatedCost, yield this.createUnsignedTx(te(f, s), "EvmCCTPExecutor.depositForBurn");
  }
  createUnsignedTx(n, t, r = !1) {
    return new nt(Ue(n, this.chainId), this.network, this.chain, t, r);
  }
}
M(Re, "CCTPExecutor", q);
class W {
  constructor(n, t, r, s) {
    c(this, "network");
    c(this, "chain");
    c(this, "provider");
    c(this, "contracts");
    c(this, "usdcId");
    c(this, "usdcTreasuryId");
    c(this, "tokenMessengerId");
    c(this, "tokenMessengerStateId");
    c(this, "messageTransmitterId");
    c(this, "messageTransmitterStateId");
    c(this, "executorId");
    c(this, "executorRequestsId");
    var u, m, l, f;
    if (this.network = n, this.chain = t, this.provider = r, this.contracts = s, n === "Devnet")
      throw new Error("CCTPExecutor not supported on Devnet");
    const a = (g, h) => {
      if (!g)
        throw new Error(h);
      return g;
    };
    this.usdcId = a(w.get(this.network, this.chain), `No USDC contract configured for network=${this.network} chain=${this.chain}`);
    const { tokenMessengerState: i, messageTransmitterState: o, usdcTreasury: d } = ct(n);
    this.usdcTreasuryId = d, this.tokenMessengerId = a((u = s.cctp) == null ? void 0 : u.tokenMessenger, `Circle Token Messenger contract for domain ${t} not found`), this.messageTransmitterId = a((m = s.cctp) == null ? void 0 : m.messageTransmitter, `Circle Message Transmitter contract for domain ${t} not found`), this.tokenMessengerStateId = i, this.messageTransmitterStateId = o, this.executorId = a((l = fe[n]) == null ? void 0 : l.executorId, `Executor contract for ${n} not found`), this.executorRequestsId = a((f = fe[n]) == null ? void 0 : f.executorRequestsId, `Executor requests contract for ${n} not found`);
  }
  static async fromRpc(n, t) {
    const [r, s] = await de.chainFromRpc(n), a = t[s];
    if (a.network !== r)
      throw new Error(`Network mismatch: ${a.network} != ${r}`);
    return new W(r, s, n, a.contracts);
  }
  async *transfer(n, t, r) {
    const s = new at(), a = new dt(n).unwrap(), i = P.get(this.network, t.chain), [o, ...d] = await de.getCoins(this.provider, n, this.usdcId);
    if (o === void 0)
      throw new Error("No USDC in wallet");
    const u = s.object(o.coinObjectId);
    d.length > 0 && s.mergeCoins(u, d.map((b) => s.object(b.coinObjectId)));
    let m;
    if (r.referrerFee > 0n) {
      const [b, E] = s.splitCoins(u, [
        r.remainingAmount,
        r.referrerFee
      ]);
      m = b, s.transferObjects([E], _e(r.referrer));
    } else {
      const [b] = s.splitCoins(u, [
        r.remainingAmount
      ]);
      m = b;
    }
    const [l, f] = s.moveCall({
      target: `${this.tokenMessengerId}::deposit_for_burn::deposit_for_burn`,
      arguments: [
        m,
        s.pure.u32(i),
        // destination_domain
        s.pure.address(t.address.toUniversalAddress().toString()),
        // mint_recipient
        s.object(this.tokenMessengerStateId),
        // token_messenger_minter state
        s.object(this.messageTransmitterStateId),
        // message_transmitter state
        s.object("0x403"),
        // deny_list id, fixed address
        s.object(this.usdcTreasuryId)
        // treasury object Treasury<USDC>
      ],
      typeArguments: [this.usdcId]
    }), [g] = s.moveCall({
      target: `${this.messageTransmitterId}::message::source_domain`,
      arguments: [f]
    }), [h] = s.moveCall({
      target: `${this.messageTransmitterId}::message::nonce`,
      arguments: [f]
    }), [y] = s.moveCall({
      target: `${this.executorRequestsId}::executor_requests::make_cctp_v1_request`,
      arguments: [g, h]
    }), [x] = s.splitCoins(s.gas, [
      s.pure.u64(r.estimatedCost)
    ]);
    s.moveCall({
      target: `${this.executorId}::executor::request_execution`,
      arguments: [
        x,
        s.object(it),
        s.pure.u16(C(t.chain)),
        s.pure.address("0x0"),
        s.pure.address(a),
        s.pure.vector("u8", r.signedQuote),
        y,
        s.pure.vector("u8", r.relayInstructions)
      ]
    }), yield this.createUnsignedTx(s, "SuiCCTPExecutor.Transfer");
  }
  createUnsignedTx(n, t, r = !1) {
    return new ft(n, this.network, this.chain, t, r);
  }
}
M(ot, "CCTPExecutor", W);
const I = new p("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
new p("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");
const j = new p("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
new p("So11111111111111111111111111111111111111112");
new p("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");
class zt extends Error {
  constructor(n) {
    super(n);
  }
}
class Tt extends zt {
  constructor() {
    super(...arguments), this.name = "TokenOwnerOffCurveError";
  }
}
var k;
(function(e) {
  e[e.InitializeMint = 0] = "InitializeMint", e[e.InitializeAccount = 1] = "InitializeAccount", e[e.InitializeMultisig = 2] = "InitializeMultisig", e[e.Transfer = 3] = "Transfer", e[e.Approve = 4] = "Approve", e[e.Revoke = 5] = "Revoke", e[e.SetAuthority = 6] = "SetAuthority", e[e.MintTo = 7] = "MintTo", e[e.Burn = 8] = "Burn", e[e.CloseAccount = 9] = "CloseAccount", e[e.FreezeAccount = 10] = "FreezeAccount", e[e.ThawAccount = 11] = "ThawAccount", e[e.TransferChecked = 12] = "TransferChecked", e[e.ApproveChecked = 13] = "ApproveChecked", e[e.MintToChecked = 14] = "MintToChecked", e[e.BurnChecked = 15] = "BurnChecked", e[e.InitializeAccount2 = 16] = "InitializeAccount2", e[e.SyncNative = 17] = "SyncNative", e[e.InitializeAccount3 = 18] = "InitializeAccount3", e[e.InitializeMultisig2 = 19] = "InitializeMultisig2", e[e.InitializeMint2 = 20] = "InitializeMint2", e[e.GetAccountDataSize = 21] = "GetAccountDataSize", e[e.InitializeImmutableOwner = 22] = "InitializeImmutableOwner", e[e.AmountToUiAmount = 23] = "AmountToUiAmount", e[e.UiAmountToAmount = 24] = "UiAmountToAmount", e[e.InitializeMintCloseAuthority = 25] = "InitializeMintCloseAuthority", e[e.TransferFeeExtension = 26] = "TransferFeeExtension", e[e.ConfidentialTransferExtension = 27] = "ConfidentialTransferExtension", e[e.DefaultAccountStateExtension = 28] = "DefaultAccountStateExtension", e[e.Reallocate = 29] = "Reallocate", e[e.MemoTransferExtension = 30] = "MemoTransferExtension", e[e.CreateNativeMint = 31] = "CreateNativeMint", e[e.InitializeNonTransferableMint = 32] = "InitializeNonTransferableMint", e[e.InterestBearingMintExtension = 33] = "InterestBearingMintExtension", e[e.CpiGuardExtension = 34] = "CpiGuardExtension", e[e.InitializePermanentDelegate = 35] = "InitializePermanentDelegate", e[e.TransferHookExtension = 36] = "TransferHookExtension", e[e.MetadataPointerExtension = 39] = "MetadataPointerExtension";
})(k || (k = {}));
function Ut(e, n, t) {
  if (t.length) {
    e.push({ pubkey: n, isSigner: !1, isWritable: !1 });
    for (const r of t)
      e.push({
        pubkey: r instanceof p ? r : r.publicKey,
        isSigner: !0,
        isWritable: !1
      });
  } else
    e.push({ pubkey: n, isSigner: !0, isWritable: !1 });
  return e;
}
const Rt = be([
  re("mintAuthorityOption"),
  ue("mintAuthority"),
  Ae("supply"),
  we("decimals"),
  lt("isInitialized"),
  re("freezeAuthorityOption"),
  ue("freezeAuthority")
]);
Rt.span;
function ge(e, n, t = !1, r = I, s = j) {
  if (!t && !p.isOnCurve(n.toBuffer()))
    throw new Tt();
  const [a] = p.findProgramAddressSync([n.toBuffer(), r.toBuffer(), e.toBuffer()], s);
  return a;
}
function _t(e, n, t, r, s = I, a = j) {
  return Nt(e, n, t, r, D.Buffer.from([1]), s, a);
}
function Nt(e, n, t, r, s, a = I, i = j) {
  const o = [
    { pubkey: e, isSigner: !0, isWritable: !0 },
    { pubkey: n, isSigner: !1, isWritable: !0 },
    { pubkey: t, isSigner: !1, isWritable: !1 },
    { pubkey: r, isSigner: !1, isWritable: !1 },
    { pubkey: Ne.programId, isSigner: !1, isWritable: !1 },
    { pubkey: a, isSigner: !1, isWritable: !1 }
  ];
  return new Ce({
    keys: o,
    programId: i,
    data: s
  });
}
const pe = be([we("instruction"), Ae("amount")]);
function $t(e, n, t, r, s = [], a = I) {
  const i = Ut([
    { pubkey: e, isSigner: !1, isWritable: !0 },
    { pubkey: n, isSigner: !1, isWritable: !0 }
  ], t, s), o = D.Buffer.alloc(pe.span);
  return pe.encode({
    instruction: k.Transfer,
    amount: BigInt(r)
  }, o), new Ce({ keys: i, programId: a, data: o });
}
const kt = {
  version: "0.1.0",
  name: "example_cctp_with_executor",
  instructions: [
    {
      name: "relayLastMessage",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "payee",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "messageTransmitter",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "executorProgram",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "args",
          type: {
            defined: "relayLastMessageArgs"
          }
        }
      ]
    }
  ],
  types: [
    {
      name: "relayLastMessageArgs",
      type: {
        kind: "struct",
        fields: [
          {
            name: "recipientChain",
            type: "u16"
          },
          {
            name: "execAmount",
            type: "u64"
          },
          {
            name: "signedQuoteBytes",
            type: "bytes"
          },
          {
            name: "relayInstructions",
            type: "bytes"
          }
        ]
      }
    }
  ]
};
class V {
  constructor(n, t, r, s) {
    c(this, "network");
    c(this, "chain");
    c(this, "connection");
    c(this, "contracts");
    c(this, "tokenMessengerProgramId");
    c(this, "messageTransmitterProgramId");
    c(this, "shimProgramId");
    c(this, "executorProgramId");
    var i, o, d;
    if (this.network = n, this.chain = t, this.connection = r, this.contracts = s, n === "Devnet")
      throw new Error("CCTPExecutor not supported on Devnet");
    const a = (u, m) => {
      if (!u)
        throw new Error(m);
      return new p(u);
    };
    this.tokenMessengerProgramId = a((i = s.cctp) == null ? void 0 : i.tokenMessenger, `Circle Token Messenger contract for domain ${t} not found`), this.messageTransmitterProgramId = a((o = s.cctp) == null ? void 0 : o.messageTransmitter, `Circle Message Transmitter contract for domain ${t} not found`), this.shimProgramId = a((d = L[n]) == null ? void 0 : d[t], `Shim contract for ${t} not found`), this.executorProgramId = a(wt[n], `Executor contract for ${n} not found`);
  }
  static async fromRpc(n, t) {
    const [r, s] = await gt.chainFromRpc(n), a = t[s];
    if (a.network !== r)
      throw new Error(`Network mismatch: ${a.network} != ${r}`);
    return new V(r, s, n, a.contracts);
  }
  async *transfer(n, t, r) {
    const s = new p(w.get(this.network, this.chain)), a = new N(n).unwrap(), i = ge(s, a), o = new N(r.referrer.address).unwrap(), d = new $e();
    if (d.feePayer = a, r.referrerFee > 0n) {
      const y = ge(s, o);
      await this.connection.getAccountInfo(y) || d.add(_t(a, y, o, s)), d.add($t(i, y, a, r.referrerFee));
    }
    const u = P.get(this.network, t.chain), m = t.address.toUniversalAddress(), l = ke.generate();
    d.add(await mt(this.messageTransmitterProgramId, this.tokenMessengerProgramId, s, u, a, i, m, r.remainingAmount, l.publicKey));
    const f = new ht(kt, this.shimProgramId, { connection: null }), g = $(ye, r.signedQuote), h = bt("message_transmitter", this.messageTransmitterProgramId);
    d.add(await f.methods.relayLastMessage({
      execAmount: new Oe(r.estimatedCost.toString()),
      recipientChain: C(t.chain),
      signedQuoteBytes: D.Buffer.from(r.signedQuote),
      relayInstructions: D.Buffer.from(r.relayInstructions)
    }).accounts({
      payer: a,
      messageTransmitter: h,
      payee: new p(g.quote.payeeAddress),
      executorProgram: this.executorProgramId
    }).instruction()), yield this.createUnsignedTx({ transaction: d, signers: [l] }, "SvmCCTPExecutor.Transfer");
  }
  createUnsignedTx(n, t, r = !1) {
    return new pt(n, this.network, this.chain, t, r);
  }
}
M(Ge, "CCTPExecutor", V);
let v;
function ir(e) {
  if (e.referrerFeeDbps < 0 || e.referrerFeeDbps > 65535n)
    throw new Error("Referrer fee must be between 0 and 65535");
  class n extends F {
  }
  return c(n, "config", e), n;
}
class F extends Le {
  constructor() {
    super(...arguments);
    // @ts-ignore
    // Since we set the config on the static class, access it with this param
    // the CCTPExecutorRoute.config will always be empty
    c(this, "staticConfig", this.constructor.config);
  }
  static supportedNetworks() {
    return ["Mainnet", "Testnet"];
  }
  static supportedChains(t) {
    return se.has(t) ? se.get(t) : [];
  }
  static async supportedDestinationTokens(t, r, s) {
    const a = w.get(r.network, r.chain);
    if (!(a && Qe(t, S.tokenId(r.chain, a))))
      return [];
    const { network: i, chain: o } = s;
    return w.has(i, o) ? [
      S.chainAddress(o, w.get(i, o))
    ] : [];
  }
  getDefaultOptions() {
    return {
      nativeGas: 0
    };
  }
  async validate(t, r) {
    var a;
    return (a = r.options) != null && a.nativeGas && (r.options.nativeGas < 0 || r.options.nativeGas > 1) ? {
      valid: !1,
      error: new Error("Invalid native gas percentage"),
      params: r
    } : { valid: !0, params: {
      normalizedParams: {
        amount: t.parseAmount(r.amount)
      },
      options: r.options ?? this.getDefaultOptions(),
      ...r
    } };
  }
  async quote(t, r) {
    var Z, Y;
    const { fromChain: s, toChain: a } = t;
    if (!w.get(s.network, s.chain))
      throw new Error("Invalid transfer, no USDC contract on source");
    const o = w.get(a.network, a.chain);
    if (!o)
      throw new Error("Invalid transfer, no USDC contract on destination");
    const d = (Z = yt[s.network]) == null ? void 0 : Z[s.chain];
    if (!d)
      return {
        success: !1,
        error: new Error("No referrer address found")
      };
    const u = S.chainAddress(s.chain, d), m = this.staticConfig.referrerFeeDbps, { referrerFee: l, remainingAmount: f } = vt(qe(r.normalizedParams.amount), this.staticConfig.referrerFeeDbps);
    if (f <= 0n)
      return {
        success: !1,
        error: new Error("Amount after fee <= 0")
      };
    const g = (Y = At[s.network]) == null ? void 0 : Y[a.chain];
    if (!g)
      return {
        success: !1,
        error: new Error("Gas limit not found")
      };
    const h = await xt(s.network);
    if (!h[C(s.chain)])
      return {
        success: !1,
        error: new Error("Unsupported source chain")
      };
    const x = h[C(a.chain)];
    if (!x || !x.requestPrefixes.includes("ERC1"))
      return {
        success: !1,
        error: new Error("Unsupported destination chain")
      };
    const { recipient: b } = t;
    let E = !0;
    if (b && a.chain === "Solana") {
      const De = S.parseAddress("Solana", o), Pe = await a.getTokenAccount(b.address, De), ee = await a.getRpc();
      E = await ee.getAccountInfo(new N(Pe.address).unwrap()) !== null, !E && !v && (v = BigInt(await ee.getMinimumBalanceForRentExemption(165)));
    }
    let B = 0n;
    a.chain === "Solana" && (B += Ct, !E && v && (B += v));
    const z = [];
    z.push({
      request: {
        type: "GasInstruction",
        gasLimit: g,
        msgValue: B
      }
    });
    const K = BigInt(x.gasDropOffLimit), T = r.options.nativeGas && K > 0n ? BigInt(Math.round(r.options.nativeGas * 100)) * K / 100n : 0n;
    (T > 0n || !E) && z.push({
      request: {
        type: "GasDropOffInstruction",
        dropOff: T,
        // If the recipient is undefined (e.g. the user hasn’t connected their wallet yet),
        // we temporarily use a dummy address to fetch a quote.
        // The recipient address is validated later in the `initiate` method, which will throw if it's still missing.
        recipient: b ? b.address.toUniversalAddress() : new We(new Uint8Array(32))
      }
    });
    const X = je(he, {
      requests: z
    }), U = await Et(s.network, s.chain, a.chain, ne.encode(X, !0));
    if (!U.estimatedCost)
      return {
        success: !1,
        error: new Error("No estimated cost")
      };
    const J = ne.decode(U.signedQuote), xe = $(ye, J), Ee = s.chain === "Polygon" ? 2e3 * 200 : Ve(s.chain) + 1e3, H = BigInt(U.estimatedCost), Se = {
      signedQuote: J,
      relayInstructions: X,
      estimatedCost: H,
      referrer: u,
      referrerFee: l,
      remainingAmount: f,
      referrerFeeDbps: m
    }, [ve, Fe] = await Promise.all([
      s.getDecimals("native"),
      a.getDecimals("native")
    ]);
    return {
      success: !0,
      params: r,
      sourceToken: {
        token: t.source.id,
        amount: r.normalizedParams.amount
      },
      destinationToken: {
        token: t.destination.id,
        amount: R(f, t.destination.decimals)
      },
      relayFee: {
        token: Ke(s.chain),
        amount: R(H, ve)
      },
      destinationNativeGas: R(T, Fe),
      eta: Ee,
      expires: xe.quote.expiryTime,
      details: Se
    };
  }
  async initiate(t, r, s, a) {
    if (!s.details)
      throw new Error("Missing quote details");
    $(he, s.details.relayInstructions).requests.forEach(({ request: h }) => {
      if (h.type === "GasDropOffInstruction" && !h.recipient.equals(a.address.toUniversalAddress()))
        throw new Error("Gas drop-off recipient does not match");
    });
    const o = await t.fromChain.getProtocol("CCTPExecutor"), d = S.parseAddress(r.chain(), r.address());
    let u = a;
    if (a.chain === "Solana") {
      const h = S.parseAddress("Solana", w.get(t.toChain.network, t.toChain.chain));
      u = await t.toChain.getTokenAccount(a.address, h);
    }
    const m = await o.transfer(d, u, s.details), l = await Xe(t.fromChain, m, r);
    let f = 0;
    return (async () => {
      for (; f < 20; ) {
        try {
          const [h] = await me(this.wh.network, l.at(-1).txid, t.fromChain.chain);
          if (h)
            break;
        } catch {
        }
        f++, await Ft(2e3);
      }
    })(), {
      from: t.fromChain.chain,
      to: t.toChain.chain,
      state: _.SourceInitiated,
      originTxs: l
    };
  }
  async *track(t, r) {
    if (ae(t) || ie(t))
      return t;
    let s = r || 60 * 60 * 1e3;
    for (; s > 0; ) {
      const a = Date.now();
      if (Je(t) || He(t) || Ze(t))
        try {
          const [i] = await me(this.wh.network, t.originTxs.at(-1).txid, t.from);
          if (!i)
            throw new Error("No transaction status found");
          const o = i == null ? void 0 : i.status;
          if ((o === A.Failed || // this could happen if simulation fails
          o === A.Underpaid || // only happens if you don't pay at least the costEstimate
          o === A.Unsupported || // capabilities check didn't pass
          o === A.Aborted) && (t = {
            ...t,
            state: _.Failed,
            error: new ut(`Relay failed with status: ${o}`)
          }), o === A.Submitted && (t = {
            ...t,
            state: _.DestinationFinalized,
            attestation: { id: i.id, attestation: {} }
          }), yield t, ae(t) || ie(t))
            return t;
        } catch (i) {
          console.error(`Error fetching transaction status: ${i.message || i}`);
        }
      await new Promise((i) => setTimeout(i, 3e3)), s -= Date.now() - a;
    }
    return t;
  }
}
c(F, "NATIVE_GAS_DROPOFF_SUPPORTED", !0), c(F, "config", { referrerFeeDbps: 0n }), c(F, "meta", {
  name: "CCTPExecutorRoute",
  provider: "Circle"
});
export {
  ir as cctpExecutorRoute
};
