var Le = Object.defineProperty;
var Ue = (r, e, t) => e in r ? Le(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
var u = (r, e, t) => Ue(r, typeof e != "symbol" ? e + "" : e, t);
import { af as p, a_ as Te, aJ as ne, d, at as Ce, d3 as _e, ao as M, bU as ke, aP as L, ar as U, aq as V, b1 as q, aX as ie, d4 as Pe, d5 as ve, ap as re, b2 as j, aB as ze, b3 as Ke } from "./address-CrYNZ_Nj.mjs";
import { d as m, P as qe, c as Fe } from "./index-B6QoC8kC.mjs";
import { d as b, g as z } from "./account-k-CXVcvA.mjs";
import { a as Ve, S as De } from "./unsignedTransaction-DmrfJNQf.mjs";
import { c as Ge } from "./create-CRa9FZnZ.mjs";
import { r as Oe } from "./chain-Dq8acwHq.mjs";
const oe = new p("BPFLoaderUpgradeab1e11111111111111111111111");
function Ne(r) {
  return b([new p(r).toBuffer()], oe);
}
class Re extends Error {
  constructor(e) {
    super(e), this.name = "IdlError";
  }
}
function ue(r, e) {
  switch (e.type.kind) {
    case "struct":
      return e.type.fields.map((t) => A(r, t.type)).reduce((t, n) => t + n, 0);
    case "enum": {
      const t = e.type.variants.map((n) => n.fields ? n.fields.map((s) => typeof s == "object" && "name" in s ? A(r, s.type) : A(r, s)).reduce((s, a) => s + a, 0) : 0);
      return Math.max(...t) + 1;
    }
    case "alias":
      return A(r, e.type.value);
  }
}
function A(r, e) {
  var t;
  switch (e) {
    case "bool":
      return 1;
    case "u8":
      return 1;
    case "i8":
      return 1;
    case "i16":
      return 2;
    case "u16":
      return 2;
    case "u32":
      return 4;
    case "i32":
      return 4;
    case "f32":
      return 4;
    case "u64":
      return 8;
    case "i64":
      return 8;
    case "f64":
      return 8;
    case "u128":
      return 16;
    case "i128":
      return 16;
    case "u256":
      return 32;
    case "i256":
      return 32;
    case "bytes":
      return 1;
    case "string":
      return 1;
    case "publicKey":
      return 32;
    default:
      if ("vec" in e)
        return 1;
      if ("option" in e)
        return 1 + A(r, e.option);
      if ("coption" in e)
        return 4 + A(r, e.coption);
      if ("defined" in e) {
        const n = ((t = r.types) == null ? void 0 : t.filter((a) => a.name === e.defined)) ?? [];
        if (n.length !== 1)
          throw new Re(`Type not found: ${JSON.stringify(e)}`);
        let s = n[0];
        return ue(r, s);
      }
      if ("array" in e) {
        let n = e.array[0], s = e.array[1];
        return A(r, n) * s;
      }
      throw new Error(`Invalid type ${JSON.stringify(e)}`);
  }
}
function k(r) {
  return r.replace(/(?:^\w|[A-Z]|\b\w)/g, function(e, t) {
    return t === 0 ? e.toLowerCase() : e.toUpperCase();
  }).replace(/[\s\-_]+/g, "");
}
function $e(r) {
  return r.charAt(0).toUpperCase() + r.slice(1);
}
const ce = [
  { name: "discriminator", binary: "bytes", size: 4 },
  { name: "consistencyLevel", binary: "uint", size: 1, endianness: "little" },
  { name: "emitterAuthority", ...ne },
  { name: "messageStatus", binary: "uint", size: 1, endianness: "little" },
  { name: "gap", binary: "uint", size: 3 },
  { name: "timestamp", binary: "uint", size: 4, endianness: "little" },
  { name: "nonce", binary: "uint", size: 4, endianness: "little" },
  { name: "sequence", binary: "uint", size: 8, endianness: "little" },
  { name: "emitterChain", binary: "uint", size: 2, endianness: "little" },
  { name: "emitterAddress", ...ne },
  { name: "payloadLength", binary: "uint", size: 4, endianness: "little" },
  { name: "payload", binary: "bytes" }
];
function ge(r) {
  return Te(ce, r);
}
function T(r, e, t, n) {
  const s = typeof e == "string" ? d.Buffer.from(e, "hex") : d.Buffer.from(e);
  if (s.length != 32)
    throw Error("address.length != 32");
  const a = d.Buffer.alloc(8);
  return a.writeBigUInt64BE(typeof n == "number" ? BigInt(n) : n), b([
    s,
    (() => {
      const i = d.Buffer.alloc(2);
      return i.writeUInt16BE(t), i;
    })(),
    a
  ], r);
}
async function Ye(r, e, t, n, s, a) {
  return r.getAccountInfo(T(e, t, n, s), a).then((i) => !!z(i)[0]);
}
function S(r) {
  return b([d.Buffer.from("Bridge")], r);
}
async function de(r, e, t) {
  return r.getAccountInfo(S(e), t).then((n) => G.deserialize(z(n)));
}
class D {
  constructor(e, t) {
    u(this, "guardianSetExpirationTime");
    u(this, "fee");
    this.guardianSetExpirationTime = e, this.fee = t;
  }
  static deserialize(e) {
    if (e.length != 12)
      throw new Error("data.length != 12");
    const t = e.readUInt32LE(0), n = e.readBigUInt64LE(4);
    return new D(t, n);
  }
}
class G {
  constructor(e, t, n) {
    u(this, "guardianSetIndex");
    u(this, "lastLamports");
    u(this, "config");
    this.guardianSetIndex = e, this.lastLamports = t, this.config = n;
  }
  static deserialize(e) {
    if (e.length != 24)
      throw new Error("data.length != 24");
    const t = e.readUInt32LE(0), n = e.readBigUInt64LE(4), s = D.deserialize(e.subarray(12));
    return new G(t, n, s);
  }
}
function O(r, e) {
  return b([d.Buffer.from("Sequence"), new p(r).toBytes()], e);
}
async function fe(r, e, t, n) {
  return r.getAccountInfo(O(e, t), n).then((s) => N.deserialize(z(s)));
}
class N {
  constructor(e, t, n) {
    u(this, "sequence");
    u(this, "bump");
    u(this, "emitterType");
    this.sequence = e, this.bump = t, this.emitterType = n;
  }
  static deserialize(e) {
    if (e.length !== 8 && e.length !== 10)
      throw new Error("data.length != 8 or data.length != 10");
    let t, n;
    const s = e.readBigUInt64LE(0);
    return e.length === 10 && (t = e[8], n = e[9]), new N(s, t, n);
  }
  value() {
    return this.sequence;
  }
}
function H(r) {
  return b([d.Buffer.from("emitter")], r);
}
function J(r, e) {
  const t = H(r);
  return {
    emitter: t,
    sequence: O(t, e)
  };
}
async function je(r, e, t, n) {
  return fe(r, H(e), t, n);
}
function C(r) {
  return b([d.Buffer.from("fee_collector")], r);
}
const se = 65, P = 20;
function He(r, e, t) {
  return new Ce({
    keys: [],
    programId: _e.programId,
    data: Je.serialize(r, e, t)
  });
}
class Je {
  // https://docs.solana.com/developing/runtime-facilities/programs#secp256k1-program
  //
  // struct Secp256k1SignatureOffsets {
  //     secp_signature_key_offset: u16,        // offset to [signature,recovery_id,etherum_address] of 64+1+20 bytes
  //     secp_signature_instruction_index: u8,  // instruction index to find data
  //     secp_pubkey_offset: u16,               // offset to [signature,recovery_id] of 64+1 bytes
  //     secp_signature_instruction_index: u8,  // instruction index to find data
  //     secp_message_data_offset: u16,         // offset to start of message data
  //     secp_message_data_size: u16,           // size of message data
  //     secp_message_instruction_index: u8,    // index of instruction data to get message data
  // }
  //
  // Pseudo code of the operation:
  //
  // process_instruction() {
  //     for i in 0..count {
  //         // i'th index values referenced:
  //         instructions = &transaction.message().instructions
  //         signature = instructions[secp_signature_instruction_index].data[secp_signature_offset..secp_signature_offset + 64]
  //         recovery_id = instructions[secp_signature_instruction_index].data[secp_signature_offset + 64]
  //         ref_eth_pubkey = instructions[secp_pubkey_instruction_index].data[secp_pubkey_offset..secp_pubkey_offset + 32]
  //         message_hash = keccak256(instructions[secp_message_instruction_index].data[secp_message_data_offset..secp_message_data_offset + secp_message_data_size])
  //         pubkey = ecrecover(signature, recovery_id, message_hash)
  //         eth_pubkey = keccak256(pubkey[1..])[12..]
  //         if eth_pubkey != ref_eth_pubkey {
  //             return Error
  //         }
  //     }
  //     return Success
  //   }
  /**
   * Serialize multiple signatures, ethereum public keys and message as Secp256k1 instruction data.
   *
   * @param {Buffer[]} signatures - 65-byte signatures (64 + 1 recovery id)
   * @param {Buffer[]} keys - ethereum public keys
   * @param {Buffer} message - 32-byte hash
   * @returns serialized Secp256k1 instruction data
   */
  static serialize(e, t, n) {
    if (e.length == 0)
      throw Error("signatures.length == 0");
    if (e.length != t.length)
      throw Error("signatures.length != keys.length");
    if (n.length != 32)
      throw Error("message.length != 32");
    const s = e.length, a = 11, i = 1 + s * a, o = se + P, c = i + s * o, f = 32, g = d.Buffer.alloc(c + f);
    g.writeUInt8(s, 0), g.write(n.toString("hex"), c, "hex");
    for (let l = 0; l < s; ++l) {
      const y = e.at(l);
      if ((y == null ? void 0 : y.length) != se)
        throw Error(`signatures[${l}].length != 65`);
      const h = t.at(l);
      if ((h == null ? void 0 : h.length) != P)
        throw Error(`keys[${l}].length != 20`);
      const I = i + o * l, _ = I + 65;
      g.writeUInt16LE(I, 1 + l * a), g.writeUInt8(0, 3 + l * a), g.writeUInt16LE(_, 4 + l * a), g.writeUInt8(0, 6 + l * a), g.writeUInt16LE(c, 7 + l * a), g.writeUInt16LE(f, 9 + l * a), g.writeUInt8(0, 10 + l * a), g.write(y.toString("hex"), I, "hex"), g.write(h.toString("hex"), _, "hex");
    }
    return g;
  }
}
function x(r, e) {
  return b([
    d.Buffer.from("GuardianSet"),
    (() => {
      const t = d.Buffer.alloc(4);
      return t.writeUInt32BE(e), t;
    })()
  ], r);
}
async function W(r, e, t, n) {
  return r.getAccountInfo(x(e, t), n).then((s) => R.deserialize(z(s)));
}
class R {
  constructor(e, t, n, s) {
    u(this, "index");
    u(this, "keys");
    u(this, "creationTime");
    u(this, "expirationTime");
    this.index = e, this.keys = t, this.creationTime = n, this.expirationTime = s;
  }
  static deserialize(e) {
    const t = e.readUInt32LE(0), n = e.readUInt32LE(4), s = 8 + n * P, a = e.readUInt32LE(s), i = e.readUInt32LE(4 + s), o = [];
    for (let c = 0; c < n; ++c) {
      const f = 8 + c * P;
      o.push(e.subarray(f, f + P));
    }
    return new R(t, o, a, i);
  }
}
function E(r, e) {
  return b([d.Buffer.from("PostedVAA"), e], r);
}
async function We(r, e, t) {
  return r.getAccountInfo(new p(e), t).then((n) => $.deserialize(z(n)));
}
class $ {
  constructor(e, t, n) {
    u(this, "signatures");
    u(this, "hash");
    u(this, "guardianSetIndex");
    this.signatures = e, this.hash = t, this.guardianSetIndex = n;
  }
  static deserialize(e) {
    const t = e.readUInt32LE(0), n = [...e.subarray(4, 4 + t)].map((o) => o != 0), s = 4 + t, a = e.subarray(s, s + 32), i = e.readUInt32LE(s + 32);
    return new $(n, a, i);
  }
}
function me(r) {
  return b([d.Buffer.from("upgrade")], r);
}
function le(r, e, t) {
  return M.transfer({
    fromPubkey: new p(e),
    toPubkey: C(r),
    lamports: t
  });
}
class Xe {
  constructor(e) {
    u(this, "idl");
    this.idl = e;
  }
  async encode(e, t) {
    switch (e) {
      default:
        throw new Error(`Invalid account name: ${e}`);
    }
  }
  decode(e, t) {
    return this.decodeUnchecked(e, t);
  }
  decodeUnchecked(e, t) {
    switch (e) {
      default:
        throw new Error(`Invalid account name: ${e}`);
    }
  }
  memcmp(e, t) {
    switch (e) {
      case "postVaa":
        return {
          dataSize: 56
          // + 4 + payload.length
        };
      default:
        throw new Error(`Invalid account name: ${e}`);
    }
  }
  size(e) {
    return ue(this.idl, e) ?? 0;
  }
}
class Qe {
  constructor(e) {
  }
  decode(e) {
    throw new Error("Wormhole program does not have events");
  }
}
class B {
  static fieldLayout(e, t) {
    const n = e.name !== void 0 ? k(e.name) : void 0;
    switch (e.type) {
      case "bool":
        return m.bool(n);
      case "u8":
        return m.u8(n);
      case "i8":
        return m.i8(n);
      case "u16":
        return m.u16(n);
      case "i16":
        return m.i16(n);
      case "u32":
        return m.u32(n);
      case "i32":
        return m.i32(n);
      case "f32":
        return m.f32(n);
      case "u64":
        return m.u64(n);
      case "i64":
        return m.i64(n);
      case "f64":
        return m.f64(n);
      case "u128":
        return m.u128(n);
      case "i128":
        return m.i128(n);
      case "u256":
        return m.u256(n);
      case "i256":
        return m.i256(n);
      case "bytes":
        return m.vecU8(n);
      case "string":
        return m.str(n);
      case "publicKey":
        return m.publicKey(n);
      default: {
        if ("vec" in e.type)
          return m.vec(B.fieldLayout({
            name: void 0,
            type: e.type.vec
          }, t), n);
        if ("option" in e.type)
          return m.option(B.fieldLayout({
            name: void 0,
            type: e.type.option
          }, t), n);
        if ("array" in e.type) {
          let s = e.type.array[0], a = e.type.array[1], i = B.fieldLayout({
            name: void 0,
            type: s
          }, t);
          return m.array(i, a, n);
        } else
          throw new Error(`Not yet implemented: ${e}`);
      }
    }
  }
}
class X {
  constructor(e) {
    u(this, "ixLayout");
    this.ixLayout = X.parseIxLayout(e);
  }
  static parseIxLayout(e) {
    const n = (e.instructions ? e.instructions : []).map((s) => {
      let a = s.args.map((o) => B.fieldLayout(o, Array.from([...e.accounts ?? [], ...e.types ?? []])));
      const i = k(s.name);
      return [i, m.struct(a, i)];
    }).concat(e.instructions.map((s) => {
      let a = s.args.map((o) => B.fieldLayout(o, Array.from([...e.accounts ?? [], ...e.types ?? []])));
      const i = k(s.name);
      return [i, m.struct(a, i)];
    }));
    return new Map(n);
  }
  encode(e, t) {
    const n = d.Buffer.alloc(1e3), s = k(e), a = this.ixLayout.get(s);
    if (!a)
      throw new Error(`Unknown method: ${s}`);
    const i = a.encode(t, n), o = n.slice(0, i);
    return Ze(F[$e(s)], o);
  }
  encodeState(e, t) {
    throw new Error("Wormhole program does not have state");
  }
  decode(e, t = "hex") {
    var o;
    typeof e == "string" && (e = t === "hex" ? d.Buffer.from(e, "hex") : ke.decode(e));
    let n = d.Buffer.from(e.slice(0, 1)).readInt8(), s = d.Buffer.from(e.slice(1)), a = k(F[n] ?? "");
    return this.ixLayout.get(a) ? { data: (o = this.ixLayout.get(a)) == null ? void 0 : o.decode(s), name: a } : null;
  }
}
var F;
(function(r) {
  r[r.Initialize = 0] = "Initialize", r[r.PostMessage = 1] = "PostMessage", r[r.PostVaa = 2] = "PostVaa", r[r.SetFees = 3] = "SetFees", r[r.TransferFees = 4] = "TransferFees", r[r.UpgradeContract = 5] = "UpgradeContract", r[r.UpgradeGuardianSet = 6] = "UpgradeGuardianSet", r[r.VerifySignatures = 7] = "VerifySignatures", r[r.PostMessageUnreliable = 8] = "PostMessageUnreliable";
})(F || (F = {}));
function Ze(r, e) {
  const t = d.Buffer.alloc(1 + (e === void 0 ? 0 : e.length));
  return t.writeUInt8(r, 0), e !== void 0 && t.write(e.toString("hex"), 1, "hex"), t;
}
class et {
  constructor(e) {
  }
  encode(e, t) {
    throw new Error("Wormhole program does not have state");
  }
  decode(e) {
    throw new Error("Wormhole program does not have state");
  }
}
class tt {
  constructor(e) {
  }
  encode(e, t) {
    throw new Error("Wormhole program does not have user-defined types");
  }
  decode(e, t) {
    throw new Error("Wormhole program does not have user-defined types");
  }
}
class nt {
  constructor(e) {
    u(this, "instruction");
    u(this, "accounts");
    u(this, "state");
    u(this, "events");
    u(this, "types");
    this.instruction = new X(e), this.accounts = new Xe(e), this.state = new et(e), this.events = new Qe(e), this.types = new tt(e);
  }
}
const Q = {
  version: "0.1.0",
  name: "wormhole",
  instructions: [
    {
      name: "initialize",
      accounts: [
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "guardianSet",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "feeCollector",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "clock",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "guardianSetExpirationTime",
          type: "u32"
        },
        {
          name: "fee",
          type: "u64"
        },
        {
          name: "initialGuardians",
          type: {
            vec: {
              array: ["u8", 20]
            }
          }
        }
      ]
    },
    {
      name: "postMessage",
      accounts: [
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "message",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "emitter",
          isMut: !1,
          isSigner: !0
        },
        {
          name: "sequence",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "feeCollector",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "clock",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "nonce",
          type: "u32"
        },
        {
          name: "payload",
          type: "bytes"
        },
        {
          name: "consistencyLevel",
          type: "u8"
        }
      ]
    },
    {
      name: "postVaa",
      accounts: [
        {
          name: "guardianSet",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "bridge",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "signatureSet",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "vaa",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "clock",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "version",
          type: "u8"
        },
        {
          name: "guardianSetIndex",
          type: "u32"
        },
        {
          name: "timestamp",
          type: "u32"
        },
        {
          name: "nonce",
          type: "u32"
        },
        {
          name: "emitterChain",
          type: "u16"
        },
        {
          name: "emitterAddress",
          type: {
            array: ["u8", 32]
          }
        },
        {
          name: "sequence",
          type: "u64"
        },
        {
          name: "consistencyLevel",
          type: "u8"
        },
        {
          name: "payload",
          type: "bytes"
        }
      ]
    },
    {
      name: "setFees",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "vaa",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "claim",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: []
    },
    {
      name: "transferFees",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "vaa",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "claim",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "feeCollector",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "recipient",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: []
    },
    {
      name: "upgradeContract",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "vaa",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "claim",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "upgradeAuthority",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "spill",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "implementation",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "programData",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "wormholeProgram",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "clock",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "bpfLoaderUpgradeable",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: []
    },
    {
      name: "upgradeGuardianSet",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "vaa",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "claim",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "guardianSetOld",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "guardianSetNew",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: []
    },
    {
      name: "verifySignatures",
      accounts: [
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "guardianSet",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "signatureSet",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "instructions",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "signatureStatus",
          type: {
            array: ["i8", 19]
          }
        }
      ]
    },
    {
      name: "postMessageUnreliable",
      accounts: [
        {
          name: "bridge",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "message",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "emitter",
          isMut: !1,
          isSigner: !0
        },
        {
          name: "sequence",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "payer",
          isMut: !0,
          isSigner: !0
        },
        {
          name: "feeCollector",
          isMut: !0,
          isSigner: !1
        },
        {
          name: "clock",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "rent",
          isMut: !1,
          isSigner: !1
        },
        {
          name: "systemProgram",
          isMut: !1,
          isSigner: !1
        }
      ],
      args: [
        {
          name: "nonce",
          type: "u32"
        },
        {
          name: "payload",
          type: "bytes"
        },
        {
          name: "consistencyLevel",
          type: "u8"
        }
      ]
    }
  ],
  accounts: [
    {
      name: "PostedMessage",
      type: {
        kind: "struct",
        fields: [
          {
            name: "vaaVersion",
            type: "u8"
          },
          {
            name: "consistencyLevel",
            type: "u8"
          },
          {
            name: "vaaTime",
            type: "u32"
          },
          {
            name: "vaaSignatureAccount",
            type: "publicKey"
          },
          {
            name: "submissionTime",
            type: "u32"
          },
          {
            name: "nonce",
            type: "u32"
          },
          {
            name: "sequence",
            type: "u64"
          },
          {
            name: "emitterChain",
            type: "u16"
          },
          {
            name: "emitterAddress",
            type: {
              array: ["u8", 32]
            }
          },
          {
            name: "payload",
            type: "bytes"
          }
        ]
      }
    },
    {
      name: "PostedVAA",
      type: {
        kind: "struct",
        fields: [
          {
            name: "vaaVersion",
            type: "u8"
          },
          {
            name: "consistencyLevel",
            type: "u8"
          },
          {
            name: "vaaTime",
            type: "u32"
          },
          {
            name: "vaaSignatureAccount",
            type: "publicKey"
          },
          {
            name: "submissionTime",
            type: "u32"
          },
          {
            name: "nonce",
            type: "u32"
          },
          {
            name: "sequence",
            type: "u64"
          },
          {
            name: "emitterChain",
            type: "u16"
          },
          {
            name: "emitterAddress",
            type: {
              array: ["u8", 32]
            }
          },
          {
            name: "payload",
            type: "bytes"
          }
        ]
      }
    }
  ]
};
function pe(r, e) {
  return new qe(Q, new p(r), e === void 0 ? { connection: null } : e, ye());
}
function w(r, e) {
  return pe(r, Fe(e));
}
function ye() {
  return new nt(Q);
}
function rt(r, e, t, n) {
  const s = w(e, r).methods.setFees();
  return s._ixFn(...s._args, {
    accounts: he(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function he(r, e, t) {
  return {
    payer: new p(e),
    bridge: S(r),
    vaa: E(r, d.Buffer.from(t.hash)),
    claim: T(r, t.emitterAddress.toString(), L(t.emitterChain), t.sequence),
    systemProgram: M.programId
  };
}
function st(r, e, t, n, s) {
  const a = w(e, r).methods.transferFees();
  return a._ixFn(...a._args, {
    accounts: Se(e, t, n, s),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Se(r, e, t, n) {
  return {
    payer: new p(e),
    bridge: S(r),
    vaa: E(r, d.Buffer.from(n.hash)),
    claim: T(r, n.emitterAddress.toString(), L(n.emitterChain), n.sequence),
    feeCollector: C(r),
    recipient: new p(t),
    rent: U,
    systemProgram: M.programId
  };
}
function at(r, e, t, n) {
  const s = w(e, r).methods.upgradeGuardianSet();
  return s._ixFn(...s._args, {
    accounts: we(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function we(r, e, t) {
  return {
    payer: new p(e),
    bridge: S(r),
    vaa: E(r, d.Buffer.from(t.hash)),
    claim: T(r, t.emitterAddress.toString(), L(t.emitterChain), t.sequence),
    guardianSetOld: x(r, t.guardianSet),
    guardianSetNew: x(r, t.guardianSet + 1),
    systemProgram: M.programId
  };
}
function it(r, e, t, n) {
  const s = w(e, r).methods.upgradeContract();
  return s._ixFn(...s._args, {
    accounts: Me(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Me(r, e, t, n) {
  const { newContract: s } = t.payload.actionArgs;
  return {
    payer: new p(e),
    bridge: S(r),
    vaa: E(r, d.Buffer.from(t.hash)),
    claim: T(r, t.emitterAddress.toString(), L(t.emitterChain), t.sequence),
    upgradeAuthority: me(r),
    spill: new p(n === void 0 ? e : n),
    implementation: new q(s).unwrap(),
    programData: Ne(r),
    wormholeProgram: new p(r),
    rent: U,
    clock: V,
    bpfLoaderUpgradeable: oe,
    systemProgram: M.programId
  };
}
function ot(r, e, t, n, s, a) {
  const i = w(e, r).methods.initialize(n, new ie(s.toString()), [
    ...a.map((o) => [...new Uint8Array(o)])
  ]);
  return i._ixFn(...i._args, {
    accounts: be(e, t),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function be(r, e) {
  return {
    bridge: S(r),
    guardianSet: x(r, 0),
    feeCollector: C(r),
    payer: new p(e),
    clock: V,
    rent: U,
    systemProgram: M.programId
  };
}
function Ie(r, e, t, n, s, a, i) {
  const o = w(e, r).methods.postMessage(a, d.Buffer.from(s), i);
  return o._ixFn(...o._args, {
    accounts: Z(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Z(r, e, t, n) {
  let s;
  return n ? { emitter: n, sequence: s } = J(n, r) : (n = e, s = O(n, r)), {
    bridge: S(r),
    message: new p(t),
    emitter: new p(n),
    sequence: s,
    payer: new p(e),
    feeCollector: C(r),
    clock: V,
    rent: U,
    systemProgram: M.programId
  };
}
function Ae(r, e, t, n, s) {
  const a = w(e, r).methods.postVaa(
    1,
    // TODO: hardcoded VAA version
    n.guardianSet,
    n.timestamp,
    n.nonce,
    L(n.emitterChain),
    [...n.emitterAddress.toUint8Array()],
    new ie(n.sequence.toString()),
    n.consistencyLevel,
    // Note: This _must_ be a Buffer, a Uint8Array does not work
    d.Buffer.from(Pe(n.payloadLiteral, n.payload))
  );
  return a._ixFn(...a._args, {
    accounts: xe(e, t, s, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function xe(r, e, t, n) {
  return {
    guardianSet: x(r, n.guardianSet),
    bridge: S(r),
    signatureSet: new p(t),
    vaa: E(r, d.Buffer.from(n.hash)),
    payer: new p(e),
    clock: V,
    rent: U,
    systemProgram: M.programId
  };
}
const ut = 19;
async function Ee(r, e, t, n, s, a) {
  const i = n.guardianSet, o = await W(r, e, i, a), c = n.signatures, f = o.keys, g = 7, l = [];
  for (let y = 0; y < Math.ceil(c.length / g); ++y) {
    const h = y * g, I = Math.min(c.length, (y + 1) * g), _ = new Array(ut).fill(-1), ee = [], te = [];
    for (let K = 0; K < I - h; ++K) {
      const Y = c.at(K + h);
      ee.push(d.Buffer.from(Y.signature.encode())), te.push(f.at(Y.guardianIndex)), _[Y.guardianIndex] = K;
    }
    l.push(He(ee, te, d.Buffer.from(n.hash))), l.push(ct(r, e, t, n, s, _));
  }
  return l;
}
function ct(r, e, t, n, s, a) {
  const i = w(e, r).methods.verifySignatures(a);
  return i._ixFn(...i._args, {
    accounts: Be(e, t, s, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Be(r, e, t, n) {
  return {
    payer: new p(e),
    guardianSet: x(r, n.guardianSet),
    signatureSet: new p(t),
    instructions: ve,
    rent: U,
    systemProgram: M.programId
  };
}
function gt(r, e) {
  const { emitter: t, sequence: n } = J(r, e);
  return {
    wormholeBridge: S(e),
    wormholeEmitter: t,
    wormholeSequence: n,
    wormholeFeeCollector: C(e)
  };
}
function dt(r, e, t, n) {
  const s = Z(e, t, n, r);
  return {
    payer: s.payer,
    wormholeBridge: s.bridge,
    wormholeMessage: s.message,
    wormholeEmitter: s.emitter,
    wormholeSequence: s.sequence,
    wormholeFeeCollector: s.feeCollector,
    clock: s.clock,
    rent: s.rent,
    systemProgram: s.systemProgram
  };
}
const ft = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  BridgeConfig: D,
  BridgeData: G,
  GuardianSetData: R,
  SequenceTracker: N,
  SignatureSetData: $,
  coder: ye,
  createBridgeFeeTransferInstruction: le,
  createInitializeInstruction: ot,
  createPostMessageInstruction: Ie,
  createPostVaaInstruction: Ae,
  createReadOnlyWormholeProgramInterface: w,
  createSetFeesInstruction: rt,
  createTransferFeesInstruction: st,
  createUpgradeContractInstruction: it,
  createUpgradeGuardianSetInstruction: at,
  createVerifySignaturesInstructions: Ee,
  createWormholeProgramInterface: pe,
  deriveClaimKey: T,
  deriveEmitterSequenceKey: O,
  deriveFeeCollectorKey: C,
  deriveGuardianSetKey: x,
  derivePostedVaaKey: E,
  deriveUpgradeAuthorityKey: me,
  deriveWormholeBridgeDataKey: S,
  deriveWormholeEmitterKey: H,
  getClaim: Ye,
  getEmitterKeys: J,
  getGuardianSet: W,
  getInitializeAccounts: be,
  getPostMessageAccounts: Z,
  getPostMessageCpiAccounts: dt,
  getPostVaaAccounts: xe,
  getProgramSequenceTracker: je,
  getSequenceTracker: fe,
  getSetFeesAccounts: he,
  getSignatureSetData: We,
  getTransferFeesAccounts: Se,
  getUpgradeContractAccounts: Me,
  getUpgradeGuardianSetAccounts: we,
  getVerifySignatureAccounts: Be,
  getWormholeBridgeData: de,
  getWormholeDerivedAccounts: gt
}, Symbol.toStringTag, { value: "Module" })), ae = "Program log: Sequence: ";
class v {
  constructor(e, t, n, s) {
    u(this, "network");
    u(this, "chain");
    u(this, "connection");
    u(this, "contracts");
    u(this, "chainId");
    u(this, "coreBridge");
    u(this, "address");
    u(this, "bridgeData");
    this.network = e, this.chain = t, this.connection = n, this.contracts = s, this.chainId = L(t);
    const a = s.coreBridge;
    if (!a)
      throw new Error(`CoreBridge contract Address for chain ${t} not found`);
    this.address = a, this.coreBridge = w(a, n);
  }
  async getGuardianSet(e) {
    const t = await W(this.connection, this.coreBridge.programId, e);
    return {
      index: t.index,
      keys: t.keys.map((n) => n.toString("hex")),
      expiry: BigInt(t.expirationTime)
    };
  }
  static async fromRpc(e, t) {
    const [n, s] = await Ve.chainFromRpc(e), a = t[s];
    if (a.network !== n)
      throw new Error(`Network mismatch for chain ${s}: ${a.network} != ${n}`);
    return new v(n, s, e, t[s].contracts);
  }
  async ensureBridgeConfig() {
    this.bridgeData || (this.bridgeData = await de(this.connection, this.coreBridge.programId));
  }
  async getMessageFee() {
    return await this.ensureBridgeConfig(), this.bridgeData.config.fee;
  }
  async getGuardianSetIndex() {
    return await this.ensureBridgeConfig(), this.bridgeData.guardianSetIndex;
  }
  async *publishMessage(e, t, n, s) {
    const a = re.generate(), i = new q(e).unwrap(), o = Ie(this.connection, this.coreBridge.programId, i, a.publicKey, t, n, s), c = await this.getMessageFee(), f = le(this.coreBridge.programId, i, c), g = new j();
    g.feePayer = i, g.add(f, o), yield this.createUnsignedTx({ transaction: g, signers: [a] }, "Core.PublishMessage");
  }
  async *verifyMessage(e, t) {
    yield* this.postVaa(e, t);
  }
  async *postVaa(e, t) {
    const n = E(this.coreBridge.programId, d.Buffer.from(t.hash));
    if (await this.connection.getAccountInfo(n))
      return;
    const a = new q(e).unwrap(), i = re.generate(), o = await Ee(this.connection, this.coreBridge.programId, a, t, i.publicKey);
    for (let f = 0; f < o.length; f += 2) {
      const g = new j().add(...o.slice(f, f + 2));
      g.feePayer = a, yield this.createUnsignedTx({ transaction: g, signers: [i] }, "Core.VerifySignature", !0);
    }
    const c = new j().add(Ae(this.connection, this.coreBridge.programId, a, t, i.publicKey));
    c.feePayer = a, yield this.createUnsignedTx({ transaction: c }, "Core.PostVAA");
  }
  static parseSequenceFromLog(e, t) {
    var c, f, g, l;
    const { meta: n, transaction: { message: s } } = t;
    if (!((c = n == null ? void 0 : n.innerInstructions) != null && c.length))
      return [];
    const a = s.staticAccountKeys;
    if (a.filter((y) => y.toString() === e).length === 0)
      return [];
    const i = (l = (g = (f = n == null ? void 0 : n.logMessages) == null ? void 0 : f.filter((y) => y.startsWith(ae))) == null ? void 0 : g[0]) == null ? void 0 : l.replace(ae, "");
    if (!i)
      return [];
    const o = [];
    for (const y of n == null ? void 0 : n.innerInstructions) {
      const h = y.instructions;
      o.push(...h.filter((I) => I.programIdIndex in a && a[I.programIdIndex].toString() === e));
    }
    return o.length < 1 ? [] : a.length < 3 ? [] : o.map((y) => [new q(a[y.accounts[2]]).toUniversalAddress(), BigInt(i)]).filter((y) => y !== null);
  }
  async getMessageAccountKeys(e) {
    let t;
    if (typeof e.transaction.message.version != "string")
      if (e.meta.loadedAddresses)
        t = e.transaction.message.getAccountKeys({
          accountKeysFromLookups: e.meta.loadedAddresses
        });
      else {
        const n = await Promise.all(e.transaction.message.addressTableLookups.map(async (s) => {
          const a = await this.connection.getAddressLookupTable(s.accountKey);
          if (!a || !a.value)
            throw new Error("Could not resolve lookup table: " + s.accountKey.toBase58());
          return a.value;
        }));
        t = e.transaction.message.getAccountKeys({
          addressLookupTableAccounts: n
        });
      }
    else
      t = e.transaction.message.getAccountKeys();
    return t;
  }
  async findInstructions(e, t) {
    var c;
    const { meta: n, transaction: { message: s } } = t, a = this.coreBridge.programId, i = (c = n.innerInstructions) == null ? void 0 : c.flatMap((f) => f.instructions.filter(
      // find the instructions where the programId equals the Wormhole ProgramId
      (g) => a.toString() === e.get(g.programIdIndex).toString()
    )).map((f) => ({
      programIdIndex: f.programIdIndex,
      accountKeyIndexes: f.accounts
    })), o = s.compiledInstructions.filter((f) => a.toString() === e.get(f.programIdIndex).toString());
    return [...i, ...o];
  }
  async parsePostMessageAccount(e) {
    const t = await this.connection.getAccountInfo(e);
    if (!(t != null && t.data))
      throw new Error("No data found in message account");
    const { timestamp: n, emitterAddress: s, emitterChain: a, consistencyLevel: i, sequence: o, nonce: c, payload: f } = ge(new Uint8Array(t == null ? void 0 : t.data));
    return Ge("Uint8Array", {
      guardianSet: await this.getGuardianSetIndex(),
      emitterChain: ze(a),
      timestamp: n,
      emitterAddress: s,
      consistencyLevel: i,
      sequence: o,
      nonce: c,
      payload: f,
      signatures: []
    });
  }
  async parseTransaction(e) {
    const t = await this.connection.getTransaction(e, {
      maxSupportedTransactionVersion: 0
    });
    if (!t || !t.meta || !t.meta.innerInstructions)
      throw new Error("transaction not found");
    try {
      const i = v.parseSequenceFromLog(this.coreBridge.programId.toBase58(), t);
      if (i.length > 0) {
        const [o, c] = i[0];
        return [
          {
            chain: this.chain,
            emitter: o,
            sequence: c
          }
        ];
      }
    } catch {
    }
    const n = await this.getMessageAccountKeys(t), s = await this.findInstructions(n, t);
    if (!s || s.length === 0)
      throw new Error("no bridge messages found");
    const a = s.map(async (i) => {
      const o = n.get(i.accountKeyIndexes[1]), c = await this.parsePostMessageAccount(o);
      return {
        chain: c.emitterChain,
        emitter: c.emitterAddress,
        sequence: c.sequence
      };
    });
    return await Promise.all(a);
  }
  async parseMessages(e) {
    const t = await this.connection.getTransaction(e, {
      maxSupportedTransactionVersion: 0
    });
    if (!t || !t.meta || !t.meta.innerInstructions)
      throw new Error("transaction not found");
    const n = await this.getMessageAccountKeys(t), s = await this.findInstructions(n, t);
    if (!s || s.length === 0)
      throw new Error("no bridge messages found");
    const a = s.map(async (i) => {
      const o = n.get(i.accountKeyIndexes[1]);
      return await this.parsePostMessageAccount(o);
    });
    return await Promise.all(a);
  }
  createUnsignedTx(e, t, n = !1) {
    return new De(e, this.network, this.chain, t, n);
  }
}
Oe(Ke, "WormholeCore", v);
const Mt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  IDL: Q,
  SolanaWormholeCore: v,
  deserializePostMessage: ge,
  postMessageLayout: ce,
  utils: ft
}, Symbol.toStringTag, { value: "Module" }));
export {
  oe as B,
  v as S,
  C as a,
  je as b,
  S as c,
  E as d,
  H as e,
  O as f,
  gt as g,
  T as h,
  ue as i,
  Z as j,
  Ne as k,
  me as l,
  dt as m,
  Ye as n,
  le as o,
  Mt as p
};
