import { $ as keccak256, Bt as isHex, J as isAddress, Q as InvalidAddressError, ct as toHex, ot as numberToHex, tt as hexToBytes } from "./chain-dTUyiOxD.mjs";
import { S as utf8ToBytes, _ as rotl, a as anumber$1, c as checkOpts, d as createHasher, f as createView, g as randomBytes, h as kdfInputToBytes, i as ahash, l as clean, m as hexToBytes$1, n as abytes$1, s as bytesToHex, u as concatBytes } from "./utils-H8TC_cI3.mjs";
import { c as publicKeyToAddress, n as hashTypedData, o as hashMessage, s as hashAuthorization, t as serializeSignature } from "./serializeSignature-CZEInS9b.mjs";
import { t as serializeTransaction } from "./serializeAuthorizationList-yxAfJ36e.mjs";
import { n as sha512, r as HashMD, t as sha256 } from "./sha2-DFR_yWJu.mjs";
import { i as hmac, r as mod, t as secp256k1 } from "./secp256k1-D_nXaWtX.mjs";
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/legacy.js
/**

SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:

- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
* @module
*/
const Rho160 = /* @__PURE__ */ Uint8Array.from([
	7,
	4,
	13,
	1,
	10,
	6,
	15,
	3,
	12,
	0,
	9,
	5,
	2,
	14,
	11,
	8
]);
const Id160 = Uint8Array.from(new Array(16).fill(0).map((_, i) => i));
const Pi160 = Id160.map((i) => (9 * i + 5) % 16);
const idxLR = /* @__PURE__ */ (() => {
	const res = [[Id160], [Pi160]];
	for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));
	return res;
})();
const idxL = idxLR[0];
const idxR = idxLR[1];
const shifts160 = /* @__PURE__ */ [
	[
		11,
		14,
		15,
		12,
		5,
		8,
		7,
		9,
		11,
		13,
		14,
		15,
		6,
		7,
		9,
		8
	],
	[
		12,
		13,
		11,
		15,
		6,
		9,
		9,
		7,
		12,
		15,
		11,
		13,
		7,
		8,
		7,
		7
	],
	[
		13,
		15,
		14,
		11,
		7,
		7,
		6,
		8,
		13,
		14,
		13,
		12,
		5,
		5,
		6,
		9
	],
	[
		14,
		11,
		12,
		14,
		8,
		6,
		5,
		5,
		15,
		12,
		15,
		14,
		9,
		9,
		8,
		6
	],
	[
		15,
		12,
		13,
		13,
		9,
		5,
		8,
		6,
		14,
		11,
		12,
		11,
		8,
		6,
		5,
		5
	]
].map((i) => Uint8Array.from(i));
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
const Kl160 = /* @__PURE__ */ Uint32Array.from([
	0,
	1518500249,
	1859775393,
	2400959708,
	2840853838
]);
const Kr160 = /* @__PURE__ */ Uint32Array.from([
	1352829926,
	1548603684,
	1836072691,
	2053994217,
	0
]);
function ripemd_f(group, x, y, z) {
	if (group === 0) return x ^ y ^ z;
	if (group === 1) return x & y | ~x & z;
	if (group === 2) return (x | ~y) ^ z;
	if (group === 3) return x & z | y & ~z;
	return x ^ (y | ~z);
}
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
var RIPEMD160 = class extends HashMD {
	constructor() {
		super(64, 20, 8, true);
		this.h0 = 1732584193;
		this.h1 = -271733879;
		this.h2 = -1732584194;
		this.h3 = 271733878;
		this.h4 = -1009589776;
	}
	get() {
		const { h0, h1, h2, h3, h4 } = this;
		return [
			h0,
			h1,
			h2,
			h3,
			h4
		];
	}
	set(h0, h1, h2, h3, h4) {
		this.h0 = h0 | 0;
		this.h1 = h1 | 0;
		this.h2 = h2 | 0;
		this.h3 = h3 | 0;
		this.h4 = h4 | 0;
	}
	process(view, offset) {
		for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);
		let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
		for (let group = 0; group < 5; group++) {
			const rGroup = 4 - group;
			const hbl = Kl160[group], hbr = Kr160[group];
			const rl = idxL[group], rr = idxR[group];
			const sl = shiftsL160[group], sr = shiftsR160[group];
			for (let i = 0; i < 16; i++) {
				const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0;
				al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl;
			}
			for (let i = 0; i < 16; i++) {
				const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0;
				ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr;
			}
		}
		this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
	}
	roundClean() {
		clean(BUF_160);
	}
	destroy() {
		this.destroyed = true;
		clean(this.buffer);
		this.set(0, 0, 0, 0, 0);
	}
};
/**
* RIPEMD-160 - a legacy hash function from 1990s.
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
*/
const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());
//#endregion
//#region node_modules/.pnpm/@scure+base@1.2.6/node_modules/@scure/base/lib/esm/index.js
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function isBytes(a) {
	return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function isArrayOf(isString, arr) {
	if (!Array.isArray(arr)) return false;
	if (arr.length === 0) return true;
	if (isString) return arr.every((item) => typeof item === "string");
	else return arr.every((item) => Number.isSafeInteger(item));
}
function afn(input) {
	if (typeof input !== "function") throw new Error("function expected");
	return true;
}
function astr(label, input) {
	if (typeof input !== "string") throw new Error(`${label}: string expected`);
	return true;
}
function anumber(n) {
	if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
	if (!Array.isArray(input)) throw new Error("array expected");
}
function astrArr(label, input) {
	if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
	if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);
}
/**
* @__NO_SIDE_EFFECTS__
*/
function chain(...args) {
	const id = (a) => a;
	const wrap = (a, b) => (c) => a(b(c));
	return {
		encode: args.map((x) => x.encode).reduceRight(wrap, id),
		decode: args.map((x) => x.decode).reduce(wrap, id)
	};
}
/**
* Encodes integer radix representation to array of strings using alphabet and back.
* Could also be array of strings.
* @__NO_SIDE_EFFECTS__
*/
function alphabet(letters) {
	const lettersA = typeof letters === "string" ? letters.split("") : letters;
	const len = lettersA.length;
	astrArr("alphabet", lettersA);
	const indexes = new Map(lettersA.map((l, i) => [l, i]));
	return {
		encode: (digits) => {
			aArr(digits);
			return digits.map((i) => {
				if (!Number.isSafeInteger(i) || i < 0 || i >= len) throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
				return lettersA[i];
			});
		},
		decode: (input) => {
			aArr(input);
			return input.map((letter) => {
				astr("alphabet.decode", letter);
				const i = indexes.get(letter);
				if (i === void 0) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
				return i;
			});
		}
	};
}
/**
* @__NO_SIDE_EFFECTS__
*/
function join(separator = "") {
	astr("join", separator);
	return {
		encode: (from) => {
			astrArr("join.decode", from);
			return from.join(separator);
		},
		decode: (to) => {
			astr("join.decode", to);
			return to.split(separator);
		}
	};
}
/**
* Pad strings array so it has integer number of bits
* @__NO_SIDE_EFFECTS__
*/
function padding(bits, chr = "=") {
	anumber(bits);
	astr("padding", chr);
	return {
		encode(data) {
			astrArr("padding.encode", data);
			while (data.length * bits % 8) data.push(chr);
			return data;
		},
		decode(input) {
			astrArr("padding.decode", input);
			let end = input.length;
			if (end * bits % 8) throw new Error("padding: invalid, string should have whole number of bytes");
			for (; end > 0 && input[end - 1] === chr; end--) if ((end - 1) * bits % 8 === 0) throw new Error("padding: invalid, string has too much padding");
			return input.slice(0, end);
		}
	};
}
/**
* @__NO_SIDE_EFFECTS__
*/
function normalize$1(fn) {
	afn(fn);
	return {
		encode: (from) => from,
		decode: (to) => fn(to)
	};
}
/**
* Slow: O(n^2) time complexity
*/
function convertRadix(data, from, to) {
	if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
	if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
	aArr(data);
	if (!data.length) return [];
	let pos = 0;
	const res = [];
	const digits = Array.from(data, (d) => {
		anumber(d);
		if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);
		return d;
	});
	const dlen = digits.length;
	while (true) {
		let carry = 0;
		let done = true;
		for (let i = pos; i < dlen; i++) {
			const digit = digits[i];
			const fromCarry = from * carry;
			const digitBase = fromCarry + digit;
			if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) throw new Error("convertRadix: carry overflow");
			const div = digitBase / to;
			carry = digitBase % to;
			const rounded = Math.floor(div);
			digits[i] = rounded;
			if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) throw new Error("convertRadix: carry overflow");
			if (!done) continue;
			else if (!rounded) pos = i;
			else done = false;
		}
		res.push(carry);
		if (done) break;
	}
	for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);
	return res.reverse();
}
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
const powers = /* @__PURE__ */ (() => {
	let res = [];
	for (let i = 0; i < 40; i++) res.push(2 ** i);
	return res;
})();
/**
* Implemented with numbers, because BigInt is 5x slower
*/
function convertRadix2(data, from, to, padding) {
	aArr(data);
	if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);
	if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);
	if (/* @__PURE__ */ radix2carry(from, to) > 32) throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`);
	let carry = 0;
	let pos = 0;
	const max = powers[from];
	const mask = powers[to] - 1;
	const res = [];
	for (const n of data) {
		anumber(n);
		if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
		carry = carry << from | n;
		if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
		pos += from;
		for (; pos >= to; pos -= to) res.push((carry >> pos - to & mask) >>> 0);
		const pow = powers[pos];
		if (pow === void 0) throw new Error("invalid carry");
		carry &= pow - 1;
	}
	carry = carry << to - pos & mask;
	if (!padding && pos >= from) throw new Error("Excess padding");
	if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);
	if (padding && pos > 0) res.push(carry >>> 0);
	return res;
}
/**
* @__NO_SIDE_EFFECTS__
*/
function radix(num) {
	anumber(num);
	const _256 = 2 ** 8;
	return {
		encode: (bytes) => {
			if (!isBytes(bytes)) throw new Error("radix.encode input should be Uint8Array");
			return convertRadix(Array.from(bytes), _256, num);
		},
		decode: (digits) => {
			anumArr("radix.decode", digits);
			return Uint8Array.from(convertRadix(digits, num, _256));
		}
	};
}
/**
* If both bases are power of same number (like `2**8 <-> 2**64`),
* there is a linear algorithm. For now we have implementation for power-of-two bases only.
* @__NO_SIDE_EFFECTS__
*/
function radix2(bits, revPadding = false) {
	anumber(bits);
	if (bits <= 0 || bits > 32) throw new Error("radix2: bits should be in (0..32]");
	if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32) throw new Error("radix2: carry overflow");
	return {
		encode: (bytes) => {
			if (!isBytes(bytes)) throw new Error("radix2.encode input should be Uint8Array");
			return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
		},
		decode: (digits) => {
			anumArr("radix2.decode", digits);
			return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
		}
	};
}
function unsafeWrapper(fn) {
	afn(fn);
	return function(...args) {
		try {
			return fn.apply(null, args);
		} catch (e) {}
	};
}
function checksum(len, fn) {
	anumber(len);
	afn(fn);
	return {
		encode(data) {
			if (!isBytes(data)) throw new Error("checksum.encode: input should be Uint8Array");
			const sum = fn(data).slice(0, len);
			const res = new Uint8Array(data.length + len);
			res.set(data);
			res.set(sum, data.length);
			return res;
		},
		decode(data) {
			if (!isBytes(data)) throw new Error("checksum.decode: input should be Uint8Array");
			const payload = data.slice(0, -len);
			const oldChecksum = data.slice(-len);
			const newChecksum = fn(payload).slice(0, len);
			for (let i = 0; i < len; i++) if (newChecksum[i] !== oldChecksum[i]) throw new Error("Invalid checksum");
			return payload;
		}
	};
}
const utils = {
	alphabet,
	chain,
	checksum,
	convertRadix,
	convertRadix2,
	radix,
	radix2,
	join,
	padding
};
chain(radix2(4), alphabet("0123456789ABCDEF"), join(""));
chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join(""));
chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join(""));
chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join(""));
chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join(""));
chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize$1((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
const hasBase64Builtin = typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function";
hasBase64Builtin || chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join(""));
hasBase64Builtin || chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join(""));
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(""));
/**
* base58: base64 without ambigous characters +, /, 0, O, I, l.
* Quadratic (O(n^2)) - so, can't be used on large inputs.
* @example
* ```js
* base58.decode('01abcdef');
* // => '3UhJW'
* ```
*/
const base58 = /* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
/**
* Method, which creates base58check encoder.
* Requires function, calculating sha256.
*/
const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);
const BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join(""));
const POLYMOD_GENERATORS = [
	996825010,
	642813549,
	513874426,
	1027748829,
	705979059
];
function bech32Polymod(pre) {
	const b = pre >> 25;
	let chk = (pre & 33554431) << 5;
	for (let i = 0; i < POLYMOD_GENERATORS.length; i++) if ((b >> i & 1) === 1) chk ^= POLYMOD_GENERATORS[i];
	return chk;
}
function bechChecksum(prefix, words, encodingConst = 1) {
	const len = prefix.length;
	let chk = 1;
	for (let i = 0; i < len; i++) {
		const c = prefix.charCodeAt(i);
		if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);
		chk = bech32Polymod(chk) ^ c >> 5;
	}
	chk = bech32Polymod(chk);
	for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
	for (let v of words) chk = bech32Polymod(chk) ^ v;
	for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);
	chk ^= encodingConst;
	return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
}
/**
* @__NO_SIDE_EFFECTS__
*/
function genBech32(encoding) {
	const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
	const _words = radix2(5);
	const fromWords = _words.decode;
	const toWords = _words.encode;
	const fromWordsUnsafe = unsafeWrapper(fromWords);
	function encode(prefix, words, limit = 90) {
		astr("bech32.encode prefix", prefix);
		if (isBytes(words)) words = Array.from(words);
		anumArr("bech32.encode", words);
		const plen = prefix.length;
		if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);
		const actualLength = plen + 7 + words.length;
		if (limit !== false && actualLength > limit) throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
		const lowered = prefix.toLowerCase();
		const sum = bechChecksum(lowered, words, ENCODING_CONST);
		return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
	}
	function decode(str, limit = 90) {
		astr("bech32.decode input", str);
		const slen = str.length;
		if (slen < 8 || limit !== false && slen > limit) throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
		const lowered = str.toLowerCase();
		if (str !== lowered && str !== str.toUpperCase()) throw new Error(`String must be lowercase or uppercase`);
		const sepIndex = lowered.lastIndexOf("1");
		if (sepIndex === 0 || sepIndex === -1) throw new Error(`Letter "1" must be present between prefix and data only`);
		const prefix = lowered.slice(0, sepIndex);
		const data = lowered.slice(sepIndex + 1);
		if (data.length < 6) throw new Error("Data must be at least 6 characters long");
		const words = BECH_ALPHABET.decode(data).slice(0, -6);
		const sum = bechChecksum(prefix, words, ENCODING_CONST);
		if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
		return {
			prefix,
			words
		};
	}
	const decodeUnsafe = unsafeWrapper(decode);
	function decodeToBytes(str) {
		const { prefix, words } = decode(str, false);
		return {
			prefix,
			words,
			bytes: fromWords(words)
		};
	}
	function encodeFromBytes(prefix, bytes) {
		return encode(prefix, toWords(bytes));
	}
	return {
		encode,
		decode,
		encodeFromBytes,
		decodeToBytes,
		decodeUnsafe,
		fromWords,
		fromWordsUnsafe,
		toWords
	};
}
genBech32("bech32");
genBech32("bech32m");
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" || chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize$1((s) => {
	if (typeof s !== "string" || s.length % 2 !== 0) throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
	return s.toLowerCase();
}));
//#endregion
//#region node_modules/.pnpm/@scure+bip32@1.7.0/node_modules/@scure/bip32/lib/esm/index.js
/**
* @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.
* @example
* ```js
* import { HDKey } from "@scure/bip32";
* const hdkey1 = HDKey.fromMasterSeed(seed);
* const hdkey2 = HDKey.fromExtendedKey(base58key);
* const hdkey3 = HDKey.fromJSON({ xpriv: string });
*
* // props
* [hdkey1.depth, hdkey1.index, hdkey1.chainCode];
* console.log(hdkey2.privateKey, hdkey2.publicKey);
* console.log(hdkey3.derive("m/0/2147483647'/1"));
* const sig = hdkey3.sign(hash);
* hdkey3.verify(hash, sig);
* ```
*/
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
const Point = secp256k1.ProjectivePoint;
const base58check = createBase58check(sha256);
function bytesToNumber(bytes) {
	abytes$1(bytes);
	const h = bytes.length === 0 ? "0" : bytesToHex(bytes);
	return BigInt("0x" + h);
}
function numberToBytes(num) {
	if (typeof num !== "bigint") throw new Error("bigint expected");
	return hexToBytes$1(num.toString(16).padStart(64, "0"));
}
const MASTER_SECRET = utf8ToBytes("Bitcoin seed");
const BITCOIN_VERSIONS = {
	private: 76066276,
	public: 76067358
};
const HARDENED_OFFSET = 2147483648;
const hash160 = (data) => ripemd160(sha256(data));
const fromU32 = (data) => createView(data).getUint32(0, false);
const toU32 = (n) => {
	if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) throw new Error("invalid number, should be from 0 to 2**32-1, got " + n);
	const buf = new Uint8Array(4);
	createView(buf).setUint32(0, n, false);
	return buf;
};
var HDKey = class HDKey {
	get fingerprint() {
		if (!this.pubHash) throw new Error("No publicKey set!");
		return fromU32(this.pubHash);
	}
	get identifier() {
		return this.pubHash;
	}
	get pubKeyHash() {
		return this.pubHash;
	}
	get privateKey() {
		return this.privKeyBytes || null;
	}
	get publicKey() {
		return this.pubKey || null;
	}
	get privateExtendedKey() {
		const priv = this.privateKey;
		if (!priv) throw new Error("No private key");
		return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)));
	}
	get publicExtendedKey() {
		if (!this.pubKey) throw new Error("No public key");
		return base58check.encode(this.serialize(this.versions.public, this.pubKey));
	}
	static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
		abytes$1(seed);
		if (8 * seed.length < 128 || 8 * seed.length > 512) throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length);
		const I = hmac(sha512, MASTER_SECRET, seed);
		return new HDKey({
			versions,
			chainCode: I.slice(32),
			privateKey: I.slice(0, 32)
		});
	}
	static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
		const keyBuffer = base58check.decode(base58key);
		const keyView = createView(keyBuffer);
		const version = keyView.getUint32(0, false);
		const opt = {
			versions,
			depth: keyBuffer[4],
			parentFingerprint: keyView.getUint32(5, false),
			index: keyView.getUint32(9, false),
			chainCode: keyBuffer.slice(13, 45)
		};
		const key = keyBuffer.slice(45);
		const isPriv = key[0] === 0;
		if (version !== versions[isPriv ? "private" : "public"]) throw new Error("Version mismatch");
		if (isPriv) return new HDKey({
			...opt,
			privateKey: key.slice(1)
		});
		else return new HDKey({
			...opt,
			publicKey: key
		});
	}
	static fromJSON(json) {
		return HDKey.fromExtendedKey(json.xpriv);
	}
	constructor(opt) {
		this.depth = 0;
		this.index = 0;
		this.chainCode = null;
		this.parentFingerprint = 0;
		if (!opt || typeof opt !== "object") throw new Error("HDKey.constructor must not be called directly");
		this.versions = opt.versions || BITCOIN_VERSIONS;
		this.depth = opt.depth || 0;
		this.chainCode = opt.chainCode || null;
		this.index = opt.index || 0;
		this.parentFingerprint = opt.parentFingerprint || 0;
		if (!this.depth) {
			if (this.parentFingerprint || this.index) throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
		}
		if (opt.publicKey && opt.privateKey) throw new Error("HDKey: publicKey and privateKey at same time.");
		if (opt.privateKey) {
			if (!secp256k1.utils.isValidPrivateKey(opt.privateKey)) throw new Error("Invalid private key");
			this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber(opt.privateKey);
			this.privKeyBytes = numberToBytes(this.privKey);
			this.pubKey = secp256k1.getPublicKey(opt.privateKey, true);
		} else if (opt.publicKey) this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true);
		else throw new Error("HDKey: no public or private key provided");
		this.pubHash = hash160(this.pubKey);
	}
	derive(path) {
		if (!/^[mM]'?/.test(path)) throw new Error("Path must start with \"m\" or \"M\"");
		if (/^[mM]'?$/.test(path)) return this;
		const parts = path.replace(/^[mM]'?\//, "").split("/");
		let child = this;
		for (const c of parts) {
			const m = /^(\d+)('?)$/.exec(c);
			const m1 = m && m[1];
			if (!m || m.length !== 3 || typeof m1 !== "string") throw new Error("invalid child index: " + c);
			let idx = +m1;
			if (!Number.isSafeInteger(idx) || idx >= 2147483648) throw new Error("Invalid index");
			if (m[2] === "'") idx += HARDENED_OFFSET;
			child = child.deriveChild(idx);
		}
		return child;
	}
	deriveChild(index) {
		if (!this.pubKey || !this.chainCode) throw new Error("No publicKey or chainCode set");
		let data = toU32(index);
		if (index >= 2147483648) {
			const priv = this.privateKey;
			if (!priv) throw new Error("Could not derive hardened child key");
			data = concatBytes(new Uint8Array([0]), priv, data);
		} else data = concatBytes(this.pubKey, data);
		const I = hmac(sha512, this.chainCode, data);
		const childTweak = bytesToNumber(I.slice(0, 32));
		const chainCode = I.slice(32);
		if (!secp256k1.utils.isValidPrivateKey(childTweak)) throw new Error("Tweak bigger than curve order");
		const opt = {
			versions: this.versions,
			chainCode,
			depth: this.depth + 1,
			parentFingerprint: this.fingerprint,
			index
		};
		try {
			if (this.privateKey) {
				const added = mod(this.privKey + childTweak, secp256k1.CURVE.n);
				if (!secp256k1.utils.isValidPrivateKey(added)) throw new Error("The tweak was out of range or the resulted private key is invalid");
				opt.privateKey = added;
			} else {
				const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));
				if (added.equals(Point.ZERO)) throw new Error("The tweak was equal to negative P, which made the result key invalid");
				opt.publicKey = added.toRawBytes(true);
			}
			return new HDKey(opt);
		} catch (err) {
			return this.deriveChild(index + 1);
		}
	}
	sign(hash) {
		if (!this.privateKey) throw new Error("No privateKey set!");
		abytes$1(hash, 32);
		return secp256k1.sign(hash, this.privKey).toCompactRawBytes();
	}
	verify(hash, signature) {
		abytes$1(hash, 32);
		abytes$1(signature, 64);
		if (!this.publicKey) throw new Error("No publicKey set!");
		let sig;
		try {
			sig = secp256k1.Signature.fromCompact(signature);
		} catch (error) {
			return false;
		}
		return secp256k1.verify(sig, hash, this.publicKey);
	}
	wipePrivateData() {
		this.privKey = void 0;
		if (this.privKeyBytes) {
			this.privKeyBytes.fill(0);
			this.privKeyBytes = void 0;
		}
		return this;
	}
	toJSON() {
		return {
			xpriv: this.privateExtendedKey,
			xpub: this.publicExtendedKey
		};
	}
	serialize(version, key) {
		if (!this.chainCode) throw new Error("No chainCode set");
		abytes$1(key, 33);
		return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
	}
};
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
/**
* PBKDF (RFC 2898). Can be used to create a key from password and salt.
* @module
*/
function pbkdf2Init(hash, _password, _salt, _opts) {
	ahash(hash);
	const { c, dkLen, asyncTick } = checkOpts({
		dkLen: 32,
		asyncTick: 10
	}, _opts);
	anumber$1(c);
	anumber$1(dkLen);
	anumber$1(asyncTick);
	if (c < 1) throw new Error("iterations (c) should be >= 1");
	const password = kdfInputToBytes(_password);
	const salt = kdfInputToBytes(_salt);
	const DK = new Uint8Array(dkLen);
	const PRF = hmac.create(hash, password);
	return {
		c,
		dkLen,
		asyncTick,
		DK,
		PRF,
		PRFSalt: PRF._cloneInto().update(salt)
	};
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
	PRF.destroy();
	PRFSalt.destroy();
	if (prfW) prfW.destroy();
	clean(u);
	return DK;
}
/**
* PBKDF2-HMAC: RFC 2898 key derivation function
* @param hash - hash function that would be used e.g. sha256
* @param password - password from which a derived key is generated
* @param salt - cryptographic salt
* @param opts - {c, dkLen} where c is work factor and dkLen is output message size
* @example
* const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
*/
function pbkdf2(hash, password, salt, opts) {
	const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
	let prfW;
	const arr = new Uint8Array(4);
	const view = createView(arr);
	const u = new Uint8Array(PRF.outputLen);
	for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
		const Ti = DK.subarray(pos, pos + PRF.outputLen);
		view.setInt32(0, ti, false);
		(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
		Ti.set(u.subarray(0, Ti.length));
		for (let ui = 1; ui < c; ui++) {
			PRF._cloneInto(prfW).update(u).digestInto(u);
			for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];
		}
	}
	return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//#endregion
//#region node_modules/.pnpm/@scure+bip39@1.6.0/node_modules/@scure/bip39/esm/index.js
/**
* Audited & minimal JS implementation of
* [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
* @module
* @example
```js
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
const mn = bip39.generateMnemonic(wordlist);
console.log(mn);
const ent = bip39.mnemonicToEntropy(mn, wordlist)
bip39.entropyToMnemonic(ent, wordlist);
bip39.validateMnemonic(mn, wordlist);
await bip39.mnemonicToSeed(mn, 'password');
bip39.mnemonicToSeedSync(mn, 'password');

