import { al as Le, aI as te, C as u, cO as Ue, ah as x, dp as Te, L as Ce, au as ke } from "./platform-Cil_UtAQ.mjs";
import { P as f, T as _e, aA as Be, S as h, d as E, b as F, B as K, ac as ae, aB as Pe, j as ve, K as ne, D as j, l as ze, _ as Ke } from "./unsignedTransaction-DCDxTFq8.mjs";
import { d, P as qe, c as Fe } from "./index-BU35GfG0.mjs";
import { d as S, g as v } from "./account-BVl6Reot.mjs";
import { c as Ve } from "./create-CChLkbGc.mjs";
const ie = new f("BPFLoaderUpgradeab1e11111111111111111111111");
function De(s) {
  return S([new f(s).toBuffer()], ie);
}
class Oe extends Error {
  constructor(e) {
    super(e), this.name = "IdlError";
  }
}
function oe(s, e) {
  switch (e.type.kind) {
    case "struct":
      return e.type.fields.map((t) => M(s, t.type)).reduce((t, n) => t + n, 0);
    case "enum": {
      const t = e.type.variants.map((n) => n.fields ? n.fields.map((r) => typeof r == "object" && "name" in r ? M(s, r.type) : M(s, r)).reduce((r, a) => r + a, 0) : 0);
      return Math.max(...t) + 1;
    }
    case "alias":
      return M(s, e.type.value);
  }
}
function M(s, e) {
  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 + M(s, e.option);
      if ("coption" in e)
        return 4 + M(s, e.coption);
      if ("defined" in e) {
        const t = s.types?.filter((r) => r.name === e.defined) ?? [];
        if (t.length !== 1)
          throw new Oe(`Type not found: ${JSON.stringify(e)}`);
        let n = t[0];
        return oe(s, n);
      }
      if ("array" in e) {
        let t = e.array[0], n = e.array[1];
        return M(s, t) * n;
      }
      throw new Error(`Invalid type ${JSON.stringify(e)}`);
  }
}
function _(s) {
  return s.replace(/(?:^\w|[A-Z]|\b\w)/g, function(e, t) {
    return t === 0 ? e.toLowerCase() : e.toUpperCase();
  }).replace(/[\s\-_]+/g, "");
}
function Ge(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}
const ce = [
  { name: "discriminator", binary: "bytes", size: 4 },
  { name: "consistencyLevel", binary: "uint", size: 1, endianness: "little" },
  { name: "emitterAuthority", ...te },
  { 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", ...te },
  { name: "payloadLength", binary: "uint", size: 4, endianness: "little" },
  { name: "payload", binary: "bytes" }
];
function ue(s) {
  return Le(ce, s);
}
function L(s, e, t, n) {
  const r = typeof e == "string" ? u.from(e, "hex") : u.from(e);
  if (r.length != 32)
    throw Error("address.length != 32");
  const a = u.alloc(8);
  return a.writeBigUInt64BE(typeof n == "number" ? BigInt(n) : n), S([
    r,
    (() => {
      const i = u.alloc(2);
      return i.writeUInt16BE(t), i;
    })(),
    a
  ], s);
}
async function Ne(s, e, t, n, r, a) {
  return s.getAccountInfo(L(e, t, n, r), a).then((i) => !!v(i)[0]);
}
function p(s) {
  return S([u.from("Bridge")], s);
}
async function ge(s, e, t) {
  return s.getAccountInfo(p(e), t).then((n) => D.deserialize(v(n)));
}
class V {
  guardianSetExpirationTime;
  fee;
  constructor(e, t) {
    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 V(t, n);
  }
}
class D {
  guardianSetIndex;
  lastLamports;
  config;
  constructor(e, t, n) {
    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), r = V.deserialize(e.subarray(12));
    return new D(t, n, r);
  }
}
function O(s, e) {
  return S([u.from("Sequence"), new f(s).toBytes()], e);
}
async function de(s, e, t, n) {
  return s.getAccountInfo(O(e, t), n).then((r) => G.deserialize(v(r)));
}
class G {
  sequence;
  bump;
  emitterType;
  constructor(e, t, n) {
    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 r = e.readBigUInt64LE(0);
    return e.length === 10 && (t = e[8], n = e[9]), new G(r, t, n);
  }
  value() {
    return this.sequence;
  }
}
function Y(s) {
  return S([u.from("emitter")], s);
}
function H(s, e) {
  const t = Y(s);
  return {
    emitter: t,
    sequence: O(t, e)
  };
}
async function Re(s, e, t, n) {
  return de(s, Y(e), t, n);
}
function U(s) {
  return S([u.from("fee_collector")], s);
}
const se = 65, B = 20;
function $e(s, e, t) {
  return new _e({
    keys: [],
    programId: Be.programId,
    data: je.serialize(s, 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 r = e.length, a = 11, i = 1 + r * a, c = se + B, o = i + r * c, m = 32, g = u.alloc(o + m);
    g.writeUInt8(r, 0), g.write(n.toString("hex"), o, "hex");
    for (let l = 0; l < r; ++l) {
      const w = e.at(l);
      if (w?.length != se)
        throw Error(`signatures[${l}].length != 65`);
      const T = t.at(l);
      if (T?.length != B)
        throw Error(`keys[${l}].length != 20`);
      const C = i + c * l, k = C + 65;
      g.writeUInt16LE(C, 1 + l * a), g.writeUInt8(0, 3 + l * a), g.writeUInt16LE(k, 4 + l * a), g.writeUInt8(0, 6 + l * a), g.writeUInt16LE(o, 7 + l * a), g.writeUInt16LE(m, 9 + l * a), g.writeUInt8(0, 10 + l * a), g.write(w.toString("hex"), C, "hex"), g.write(T.toString("hex"), k, "hex");
    }
    return g;
  }
}
function I(s, e) {
  return S([
    u.from("GuardianSet"),
    (() => {
      const t = u.alloc(4);
      return t.writeUInt32BE(e), t;
    })()
  ], s);
}
async function W(s, e, t, n) {
  return s.getAccountInfo(I(e, t), n).then((r) => N.deserialize(v(r)));
}
class N {
  index;
  keys;
  creationTime;
  expirationTime;
  constructor(e, t, n, r) {
    this.index = e, this.keys = t, this.creationTime = n, this.expirationTime = r;
  }
  static deserialize(e) {
    const t = e.readUInt32LE(0), n = e.readUInt32LE(4), r = 8 + n * B, a = e.readUInt32LE(r), i = e.readUInt32LE(4 + r), c = [];
    for (let o = 0; o < n; ++o) {
      const m = 8 + o * B;
      c.push(e.subarray(m, m + B));
    }
    return new N(t, c, a, i);
  }
}
function b(s, e) {
  return S([u.from("PostedVAA"), e], s);
}
async function Ye(s, e, t) {
  return s.getAccountInfo(new f(e), t).then((n) => R.deserialize(v(n)));
}
class R {
  signatures;
  hash;
  guardianSetIndex;
  constructor(e, t, n) {
    this.signatures = e, this.hash = t, this.guardianSetIndex = n;
  }
  static deserialize(e) {
    const t = e.readUInt32LE(0), n = [...e.subarray(4, 4 + t)].map((c) => c != 0), r = 4 + t, a = e.subarray(r, r + 32), i = e.readUInt32LE(r + 32);
    return new R(n, a, i);
  }
}
function me(s) {
  return S([u.from("upgrade")], s);
}
function fe(s, e, t) {
  return h.transfer({
    fromPubkey: new f(e),
    toPubkey: U(s),
    lamports: t
  });
}
class He {
  idl;
  constructor(e) {
    this.idl = e;
  }
  async encode(e, t) {
    throw new Error(`Invalid account name: ${e}`);
  }
  decode(e, t) {
    return this.decodeUnchecked(e, t);
  }
  decodeUnchecked(e, t) {
    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 oe(this.idl, e) ?? 0;
  }
}
class We {
  constructor(e) {
  }
  decode(e) {
    throw new Error("Wormhole program does not have events");
  }
}
class A {
  static fieldLayout(e, t) {
    const n = e.name !== void 0 ? _(e.name) : void 0;
    switch (e.type) {
      case "bool":
        return d.bool(n);
      case "u8":
        return d.u8(n);
      case "i8":
        return d.i8(n);
      case "u16":
        return d.u16(n);
      case "i16":
        return d.i16(n);
      case "u32":
        return d.u32(n);
      case "i32":
        return d.i32(n);
      case "f32":
        return d.f32(n);
      case "u64":
        return d.u64(n);
      case "i64":
        return d.i64(n);
      case "f64":
        return d.f64(n);
      case "u128":
        return d.u128(n);
      case "i128":
        return d.i128(n);
      case "u256":
        return d.u256(n);
      case "i256":
        return d.i256(n);
      case "bytes":
        return d.vecU8(n);
      case "string":
        return d.str(n);
      case "publicKey":
        return d.publicKey(n);
      default: {
        if ("vec" in e.type)
          return d.vec(A.fieldLayout({
            name: void 0,
            type: e.type.vec
          }, t), n);
        if ("option" in e.type)
          return d.option(A.fieldLayout({
            name: void 0,
            type: e.type.option
          }, t), n);
        if ("array" in e.type) {
          let r = e.type.array[0], a = e.type.array[1], i = A.fieldLayout({
            name: void 0,
            type: r
          }, t);
          return d.array(i, a, n);
        } else
          throw new Error(`Not yet implemented: ${e}`);
      }
    }
  }
}
class J {
  ixLayout;
  constructor(e) {
    this.ixLayout = J.parseIxLayout(e);
  }
  static parseIxLayout(e) {
    const n = (e.instructions ? e.instructions : []).map((r) => {
      let a = r.args.map((c) => A.fieldLayout(c, Array.from([...e.accounts ?? [], ...e.types ?? []])));
      const i = _(r.name);
      return [i, d.struct(a, i)];
    }).concat(e.instructions.map((r) => {
      let a = r.args.map((c) => A.fieldLayout(c, Array.from([...e.accounts ?? [], ...e.types ?? []])));
      const i = _(r.name);
      return [i, d.struct(a, i)];
    }));
    return new Map(n);
  }
  encode(e, t) {
    const n = u.alloc(1e3), r = _(e), a = this.ixLayout.get(r);
    if (!a)
      throw new Error(`Unknown method: ${r}`);
    const i = a.encode(t, n), c = n.slice(0, i);
    return Je(q[Ge(r)], c);
  }
  encodeState(e, t) {
    throw new Error("Wormhole program does not have state");
  }
  decode(e, t = "hex") {
    typeof e == "string" && (e = t === "hex" ? u.from(e, "hex") : Ue.decode(e));
    let n = u.from(e.slice(0, 1)).readInt8(), r = u.from(e.slice(1)), a = _(q[n] ?? "");
    return this.ixLayout.get(a) ? { data: this.ixLayout.get(a)?.decode(r), name: a } : null;
  }
}
var q;
(function(s) {
  s[s.Initialize = 0] = "Initialize", s[s.PostMessage = 1] = "PostMessage", s[s.PostVaa = 2] = "PostVaa", s[s.SetFees = 3] = "SetFees", s[s.TransferFees = 4] = "TransferFees", s[s.UpgradeContract = 5] = "UpgradeContract", s[s.UpgradeGuardianSet = 6] = "UpgradeGuardianSet", s[s.VerifySignatures = 7] = "VerifySignatures", s[s.PostMessageUnreliable = 8] = "PostMessageUnreliable";
})(q || (q = {}));
function Je(s, e) {
  const t = u.alloc(1 + (e === void 0 ? 0 : e.length));
  return t.writeUInt8(s, 0), e !== void 0 && t.write(e.toString("hex"), 1, "hex"), t;
}
class Qe {
  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 Xe {
  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 Ze {
  instruction;
  accounts;
  state;
  events;
  types;
  constructor(e) {
    this.instruction = new J(e), this.accounts = new He(e), this.state = new Qe(e), this.events = new We(e), this.types = new Xe(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 le(s, e) {
  return new qe(Q, new f(s), e === void 0 ? { connection: null } : e, pe());
}
function y(s, e) {
  return le(s, Fe(e));
}
function pe() {
  return new Ze(Q);
}
function et(s, e, t, n) {
  const r = y(e, s).methods.setFees();
  return r._ixFn(...r._args, {
    accounts: ye(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function ye(s, e, t) {
  return {
    payer: new f(e),
    bridge: p(s),
    vaa: b(s, u.from(t.hash)),
    claim: L(s, t.emitterAddress.toString(), x(t.emitterChain), t.sequence),
    systemProgram: h.programId
  };
}
function tt(s, e, t, n, r) {
  const a = y(e, s).methods.transferFees();
  return a._ixFn(...a._args, {
    accounts: he(e, t, n, r),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function he(s, e, t, n) {
  return {
    payer: new f(e),
    bridge: p(s),
    vaa: b(s, u.from(n.hash)),
    claim: L(s, n.emitterAddress.toString(), x(n.emitterChain), n.sequence),
    feeCollector: U(s),
    recipient: new f(t),
    rent: E,
    systemProgram: h.programId
  };
}
function nt(s, e, t, n) {
  const r = y(e, s).methods.upgradeGuardianSet();
  return r._ixFn(...r._args, {
    accounts: Se(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Se(s, e, t) {
  return {
    payer: new f(e),
    bridge: p(s),
    vaa: b(s, u.from(t.hash)),
    claim: L(s, t.emitterAddress.toString(), x(t.emitterChain), t.sequence),
    guardianSetOld: I(s, t.guardianSet),
    guardianSetNew: I(s, t.guardianSet + 1),
    systemProgram: h.programId
  };
}
function st(s, e, t, n) {
  const r = y(e, s).methods.upgradeContract();
  return r._ixFn(...r._args, {
    accounts: we(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function we(s, e, t, n) {
  const { newContract: r } = t.payload.actionArgs;
  return {
    payer: new f(e),
    bridge: p(s),
    vaa: b(s, u.from(t.hash)),
    claim: L(s, t.emitterAddress.toString(), x(t.emitterChain), t.sequence),
    upgradeAuthority: me(s),
    spill: new f(n === void 0 ? e : n),
    implementation: new K(r).unwrap(),
    programData: De(s),
    wormholeProgram: new f(s),
    rent: E,
    clock: F,
    bpfLoaderUpgradeable: ie,
    systemProgram: h.programId
  };
}
function rt(s, e, t, n, r, a) {
  const i = y(e, s).methods.initialize(n, new ae(r.toString()), [
    ...a.map((c) => [...new Uint8Array(c)])
  ]);
  return i._ixFn(...i._args, {
    accounts: Me(e, t),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Me(s, e) {
  return {
    bridge: p(s),
    guardianSet: I(s, 0),
    feeCollector: U(s),
    payer: new f(e),
    clock: F,
    rent: E,
    systemProgram: h.programId
  };
}
function Ie(s, e, t, n, r, a, i) {
  const c = y(e, s).methods.postMessage(a, u.from(r), i);
  return c._ixFn(...c._args, {
    accounts: X(e, t, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function X(s, e, t, n) {
  let r;
  return n ? { emitter: n, sequence: r } = H(n, s) : (n = e, r = O(n, s)), {
    bridge: p(s),
    message: new f(t),
    emitter: new f(n),
    sequence: r,
    payer: new f(e),
    feeCollector: U(s),
    clock: F,
    rent: E,
    systemProgram: h.programId
  };
}
function be(s, e, t, n, r) {
  const a = y(e, s).methods.postVaa(
    1,
    // TODO: hardcoded VAA version
    n.guardianSet,
    n.timestamp,
    n.nonce,
    x(n.emitterChain),
    [...n.emitterAddress.toUint8Array()],
    new ae(n.sequence.toString()),
    n.consistencyLevel,
    // Note: This _must_ be a Buffer, a Uint8Array does not work
    u.from(Te(n.payloadLiteral, n.payload))
  );
  return a._ixFn(...a._args, {
    accounts: Ae(e, t, r, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Ae(s, e, t, n) {
  return {
    guardianSet: I(s, n.guardianSet),
    bridge: p(s),
    signatureSet: new f(t),
    vaa: b(s, u.from(n.hash)),
    payer: new f(e),
    clock: F,
    rent: E,
    systemProgram: h.programId
  };
}
const at = 19;
async function xe(s, e, t, n, r, a) {
  const i = n.guardianSet, c = await W(s, e, i, a), o = n.signatures, m = c.keys, g = 7, l = [];
  for (let w = 0; w < Math.ceil(o.length / g); ++w) {
    const T = w * g, C = Math.min(o.length, (w + 1) * g), k = new Array(at).fill(-1), Z = [], ee = [];
    for (let z = 0; z < C - T; ++z) {
      const $ = o.at(z + T);
      Z.push(u.from($.signature.encode())), ee.push(m.at($.guardianIndex)), k[$.guardianIndex] = z;
    }
    l.push($e(Z, ee, u.from(n.hash))), l.push(it(s, e, t, n, r, k));
  }
  return l;
}
function it(s, e, t, n, r, a) {
  const i = y(e, s).methods.verifySignatures(a);
  return i._ixFn(...i._args, {
    accounts: Ee(e, t, r, n),
    signers: void 0,
    remainingAccounts: void 0,
    preInstructions: void 0,
    postInstructions: void 0
  });
}
function Ee(s, e, t, n) {
  return {
    payer: new f(e),
    guardianSet: I(s, n.guardianSet),
    signatureSet: new f(t),
    instructions: Pe,
    rent: E,
    systemProgram: h.programId
  };
}
function ot(s, e) {
  const { emitter: t, sequence: n } = H(s, e);
  return {
    wormholeBridge: p(e),
    wormholeEmitter: t,
    wormholeSequence: n,
    wormholeFeeCollector: U(e)
  };
}
function ct(s, e, t, n) {
  const r = X(e, t, n, s);
  return {
    payer: r.payer,
    wormholeBridge: r.bridge,
    wormholeMessage: r.message,
    wormholeEmitter: r.emitter,
    wormholeSequence: r.sequence,
    wormholeFeeCollector: r.feeCollector,
    clock: r.clock,
    rent: r.rent,
    systemProgram: r.systemProgram
  };
}
const ut = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  BridgeConfig: V,
  BridgeData: D,
  GuardianSetData: N,
  SequenceTracker: G,
  SignatureSetData: R,
  coder: pe,
  createBridgeFeeTransferInstruction: fe,
  createInitializeInstruction: rt,
  createPostMessageInstruction: Ie,
  createPostVaaInstruction: be,
  createReadOnlyWormholeProgramInterface: y,
  createSetFeesInstruction: et,
  createTransferFeesInstruction: tt,
  createUpgradeContractInstruction: st,
  createUpgradeGuardianSetInstruction: nt,
  createVerifySignaturesInstructions: xe,
  createWormholeProgramInterface: le,
  deriveClaimKey: L,
  deriveEmitterSequenceKey: O,
  deriveFeeCollectorKey: U,
  deriveGuardianSetKey: I,
  derivePostedVaaKey: b,
  deriveUpgradeAuthorityKey: me,
  deriveWormholeBridgeDataKey: p,
  deriveWormholeEmitterKey: Y,
  getClaim: Ne,
  getEmitterKeys: H,
  getGuardianSet: W,
  getInitializeAccounts: Me,
  getPostMessageAccounts: X,
  getPostMessageCpiAccounts: ct,
  getPostVaaAccounts: Ae,
  getProgramSequenceTracker: Re,
  getSequenceTracker: de,
  getSetFeesAccounts: ye,
  getSignatureSetData: Ye,
  getTransferFeesAccounts: he,
  getUpgradeContractAccounts: we,
  getUpgradeGuardianSetAccounts: Se,
  getVerifySignatureAccounts: Ee,
  getWormholeBridgeData: ge,
  getWormholeDerivedAccounts: ot
}, Symbol.toStringTag, { value: "Module" })), re = "Program log: Sequence: ";
class P {
  network;
  chain;
  connection;
  contracts;
  chainId;
  coreBridge;
  address;
  bridgeData;
  constructor(e, t, n, r) {
    this.network = e, this.chain = t, this.connection = n, this.contracts = r, this.chainId = x(t);
    const a = r.coreBridge;
    if (!a)
      throw new Error(`CoreBridge contract Address for chain ${t} not found`);
    this.address = a, this.coreBridge = y(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, r] = await ve.chainFromRpc(e), a = t[r];
    if (a.network !== n)
      throw new Error(`Network mismatch for chain ${r}: ${a.network} != ${n}`);
    return new P(n, r, e, t[r].contracts);
  }
  async ensureBridgeConfig() {
    this.bridgeData || (this.bridgeData = await ge(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, r) {
    const a = ne.generate(), i = new K(e).unwrap(), c = Ie(this.connection, this.coreBridge.programId, i, a.publicKey, t, n, r), o = await this.getMessageFee(), m = fe(this.coreBridge.programId, i, o), g = new j();
    g.feePayer = i, g.add(m, c), yield this.createUnsignedTx({ transaction: g, signers: [a] }, "Core.PublishMessage");
  }
  async *verifyMessage(e, t) {
    yield* this.postVaa(e, t);
  }
  async *postVaa(e, t) {
    const n = b(this.coreBridge.programId, u.from(t.hash));
    if (await this.connection.getAccountInfo(n))
      return;
    const a = new K(e).unwrap(), i = ne.generate(), c = await xe(this.connection, this.coreBridge.programId, a, t, i.publicKey);
    for (let m = 0; m < c.length; m += 2) {
      const g = new j().add(...c.slice(m, m + 2));
      g.feePayer = a, yield this.createUnsignedTx({ transaction: g, signers: [i] }, "Core.VerifySignature", !0);
    }
    const o = new j().add(be(this.connection, this.coreBridge.programId, a, t, i.publicKey));
    o.feePayer = a, yield this.createUnsignedTx({ transaction: o }, "Core.PostVAA");
  }
  static parseSequenceFromLog(e, t) {
    const { meta: n, transaction: { message: r } } = t;
    if (!n?.innerInstructions?.length)
      return [];
    const a = r.staticAccountKeys;
    if (a.filter((o) => o.toString() === e).length === 0)
      return [];
    const i = n?.logMessages?.filter((o) => o.startsWith(re))?.[0]?.replace(re, "");
    if (!i)
      return [];
    const c = [];
    for (const o of n?.innerInstructions) {
      const m = o.instructions;
      c.push(...m.filter((g) => g.programIdIndex in a && a[g.programIdIndex].toString() === e));
    }
    return c.length < 1 ? [] : a.length < 3 ? [] : c.map((o) => [new K(a[o.accounts[2]]).toUniversalAddress(), BigInt(i)]).filter((o) => o !== 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 (r) => {
          const a = await this.connection.getAddressLookupTable(r.accountKey);
          if (!a || !a.value)
            throw new Error("Could not resolve lookup table: " + r.accountKey.toBase58());
          return a.value;
        }));
        t = e.transaction.message.getAccountKeys({
          addressLookupTableAccounts: n
        });
      }
    else
      t = e.transaction.message.getAccountKeys();
    return t;
  }
  async findInstructions(e, t) {
    const { meta: n, transaction: { message: r } } = t, a = this.coreBridge.programId, i = n.innerInstructions?.flatMap((o) => o.instructions.filter(
      // find the instructions where the programId equals the Wormhole ProgramId
      (m) => a.toString() === e.get(m.programIdIndex).toString()
    )).map((o) => ({
      programIdIndex: o.programIdIndex,
      accountKeyIndexes: o.accounts
    })), c = r.compiledInstructions.filter((o) => a.toString() === e.get(o.programIdIndex).toString());
    return [...i, ...c];
  }
  async parsePostMessageAccount(e) {
    const t = await this.connection.getAccountInfo(e);
    if (!t?.data)
      throw new Error("No data found in message account");
    const { timestamp: n, emitterAddress: r, emitterChain: a, consistencyLevel: i, sequence: c, nonce: o, payload: m } = ue(new Uint8Array(t?.data));
    return Ve("Uint8Array", {
      guardianSet: await this.getGuardianSetIndex(),
      emitterChain: Ce(a),
      timestamp: n,
      emitterAddress: r,
      consistencyLevel: i,
      sequence: c,
      nonce: o,
      payload: m,
      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 = P.parseSequenceFromLog(this.coreBridge.programId.toBase58(), t);
      if (i.length > 0) {
        const [c, o] = i[0];
        return [
          {
            chain: this.chain,
            emitter: c,
            sequence: o
          }
        ];
      }
    } catch {
    }
    const n = await this.getMessageAccountKeys(t), r = await this.findInstructions(n, t);
    if (!r || r.length === 0)
      throw new Error("no bridge messages found");
    const a = r.map(async (i) => {
      const c = n.get(i.accountKeyIndexes[1]), o = await this.parsePostMessageAccount(c);
      return {
        chain: o.emitterChain,
        emitter: o.emitterAddress,
        sequence: o.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), r = await this.findInstructions(n, t);
    if (!r || r.length === 0)
      throw new Error("no bridge messages found");
    const a = r.map(async (i) => {
      const c = n.get(i.accountKeyIndexes[1]);
      return await this.parsePostMessageAccount(c);
    });
    return await Promise.all(a);
  }
  createUnsignedTx(e, t, n = !1) {
    return new ze(e, this.network, this.chain, t, n);
  }
}
ke(Ke, "WormholeCore", P);
const pt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  IDL: Q,
  SolanaWormholeCore: P,
  deserializePostMessage: ue,
  postMessageLayout: ce,
  utils: ut
}, Symbol.toStringTag, { value: "Module" }));
export {
  ie as B,
  P as S,
  oe as a,
  X as b,
  L as c,
  b as d,
  De as e,
  me as f,
  ot as g,
  ct as h,
  Ne as i,
  fe as j,
  U as k,
  Re as l,
  p as m,
  Y as n,
  O as o,
  pt as p
};
