import { ar as y, t as l, ab as g, o as D, as as x, p as K, F as S, at as U, au as _, aj as o } from "./unsignedTransaction-DCDxTFq8.mjs";
import { bt as L, b2 as h, cX as b, cZ as v } from "./platform-Cil_UtAQ.mjs";
import { m as M } from "./index-Co3mm7UN.mjs";
function I(s, e) {
  return y.IntentMessage(y.fixedArray(e.length, y.u8())).serialize({
    intent: {
      scope: { [s]: !0 },
      version: { V0: !0 },
      appId: { Sui: !0 }
    },
    value: e
  }).toBytes();
}
const p = {
  ED25519: 0,
  Secp256k1: 1,
  Secp256r1: 2,
  MultiSig: 3,
  ZkLogin: 5,
  Passkey: 6
}, H = {
  ED25519: 32,
  Secp256k1: 33,
  Secp256r1: 33,
  Passkey: 33
}, A = {
  0: "ED25519",
  1: "Secp256k1",
  2: "Secp256r1",
  3: "MultiSig",
  5: "ZkLogin",
  6: "Passkey"
};
function P(s, e) {
  if (s === e) return !0;
  if (s.length !== e.length)
    return !1;
  for (let t = 0; t < s.length; t++)
    if (s[t] !== e[t])
      return !1;
  return !0;
}
class W {
  /**
   * Checks if two public keys are equal
   */
  equals(e) {
    return P(this.toRawBytes(), e.toRawBytes());
  }
  /**
   * Return the base-64 representation of the public key
   */
  toBase64() {
    return l(this.toRawBytes());
  }
  toString() {
    throw new Error(
      "`toString` is not implemented on public keys. Use `toBase64()` or `toRawBytes()` instead."
    );
  }
  /**
   * Return the Sui representation of the public key encoded in
   * base-64. A Sui public key is formed by the concatenation
   * of the scheme flag with the raw bytes of the public key
   */
  toSuiPublicKey() {
    const e = this.toSuiBytes();
    return l(e);
  }
  verifyWithIntent(e, t, n) {
    const r = I(n, e), i = g(r, { dkLen: 32 });
    return this.verify(i, t);
  }
  /**
   * Verifies that the signature is valid for for the provided PersonalMessage
   */
  verifyPersonalMessage(e, t) {
    return this.verifyWithIntent(
      y.vector(y.u8()).serialize(e).toBytes(),
      t,
      "PersonalMessage"
    );
  }
  /**
   * Verifies that the signature is valid for for the provided Transaction
   */
  verifyTransaction(e, t) {
    return this.verifyWithIntent(e, t, "TransactionData");
  }
  /**
   * Verifies that the public key is associated with the provided address
   */
  verifyAddress(e) {
    return this.toSuiAddress() === e;
  }
  /**
   * Returns the bytes representation of the public key
   * prefixed with the signature scheme flag
   */
  toSuiBytes() {
    const e = this.toRawBytes(), t = new Uint8Array(e.length + 1);
    return t.set([this.flag()]), t.set(e, 1), t;
  }
  /**
   * Return the Sui address associated with this Ed25519 public key
   */
  toSuiAddress() {
    return D(
      L(g(this.toSuiBytes(), { dkLen: 32 })).slice(0, x * 2)
    );
  }
}
function C(s) {
  const e = K(s), t = A[e[0]];
  switch (t) {
    case "ED25519":
    case "Secp256k1":
    case "Secp256r1":
      const n = H[t], r = e.slice(1, e.length - n), i = e.slice(1 + r.length);
      return {
        serializedSignature: s,
        signatureScheme: t,
        signature: r,
        publicKey: i,
        bytes: e
      };
    default:
      throw new Error("Unsupported signature scheme");
  }
}
function F({
  signature: s,
  signatureScheme: e,
  publicKey: t
}) {
  if (!t)
    throw new Error("`publicKey` is required");
  const n = t.toRawBytes(), r = new Uint8Array(1 + s.length + n.length);
  return r.set([p[e]]), r.set(s, 1), r.set(n, 1 + s.length), l(r);
}
const d = 32, k = "suiprivkey";
class V {
  /**
   * Sign messages with a specific intent. By combining the message bytes with the intent before hashing and signing,
   * it ensures that a signed message is tied to a specific purpose and domain separator is provided
   */
  async signWithIntent(e, t) {
    const n = I(t, e), r = g(n, { dkLen: 32 });
    return {
      signature: F({
        signature: await this.sign(r),
        signatureScheme: this.getKeyScheme(),
        publicKey: this.getPublicKey()
      }),
      bytes: l(e)
    };
  }
  /**
   * Signs provided transaction by calling `signWithIntent()` with a `TransactionData` provided as intent scope
   */
  async signTransaction(e) {
    return this.signWithIntent(e, "TransactionData");
  }
  /**
   * Signs provided personal message by calling `signWithIntent()` with a `PersonalMessage` provided as intent scope
   */
  async signPersonalMessage(e) {
    const { signature: t } = await this.signWithIntent(
      S.vector(S.u8()).serialize(e).toBytes(),
      "PersonalMessage"
    );
    return {
      bytes: l(e),
      signature: t
    };
  }
  async signAndExecuteTransaction({
    transaction: e,
    client: t
  }) {
    const n = await e.build({ client: t }), { signature: r } = await this.signTransaction(n);
    return (await t.core.executeTransaction({
      transaction: n,
      signatures: [r]
    })).transaction;
  }
  toSuiAddress() {
    return this.getPublicKey().toSuiAddress();
  }
}
class z extends V {
}
function N(s) {
  const { prefix: e, words: t } = h.decode(s);
  if (e !== k)
    throw new Error("invalid private key prefix");
  const n = new Uint8Array(h.fromWords(t)), r = n.slice(1), i = A[n[0]];
  return {
    scheme: i,
    schema: i,
    secretKey: r
  };
}
function Z(s, e) {
  if (s.length !== d)
    throw new Error("Invalid bytes length");
  const t = p[e], n = new Uint8Array(s.length + 1);
  return n.set([t]), n.set(s, 1), h.encode(k, h.toWords(n));
}
function w(s) {
  return !!new RegExp("^m\\/44'\\/784'\\/[0-9]+'\\/[0-9]+'\\/[0-9]+'+$").test(s);
}
function $(s) {
  return M(s, "");
}
function G(s) {
  return U($(s));
}
const q = "ed25519 seed", O = 2147483648, Y = new RegExp("^m(\\/[0-9]+')+$"), B = (s) => s.replace("'", ""), X = (s) => {
  const t = b.create(v, q).update(_(s)).digest(), n = t.slice(0, 32), r = t.slice(32);
  return {
    key: n,
    chainCode: r
  };
}, j = ({ key: s, chainCode: e }, t) => {
  const n = new ArrayBuffer(4);
  new DataView(n).setUint32(0, t);
  const i = new Uint8Array(1 + s.length + n.byteLength);
  i.set(new Uint8Array(1).fill(0)), i.set(s, 1), i.set(new Uint8Array(n, 0, n.byteLength), s.length + 1);
  const a = b.create(v, e).update(i).digest(), c = a.slice(0, 32), R = a.slice(32);
  return {
    key: c,
    chainCode: R
  };
}, J = (s) => Y.test(s) ? !s.split("/").slice(1).map(B).some(
  isNaN
  /* ts T_T*/
) : !1, E = (s, e, t = O) => {
  if (!J(s))
    throw new Error("Invalid derivation path");
  const { key: n, chainCode: r } = X(e);
  return s.split("/").slice(1).map(B).map((a) => parseInt(a, 10)).reduce((a, c) => j(a, c + t), {
    key: n,
    chainCode: r
  });
}, f = 32;
class T extends W {
  /**
   * Create a new Ed25519PublicKey object
   * @param value ed25519 public key as buffer or base-64 encoded string
   */
  constructor(e) {
    if (super(), typeof e == "string" ? this.data = K(e) : e instanceof Uint8Array ? this.data = e : this.data = Uint8Array.from(e), this.data.length !== f)
      throw new Error(
        `Invalid public key input. Expected ${f} bytes, got ${this.data.length}`
      );
  }
  /**
   * Checks if two Ed25519 public keys are equal
   */
  equals(e) {
    return super.equals(e);
  }
  /**
   * Return the byte array representation of the Ed25519 public key
   */
  toRawBytes() {
    return this.data;
  }
  /**
   * Return the Sui address associated with this Ed25519 public key
   */
  flag() {
    return p.ED25519;
  }
  /**
   * Verifies that the signature is valid for for the provided message
   */
  async verify(e, t) {
    let n;
    if (typeof t == "string") {
      const r = C(t);
      if (r.signatureScheme !== "ED25519")
        throw new Error("Invalid signature scheme");
      if (!P(this.toRawBytes(), r.publicKey))
        throw new Error("Signature does not match public key");
      n = r.signature;
    } else
      n = t;
    return o.verify(n, e, this.toRawBytes());
  }
}
T.SIZE = f;
const m = "m/44'/784'/0'/0'/0'";
class u extends z {
  /**
   * Create a new Ed25519 keypair instance.
   * Generate random keypair if no {@link Ed25519Keypair} is provided.
   *
   * @param keypair Ed25519 keypair
   */
  constructor(e) {
    if (super(), e)
      this.keypair = {
        publicKey: e.publicKey,
        secretKey: e.secretKey.slice(0, 32)
      };
    else {
      const t = o.utils.randomPrivateKey();
      this.keypair = {
        publicKey: o.getPublicKey(t),
        secretKey: t
      };
    }
  }
  /**
   * Get the key scheme of the keypair ED25519
   */
  getKeyScheme() {
    return "ED25519";
  }
  /**
   * Generate a new random Ed25519 keypair
   */
  static generate() {
    const e = o.utils.randomPrivateKey();
    return new u({
      publicKey: o.getPublicKey(e),
      secretKey: e
    });
  }
  /**
   * Create a Ed25519 keypair from a raw secret key byte array, also known as seed.
   * This is NOT the private scalar which is result of hashing and bit clamping of
   * the raw secret key.
   *
   * @throws error if the provided secret key is invalid and validation is not skipped.
   *
   * @param secretKey secret key as a byte array or Bech32 secret key string
   * @param options: skip secret key validation
   */
  static fromSecretKey(e, t) {
    if (typeof e == "string") {
      const i = N(e);
      if (i.schema !== "ED25519")
        throw new Error(`Expected a ED25519 keypair, got ${i.schema}`);
      return this.fromSecretKey(i.secretKey, t);
    }
    const n = e.length;
    if (n !== d)
      throw new Error(
        `Wrong secretKey size. Expected ${d} bytes, got ${n}.`
      );
    const r = {
      publicKey: o.getPublicKey(e),
      secretKey: e
    };
    if (!t || !t.skipValidation) {
      const a = new TextEncoder().encode("sui validation"), c = o.sign(a, e);
      if (!o.verify(c, a, r.publicKey))
        throw new Error("provided secretKey is invalid");
    }
    return new u(r);
  }
  /**
   * The public key for this Ed25519 keypair
   */
  getPublicKey() {
    return new T(this.keypair.publicKey);
  }
  /**
   * The Bech32 secret key string for this Ed25519 keypair
   */
  getSecretKey() {
    return Z(
      this.keypair.secretKey.slice(0, d),
      this.getKeyScheme()
    );
  }
  /**
   * Return the signature for the provided data using Ed25519.
   */
  async sign(e) {
    return o.sign(e, this.keypair.secretKey);
  }
  /**
   * Derive Ed25519 keypair from mnemonics and path. The mnemonics must be normalized
   * and validated against the english wordlist.
   *
   * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must
   * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'.
   */
  static deriveKeypair(e, t) {
    if (t == null && (t = m), !w(t))
      throw new Error("Invalid derivation path");
    const { key: n } = E(t, G(e));
    return u.fromSecretKey(n);
  }
  /**
   * Derive Ed25519 keypair from mnemonicSeed and path.
   *
   * If path is none, it will default to m/44'/784'/0'/0'/0', otherwise the path must
   * be compliant to SLIP-0010 in form m/44'/784'/{account_index}'/{change_index}'/{address_index}'.
   */
  static deriveKeypairFromSeed(e, t) {
    if (t == null && (t = m), !w(t))
      throw new Error("Invalid derivation path");
    const { key: n } = E(t, e);
    return u.fromSecretKey(n);
  }
}
export {
  u as E
};
