var oe = Object.defineProperty;
var se = (k, t, e) => t in k ? oe(k, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : k[t] = e;
var h = (k, t, e) => se(k, typeof t != "symbol" ? t + "" : t, e);
import { co as N, cp as F, cq as ae, cr as Q, cs as V, ct as $, cu as S, b4 as ie, I, bw as R, cv as b, bx as q, b9 as ce, b2 as j, K as C, m as v, b6 as de, bC as H, bz as le, cw as B, cx as O, cy as ge, cz as ue, cA as M, cB as fe, ba as W, cC as D, cD as X, cE as pe, cF as x, cG as he, cH as we, r as U, cI as ye, cJ as Z, cf as ke, cK as me, c2 as G, cL as be, cM as Ie, cN as L, bf as ee } from "./index-6NRj6D5S.mjs";
import "./index-CRfcoCAy.mjs";
const Y = async (k, t, e) => {
  var d, r, n;
  if (!N(e))
    throw new Error(`Invalid Sui type: ${e}`);
  const i = await F(k, t);
  if (!i)
    throw new Error(`Unable to fetch object fields from token bridge state. Object ID: ${t}`);
  const o = (r = (d = i.token_registry.fields) == null ? void 0 : d.id) == null ? void 0 : r.id;
  if (!o)
    throw new Error("Unable to fetch token registry object ID");
  const a = ae((n = i.token_registry) == null ? void 0 : n.type);
  if (!a)
    throw new Error("Unable to fetch token registry package ID");
  return k.getDynamicFieldObject({
    parentId: o,
    name: {
      type: `${a}::token_registry::Key<${e}>`,
      value: {
        dummy_field: !1
      }
    }
  });
}, P = async (k, t, e, i) => {
  var s, u, f, w;
  const o = await F(k, t);
  if (!o)
    throw new Error("Unable to fetch object fields from token bridge state");
  const a = (u = (s = o.token_registry) == null ? void 0 : s.fields) == null ? void 0 : u.coin_types, d = (w = (f = a == null ? void 0 : a.fields) == null ? void 0 : f.id) == null ? void 0 : w.id;
  if (!d)
    throw new Error("Unable to fetch coin types");
  const r = Q(a == null ? void 0 : a.type);
  if (!r)
    throw new Error("Unable to get key type");
  const n = await k.getDynamicFieldObject({
    parentId: d,
    name: {
      type: r,
      value: {
        addr: [...e],
        chain: i
      }
    }
  });
  if (n.error) {
    if (n.error.code === "dynamicFieldNotFound")
      return null;
    throw new Error(`Unexpected getDynamicFieldObject response ${n.error}`);
  }
  const l = V(n);
  if (!l)
    return null;
  if (!$(l))
    throw new Error("What?");
  return "value" in l ? S(l.value) : null;
};
class z {
  constructor(t, e, i, o) {
    h(this, "network");
    h(this, "chain");
    h(this, "provider");
    h(this, "contracts");
    h(this, "coreBridgeObjectId");
    h(this, "tokenBridgeObjectId");
    h(this, "chainId");
    this.network = t, this.chain = e, this.provider = i, this.contracts = o, this.chainId = ie.get(t, e);
    const a = this.contracts.tokenBridge;
    if (!a)
      throw new Error(`Wormhole Token Bridge contract for domain ${e} not found`);
    const d = this.contracts.coreBridge;
    if (!d)
      throw new Error(`Wormhole Token Bridge contract for domain ${e} not found`);
    this.tokenBridgeObjectId = a, this.coreBridgeObjectId = d;
  }
  static async fromRpc(t, e) {
    const [i, o] = await I.chainFromRpc(t), a = e[o];
    if (a.network !== i)
      throw new Error(`Network mismatch: ${a.network} != ${i}`);
    return new z(i, o, t, a.contracts);
  }
  async isWrappedAsset(t) {
    try {
      return await this.getOriginalAsset(t), !0;
    } catch {
      return !1;
    }
  }
  async getOriginalAsset(t) {
    let e = t.getCoinType();
    if (!N(e))
      throw new Error(`Invalid Sui type: ${e}`);
    const i = await Y(this.provider, this.tokenBridgeObjectId, e), o = V(i);
    if (!o)
      throw R(e);
    if (!$(o))
      throw new Error("Expected fields to be a MoveStruct");
    if (!("value" in o))
      throw new Error("Expected a `value` key in fields of MoveStruct");
    const a = o.value;
    if (!b(a))
      throw new Error("Expected fields to be a MoveStruct");
    const d = S(a.type);
    if (e = S(e), d.includes(`wrapped_asset::WrappedAsset<${e}>`)) {
      const r = a.fields.info;
      if (!b(r))
        throw new Error("Expected fields to be a MoveStruct");
      const n = r.fields.token_address;
      if (!b(n))
        throw new Error("Expected fields to be a MoveStruct");
      if (!$(n.fields))
        throw new Error("Expected address data to be a MoveObject");
      if (!("value" in n.fields))
        throw new Error("Expected a `value` key in fields of MoveStruct");
      const l = n.fields.value;
      if (!b(l))
        throw new Error("Expected fields to be a MoveStruct");
      const s = new Uint8Array(l.fields.data);
      return {
        chain: ce(Number(r.fields.token_chain)),
        address: new q(s)
      };
    }
    throw R(e);
  }
  async getTokenUniversalAddress(t) {
    let e = t.getCoinType();
    if (!N(e))
      throw new Error(`Invalid Sui type: ${e}`);
    const i = await Y(this.provider, this.tokenBridgeObjectId, e), o = V(i);
    if (!o)
      throw new Error(`Token of type ${e} has not been registered with the token bridge. Has it been attested?`);
    if (!$(o))
      throw new Error("Expected fields to be a MoveStruct");
    if (!("value" in o))
      throw new Error("Expected a `value` key in fields of MoveStruct");
    const a = o.value;
    if (!b(a))
      throw new Error("Expected fields to be a MoveStruct");
    const d = S(a.type);
    if (e = S(e), d.includes(`native_asset::NativeAsset<${e}>`)) {
      const r = a.fields.token_address;
      if (!b(r))
        throw new Error("Expected fields to be a MoveStruct");
      if (!("value" in r.fields))
        throw new Error("Expected a `value` key in fields of MoveStruct");
      const n = r.fields.value;
      if (!b(n))
        throw new Error("Expected fields to be a MoveStruct");
      const l = new Uint8Array(n.fields.data);
      return new q(l);
    }
    throw new Error(`Token of type ${e} is not a native asset`);
  }
  async getTokenNativeAddress(t, e) {
    const i = await P(this.provider, this.tokenBridgeObjectId, e.toUint8Array(), j(t));
    if (!i)
      throw new Error(`Token ${e.toString()} not found in token registry`);
    return new C(i);
  }
  async hasWrappedAsset(t) {
    try {
      return await this.getWrappedAsset(t), !0;
    } catch {
    }
    return !1;
  }
  async getWrappedAsset(t) {
    if (v(t.address))
      throw new Error("Token Address required, 'native' literal not supported");
    const e = await P(this.provider, this.tokenBridgeObjectId, t.address.toUniversalAddress().toUint8Array(), j(t.chain));
    if (!e)
      throw R(de(t));
    return H(this.chain, e);
  }
  async isTransferCompleted(t) {
    var r, n, l, s, u, f, w, y;
    const e = await F(this.provider, this.tokenBridgeObjectId);
    if (!e)
      throw new Error("Unable to fetch object fields from token bridge state");
    const i = (n = (r = e.consumed_vaas) == null ? void 0 : r.fields) == null ? void 0 : n.hashes, o = Q((s = (l = i == null ? void 0 : i.fields) == null ? void 0 : l.items) == null ? void 0 : s.type);
    if (!o)
      throw new Error("Unable to get key type");
    const a = (y = (w = (f = (u = i == null ? void 0 : i.fields) == null ? void 0 : u.items) == null ? void 0 : f.fields) == null ? void 0 : w.id) == null ? void 0 : y.id;
    if (!a)
      throw new Error("Unable to fetch consumed VAAs table");
    const d = await this.provider.getDynamicFieldObject({
      parentId: a,
      name: {
        type: o,
        value: {
          data: [...le(t.hash)]
        }
      }
    });
    if (!d.error)
      return !0;
    if (d.error.code === "dynamicFieldNotFound")
      return !1;
    throw new Error(`Unexpected getDynamicFieldObject response ${d.error}`);
  }
  async *createAttestation(t) {
    const e = 0n, o = t.toString(), a = await this.provider.getCoinMetadata({ coinType: o });
    if (a === null || a.id === null)
      throw new Error(`Coin metadata ID for type ${o} not found`);
    const [d, r] = await this.getPackageIds(), n = new B(), [l] = n.splitCoins(n.gas, [n.pure.u64(e)]), [s] = n.moveCall({
      target: `${r}::attest_token::attest_token`,
      arguments: [n.object(this.tokenBridgeObjectId), n.object(a.id), n.pure.u32(0)],
      typeArguments: [o]
    });
    n.moveCall({
      target: `${d}::publish_message::publish_message`,
      arguments: [
        n.object(this.coreBridgeObjectId),
        l,
        s,
        n.object(O)
      ]
    }), yield this.createUnsignedTx(n, "Sui.TokenBridge.CreateAttestation");
  }
  async *submitAttestation(t, e) {
    const [i, o] = await this.getPackageIds(), a = e.toString(), d = Math.min(t.payload.decimals, 8), r = await this.getCoinBuildOutput(i, o, d), n = await ge(r, a);
    yield this.createUnsignedTx(n, "Sui.TokenBridge.PrepareCreateWrapped");
    let l = "", s = "", u = "", f = "", w = "", y = !1;
    for (; !y; ) {
      await new Promise((p) => setTimeout(p, 500));
      const _ = await this.provider.queryTransactionBlocks({
        filter: { FromAddress: a },
        options: { showObjectChanges: !0 },
        limit: 3
      });
      for (const p of _.data)
        if ("objectChanges" in p) {
          for (const g of p.objectChanges)
            ue(g) && g.packageId !== void 0 ? l = g.packageId : M(g) && g.objectType.includes("WrappedAssetSetup") ? (s = g.objectId, w = g.objectType.split(", ")[1].replace(">", "")) : M(g) && g.objectType.includes("UpgradeCap") ? u = g.objectId : M(g) && g.objectType.includes("CoinMetadata") && (f = g.objectId);
          if (l !== "" && s !== "" && u !== "" && f !== "") {
            y = !0;
            break;
          } else
            l = "", s = "", u = "", f = "";
        }
    }
    const m = fe(l), c = new B(), [A] = c.moveCall({
      target: `${i}::vaa::parse_and_verify`,
      arguments: [
        c.object(this.coreBridgeObjectId),
        c.pure.vector("u8", W(t)),
        c.object(O)
      ]
    }), [E] = c.moveCall({
      target: `${o}::vaa::verify_only_once`,
      arguments: [c.object(this.tokenBridgeObjectId), A]
    });
    c.moveCall({
      target: `${o}::create_wrapped::complete_registration`,
      arguments: [
        c.object(this.tokenBridgeObjectId),
        c.object(f),
        c.object(s),
        c.object(u),
        E
      ],
      typeArguments: [m, w]
    }), yield this.createUnsignedTx(c, "Sui.TokenBridge.SubmitAttestation");
  }
  async *transfer(t, e, i, o, a) {
    const d = 0n, r = 0n, l = t.toString(), s = (v(i) ? D : i).toString(), u = await I.getCoins(this.provider, t, s), [f, ...w] = u.filter((p) => X(p.coinType, s));
    if (f === void 0)
      throw new Error(`Coins array doesn't contain any coins of type ${s}`);
    const [y, m] = await this.getPackageIds(), c = new B(), [A] = (() => {
      if (s === D)
        return c.splitCoins(c.gas, [c.pure.u64(o)]);
      {
        const p = c.object(f.coinObjectId);
        return w.length && c.mergeCoins(p, w.map((g) => c.object(g.coinObjectId))), c.splitCoins(p, [c.pure.u64(o)]);
      }
    })(), [E] = c.splitCoins(c.gas, [c.pure.u64(d)]), [_] = c.moveCall({
      target: `${m}::state::verified_asset`,
      arguments: [c.object(this.tokenBridgeObjectId)],
      typeArguments: [s]
    });
    if (a) {
      if (!l)
        throw new Error("senderAddress is required for transfer with payload");
      let p = !1;
      const g = await (async () => {
        const K = await pe(this.provider, y, l);
        if (K !== null)
          return c.object(K);
        {
          const [ne] = c.moveCall({
            target: `${y}::emitter::new`,
            arguments: [c.object(this.coreBridgeObjectId)]
          });
          return p = !0, ne;
        }
      })(), [T, te] = c.moveCall({
        target: `${m}::transfer_tokens_with_payload::prepare_transfer`,
        arguments: [
          g,
          _,
          A,
          c.pure.u16(j(e.chain)),
          c.pure.vector("u8", e.address.toUint8Array()),
          c.pure.vector("u8", a),
          c.pure.u32(0)
        ],
        typeArguments: [s]
      });
      c.moveCall({
        target: `${m}::coin_utils::return_nonzero`,
        arguments: [te],
        typeArguments: [s]
      });
      const [re] = c.moveCall({
        target: `${m}::transfer_tokens_with_payload::transfer_tokens_with_payload`,
        arguments: [c.object(this.tokenBridgeObjectId), T],
        typeArguments: [s]
      });
      c.moveCall({
        target: `${y}::publish_message::publish_message`,
        arguments: [
          c.object(this.coreBridgeObjectId),
          E,
          re,
          c.object(O)
        ]
      }), p && c.transferObjects([g], c.pure.address(l)), yield this.createUnsignedTx(c, "Sui.TokenBridge.TransferWithPayload");
    } else {
      const [p, g] = c.moveCall({
        target: `${m}::transfer_tokens::prepare_transfer`,
        arguments: [
          _,
          A,
          c.pure.u16(j(e.chain)),
          c.pure.vector("u8", e.address.toUint8Array()),
          c.pure.u64(r),
          c.pure.u32(0)
        ],
        typeArguments: [s]
      });
      c.moveCall({
        target: `${m}::coin_utils::return_nonzero`,
        arguments: [g],
        typeArguments: [s]
      });
      const [T] = c.moveCall({
        target: `${m}::transfer_tokens::transfer_tokens`,
        arguments: [c.object(this.tokenBridgeObjectId), p],
        typeArguments: [s]
      });
      c.moveCall({
        target: `${y}::publish_message::publish_message`,
        arguments: [
          c.object(this.coreBridgeObjectId),
          E,
          T,
          c.object(O)
        ]
      }), yield this.createUnsignedTx(c, "Sui.TokenBridge.Transfer");
    }
  }
  async *redeem(t, e, i = !0) {
    const o = await P(this.provider, this.tokenBridgeObjectId, e.payload.token.address.toUint8Array(), j(e.payload.token.chain));
    if (!o)
      throw new Error("Unable to fetch token coinType");
    const [a, d] = await this.getPackageIds(), r = new B(), [n] = r.moveCall({
      target: `${a}::vaa::parse_and_verify`,
      arguments: [
        r.object(this.coreBridgeObjectId),
        r.pure.vector("u8", W(e)),
        r.object(O)
      ]
    }), [l] = r.moveCall({
      target: `${d}::vaa::verify_only_once`,
      arguments: [r.object(this.tokenBridgeObjectId), n]
    }), [s] = r.moveCall({
      target: `${d}::complete_transfer::authorize_transfer`,
      arguments: [r.object(this.tokenBridgeObjectId), l],
      typeArguments: [o]
    }), [u] = r.moveCall({
      target: `${d}::complete_transfer::redeem_relayer_payout`,
      arguments: [s],
      typeArguments: [o]
    });
    r.moveCall({
      target: `${d}::coin_utils::return_nonzero`,
      arguments: [u],
      typeArguments: [o]
    }), yield this.createUnsignedTx(r, "Sui.TokenBridge.Redeem");
  }
  async getWrappedNative() {
    return H(this.chain, D);
  }
  async getPackageIds() {
    return Promise.all([
      x(this.provider, this.coreBridgeObjectId),
      x(this.provider, this.tokenBridgeObjectId)
    ]);
  }
  async getCoinBuildOutput(t, e, i) {
    var r;
    if (i > 8)
      throw new Error("Decimals is capped at 8");
    const o = (r = await he(this.provider, this.tokenBridgeObjectId)) == null ? void 0 : r.replace("0x", "");
    if (!o)
      throw new Error(`Original token bridge package ID not found for object ID ${this.tokenBridgeObjectId}`);
    const a = "a11ceb0b060000000901000a020a14031e1704350405392d07669f01088502600ae502050cea02160004010b010c0205020d000002000201020003030c020001000104020700000700010001090801010c020a050600030803040202000302010702080007080100020800080303090002070801010b020209000901010608010105010b0202080008030209000504434f494e095478436f6e7465787408565f5f305f325f3011577261707065644173736574536574757004636f696e0e6372656174655f777261707065640b64756d6d795f6669656c6404696e697414707265706172655f726567697374726174696f6e0f7075626c69635f7472616e736665720673656e646572087472616e736665720a74785f636f6e746578740f76657273696f6e5f636f6e74726f6c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002" + o + "00020106010000000001090b0031" + i.toString(16).padStart(2, "0") + "0a0138000b012e110238010200";
    return {
      modules: [we.encode(U.decode(a))],
      dependencies: ["0x1", "0x2", e, t].map((n) => ye(n))
    };
  }
  createUnsignedTx(t, e, i = !1) {
    return new Z(t, this.network, this.chain, e, i);
  }
}
class J {
  constructor(t, e, i, o) {
    h(this, "network");
    h(this, "chain");
    h(this, "connection");
    h(this, "contracts");
    h(this, "tokenBridgeRelayerObjectId");
    h(this, "coreBridgeObjectId");
    h(this, "tokenBridgeObjectId");
    h(this, "fields");
    this.network = t, this.chain = e, this.connection = i, this.contracts = o;
    const { tokenBridge: a, tokenBridgeRelayer: d, coreBridge: r } = o;
    if (!a || !d || !r)
      throw new Error(`Some object IDs for ${e} Automatic Token Bridge not found`);
    this.tokenBridgeRelayerObjectId = d, this.tokenBridgeObjectId = a, this.coreBridgeObjectId = r;
  }
  static async fromRpc(t, e) {
    const [i, o] = await I.chainFromRpc(t), a = e[o];
    if (a.network !== i)
      throw new Error(`Network mismatch for chain ${o}: ${a.network} != ${i}`);
    return new J(i, o, t, a.contracts);
  }
  async *transfer(t, e, i, o, a) {
    const r = new C(v(i) ? I.nativeTokenId(this.network, this.chain).address : i).getCoinType(), { coreBridge: n, tokenBridge: l } = await this.getPackageIds(), s = new B(), u = BigInt(0), [f] = s.splitCoins(s.gas, [s.pure.u64(u)]), [w] = await (async () => {
      if (v(i))
        return s.splitCoins(s.gas, [s.pure.u64(o)]);
      {
        const E = await I.getCoins(this.connection, t, r), [_, ...p] = E.filter((T) => T.coinType === r);
        if (_ === void 0)
          throw new Error(`Coins array doesn't contain any coins of type ${r}`);
        const g = s.object(_.coinObjectId);
        return p.length && s.mergeCoins(g, p.map((T) => s.object(T.coinObjectId))), s.splitCoins(g, [s.pure.u64(o)]);
      }
    })(), [y] = s.moveCall({
      target: `${l}::state::verified_asset`,
      arguments: [s.object(this.tokenBridgeObjectId)],
      typeArguments: [r]
    }), m = await this.getPackageId(), [c] = s.moveCall({
      target: `${m}::transfer::transfer_tokens_with_relay`,
      arguments: [
        s.object(this.tokenBridgeRelayerObjectId),
        w,
        y,
        s.pure.u64(a ?? 0n),
        s.pure.u16(j(e.chain)),
        s.pure.address(U.encode(e.address.toUint8Array(), !0)),
        s.pure.u32(123)
      ],
      typeArguments: [r]
    }), [A] = s.moveCall({
      target: `${l}::transfer_tokens_with_payload::transfer_tokens_with_payload`,
      arguments: [s.object(this.tokenBridgeObjectId), c],
      typeArguments: [r]
    });
    s.moveCall({
      target: `${n}::publish_message::publish_message`,
      arguments: [
        s.object(this.coreBridgeObjectId),
        f,
        A,
        s.object(O)
      ]
    }), yield this.createUnsignedTx(s, "AutomaticTokenBridge.transfer");
  }
  async *redeem(t, e) {
    const { coreBridge: i, tokenBridge: o } = await this.getPackageIds(), { address: a, chain: d } = e.payload.token, r = await P(this.connection, this.tokenBridgeObjectId, a.toUniversalAddress().toUint8Array(), j(d));
    if (!r)
      throw new Error("Unable to fetch token coinType");
    const n = new B(), [l] = n.moveCall({
      target: `${i}::vaa::parse_and_verify`,
      arguments: [
        n.object(this.coreBridgeObjectId),
        n.pure.vector("u8", W(e)),
        n.object(O)
      ]
    }), [s] = n.moveCall({
      target: `${o}::vaa::verify_only_once`,
      arguments: [n.object(this.tokenBridgeObjectId), l]
    }), [u] = n.moveCall({
      target: `${o}::complete_transfer_with_payload::authorize_transfer`,
      arguments: [n.object(this.tokenBridgeObjectId), s],
      typeArguments: [r]
    }), f = await this.getPackageId();
    n.moveCall({
      target: `${f}::redeem::complete_transfer`,
      arguments: [n.object(this.tokenBridgeRelayerObjectId), u],
      typeArguments: [r]
    }), yield this.createUnsignedTx(n, "AutomaticTokenBridge.redeem");
  }
  async getRelayerFee(t, e) {
    const i = v(e) ? I.nativeTokenId(this.network, this.chain) : e, o = await this.getTokenInfo(i.toString());
    if (o === null)
      throw new Error("Unsupported token for relay");
    const a = await this.getFields(), d = await this.connection.getDynamicFieldObject({
      parentId: this.tokenBridgeRelayerObjectId,
      name: { type: "vector<u8>", value: Array.from(ke.encode("relayer_fees")) }
    });
    if (!d.data || !d.data.content)
      throw d.error ? new Error("Failed to get relayer fees: " + JSON.stringify(d.error)) : new Error("Unable to compute relayer fee");
    const { content: r } = d.data;
    if (!b(r) || !me(r.fields.id))
      throw new Error("Unable to compute relayer fee");
    const n = await this.connection.getDynamicFieldObject({
      parentId: r.fields.id.id,
      name: { type: "u16", value: j(t) }
    });
    if (!n.data || !n.data.content)
      throw n.error ? new Error("Failed to get relayer fees: " + JSON.stringify(d.error)) : new Error("Unable to compute relayer fee");
    const { content: l } = n.data;
    if (!b(l))
      throw new Error("Unable to compute relayer fee");
    const s = await I.getDecimals(this.chain, this.connection, e.toString()), u = o.swap_rate, f = a.relayer_fee_precision, w = a.swap_rate_precision, y = l.fields.value;
    return 10n ** BigInt(s) * BigInt(y) * BigInt(w) / (BigInt(u) * BigInt(f));
  }
  async maxSwapAmount(t) {
    var n, l;
    const i = (v(t) ? I.nativeTokenId(this.network, this.chain) : t).toString(), o = await this.connection.getCoinMetadata({ coinType: i });
    if (!o)
      throw new Error("metadata is null");
    const a = await this.getPackageId(), d = new B();
    d.moveCall({
      // Calculates the max number of tokens the recipient can convert to native
      // Sui. The max amount of native assets the contract will swap with the
      // recipient is governed by the `max_native_swap_amount` variable.
      target: `${a}::redeem::calculate_max_swap_amount_in`,
      arguments: [d.object(this.tokenBridgeRelayerObjectId), d.pure.u8(o.decimals)],
      typeArguments: [i]
    });
    const r = await this.connection.devInspectTransactionBlock({
      transactionBlock: d,
      sender: U.encode(new Uint8Array(32))
    });
    if (!r.results || r.results.length == 0 || !((n = r.results[0]) != null && n.returnValues) || ((l = r.results[0]) == null ? void 0 : l.returnValues.length) !== 1)
      throw Error("swap rate not set");
    return G.decode(new Uint8Array(r.results[0].returnValues[0][0].toReversed()));
  }
  async nativeTokenAmount(t, e) {
    var l, s;
    const o = (v(t) ? I.nativeTokenId(this.network, this.chain) : t).toString(), a = await this.connection.getCoinMetadata({ coinType: o });
    if (!a)
      throw new Error("metadata is null");
    const d = await this.getPackageId(), r = new B();
    r.moveCall({
      // Calculates the amount of native Sui that the recipient will receive
      // for swapping the `to_native_amount` of tokens.
      target: `${d}::redeem::calculate_native_swap_amount_out`,
      arguments: [
        r.object(this.tokenBridgeRelayerObjectId),
        r.pure.u64(e),
        r.pure.u8(a.decimals)
      ],
      typeArguments: [o]
    });
    const n = await this.connection.devInspectTransactionBlock({
      transactionBlock: r,
      sender: U.encode(new Uint8Array(32))
    });
    if (!n.results || n.results.length == 0 || !((l = n.results[0]) != null && l.returnValues) || ((s = n.results[0]) == null ? void 0 : s.returnValues.length) !== 1)
      throw Error("swap rate not set");
    return G.decode(new Uint8Array(n.results[0].returnValues[0][0].toReversed()));
  }
  async getRegisteredTokens() {
    const e = (await this.getFields()).registered_tokens.fields.id.id;
    return (await this.connection.getDynamicFields({
      parentId: e
    })).data.map((a) => {
      const { address: d, module: r, name: n } = be(a.objectType);
      return new C([d, r, n].join(Ie));
    });
  }
  async isRegisteredToken(t) {
    const e = new C(v(t) ? I.nativeTokenId(this.network, this.chain).address : t).unwrap();
    try {
      return await this.getTokenInfo(e) !== null;
    } catch (i) {
      console.error(i);
    }
    return !1;
  }
  async getTokenInfo(t) {
    var n;
    const e = await this.getFields(), o = new C(e.registered_tokens.type).getPackageId(), a = e.registered_tokens.fields.id.id, d = new C(t), r = X(L, d.unwrap()) ? L : d.getCoinType();
    try {
      const l = await this.connection.getDynamicFieldObject({
        parentId: a,
        name: {
          type: `${o}::registered_tokens::Key<${r}>`,
          value: { dummy_field: !1 }
        }
      });
      if (l.error)
        throw new Error("Failed to get token info: " + JSON.stringify(l.error));
      if (!l.data || !l.data.content)
        throw new Error("Failed to get token info: " + JSON.stringify(l));
      const { content: s } = l.data;
      return b(s) && b(s.fields.value) ? s.fields.value.fields : null;
    } catch (l) {
      if ((l == null ? void 0 : l.code) === -32e3 && ((n = l.message) != null && n.includes("RPC Error")))
        return console.error(l), null;
      throw l;
    }
  }
  async getFields() {
    if (!this.fields) {
      const t = await F(this.connection, this.tokenBridgeRelayerObjectId);
      if (t === null)
        throw new Error("Failed to get fields from token bridge relayer state");
      this.fields = t;
    }
    return this.fields;
  }
  async getPackageId() {
    const t = await this.getFields();
    return new C(t.registered_tokens.type).getPackageId();
  }
  async getPackageIds() {
    const [t, e] = await Promise.all([
      x(this.connection, this.coreBridgeObjectId),
      x(this.connection, this.tokenBridgeObjectId)
    ]);
    return { coreBridge: t, tokenBridge: e };
  }
  createUnsignedTx(t, e, i = !1) {
    return new Z(t, this.network, this.chain, e, i);
  }
}
ee("Sui", "TokenBridge", z);
ee("Sui", "AutomaticTokenBridge", J);
export {
  J as SuiAutomaticTokenBridge,
  z as SuiTokenBridge,
  P as getTokenCoinType,
  Y as getTokenFromTokenRegistry
};