// Wordlists
import { wordlist as czech } from '@scure/bip39/wordlists/czech';
import { wordlist as english } from '@scure/bip39/wordlists/english';
import { wordlist as french } from '@scure/bip39/wordlists/french';
import { wordlist as italian } from '@scure/bip39/wordlists/italian';
import { wordlist as japanese } from '@scure/bip39/wordlists/japanese';
import { wordlist as korean } from '@scure/bip39/wordlists/korean';
import { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';
import { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';
import { wordlist as spanish } from '@scure/bip39/wordlists/spanish';
import { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';
```
*/
/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
const isJapanese = (wordlist) => wordlist[0] === "あいこくしん";
function nfkd(str) {
	if (typeof str !== "string") throw new TypeError("invalid mnemonic type: " + typeof str);
	return str.normalize("NFKD");
}
function normalize(str) {
	const norm = nfkd(str);
	const words = norm.split(" ");
	if (![
		12,
		15,
		18,
		21,
		24
	].includes(words.length)) throw new Error("Invalid mnemonic");
	return {
		nfkd: norm,
		words
	};
}
function aentropy(ent) {
	abytes$1(ent, 16, 20, 24, 28, 32);
}
/**
* Generate x random words. Uses Cryptographically-Secure Random Number Generator.
* @param wordlist imported wordlist for specific language
* @param strength mnemonic strength 128-256 bits
* @example
* generateMnemonic(wordlist, 128)
* // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
*/
function generateMnemonic$1(wordlist, strength = 128) {
	anumber$1(strength);
	if (strength % 32 !== 0 || strength > 256) throw new TypeError("Invalid entropy");
	return entropyToMnemonic(randomBytes(strength / 8), wordlist);
}
const calcChecksum = (entropy) => {
	const bitsLeft = 8 - entropy.length / 4;
	return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]);
};
function getCoder(wordlist) {
	if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== "string") throw new Error("Wordlist: expected array of 2048 strings");
	wordlist.forEach((i) => {
		if (typeof i !== "string") throw new Error("wordlist: non-string element: " + i);
	});
	return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist));
}
/**
* Reversible: Converts raw entropy in form of byte array to mnemonic string.
* @param entropy byte array
* @param wordlist imported wordlist for specific language
* @returns 12-24 words
* @example
* const ent = new Uint8Array([
*   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
*   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
* ]);
* entropyToMnemonic(ent, wordlist);
* // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
*/
function entropyToMnemonic(entropy, wordlist) {
	aentropy(entropy);
	return getCoder(wordlist).encode(entropy).join(isJapanese(wordlist) ? "　" : " ");
}
const psalt = (passphrase) => nfkd("mnemonic" + passphrase);
/**
* Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
* @param mnemonic 12-24 words
* @param passphrase string that will additionally protect the key
* @returns 64 bytes of key data
* @example
* const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
* mnemonicToSeedSync(mnem, 'password');
* // new Uint8Array([...64 bytes])
*/
function mnemonicToSeedSync(mnemonic, passphrase = "") {
	return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {
		c: 2048,
		dkLen: 64
	});
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/generateMnemonic.js
/**
* @description Generates a random mnemonic phrase with a given wordlist.
*
* @param wordlist The wordlist to use for generating the mnemonic phrase.
* @param strength mnemonic strength 128-256 bits
*
* @returns A randomly generated mnemonic phrase.
*/
function generateMnemonic(wordlist, strength) {
	return generateMnemonic$1(wordlist, strength);
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/generatePrivateKey.js
/**
* @description Generates a random private key.
*
* @returns A randomly generated private key.
*/
function generatePrivateKey() {
	return toHex(secp256k1.utils.randomPrivateKey());
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/toAccount.js
/**
* @description Creates an Account from a custom signing implementation.
*
* @returns A Local Account.
*/
function toAccount(source) {
	if (typeof source === "string") {
		if (!isAddress(source, { strict: false })) throw new InvalidAddressError({ address: source });
		return {
			address: source,
			type: "json-rpc"
		};
	}
	if (!isAddress(source.address, { strict: false })) throw new InvalidAddressError({ address: source.address });
	return {
		address: source.address,
		nonceManager: source.nonceManager,
		sign: source.sign,
		signAuthorization: source.signAuthorization,
		signMessage: source.signMessage,
		signTransaction: source.signTransaction,
		signTypedData: source.signTypedData,
		source: "custom",
		type: "local"
	};
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/utils/sign.js
let extraEntropy = false;
/**
* @description Signs a hash with a given private key.
*
* @param hash The hash to sign.
* @param privateKey The private key to sign with.
*
* @returns The signature.
*/
async function sign({ hash, privateKey, to = "object" }) {
	const { r, s, recovery } = secp256k1.sign(hash.slice(2), privateKey.slice(2), {
		lowS: true,
		extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
	});
	const signature = {
		r: numberToHex(r, { size: 32 }),
		s: numberToHex(s, { size: 32 }),
		v: recovery ? 28n : 27n,
		yParity: recovery
	};
	return (() => {
		if (to === "bytes" || to === "hex") return serializeSignature({
			...signature,
			to
		});
		return signature;
	})();
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/utils/signAuthorization.js
/**
* Signs an Authorization hash in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.
*/
async function signAuthorization(parameters) {
	const { chainId, nonce, privateKey, to = "object" } = parameters;
	const address = parameters.contractAddress ?? parameters.address;
	const signature = await sign({
		hash: hashAuthorization({
			address,
			chainId,
			nonce
		}),
		privateKey,
		to
	});
	if (to === "object") return {
		address,
		chainId,
		nonce,
		...signature
	};
	return signature;
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/utils/signMessage.js
/**
* @description Calculates an Ethereum-specific signature in [EIP-191 format](https://eips.ethereum.org/EIPS/eip-191):
* `keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))`.
*
* @returns The signature.
*/
async function signMessage({ message, privateKey }) {
	return await sign({
		hash: hashMessage(message),
		privateKey,
		to: "hex"
	});
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/utils/signTransaction.js
async function signTransaction(parameters) {
	const { privateKey, transaction, serializer = serializeTransaction } = parameters;
	return await serializer(transaction, await sign({
		hash: keccak256(await serializer((() => {
			if (transaction.type === "eip4844") return {
				...transaction,
				sidecars: false
			};
			return transaction;
		})())),
		privateKey
	}));
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/utils/signTypedData.js
/**
* @description Signs typed data and calculates an Ethereum-specific signature in [https://eips.ethereum.org/EIPS/eip-712](https://eips.ethereum.org/EIPS/eip-712):
* `sign(keccak256("\x19\x01" ‖ domainSeparator ‖ hashStruct(message)))`.
*
* @returns The signature.
*/
async function signTypedData(parameters) {
	const { privateKey, ...typedData } = parameters;
	return await sign({
		hash: hashTypedData(typedData),
		privateKey,
		to: "hex"
	});
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/privateKeyToAccount.js
/**
* @description Creates an Account from a private key.
*
* @returns A Private Key Account.
*/
function privateKeyToAccount(privateKey, options = {}) {
	const { nonceManager } = options;
	const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
	return {
		...toAccount({
			address: publicKeyToAddress(publicKey),
			nonceManager,
			async sign({ hash }) {
				return sign({
					hash,
					privateKey,
					to: "hex"
				});
			},
			async signAuthorization(authorization) {
				return signAuthorization({
					...authorization,
					privateKey
				});
			},
			async signMessage({ message }) {
				return signMessage({
					message,
					privateKey
				});
			},
			async signTransaction(transaction, { serializer } = {}) {
				return signTransaction({
					privateKey,
					transaction,
					serializer
				});
			},
			async signTypedData(typedData) {
				return signTypedData({
					...typedData,
					privateKey
				});
			}
		}),
		publicKey,
		source: "privateKey"
	};
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/hdKeyToAccount.js
/**
* @description Creates an Account from a HD Key.
*
* @returns A HD Account.
*/
function hdKeyToAccount(hdKey_, { accountIndex = 0, addressIndex = 0, changeIndex = 0, path, ...options } = {}) {
	const hdKey = hdKey_.derive(path || `m/44'/60'/${accountIndex}'/${changeIndex}/${addressIndex}`);
	return {
		...privateKeyToAccount(toHex(hdKey.privateKey), options),
		getHdKey: () => hdKey,
		source: "hd"
	};
}
//#endregion
//#region node_modules/.pnpm/viem@2.47.6_typescript@6.0.2_zod@4.3.6/node_modules/viem/_esm/accounts/mnemonicToAccount.js
/**
* @description Creates an Account from a mnemonic phrase.
*
* @returns A HD Account.
*/
function mnemonicToAccount(mnemonic, { passphrase, ...hdKeyOpts } = {}) {
	const seed = mnemonicToSeedSync(mnemonic, passphrase);
	return hdKeyToAccount(HDKey.fromMasterSeed(seed), hdKeyOpts);
}
//#endregion
export { generateMnemonic, generatePrivateKey, mnemonicToAccount, privateKeyToAccount };

//# sourceMappingURL=accounts-CgUUF-_i.mjs.map