var S = Object.defineProperty;
var x = (r, t, e) => t in r ? S(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
var h = (r, t, e) => x(r, typeof t != "symbol" ? t + "" : t, e);
import { e as _, b6 as I, a4 as P, b7 as A, b8 as M, b2 as y, b3 as R, u as L, b5 as b } from "./index-CjwA7HmM.mjs";
const F = 0.5, E = 1, T = 1, k = 1e9, B = 5, U = 25e4;
async function V(r, t, e) {
  const [n, i] = await _.chainFromRpc(r), g = typeof t == "string" ? I.fromSecretKey(P.decode(t)) : t;
  if (e != null && e.priorityFee && e.priorityFee.percentile && e.priorityFee.percentile > 1)
    throw new Error("priorityFeePercentile must be a number between 0 and 1");
  return new C(r, i, g, (e == null ? void 0 : e.debug) ?? !1, (e == null ? void 0 : e.priorityFee) ?? {}, (e == null ? void 0 : e.retries) ?? B, e == null ? void 0 : e.sendOpts);
}
class C {
  constructor(t, e, n, i = !1, g, l = B, u) {
    h(this, "_rpc");
    h(this, "_chain");
    h(this, "_keypair");
    h(this, "_debug");
    h(this, "_priorityFee");
    h(this, "_maxResubmits");
    h(this, "_sendOpts");
    this._rpc = t, this._chain = e, this._keypair = n, this._debug = i, this._priorityFee = g, this._maxResubmits = l, this._sendOpts = u, this._sendOpts = this._sendOpts ?? {
      preflightCommitment: this._rpc.commitment
    };
  }
  chain() {
    return this._chain;
  }
  address() {
    return this._keypair.publicKey.toBase58();
  }
  // Handles retrying a Transaction if the error is deemed to be
  // recoverable. Currently handles:
  // - Transaction expired
  // - Blockhash not found
  // - Not enough bytes (storage account not seen yet)
  retryable(t) {
    var n;
    if (t instanceof A)
      return !0;
    if (!(t instanceof M) || !t.message.includes("Transaction simulation failed"))
      return !1;
    if (t.message.includes("Blockhash not found"))
      return !0;
    const e = (n = t.logs) == null ? void 0 : n.find((i) => i.startsWith("Program log: Error: "));
    return e ? !!(e.includes("Not enough bytes") || e.includes("Unexpected length of input")) : !1;
  }
  async signAndSend(t) {
    var u;
    let { blockhash: e, lastValidBlockHeight: n } = await _.latestBlock(this._rpc);
    const i = [];
    for (const a of t) {
      const { description: c, transaction: { transaction: o, signers: s } } = a;
      this._debug && console.log(`Signing: ${c} for ${this.address()}`);
      let d;
      (u = this._priorityFee) != null && u.percentile && this._priorityFee.percentile > 0 && (d = await O(this._rpc, o, this._priorityFee.percentile, this._priorityFee.percentileMultiple, this._priorityFee.min, this._priorityFee.max)), this._debug && D(o);
      for (let m = 0; m < this._maxResubmits; m++)
        try {
          if (y(o)) {
            if (d && m === 0) {
              const p = R.decompile(o.message);
              p.instructions.push(...d), o.message = p.compileToV0Message();
            }
            o.message.recentBlockhash = e, o.sign([this._keypair, ...s ?? []]);
          } else
            d && m === 0 && o.add(...d), o.recentBlockhash = e, o.lastValidBlockHeight = n, o.partialSign(this._keypair, ...s ?? []);
          this._debug && console.log("Submitting transactions ");
          const { signature: f } = await _.sendTxWithRetry(this._rpc, o.serialize(), this._sendOpts);
          i.push(f);
          break;
        } catch (f) {
          if (m === this._maxResubmits - 1 || !this.retryable(f))
            throw f;
          this._debug && console.log(`Failed to send transaction on attempt ${m}, retrying: `, f);
          const { blockhash: p, lastValidBlockHeight: w } = await _.latestBlock(this._rpc);
          n = w, e = p;
        }
    }
    this._debug && console.log("Waiting for confirmation for: ", i);
    const l = (await Promise.all(i.map(async (a) => {
      try {
        return await this._rpc.confirmTransaction({
          signature: a,
          blockhash: e,
          lastValidBlockHeight: n
        }, this._rpc.commitment);
      } catch (c) {
        throw console.error("Failed to confirm transaction: ", c), c;
      }
    }))).filter((a) => a.value.err).map((a) => a.value.err);
    if (l.length > 0)
      throw new Error(`Failed to confirm transaction: ${l}`);
    return i;
  }
}
function D(r) {
  if (y(r)) {
    console.log(r.signatures);
    const t = r.message, e = t.getAccountKeys();
    t.compiledInstructions.forEach((n) => {
      console.log("Program", e.get(n.programIdIndex).toBase58()), console.log("Data: ", L.encode(n.data)), console.log("Keys: ", n.accountKeyIndexes.map((i) => [i, e.get(i).toBase58()]));
    });
  } else
    console.log(r.signatures), console.log(r.feePayer), r.instructions.forEach((t) => {
      console.log("Program", t.programId.toBase58()), console.log("Data: ", t.data.toString("hex")), console.log("Keys: ", t.keys.map((e) => [e, e.pubkey.toBase58()]));
    });
}
async function O(r, t, e = F, n = E, i = T, g = k) {
  const [l, u] = await Promise.all([
    K(r, t),
    W(r, t, e, n, i, g)
  ]);
  return [
    b.setComputeUnitLimit({
      units: l
    }),
    b.setComputeUnitPrice({
      microLamports: u
    })
  ];
}
async function K(r, t) {
  var n;
  let e = U;
  try {
    const i = await (y(t), r.simulateTransaction(t));
    i.value.err && console.error(`Error simulating Solana transaction: ${i.value.err}`), (n = i == null ? void 0 : i.value) != null && n.unitsConsumed && (e = Math.round(i.value.unitsConsumed * 1.2));
  } catch (i) {
    console.error(`Failed to calculate compute unit limit for Solana transaction: ${i}`);
  }
  return e;
}
async function W(r, t, e = F, n = E, i = T, g = k) {
  let l = i, u = [];
  if (y(t)) {
    const a = (await Promise.all(t.message.addressTableLookups.map((s) => r.getAddressLookupTable(s.accountKey)))).map((s) => s.value).filter((s) => s !== null), c = t.message, o = c.getAccountKeys({
      addressLookupTableAccounts: a ?? void 0
    });
    u = c.compiledInstructions.flatMap((s) => s.accountKeyIndexes).map((s) => c.isAccountWritable(s) ? o.get(s) : null).filter((s) => s !== null);
  } else
    u = t.instructions.flatMap((a) => a.keys).map((a) => a.isWritable ? a.pubkey : null).filter((a) => a !== null);
  try {
    const a = await r.getRecentPrioritizationFees({
      lockedWritableAccounts: u
    });
    if (a) {
      const c = a.map((s) => s.prioritizationFee).sort((s, d) => s - d), o = Math.ceil(c.length * e);
      if (c.length > o) {
        let s = c[o];
        n > 0 && (s *= n), l = Math.max(l, s);
      }
    }
  } catch (a) {
    console.error("Error fetching Solana recent fees", a);
  }
  return Math.min(Math.max(l, i), g);
}
export {
  W as d,
  V as g
};
