(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pezkuwi/util')) :
    typeof define === 'function' && define.amd ? define(['exports', '@pezkuwi/util'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pezkuwiUtilCrypto = {}, global.pezkuwiUtil));
})(this, (function (exports, util) { 'use strict';

    const global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : window;

    var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
    const packageInfo$2 = { name: '@pezkuwi/x-global', path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '14.0.10' };

    function evaluateThis(fn) {
        return fn('return this');
    }
    const xglobal =  (typeof globalThis !== 'undefined'
        ? globalThis
        : typeof global !== 'undefined'
            ? global
            : typeof self !== 'undefined'
                ? self
                : typeof window !== 'undefined'
                    ? window
                    : evaluateThis(Function));
    function extractGlobal(name, fallback) {
        return typeof xglobal[name] === 'undefined'
            ? fallback
            : xglobal[name];
    }
    function exposeGlobal(name, fallback) {
        if (typeof xglobal[name] === 'undefined') {
            xglobal[name] = fallback;
        }
    }

    const build = /*#__PURE__*/Object.freeze({
        __proto__: null,
        exposeGlobal: exposeGlobal,
        extractGlobal: extractGlobal,
        packageInfo: packageInfo$2,
        xglobal: xglobal
    });

    function invalidFallback() {
        return Number.NaN;
    }
    const BigInt$1 =  extractGlobal('BigInt', invalidFallback);

    exposeGlobal('BigInt', BigInt$1);

    function getDefaultExportFromCjs (x) {
    	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
    }

    function getAugmentedNamespace(n) {
      if (n.__esModule) return n;
      var f = n.default;
    	if (typeof f == "function") {
    		var a = function a () {
    			if (this instanceof a) {
            return Reflect.construct(f, arguments, this.constructor);
    			}
    			return f.apply(this, arguments);
    		};
    		a.prototype = f.prototype;
      } else a = {};
      Object.defineProperty(a, '__esModule', {value: true});
    	Object.keys(n).forEach(function (k) {
    		var d = Object.getOwnPropertyDescriptor(n, k);
    		Object.defineProperty(a, k, d.get ? d : {
    			enumerable: true,
    			get: function () {
    				return n[k];
    			}
    		});
    	});
    	return a;
    }

    var browser = {};

    const require$$0 = /*@__PURE__*/getAugmentedNamespace(build);

    var packageInfo$1 = {};

    Object.defineProperty(packageInfo$1, "__esModule", { value: true });
    packageInfo$1.packageInfo = void 0;
    packageInfo$1.packageInfo = { name: '@pezkuwi/x-randomvalues', path: typeof __dirname === 'string' ? __dirname : 'auto', type: 'cjs', version: '14.0.10' };

    (function (exports$1) {
    	Object.defineProperty(exports$1, "__esModule", { value: true });
    	exports$1.crypto = exports$1.packageInfo = void 0;
    	exports$1.getRandomValues = getRandomValues;
    	const x_global_1 = require$$0;
    	var packageInfo_js_1 = packageInfo$1;
    	Object.defineProperty(exports$1, "packageInfo", { enumerable: true, get: function () { return packageInfo_js_1.packageInfo; } });
    	exports$1.crypto = x_global_1.xglobal.crypto;
    	function getRandomValues(arr) {
    	    return exports$1.crypto.getRandomValues(arr);
    	}
    } (browser));
    getDefaultExportFromCjs(browser);

    const DEFAULT_CRYPTO = { getRandomValues: browser.getRandomValues };
    const DEFAULT_SELF = { crypto: DEFAULT_CRYPTO };
    class Wbg {
        #bridge;
        constructor(bridge) {
            this.#bridge = bridge;
        }
        abort = () => {
            throw new Error('abort');
        };
        __wbindgen_is_undefined = (idx) => {
            return this.#bridge.getObject(idx) === undefined;
        };
        __wbindgen_throw = (ptr, len) => {
            throw new Error(this.#bridge.getString(ptr, len));
        };
        __wbg_self_1b7a39e3a92c949c = () => {
            return this.#bridge.addObject(DEFAULT_SELF);
        };
        __wbg_require_604837428532a733 = (ptr, len) => {
            throw new Error(`Unable to require ${this.#bridge.getString(ptr, len)}`);
        };
        __wbg_crypto_968f1772287e2df0 = (_idx) => {
            return this.#bridge.addObject(DEFAULT_CRYPTO);
        };
        __wbg_getRandomValues_a3d34b4fee3c2869 = (_idx) => {
            return this.#bridge.addObject(DEFAULT_CRYPTO.getRandomValues);
        };
        __wbg_getRandomValues_f5e14ab7ac8e995d = (_arg0, ptr, len) => {
            DEFAULT_CRYPTO.getRandomValues(this.#bridge.getU8a(ptr, len));
        };
        __wbg_randomFillSync_d5bd2d655fdf256a = (_idx, _ptr, _len) => {
            throw new Error('randomFillsync is not available');
        };
        __wbindgen_object_drop_ref = (idx) => {
            this.#bridge.takeObject(idx);
        };
    }

    class Bridge {
        #createWasm;
        #heap;
        #wbg;
        #cachegetInt32;
        #cachegetUint8;
        #heapNext;
        #wasm;
        #wasmError;
        #wasmPromise;
        #type;
        constructor(createWasm) {
            this.#createWasm = createWasm;
            this.#cachegetInt32 = null;
            this.#cachegetUint8 = null;
            this.#heap = new Array(32)
                .fill(undefined)
                .concat(undefined, null, true, false);
            this.#heapNext = this.#heap.length;
            this.#type = 'none';
            this.#wasm = null;
            this.#wasmError = null;
            this.#wasmPromise = null;
            this.#wbg = { ...new Wbg(this) };
        }
        get error() {
            return this.#wasmError;
        }
        get type() {
            return this.#type;
        }
        get wasm() {
            return this.#wasm;
        }
        async init(createWasm) {
            if (!this.#wasmPromise || createWasm) {
                this.#wasmPromise = (createWasm || this.#createWasm)(this.#wbg);
            }
            const { error, type, wasm } = await this.#wasmPromise;
            this.#type = type;
            this.#wasm = wasm;
            this.#wasmError = error;
            return this.#wasm;
        }
        getObject(idx) {
            return this.#heap[idx];
        }
        dropObject(idx) {
            if (idx < 36) {
                return;
            }
            this.#heap[idx] = this.#heapNext;
            this.#heapNext = idx;
        }
        takeObject(idx) {
            const ret = this.getObject(idx);
            this.dropObject(idx);
            return ret;
        }
        addObject(obj) {
            if (this.#heapNext === this.#heap.length) {
                this.#heap.push(this.#heap.length + 1);
            }
            const idx = this.#heapNext;
            this.#heapNext = this.#heap[idx];
            this.#heap[idx] = obj;
            return idx;
        }
        getInt32() {
            if (this.#cachegetInt32 === null || this.#cachegetInt32.buffer !== this.#wasm.memory.buffer) {
                this.#cachegetInt32 = new Int32Array(this.#wasm.memory.buffer);
            }
            return this.#cachegetInt32;
        }
        getUint8() {
            if (this.#cachegetUint8 === null || this.#cachegetUint8.buffer !== this.#wasm.memory.buffer) {
                this.#cachegetUint8 = new Uint8Array(this.#wasm.memory.buffer);
            }
            return this.#cachegetUint8;
        }
        getU8a(ptr, len) {
            return this.getUint8().subarray(ptr / 1, ptr / 1 + len);
        }
        getString(ptr, len) {
            return util.u8aToString(this.getU8a(ptr, len));
        }
        allocU8a(arg) {
            const ptr = this.#wasm.__wbindgen_malloc(arg.length * 1);
            this.getUint8().set(arg, ptr / 1);
            return [ptr, arg.length];
        }
        allocString(arg) {
            return this.allocU8a(util.stringToU8a(arg));
        }
        resultU8a() {
            const r0 = this.getInt32()[8 / 4 + 0];
            const r1 = this.getInt32()[8 / 4 + 1];
            const ret = this.getU8a(r0, r1).slice();
            this.#wasm.__wbindgen_free(r0, r1 * 1);
            return ret;
        }
        resultString() {
            return util.u8aToString(this.resultU8a());
        }
    }

    function createWasmFn(root, wasmBytes, asmFn) {
        return async (wbg) => {
            const result = {
                error: null,
                type: 'none',
                wasm: null
            };
            try {
                if (!wasmBytes?.length) {
                    throw new Error('No WebAssembly provided for initialization');
                }
                else if (typeof WebAssembly !== 'object' || typeof WebAssembly.instantiate !== 'function') {
                    throw new Error('WebAssembly is not available in your environment');
                }
                const source = await WebAssembly.instantiate(wasmBytes, { wbg });
                result.wasm = source.instance.exports;
                result.type = 'wasm';
            }
            catch (error) {
                {
                    result.error = `FATAL: Unable to initialize @pezkuwi/wasm-${root}:: ${error.message}`;
                    console.error(result.error);
                }
            }
            return result;
        };
    }

    const CHR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    const map = new Array(256);
    for (let i = 0, count = CHR.length; i < count; i++) {
        map[CHR.charCodeAt(i)] = i;
    }
    function base64Decode$1(data, out) {
        let byte = 0;
        let bits = 0;
        let pos = -1;
        for (let i = 0, last = out.length - 1; pos !== last; i++) {
            byte = (byte << 6) | map[data.charCodeAt(i)];
            if ((bits += 6) >= 8) {
                out[++pos] = (byte >>> (bits -= 8)) & 0xff;
            }
        }
        return out;
    }

    const u8 = Uint8Array, u16 = Uint16Array, u32$1 = Uint32Array;
    const clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
    const fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,  0, 0,  0]);
    const fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,  0, 0]);
    const freb = (eb, start) => {
        const b = new u16(31);
        for (let i = 0; i < 31; ++i) {
            b[i] = start += 1 << eb[i - 1];
        }
        const r = new u32$1(b[30]);
        for (let i = 1; i < 30; ++i) {
            for (let j = b[i]; j < b[i + 1]; ++j) {
                r[j] = ((j - b[i]) << 5) | i;
            }
        }
        return [b, r];
    };
    const [fl, revfl] = freb(fleb, 2);
    fl[28] = 258, revfl[258] = 28;
    const [fd] = freb(fdeb, 0);
    const rev = new u16(32768);
    for (let i = 0; i < 32768; ++i) {
        let x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
        x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
        x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
        rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
    }
    const hMap = ((cd, mb, r) => {
        const s = cd.length;
        let i = 0;
        const l = new u16(mb);
        for (; i < s; ++i) {
            if (cd[i])
                ++l[cd[i] - 1];
        }
        const le = new u16(mb);
        for (i = 1; i < mb; ++i) {
            le[i] = (le[i - 1] + l[i - 1]) << 1;
        }
        let co;
        {
            co = new u16(1 << mb);
            const rvb = 15 - mb;
            for (i = 0; i < s; ++i) {
                if (cd[i]) {
                    const sv = (i << 4) | cd[i];
                    const r = mb - cd[i];
                    let v = le[cd[i] - 1]++ << r;
                    for (const m = v | ((1 << r) - 1); v <= m; ++v) {
                        co[rev[v] >> rvb] = sv;
                    }
                }
            }
        }
        return co;
    });
    const flt = new u8(288);
    for (let i = 0; i < 144; ++i)
        flt[i] = 8;
    for (let i = 144; i < 256; ++i)
        flt[i] = 9;
    for (let i = 256; i < 280; ++i)
        flt[i] = 7;
    for (let i = 280; i < 288; ++i)
        flt[i] = 8;
    const fdt = new u8(32);
    for (let i = 0; i < 32; ++i)
        fdt[i] = 5;
    const flrm = hMap(flt, 9);
    const fdrm = hMap(fdt, 5);
    const bits = (d, p, m) => {
        const o = p >>> 3;
        return ((d[o] | (d[o + 1] << 8)) >>> (p & 7)) & m;
    };
    const bits16 = (d, p) => {
        const o = p >>> 3;
        return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >>> (p & 7));
    };
    const shft = (p) => (p >>> 3) + (p & 7 && 1);
    const slc = (v, s, e) => {
        if (e == null || e > v.length)
            e = v.length;
        const n = new (v instanceof u16 ? u16 : v instanceof u32$1 ? u32$1 : u8)(e - s);
        n.set(v.subarray(s, e));
        return n;
    };
    const max = (a) => {
        let m = a[0];
        for (let i = 1, count = a.length; i < count; ++i) {
            if (a[i] > m)
                m = a[i];
        }
        return m;
    };
    const inflt = (dat, buf, st) => {
        const noSt = !st || st.i;
        if (!st)
            st = {};
        const sl = dat.length;
        const noBuf = !buf || !noSt;
        if (!buf)
            buf = new u8(sl * 3);
        const cbuf = (l) => {
            let bl = buf.length;
            if (l > bl) {
                const nbuf = new u8(Math.max(bl << 1, l));
                nbuf.set(buf);
                buf = nbuf;
            }
        };
        let final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
        if (final && !lm)
            return buf;
        const tbts = sl << 3;
        do {
            if (!lm) {
                st.f = final = bits(dat, pos, 1);
                const type = bits(dat, pos + 1, 3);
                pos += 3;
                if (!type) {
                    const s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                    if (t > sl) {
                        if (noSt)
                            throw 'unexpected EOF';
                        break;
                    }
                    if (noBuf)
                        cbuf(bt + l);
                    buf.set(dat.subarray(s, t), bt);
                    st.b = bt += l, st.p = pos = t << 3;
                    continue;
                }
                else if (type == 1)
                    lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
                else if (type == 2) {
                    const hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                    const tl = hLit + bits(dat, pos + 5, 31) + 1;
                    pos += 14;
                    const ldt = new u8(tl);
                    const clt = new u8(19);
                    for (let i = 0; i < hcLen; ++i) {
                        clt[clim[i]] = bits(dat, pos + i * 3, 7);
                    }
                    pos += hcLen * 3;
                    const clb = max(clt), clbmsk = (1 << clb) - 1;
                    if (!noSt && pos + tl * (clb + 7) > tbts)
                        break;
                    const clm = hMap(clt, clb);
                    for (let i = 0; i < tl;) {
                        const r = clm[bits(dat, pos, clbmsk)];
                        pos += r & 15;
                        const s = r >>> 4;
                        if (s < 16) {
                            ldt[i++] = s;
                        }
                        else {
                            let c = 0, n = 0;
                            if (s == 16)
                                n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                            else if (s == 17)
                                n = 3 + bits(dat, pos, 7), pos += 3;
                            else if (s == 18)
                                n = 11 + bits(dat, pos, 127), pos += 7;
                            while (n--)
                                ldt[i++] = c;
                        }
                    }
                    const lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                    lbt = max(lt);
                    dbt = max(dt);
                    lm = hMap(lt, lbt);
                    dm = hMap(dt, dbt);
                }
                else
                    throw 'invalid block type';
                if (pos > tbts)
                    throw 'unexpected EOF';
            }
            if (noBuf)
                cbuf(bt + 131072);
            const lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
            const mxa = lbt + dbt + 18;
            while (noSt || pos + mxa < tbts) {
                const c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
                pos += c & 15;
                if (pos > tbts)
                    throw 'unexpected EOF';
                if (!c)
                    throw 'invalid length/literal';
                if (sym < 256)
                    buf[bt++] = sym;
                else if (sym == 256) {
                    lm = undefined;
                    break;
                }
                else {
                    let add = sym - 254;
                    if (sym > 264) {
                        const i = sym - 257, b = fleb[i];
                        add = bits(dat, pos, (1 << b) - 1) + fl[i];
                        pos += b;
                    }
                    const d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
                    if (!d)
                        throw 'invalid distance';
                    pos += d & 15;
                    let dt = fd[dsym];
                    if (dsym > 3) {
                        const b = fdeb[dsym];
                        dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
                    }
                    if (pos > tbts)
                        throw 'unexpected EOF';
                    if (noBuf)
                        cbuf(bt + 131072);
                    const end = bt + add;
                    for (; bt < end; bt += 4) {
                        buf[bt] = buf[bt - dt];
                        buf[bt + 1] = buf[bt + 1 - dt];
                        buf[bt + 2] = buf[bt + 2 - dt];
                        buf[bt + 3] = buf[bt + 3 - dt];
                    }
                    bt = end;
                }
            }
            st.l = lm, st.p = pos, st.b = bt;
            if (lm)
                final = 1, st.m = lbt, st.d = dm, st.n = dbt;
        } while (!final);
        return bt == buf.length ? buf : slc(buf, 0, bt);
    };
    const zlv = (d) => {
        if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
            throw 'invalid zlib data';
        if (d[1] & 32)
            throw 'invalid zlib data: preset dictionaries not supported';
    };
    function unzlibSync(data, out) {
        return inflt((zlv(data), data.subarray(2, -4)), out);
    }

    var lenIn = 168782;
    var lenOut = 335277;
    var bytes_1 = '[encoded data, 225044 characters]';

    const wasmBytes =  unzlibSync(base64Decode$1(bytes_1, new Uint8Array(lenIn)), new Uint8Array(lenOut));

    const createWasm =  createWasmFn('crypto', wasmBytes);

    const bridge = new Bridge(createWasm);
    async function initBridge(createWasm) {
        return bridge.init(createWasm);
    }

    function withWasm(fn) {
        return (...params) => {
            if (!bridge.wasm) {
                throw new Error('The WASM interface has not been initialized. Ensure that you wait for the initialization Promise with waitReady() from @pezkuwi/wasm-crypto (or cryptoWaitReady() from @pezkuwi/util-crypto) before attempting to use WASM-only interfaces.');
            }
            return fn(bridge.wasm, ...params);
        };
    }
    const bip39Generate =  withWasm((wasm, words) => {
        wasm.ext_bip39_generate(8, words);
        return bridge.resultString();
    });
    const bip39ToEntropy =  withWasm((wasm, phrase) => {
        wasm.ext_bip39_to_entropy(8, ...bridge.allocString(phrase));
        return bridge.resultU8a();
    });
    const bip39ToMiniSecret =  withWasm((wasm, phrase, password) => {
        wasm.ext_bip39_to_mini_secret(8, ...bridge.allocString(phrase), ...bridge.allocString(password));
        return bridge.resultU8a();
    });
    const bip39ToSeed =  withWasm((wasm, phrase, password) => {
        wasm.ext_bip39_to_seed(8, ...bridge.allocString(phrase), ...bridge.allocString(password));
        return bridge.resultU8a();
    });
    const bip39Validate =  withWasm((wasm, phrase) => {
        const ret = wasm.ext_bip39_validate(...bridge.allocString(phrase));
        return ret !== 0;
    });
    const ed25519KeypairFromSeed =  withWasm((wasm, seed) => {
        wasm.ext_ed_from_seed(8, ...bridge.allocU8a(seed));
        return bridge.resultU8a();
    });
    const ed25519Sign$1 =  withWasm((wasm, pubkey, seckey, message) => {
        wasm.ext_ed_sign(8, ...bridge.allocU8a(pubkey), ...bridge.allocU8a(seckey), ...bridge.allocU8a(message));
        return bridge.resultU8a();
    });
    const ed25519Verify$1 =  withWasm((wasm, signature, message, pubkey) => {
        const ret = wasm.ext_ed_verify(...bridge.allocU8a(signature), ...bridge.allocU8a(message), ...bridge.allocU8a(pubkey));
        return ret !== 0;
    });
    const secp256k1FromSeed =  withWasm((wasm, seckey) => {
        wasm.ext_secp_from_seed(8, ...bridge.allocU8a(seckey));
        return bridge.resultU8a();
    });
    const secp256k1Compress$1 =  withWasm((wasm, pubkey) => {
        wasm.ext_secp_pub_compress(8, ...bridge.allocU8a(pubkey));
        return bridge.resultU8a();
    });
    const secp256k1Expand$1 =  withWasm((wasm, pubkey) => {
        wasm.ext_secp_pub_expand(8, ...bridge.allocU8a(pubkey));
        return bridge.resultU8a();
    });
    const secp256k1Recover$1 =  withWasm((wasm, msgHash, sig, recovery) => {
        wasm.ext_secp_recover(8, ...bridge.allocU8a(msgHash), ...bridge.allocU8a(sig), recovery);
        return bridge.resultU8a();
    });
    const secp256k1Sign$1 =  withWasm((wasm, msgHash, seckey) => {
        wasm.ext_secp_sign(8, ...bridge.allocU8a(msgHash), ...bridge.allocU8a(seckey));
        return bridge.resultU8a();
    });
    const blake2b$2 =  withWasm((wasm, data, key, size) => {
        wasm.ext_blake2b(8, ...bridge.allocU8a(data), ...bridge.allocU8a(key), size);
        return bridge.resultU8a();
    });
    const hmacSha256 =  withWasm((wasm, key, data) => {
        wasm.ext_hmac_sha256(8, ...bridge.allocU8a(key), ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const hmacSha512 =  withWasm((wasm, key, data) => {
        wasm.ext_hmac_sha512(8, ...bridge.allocU8a(key), ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const keccak256 =  withWasm((wasm, data) => {
        wasm.ext_keccak256(8, ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const keccak512 =  withWasm((wasm, data) => {
        wasm.ext_keccak512(8, ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const pbkdf2$1 =  withWasm((wasm, data, salt, rounds) => {
        wasm.ext_pbkdf2(8, ...bridge.allocU8a(data), ...bridge.allocU8a(salt), rounds);
        return bridge.resultU8a();
    });
    const scrypt$1 =  withWasm((wasm, password, salt, log2n, r, p) => {
        wasm.ext_scrypt(8, ...bridge.allocU8a(password), ...bridge.allocU8a(salt), log2n, r, p);
        return bridge.resultU8a();
    });
    const sha256$2 =  withWasm((wasm, data) => {
        wasm.ext_sha256(8, ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const sha512$2 =  withWasm((wasm, data) => {
        wasm.ext_sha512(8, ...bridge.allocU8a(data));
        return bridge.resultU8a();
    });
    const twox =  withWasm((wasm, data, rounds) => {
        wasm.ext_twox(8, ...bridge.allocU8a(data), rounds);
        return bridge.resultU8a();
    });
    function isReady() {
        return !!bridge.wasm;
    }
    async function waitReady() {
        try {
            const wasm = await initBridge();
            return !!wasm;
        }
        catch {
            return false;
        }
    }

    const cryptoIsReady = isReady;
    function cryptoWaitReady() {
        return waitReady()
            .then(() => {
            if (!isReady()) {
                throw new Error('Unable to initialize @pezkuwi/util-crypto');
            }
            return true;
        })
            .catch(() => false);
    }

    cryptoWaitReady().catch(() => {
    });

    const packageInfo = { name: '@pezkuwi/util-crypto', path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('bundle-pezkuwi-util-crypto.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto', type: 'esm', version: '14.0.10' };

    /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    function isBytes$2(a) {
        return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
    }
    function abytes$2(b, ...lengths) {
        if (!isBytes$2(b))
            throw new Error('Uint8Array expected');
        if (lengths.length > 0 && !lengths.includes(b.length))
            throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
    }
    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$1(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`);
    }
    function chain(...args) {
        const id = (a) => a;
        const wrap = (a, b) => (c) => a(b(c));
        const encode = args.map((x) => x.encode).reduceRight(wrap, id);
        const decode = args.map((x) => x.decode).reduce(wrap, id);
        return { encode, decode };
    }
    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 === undefined)
                        throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
                    return i;
                });
            },
        };
    }
    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);
            },
        };
    }
    function padding(bits, chr = '=') {
        anumber$1(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--) {
                    const last = end - 1;
                    const byte = last * bits;
                    if (byte % 8 === 0)
                        throw new Error('padding: invalid, string has too much padding');
                }
                return input.slice(0, end);
            },
        };
    }
    function normalize$1(fn) {
        afn(fn);
        return { encode: (from) => from, decode: (to) => fn(to) };
    }
    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$1(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 =  (from, to) => from + (to - gcd(from, to));
    const powers =  (() => {
        let res = [];
        for (let i = 0; i < 40; i++)
            res.push(2 ** i);
        return res;
    })();
    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 (radix2carry(from, to) > 32) {
            throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${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$1(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 === undefined)
                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;
    }
    function radix(num) {
        anumber$1(num);
        const _256 = 2 ** 8;
        return {
            encode: (bytes) => {
                if (!isBytes$2(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));
            },
        };
    }
    function radix2(bits, revPadding = false) {
        anumber$1(bits);
        if (bits <= 0 || bits > 32)
            throw new Error('radix2: bits should be in (0..32]');
        if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
            throw new Error('radix2: carry overflow');
        return {
            encode: (bytes) => {
                if (!isBytes$2(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$1(len);
        afn(fn);
        return {
            encode(data) {
                if (!isBytes$2(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$2(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')();
    const decodeBase64Builtin = (s, isUrl) => {
        astr('base64', s);
        const re = /^[A-Za-z0-9=+/]+$/;
        const alphabet = 'base64';
        if (s.length > 0 && !re.test(s))
            throw new Error('invalid base64');
        return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
    };
    const base64 = hasBase64Builtin ? {
        encode(b) { abytes$2(b); return b.toBase64(); },
        decode(s) { return decodeBase64Builtin(s); },
    } : 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 =  (abc) => chain(radix(58), alphabet(abc), join(''));
    const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
    genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
    genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
    const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
    const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
    function bech32Polymod(pre) {
        const b = pre >> 25;
        let chk = (pre & 0x1ffffff) << 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) & 0x1f);
        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));
    }
    function genBech32(encoding) {
        const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
        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$2(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');
    const hasHexBuiltin$1 =  (() => typeof Uint8Array.from([]).toHex === 'function' &&
        typeof Uint8Array.fromHex === 'function')();
    const hexBuiltin = {
        };
    hasHexBuiltin$1
        ? hexBuiltin
        : 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();
        }));

    function createDecode({ coder, ipfs }, validate) {
        return (value, ipfsCompat) => {
            validate(value, ipfsCompat);
            return coder.decode(ipfs && ipfsCompat
                ? value.substring(1)
                : value);
        };
    }
    function createEncode({ coder, ipfs }) {
        return (value, ipfsCompat) => {
            const out = coder.encode(util.u8aToU8a(value));
            return ipfs && ipfsCompat
                ? `${ipfs}${out}`
                : out;
        };
    }
    function createIs(validate) {
        return (value, ipfsCompat) => {
            try {
                return validate(value, ipfsCompat);
            }
            catch {
                return false;
            }
        };
    }
    function createValidate({ chars, ipfs, type, withPadding }) {
        return (value, ipfsCompat) => {
            if (typeof value !== 'string') {
                throw new Error(`Expected ${type} string input`);
            }
            else if (ipfs && ipfsCompat && !value.startsWith(ipfs)) {
                throw new Error(`Expected ipfs-compatible ${type} to start with '${ipfs}'`);
            }
            for (let i = (ipfsCompat ? 1 : 0), count = value.length; i < count; i++) {
                if (chars.includes(value[i])) ;
                else if (withPadding && value[i] === '=') {
                    if (i === count - 1) ;
                    else if (value[i + 1] === '=') ;
                    else {
                        throw new Error(`Invalid ${type} padding sequence "${value[i]}${value[i + 1]}" at index ${i}`);
                    }
                }
                else {
                    throw new Error(`Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
                }
            }
            return true;
        };
    }

    const config$2 = {
        chars: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
        coder: base58,
        ipfs: 'z',
        type: 'base58'
    };
    const base58Validate =  createValidate(config$2);
    const base58Decode =  createDecode(config$2, base58Validate);
    const base58Encode =  createEncode(config$2);
    const isBase58 =  createIs(base58Validate);

    const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;

    /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    function isBytes$1(a) {
        return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
    }
    function anumber(n) {
        if (!Number.isSafeInteger(n) || n < 0)
            throw new Error('positive integer expected, got ' + n);
    }
    function abytes$1(b, ...lengths) {
        if (!isBytes$1(b))
            throw new Error('Uint8Array expected');
        if (lengths.length > 0 && !lengths.includes(b.length))
            throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
    }
    function ahash(h) {
        if (typeof h !== 'function' || typeof h.create !== 'function')
            throw new Error('Hash should be wrapped by utils.createHasher');
        anumber(h.outputLen);
        anumber(h.blockLen);
    }
    function aexists(instance, checkFinished = true) {
        if (instance.destroyed)
            throw new Error('Hash instance has been destroyed');
        if (checkFinished && instance.finished)
            throw new Error('Hash#digest() has already been called');
    }
    function aoutput(out, instance) {
        abytes$1(out);
        const min = instance.outputLen;
        if (out.length < min) {
            throw new Error('digestInto() expects output buffer of length at least ' + min);
        }
    }
    function u32(arr) {
        return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
    }
    function clean(...arrays) {
        for (let i = 0; i < arrays.length; i++) {
            arrays[i].fill(0);
        }
    }
    function createView(arr) {
        return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
    }
    function rotr(word, shift) {
        return (word << (32 - shift)) | (word >>> shift);
    }
    function rotl$1(word, shift) {
        return (word << shift) | ((word >>> (32 - shift)) >>> 0);
    }
    const isLE =  (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
    function byteSwap(word) {
        return (((word << 24) & 0xff000000) |
            ((word << 8) & 0xff0000) |
            ((word >>> 8) & 0xff00) |
            ((word >>> 24) & 0xff));
    }
    const swap8IfBE = isLE
        ? (n) => n
        : (n) => byteSwap(n);
    function byteSwap32(arr) {
        for (let i = 0; i < arr.length; i++) {
            arr[i] = byteSwap(arr[i]);
        }
        return arr;
    }
    const swap32IfBE = isLE
        ? (u) => u
        : byteSwap32;
    const hasHexBuiltin =  (() =>
    typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
    const hexes =  Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
    function bytesToHex(bytes) {
        abytes$1(bytes);
        if (hasHexBuiltin)
            return bytes.toHex();
        let hex = '';
        for (let i = 0; i < bytes.length; i++) {
            hex += hexes[bytes[i]];
        }
        return hex;
    }
    const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    function asciiToBase16(ch) {
        if (ch >= asciis._0 && ch <= asciis._9)
            return ch - asciis._0;
        if (ch >= asciis.A && ch <= asciis.F)
            return ch - (asciis.A - 10);
        if (ch >= asciis.a && ch <= asciis.f)
            return ch - (asciis.a - 10);
        return;
    }
    function hexToBytes(hex) {
        if (typeof hex !== 'string')
            throw new Error('hex string expected, got ' + typeof hex);
        if (hasHexBuiltin)
            return Uint8Array.fromHex(hex);
        const hl = hex.length;
        const al = hl / 2;
        if (hl % 2)
            throw new Error('hex string expected, got unpadded hex of length ' + hl);
        const array = new Uint8Array(al);
        for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
            const n1 = asciiToBase16(hex.charCodeAt(hi));
            const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
            if (n1 === undefined || n2 === undefined) {
                const char = hex[hi] + hex[hi + 1];
                throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
            }
            array[ai] = n1 * 16 + n2;
        }
        return array;
    }
    function utf8ToBytes(str) {
        if (typeof str !== 'string')
            throw new Error('string expected');
        return new Uint8Array(new TextEncoder().encode(str));
    }
    function toBytes(data) {
        if (typeof data === 'string')
            data = utf8ToBytes(data);
        abytes$1(data);
        return data;
    }
    function kdfInputToBytes(data) {
        if (typeof data === 'string')
            data = utf8ToBytes(data);
        abytes$1(data);
        return data;
    }
    function concatBytes(...arrays) {
        let sum = 0;
        for (let i = 0; i < arrays.length; i++) {
            const a = arrays[i];
            abytes$1(a);
            sum += a.length;
        }
        const res = new Uint8Array(sum);
        for (let i = 0, pad = 0; i < arrays.length; i++) {
            const a = arrays[i];
            res.set(a, pad);
            pad += a.length;
        }
        return res;
    }
    function checkOpts(defaults, opts) {
        if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
            throw new Error('options should be object or undefined');
        const merged = Object.assign(defaults, opts);
        return merged;
    }
    class Hash {
    }
    function createHasher$1(hashCons) {
        const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
        const tmp = hashCons();
        hashC.outputLen = tmp.outputLen;
        hashC.blockLen = tmp.blockLen;
        hashC.create = () => hashCons();
        return hashC;
    }
    function createOptHasher(hashCons) {
        const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
        const tmp = hashCons({});
        hashC.outputLen = tmp.outputLen;
        hashC.blockLen = tmp.blockLen;
        hashC.create = (opts) => hashCons(opts);
        return hashC;
    }
    function createXOFer(hashCons) {
        const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
        const tmp = hashCons({});
        hashC.outputLen = tmp.outputLen;
        hashC.blockLen = tmp.blockLen;
        hashC.create = (opts) => hashCons(opts);
        return hashC;
    }
    function randomBytes(bytesLength = 32) {
        if (crypto && typeof crypto.getRandomValues === 'function') {
            return crypto.getRandomValues(new Uint8Array(bytesLength));
        }
        if (crypto && typeof crypto.randomBytes === 'function') {
            return Uint8Array.from(crypto.randomBytes(bytesLength));
        }
        throw new Error('crypto.getRandomValues must be defined');
    }

    const BSIGMA =  Uint8Array.from([
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
        14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
        11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
        7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
        9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
        2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
        12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
        13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
        6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
        10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
        14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
        11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
        7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
        9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
        2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
    ]);
    function G1s(a, b, c, d, x) {
        a = (a + b + x) | 0;
        d = rotr(d ^ a, 16);
        c = (c + d) | 0;
        b = rotr(b ^ c, 12);
        return { a, b, c, d };
    }
    function G2s(a, b, c, d, x) {
        a = (a + b + x) | 0;
        d = rotr(d ^ a, 8);
        c = (c + d) | 0;
        b = rotr(b ^ c, 7);
        return { a, b, c, d };
    }

    function setBigUint64(view, byteOffset, value, isLE) {
        if (typeof view.setBigUint64 === 'function')
            return view.setBigUint64(byteOffset, value, isLE);
        const _32n = BigInt(32);
        const _u32_max = BigInt(0xffffffff);
        const wh = Number((value >> _32n) & _u32_max);
        const wl = Number(value & _u32_max);
        const h = isLE ? 4 : 0;
        const l = isLE ? 0 : 4;
        view.setUint32(byteOffset + h, wh, isLE);
        view.setUint32(byteOffset + l, wl, isLE);
    }
    function Chi(a, b, c) {
        return (a & b) ^ (~a & c);
    }
    function Maj(a, b, c) {
        return (a & b) ^ (a & c) ^ (b & c);
    }
    class HashMD extends Hash {
        constructor(blockLen, outputLen, padOffset, isLE) {
            super();
            this.finished = false;
            this.length = 0;
            this.pos = 0;
            this.destroyed = false;
            this.blockLen = blockLen;
            this.outputLen = outputLen;
            this.padOffset = padOffset;
            this.isLE = isLE;
            this.buffer = new Uint8Array(blockLen);
            this.view = createView(this.buffer);
        }
        update(data) {
            aexists(this);
            data = toBytes(data);
            abytes$1(data);
            const { view, buffer, blockLen } = this;
            const len = data.length;
            for (let pos = 0; pos < len;) {
                const take = Math.min(blockLen - this.pos, len - pos);
                if (take === blockLen) {
                    const dataView = createView(data);
                    for (; blockLen <= len - pos; pos += blockLen)
                        this.process(dataView, pos);
                    continue;
                }
                buffer.set(data.subarray(pos, pos + take), this.pos);
                this.pos += take;
                pos += take;
                if (this.pos === blockLen) {
                    this.process(view, 0);
                    this.pos = 0;
                }
            }
            this.length += data.length;
            this.roundClean();
            return this;
        }
        digestInto(out) {
            aexists(this);
            aoutput(out, this);
            this.finished = true;
            const { buffer, view, blockLen, isLE } = this;
            let { pos } = this;
            buffer[pos++] = 0b10000000;
            clean(this.buffer.subarray(pos));
            if (this.padOffset > blockLen - pos) {
                this.process(view, 0);
                pos = 0;
            }
            for (let i = pos; i < blockLen; i++)
                buffer[i] = 0;
            setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
            this.process(view, 0);
            const oview = createView(out);
            const len = this.outputLen;
            if (len % 4)
                throw new Error('_sha2: outputLen should be aligned to 32bit');
            const outLen = len / 4;
            const state = this.get();
            if (outLen > state.length)
                throw new Error('_sha2: outputLen bigger than state');
            for (let i = 0; i < outLen; i++)
                oview.setUint32(4 * i, state[i], isLE);
        }
        digest() {
            const { buffer, outputLen } = this;
            this.digestInto(buffer);
            const res = buffer.slice(0, outputLen);
            this.destroy();
            return res;
        }
        _cloneInto(to) {
            to || (to = new this.constructor());
            to.set(...this.get());
            const { blockLen, buffer, length, finished, destroyed, pos } = this;
            to.destroyed = destroyed;
            to.finished = finished;
            to.length = length;
            to.pos = pos;
            if (length % blockLen)
                to.buffer.set(buffer);
            return to;
        }
        clone() {
            return this._cloneInto();
        }
    }
    const SHA256_IV =  Uint32Array.from([
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ]);
    const SHA224_IV =  Uint32Array.from([
        0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
    ]);
    const SHA384_IV =  Uint32Array.from([
        0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
        0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
    ]);
    const SHA512_IV =  Uint32Array.from([
        0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
        0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
    ]);

    const U32_MASK64 =  BigInt(2 ** 32 - 1);
    const _32n$1 =  BigInt(32);
    function fromBig(n, le = false) {
        if (le)
            return { h: Number(n & U32_MASK64), l: Number((n >> _32n$1) & U32_MASK64) };
        return { h: Number((n >> _32n$1) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
    }
    function split(lst, le = false) {
        const len = lst.length;
        let Ah = new Uint32Array(len);
        let Al = new Uint32Array(len);
        for (let i = 0; i < len; i++) {
            const { h, l } = fromBig(lst[i], le);
            [Ah[i], Al[i]] = [h, l];
        }
        return [Ah, Al];
    }
    const shrSH = (h, _l, s) => h >>> s;
    const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
    const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
    const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
    const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
    const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
    const rotr32H = (_h, l) => l;
    const rotr32L = (h, _l) => h;
    const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
    const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
    const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
    const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
    function add(Ah, Al, Bh, Bl) {
        const l = (Al >>> 0) + (Bl >>> 0);
        return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
    }
    const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
    const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
    const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
    const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
    const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
    const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;

    const B2B_IV =  Uint32Array.from([
        0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
        0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
    ]);
    const BBUF =  new Uint32Array(32);
    function G1b(a, b, c, d, msg, x) {
        const Xl = msg[x], Xh = msg[x + 1];
        let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
        let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
        let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
        let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
        let ll = add3L(Al, Bl, Xl);
        Ah = add3H(ll, Ah, Bh, Xh);
        Al = ll | 0;
        ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
        ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh) });
        ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
        ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
        ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
        (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
        (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
        (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
        (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
    }
    function G2b(a, b, c, d, msg, x) {
        const Xl = msg[x], Xh = msg[x + 1];
        let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1];
        let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1];
        let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1];
        let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1];
        let ll = add3L(Al, Bl, Xl);
        Ah = add3H(ll, Ah, Bh, Xh);
        Al = ll | 0;
        ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
        ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
        ({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
        ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
        ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
        (BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
        (BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
        (BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
        (BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
    }
    function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
        anumber(keyLen);
        if (outputLen < 0 || outputLen > keyLen)
            throw new Error('outputLen bigger than keyLen');
        const { key, salt, personalization } = opts;
        if (key !== undefined && (key.length < 1 || key.length > keyLen))
            throw new Error('key length must be undefined or 1..' + keyLen);
        if (salt !== undefined && salt.length !== saltLen)
            throw new Error('salt must be undefined or ' + saltLen);
        if (personalization !== undefined && personalization.length !== persLen)
            throw new Error('personalization must be undefined or ' + persLen);
    }
    class BLAKE2 extends Hash {
        constructor(blockLen, outputLen) {
            super();
            this.finished = false;
            this.destroyed = false;
            this.length = 0;
            this.pos = 0;
            anumber(blockLen);
            anumber(outputLen);
            this.blockLen = blockLen;
            this.outputLen = outputLen;
            this.buffer = new Uint8Array(blockLen);
            this.buffer32 = u32(this.buffer);
        }
        update(data) {
            aexists(this);
            data = toBytes(data);
            abytes$1(data);
            const { blockLen, buffer, buffer32 } = this;
            const len = data.length;
            const offset = data.byteOffset;
            const buf = data.buffer;
            for (let pos = 0; pos < len;) {
                if (this.pos === blockLen) {
                    swap32IfBE(buffer32);
                    this.compress(buffer32, 0, false);
                    swap32IfBE(buffer32);
                    this.pos = 0;
                }
                const take = Math.min(blockLen - this.pos, len - pos);
                const dataOffset = offset + pos;
                if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
                    const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
                    swap32IfBE(data32);
                    for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
                        this.length += blockLen;
                        this.compress(data32, pos32, false);
                    }
                    swap32IfBE(data32);
                    continue;
                }
                buffer.set(data.subarray(pos, pos + take), this.pos);
                this.pos += take;
                this.length += take;
                pos += take;
            }
            return this;
        }
        digestInto(out) {
            aexists(this);
            aoutput(out, this);
            const { pos, buffer32 } = this;
            this.finished = true;
            clean(this.buffer.subarray(pos));
            swap32IfBE(buffer32);
            this.compress(buffer32, 0, true);
            swap32IfBE(buffer32);
            const out32 = u32(out);
            this.get().forEach((v, i) => (out32[i] = swap8IfBE(v)));
        }
        digest() {
            const { buffer, outputLen } = this;
            this.digestInto(buffer);
            const res = buffer.slice(0, outputLen);
            this.destroy();
            return res;
        }
        _cloneInto(to) {
            const { buffer, length, finished, destroyed, outputLen, pos } = this;
            to || (to = new this.constructor({ dkLen: outputLen }));
            to.set(...this.get());
            to.buffer.set(buffer);
            to.destroyed = destroyed;
            to.finished = finished;
            to.length = length;
            to.pos = pos;
            to.outputLen = outputLen;
            return to;
        }
        clone() {
            return this._cloneInto();
        }
    }
    class BLAKE2b extends BLAKE2 {
        constructor(opts = {}) {
            const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
            super(128, olen);
            this.v0l = B2B_IV[0] | 0;
            this.v0h = B2B_IV[1] | 0;
            this.v1l = B2B_IV[2] | 0;
            this.v1h = B2B_IV[3] | 0;
            this.v2l = B2B_IV[4] | 0;
            this.v2h = B2B_IV[5] | 0;
            this.v3l = B2B_IV[6] | 0;
            this.v3h = B2B_IV[7] | 0;
            this.v4l = B2B_IV[8] | 0;
            this.v4h = B2B_IV[9] | 0;
            this.v5l = B2B_IV[10] | 0;
            this.v5h = B2B_IV[11] | 0;
            this.v6l = B2B_IV[12] | 0;
            this.v6h = B2B_IV[13] | 0;
            this.v7l = B2B_IV[14] | 0;
            this.v7h = B2B_IV[15] | 0;
            checkBlake2Opts(olen, opts, 64, 16, 16);
            let { key, personalization, salt } = opts;
            let keyLength = 0;
            if (key !== undefined) {
                key = toBytes(key);
                keyLength = key.length;
            }
            this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
            if (salt !== undefined) {
                salt = toBytes(salt);
                const slt = u32(salt);
                this.v4l ^= swap8IfBE(slt[0]);
                this.v4h ^= swap8IfBE(slt[1]);
                this.v5l ^= swap8IfBE(slt[2]);
                this.v5h ^= swap8IfBE(slt[3]);
            }
            if (personalization !== undefined) {
                personalization = toBytes(personalization);
                const pers = u32(personalization);
                this.v6l ^= swap8IfBE(pers[0]);
                this.v6h ^= swap8IfBE(pers[1]);
                this.v7l ^= swap8IfBE(pers[2]);
                this.v7h ^= swap8IfBE(pers[3]);
            }
            if (key !== undefined) {
                const tmp = new Uint8Array(this.blockLen);
                tmp.set(key);
                this.update(tmp);
            }
        }
        get() {
            let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
            return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
        }
        set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
            this.v0l = v0l | 0;
            this.v0h = v0h | 0;
            this.v1l = v1l | 0;
            this.v1h = v1h | 0;
            this.v2l = v2l | 0;
            this.v2h = v2h | 0;
            this.v3l = v3l | 0;
            this.v3h = v3h | 0;
            this.v4l = v4l | 0;
            this.v4h = v4h | 0;
            this.v5l = v5l | 0;
            this.v5h = v5h | 0;
            this.v6l = v6l | 0;
            this.v6h = v6h | 0;
            this.v7l = v7l | 0;
            this.v7h = v7h | 0;
        }
        compress(msg, offset, isLast) {
            this.get().forEach((v, i) => (BBUF[i] = v));
            BBUF.set(B2B_IV, 16);
            let { h, l } = fromBig(BigInt(this.length));
            BBUF[24] = B2B_IV[8] ^ l;
            BBUF[25] = B2B_IV[9] ^ h;
            if (isLast) {
                BBUF[28] = ~BBUF[28];
                BBUF[29] = ~BBUF[29];
            }
            let j = 0;
            const s = BSIGMA;
            for (let i = 0; i < 12; i++) {
                G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
                G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
                G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
                G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
                G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
                G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
                G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
                G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
                G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
                G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
                G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
                G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
                G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
                G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
                G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
                G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
            }
            this.v0l ^= BBUF[0] ^ BBUF[16];
            this.v0h ^= BBUF[1] ^ BBUF[17];
            this.v1l ^= BBUF[2] ^ BBUF[18];
            this.v1h ^= BBUF[3] ^ BBUF[19];
            this.v2l ^= BBUF[4] ^ BBUF[20];
            this.v2h ^= BBUF[5] ^ BBUF[21];
            this.v3l ^= BBUF[6] ^ BBUF[22];
            this.v3h ^= BBUF[7] ^ BBUF[23];
            this.v4l ^= BBUF[8] ^ BBUF[24];
            this.v4h ^= BBUF[9] ^ BBUF[25];
            this.v5l ^= BBUF[10] ^ BBUF[26];
            this.v5h ^= BBUF[11] ^ BBUF[27];
            this.v6l ^= BBUF[12] ^ BBUF[28];
            this.v6h ^= BBUF[13] ^ BBUF[29];
            this.v7l ^= BBUF[14] ^ BBUF[30];
            this.v7h ^= BBUF[15] ^ BBUF[31];
            clean(BBUF);
        }
        destroy() {
            this.destroyed = true;
            clean(this.buffer32);
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        }
    }
    const blake2b$1 =  createOptHasher((opts) => new BLAKE2b(opts));
    function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
        let j = 0;
        for (let i = 0; i < rounds; i++) {
            ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
            ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
            ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
            ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
            ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
            ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
            ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
            ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
            ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
            ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
            ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
            ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
            ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
            ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
            ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
            ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
        }
        return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
    }
    const B2S_IV = SHA256_IV;
    class BLAKE2s extends BLAKE2 {
        constructor(opts = {}) {
            const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
            super(64, olen);
            this.v0 = B2S_IV[0] | 0;
            this.v1 = B2S_IV[1] | 0;
            this.v2 = B2S_IV[2] | 0;
            this.v3 = B2S_IV[3] | 0;
            this.v4 = B2S_IV[4] | 0;
            this.v5 = B2S_IV[5] | 0;
            this.v6 = B2S_IV[6] | 0;
            this.v7 = B2S_IV[7] | 0;
            checkBlake2Opts(olen, opts, 32, 8, 8);
            let { key, personalization, salt } = opts;
            let keyLength = 0;
            if (key !== undefined) {
                key = toBytes(key);
                keyLength = key.length;
            }
            this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
            if (salt !== undefined) {
                salt = toBytes(salt);
                const slt = u32(salt);
                this.v4 ^= swap8IfBE(slt[0]);
                this.v5 ^= swap8IfBE(slt[1]);
            }
            if (personalization !== undefined) {
                personalization = toBytes(personalization);
                const pers = u32(personalization);
                this.v6 ^= swap8IfBE(pers[0]);
                this.v7 ^= swap8IfBE(pers[1]);
            }
            if (key !== undefined) {
                abytes$1(key);
                const tmp = new Uint8Array(this.blockLen);
                tmp.set(key);
                this.update(tmp);
            }
        }
        get() {
            const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
            return [v0, v1, v2, v3, v4, v5, v6, v7];
        }
        set(v0, v1, v2, v3, v4, v5, v6, v7) {
            this.v0 = v0 | 0;
            this.v1 = v1 | 0;
            this.v2 = v2 | 0;
            this.v3 = v3 | 0;
            this.v4 = v4 | 0;
            this.v5 = v5 | 0;
            this.v6 = v6 | 0;
            this.v7 = v7 | 0;
        }
        compress(msg, offset, isLast) {
            const { h, l } = fromBig(BigInt(this.length));
            const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
            this.v0 ^= v0 ^ v8;
            this.v1 ^= v1 ^ v9;
            this.v2 ^= v2 ^ v10;
            this.v3 ^= v3 ^ v11;
            this.v4 ^= v4 ^ v12;
            this.v5 ^= v5 ^ v13;
            this.v6 ^= v6 ^ v14;
            this.v7 ^= v7 ^ v15;
        }
        destroy() {
            this.destroyed = true;
            clean(this.buffer32);
            this.set(0, 0, 0, 0, 0, 0, 0, 0);
        }
    }
    createOptHasher((opts) => new BLAKE2s(opts));

    const blake2b = blake2b$1;

    function createAsHex(fn) {
        return (...args) => util.u8aToHex(fn(...args));
    }
    function createBitHasher(bitLength, fn) {
        return (data, onlyJs) => fn(data, bitLength, onlyJs);
    }
    function createDualHasher(wa, js) {
        return (value, bitLength = 256, onlyJs) => {
            const u8a = util.u8aToU8a(value);
            return !util.hasBigInt || (!onlyJs && isReady())
                ? wa[bitLength](u8a)
                : js[bitLength](u8a);
        };
    }

    function blake2AsU8a(data, bitLength = 256, key, onlyJs) {
        const byteLength = Math.ceil(bitLength / 8);
        const u8a = util.u8aToU8a(data);
        return !util.hasBigInt || (!onlyJs && isReady())
            ? blake2b$2(u8a, util.u8aToU8a(key), byteLength)
            : key
                ? blake2b(u8a, { dkLen: byteLength, key })
                : blake2b(u8a, { dkLen: byteLength });
    }
    const blake2AsHex =  createAsHex(blake2AsU8a);

    const SS58_PREFIX = util.stringToU8a('SS58PRE');
    function sshash(key) {
        return blake2AsU8a(util.u8aConcat(SS58_PREFIX, key), 512);
    }

    function checkAddressChecksum(decoded) {
        const ss58Length = (decoded[0] & 0b0100_0000) ? 2 : 1;
        const ss58Decoded = ss58Length === 1
            ? decoded[0]
            : ((decoded[0] & 0b0011_1111) << 2) | (decoded[1] >> 6) | ((decoded[1] & 0b0011_1111) << 8);
        const isPublicKey = [34 + ss58Length, 35 + ss58Length].includes(decoded.length);
        const length = decoded.length - (isPublicKey ? 2 : 1);
        const hash = sshash(decoded.subarray(0, length));
        const isValid = (decoded[0] & 0b1000_0000) === 0 && ![46, 47].includes(decoded[0]) && (isPublicKey
            ? decoded[decoded.length - 2] === hash[0] && decoded[decoded.length - 1] === hash[1]
            : decoded[decoded.length - 1] === hash[0]);
        return [isValid, length, ss58Length, ss58Decoded];
    }

    const knownGenesis = {
        acala: [
            '0xfc41b9bd8ef8fe53d58c7ea67c794c7ec9a73daf05e6d54b14ff6342c99ba64c'
        ],
        ajuna: [
            '0xe358eb1d11b31255a286c12e44fe6780b7edb171d657905a97e39f71d9c6c3ee'
        ],
        'aleph-node': [
            '0x70255b4d28de0fc4e1a193d7e175ad1ccef431598211c55538f1018651a0344e'
        ],
        astar: [
            '0x9eb76c5184c4ab8679d2d5d819fdf90b9c001403e9e17da2e14b6d8aec4029c6'
        ],
        basilisk: [
            '0xa85cfb9b9fd4d622a5b28289a02347af987d8f73fa3108450e2b4a11c1ce5755'
        ],
        bifrost: [
            '0x262e1b2ad728475fd6fe88e62d34c200abe6fd693931ddad144059b1eb884e5b'
        ],
        'bifrost-kusama': [
            '0x9f28c6a68e0fc9646eff64935684f6eeeece527e37bbe1f213d22caa1d9d6bed'
        ],
        bittensor: [
            '0x2f0555cc76fc2840a25a6ea3b9637146806f1f44b090c175ffde2a7e5ab36c03'
        ],
        centrifuge: [
            '0xb3db41421702df9a7fcac62b53ffeac85f7853cc4e689e0b93aeb3db18c09d82',
            '0x67dddf2673b69e5f875f6f25277495834398eafd67f492e09f3f3345e003d1b5'
        ],
        cere: [
            '0x81443836a9a24caaa23f1241897d1235717535711d1d3fe24eae4fdc942c092c'
        ],
        composable: [
            '0xdaab8df776eb52ec604a5df5d388bb62a050a0aaec4556a64265b9d42755552d'
        ],
        creditcoin3: [
            '0x4436a7d64e363df85e065a894721002a86643283f9707338bf195d360ba2ee71',
            '0xfc4ec97a1c1f119c4353aecb4a17c7c0cf7b40d5d660143d8bad9117e9866572',
            '0xfc9df99a665f964aed6649f275055e54df5e3420489538ed31d7788f53d11ef6'
        ],
        darwinia: [
            '0xe71578b37a7c799b0ab4ee87ffa6f059a6b98f71f06fb8c84a8d88013a548ad6'
        ],
        dentnet: [
            '0x0313f6a011d128d22f996703cbab05162e2fdc9e031493314fe6db79979c5ca7'
        ],
        'dock-mainnet': [
            '0x6bfe24dca2a3be10f22212678ac13a6446ec764103c0f3471c71609eac384aae',
            '0xf73467c6544aa68df2ee546b135f955c46b90fa627e9b5d7935f41061bb8a5a9'
        ],
        edgeware: [
            '0x742a2ca70c2fda6cee4f8df98d64c4c670a052d9568058982dad9d5a7a135c5b'
        ],
        encointer: [
            '0x7dd99936c1e9e6d1ce7d90eb6f33bea8393b4bf87677d675aa63c9cb3e8c5b5b'
        ],
        enjin: [
            '0xd8761d3c88f26dc12875c00d3165f7d67243d56fc85b4cf19937601a7916e5a9'
        ],
        equilibrium: [
            '0x6f1a800de3daff7f5e037ddf66ab22ce03ab91874debeddb1086f5f7dbd48925'
        ],
        frequency: [
            '0x4a587bf17a404e3572747add7aab7bbe56e805a5479c6c436f07f36fcc8d3ae1'
        ],
        genshiro: [
            '0x9b8cefc0eb5c568b527998bdd76c184e2b76ae561be76e4667072230217ea243'
        ],
        hydradx: [
            '0xafdc188f45c71dacbaa0b62e16a91f726c7b8699a9748cdf715459de6b7f366d',
            '0xd2a620c27ec5cbc5621ff9a522689895074f7cca0d08e7134a7804e1a3ba86fc',
            '0x10af6e84234477d84dc572bac0789813b254aa490767ed06fb9591191d1073f9',
            '0x3d75507dd46301767e601265791da1d9cb47b6ebc94e87347b635e5bf58bd047',
            '0x0ed32bfcab4a83517fac88f2aa7cbc2f88d3ab93be9a12b6188a036bf8a943c2'
        ],
        integritee: [
            '0xcdedc8eadbfa209d3f207bba541e57c3c58a667b05a2e1d1e86353c9000758da',
            '0xe13e7af377c64e83f95e0d70d5e5c3c01d697a84538776c5b9bbe0e7d7b6034c'
        ],
        'interlay-parachain': [
            '0xbf88efe70e9e0e916416e8bed61f2b45717f517d7f3523e33c7b001e5ffcbc72'
        ],
        karura: [
            '0xbaf5aabe40646d11f0ee8abbdc64f4a4b7674925cba08e4a05ff9ebed6e2126b'
        ],
        khala: [
            '0xd43540ba6d3eb4897c28a77d48cb5b729fea37603cbbfc7a86a73b72adb3be8d'
        ],
        kulupu: [
            '0xf7a99d3cb92853d00d5275c971c132c074636256583fee53b3bbe60d7b8769ba'
        ],
        kusama: [
            '0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe',
            '0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636',
            '0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf'
        ],
        dicle: [
            '0xd9d3cd7c1e5d890d969b957f4c5b71a111bbeeabc968f1d0d4538c2663f080a7'
        ],
        liberland: [
            '0x6bd89e052d67a45bb60a9a23e8581053d5e0d619f15cb9865946937e690c42d6'
        ],
        matrixchain: [
            '0x3af4ff48ec76d2efc8476730f423ac07e25ad48f5f4c9dc39c778b164d808615'
        ],
        mythos: [
            '0xf6ee56e9c5277df5b4ce6ae9983ee88f3cbed27d31beeb98f9f84f997a1ab0b9'
        ],
        nodle: [
            '0x97da7ede98d7bad4e36b4d734b6055425a3be036da2a332ea5a7037656427a21'
        ],
        origintrail: [
            '0xe7e0962324a3b86c83404dbea483f25fb5dab4c224791c81b756cfc948006174'
        ],
        p3d: [
            '0x6c5894837ad89b6d92b114a2fb3eafa8fe3d26a54848e3447015442cd6ef4e66'
        ],
        parallel: [
            '0xe61a41c53f5dcd0beb09df93b34402aada44cb05117b71059cce40a2723a4e97'
        ],
        peaq: [
            '0xd2a5d385932d1f650dae03ef8e2748983779ee342c614f80854d32b8cd8fa48c'
        ],
        pendulum: [
            '0x5d3c298622d5634ed019bf61ea4b71655030015bde9beb0d6a24743714462c86'
        ],
        phala: [
            '0x1bb969d85965e4bb5a651abbedf21a54b6b31a21f66b5401cc3f1e286268d736'
        ],
        picasso: [
            '0x6811a339673c9daa897944dcdac99c6e2939cc88245ed21951a0a3c9a2be75bc',
            '0xe8e7f0f4c4f5a00720b4821dbfddefea7490bcf0b19009961cc46957984e2c1c'
        ],
        polimec: [
            '0x7eb9354488318e7549c722669dcbdcdc526f1fef1420e7944667212f3601fdbd'
        ],
        polkadex: [
            '0x3920bcb4960a1eef5580cd5367ff3f430eef052774f78468852f7b9cb39f8a3c'
        ],
        polkadot: [
            '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'
        ],
        pezkuwi: [
            '0x41693961995d879073269a008d0a52832caa3e0ae73869f02127f3d5daa4934c'
        ],
        polymesh: [
            '0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063'
        ],
        quartz: [
            '0xcd4d732201ebe5d6b014edda071c4203e16867305332301dc8d092044b28e554'
        ],
        rococo: [
            '0x6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e',
            '0xaaf2cd1b74b5f726895921259421b534124726263982522174147046b8827897',
            '0x037f5f3c8e67b314062025fc886fcd6238ea25a4a9b45dce8d246815c9ebe770',
            '0xc196f81260cf1686172b47a79cf002120735d7cb0eb1474e8adce56618456fff',
            '0xf6e9983c37baf68846fedafe21e56718790e39fb1c582abc408b81bc7b208f9a',
            '0x5fce687da39305dfe682b117f0820b319348e8bb37eb16cf34acbf6a202de9d9',
            '0xe7c3d5edde7db964317cd9b51a3a059d7cd99f81bdbce14990047354334c9779',
            '0x1611e1dbf0405379b861e2e27daa90f480b2e6d3682414a80835a52e8cb8a215',
            '0x343442f12fa715489a8714e79a7b264ea88c0d5b8c66b684a7788a516032f6b9',
            '0x78bcd530c6b3a068bc17473cf5d2aff9c287102bed9af3ae3c41c33b9d6c6147',
            '0x47381ee0697153d64404fc578392c8fd5cba9073391908f46c888498415647bd',
            '0x19c0e4fa8ab75f5ac7865e0b8f74ff91eb9a100d336f423cd013a8befba40299'
        ],
        pezkuwichain: [
            '0x32154fd2c844f928c82964ff66168b41b15fc235f3a956d14393734c1ed4326b'
        ],
        sora: [
            '0x7e4e32d0feafd4f9c9414b0be86373f9a1efa904809b683453a9af6856d38ad5'
        ],
        stafi: [
            '0x290a4149f09ea0e402c74c1c7e96ae4239588577fe78932f94f5404c68243d80'
        ],
        statemine: [
            '0x48239ef607d7928874027a43a67689209727dfb3d3dc5e5b03a39bdc2eda771a'
        ],
        statemint: [
            '0x68d56f15f85d3136970ec16946040bc1752654e906147f7e43e9d539d7c3de2f'
        ],
        subsocial: [
            '0x0bd72c1c305172e1275278aaeb3f161e02eccb7a819e63f62d47bd53a28189f8'
        ],
        ternoa: [
            '0x6859c81ca95ef624c9dfe4dc6e3381c33e5d6509e35e147092bfbc780f777c4e'
        ],
        unique: [
            '0x84322d9cddbf35088f1e54e9a85c967a41a56a4f43445768125e61af166c7d31'
        ],
        vara: [
            '0xfe1b4c55fd4d668101126434206571a7838a8b6b93a6d1b95d607e78e6c53763'
        ],
        vtb: [
            '0x286bc8414c7000ce1d6ee6a834e29a54c1784814b76243eb77ed0b2c5573c60f',
            '0x7483b89572fb2bd687c7b9a93b242d0b237f9aba463aba07ec24503931038aaa'
        ],
        westend: [
            '0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e'
        ],
        zagros: [
            '0x297f5a4d105b4b28312586ff1915572ffe4ee015ff772b76399ecbff25a22026'
        ],
        xxnetwork: [
            '0x50dd5d206917bf10502c68fb4d18a59fc8aa31586f4e8856b493e43544aa82aa'
        ],
        zeitgeist: [
            '0x1bf2a2ecb4a868de66ea8610f2ce7c8c43706561b6476031315f6640fe38e060'
        ]
    };

    const knownIcon = {
        centrifuge: 'polkadot',
        kusama: 'polkadot',
        polkadot: 'polkadot',
        sora: 'polkadot',
        statemine: 'polkadot',
        statemint: 'polkadot',
        westmint: 'polkadot'
    };

    const knownLedger = {
        acala: 0x00000313,
        ajuna: 0x00000162,
        'aleph-node': 0x00000283,
        astar: 0x0000032a,
        bifrost: 0x00000314,
        'bifrost-kusama': 0x00000314,
        bittensor: 0x00000162,
        centrifuge: 0x000002eb,
        composable: 0x00000162,
        creditcoin3: 0x00000162,
        darwinia: 0x00000162,
        dentnet: 0x000002de,
        'dock-mainnet': 0x00000252,
        edgeware: 0x0000020b,
        encointer: 0x000001b2,
        enjin: 0x00000483,
        equilibrium: 0x05f5e0fd,
        frequency: 0x0000082b,
        genshiro: 0x05f5e0fc,
        hydradx: 0x00000162,
        integritee: 0x000007df,
        'interlay-parachain': 0x00000162,
        karura: 0x000002ae,
        khala: 0x000001b2,
        kusama: 0x000001b2,
        liberland: 0x000002ff,
        matrixchain: 0x00000483,
        mythos: 0x0000003c,
        nodle: 0x000003eb,
        origintrail: 0x00000162,
        parallel: 0x00000162,
        peaq: 0x00000d0a,
        pendulum: 0x00000162,
        phala: 0x00000162,
        picasso: 0x000001b2,
        polimec: 0x00000d10,
        polkadex: 0x0000031f,
        polkadot: 0x00000162,
        polymesh: 0x00000253,
        quartz: 0x00000277,
        sora: 0x00000269,
        stafi: 0x0000038b,
        statemine: 0x000001b2,
        statemint: 0x00000162,
        ternoa: 0x00003e3,
        unique: 0x00000295,
        vara: 0x00001370,
        vtb: 0x000002b6,
        xxnetwork: 0x000007a3,
        zeitgeist: 0x00000162
    };

    const knownTestnet = {
        '': true,
        'cess-testnet': true,
        'dock-testnet': true,
        jupiter: true,
        'mathchain-testnet': true,
        p3dt: true,
        subspace_testnet: true,
        'zero-alphaville': true
    };

    const UNSORTED = [0, 2, 42];
    const TESTNETS = ['testnet'];
    const customNetworks = [
        {
            decimals: [10],
            displayName: 'Pezkuwi Relay Chain',
            network: 'pezkuwi',
            prefix: 0,
            standardAccount: '*25519',
            symbols: ['PZW'],
            website: 'https://pezkuwi.com'
        },
        {
            decimals: [12],
            displayName: 'Zagros Relay Chain',
            network: 'zagros',
            prefix: 2,
            standardAccount: '*25519',
            symbols: ['ZGS'],
            website: 'https://zagros.pezkuwi.com'
        },
        {
            decimals: [12],
            displayName: 'Bizinikiwi',
            network: 'bizinikiwi',
            prefix: 42,
            standardAccount: '*25519',
            symbols: ['BZN'],
            website: 'https://bizinikiwi.com'
        },
        {
            decimals: [18],
            displayName: 'PezkuwiChain',
            network: 'pezkuwichain',
            prefix: 1453,
            standardAccount: '*25519',
            symbols: ['PZC'],
            website: 'https://chain.pezkuwi.com'
        }
    ];
    function toExpanded(o) {
        const network = o.network || '';
        const nameParts = network.replace(/_/g, '-').split('-');
        const n = o;
        n.slip44 = knownLedger[network];
        n.hasLedgerSupport = !!n.slip44;
        n.genesisHash = knownGenesis[network] || [];
        n.icon = knownIcon[network] || 'substrate';
        n.isTestnet = !!knownTestnet[network] || TESTNETS.includes(nameParts[nameParts.length - 1]);
        n.isIgnored = n.isTestnet || (!(o.standardAccount &&
            o.decimals?.length &&
            o.symbols?.length) &&
            o.prefix !== 42);
        return n;
    }
    function filterSelectable({ genesisHash, prefix }) {
        return !!genesisHash.length || prefix === 42;
    }
    function filterAvailable(n) {
        return !n.isIgnored && !!n.network;
    }
    function sortNetworks(a, b) {
        const isUnSortedA = UNSORTED.includes(a.prefix);
        const isUnSortedB = UNSORTED.includes(b.prefix);
        return isUnSortedA === isUnSortedB
            ? isUnSortedA
                ? 0
                : a.displayName.localeCompare(b.displayName)
            : isUnSortedA
                ? -1
                : 1;
    }
    const allNetworks = customNetworks.map(toExpanded);
    const availableNetworks = allNetworks.filter(filterAvailable).sort(sortNetworks);
    const selectableNetworks = availableNetworks.filter(filterSelectable);

    const defaults = {
        allowedDecodedLengths: [1, 2, 4, 8, 32, 33],
        allowedEncodedLengths: [3, 4, 6, 10, 35, 36, 37, 38],
        allowedPrefix: availableNetworks.map(({ prefix }) => prefix),
        prefix: 42
    };

    function decodeAddress(encoded, ignoreChecksum, ss58Format = -1) {
        if (!encoded) {
            throw new Error('Invalid empty address passed');
        }
        if (util.isU8a(encoded) || util.isHex(encoded)) {
            return util.u8aToU8a(encoded);
        }
        try {
            const decoded = base58Decode(encoded);
            if (!defaults.allowedEncodedLengths.includes(decoded.length)) {
                throw new Error('Invalid decoded address length');
            }
            const [isValid, endPos, ss58Length, ss58Decoded] = checkAddressChecksum(decoded);
            if (!isValid && !ignoreChecksum) {
                throw new Error('Invalid decoded address checksum');
            }
            else if (ss58Format !== -1 && ss58Format !== ss58Decoded) {
                throw new Error(`Expected ss58Format ${ss58Format}, received ${ss58Decoded}`);
            }
            return decoded.slice(ss58Length, endPos);
        }
        catch (error) {
            throw new Error(`Decoding ${encoded}: ${error.message}`);
        }
    }

    function addressToEvm(address, ignoreChecksum) {
        return decodeAddress(address, ignoreChecksum).subarray(0, 20);
    }

    function checkAddress(address, prefix) {
        let decoded;
        try {
            decoded = base58Decode(address);
        }
        catch (error) {
            return [false, error.message];
        }
        const [isValid, , , ss58Decoded] = checkAddressChecksum(decoded);
        if (ss58Decoded !== prefix) {
            return [false, `Prefix mismatch, expected ${prefix}, found ${ss58Decoded}`];
        }
        else if (!defaults.allowedEncodedLengths.includes(decoded.length)) {
            return [false, 'Invalid decoded address length'];
        }
        return [isValid, isValid ? null : 'Invalid decoded address checksum'];
    }

    const BN_BE_OPTS = { isLe: false };
    const BN_LE_OPTS = { isLe: true };
    const BN_LE_16_OPTS = { bitLength: 16, isLe: true };
    const BN_BE_32_OPTS = { bitLength: 32, isLe: false };
    const BN_LE_32_OPTS = { bitLength: 32, isLe: true };
    const BN_BE_256_OPTS = { bitLength: 256, isLe: false };
    const BN_LE_256_OPTS = { bitLength: 256, isLe: true };
    const BN_LE_512_OPTS = { bitLength: 512, isLe: true };

    const RE_NUMBER = /^\d+$/;
    const JUNCTION_ID_LEN = 32;
    class DeriveJunction {
        #chainCode = new Uint8Array(32);
        #isHard = false;
        static from(value) {
            const result = new DeriveJunction();
            const [code, isHard] = value.startsWith('/')
                ? [value.substring(1), true]
                : [value, false];
            result.soft(RE_NUMBER.test(code)
                ? new util.BN(code, 10)
                : code);
            return isHard
                ? result.harden()
                : result;
        }
        get chainCode() {
            return this.#chainCode;
        }
        get isHard() {
            return this.#isHard;
        }
        get isSoft() {
            return !this.#isHard;
        }
        hard(value) {
            return this.soft(value).harden();
        }
        harden() {
            this.#isHard = true;
            return this;
        }
        soft(value) {
            if (util.isNumber(value) || util.isBn(value) || util.isBigInt(value)) {
                return this.soft(util.bnToU8a(value, BN_LE_256_OPTS));
            }
            else if (util.isHex(value)) {
                return this.soft(util.hexToU8a(value));
            }
            else if (util.isString(value)) {
                return this.soft(util.compactAddLength(util.stringToU8a(value)));
            }
            else if (value.length > JUNCTION_ID_LEN) {
                return this.soft(blake2AsU8a(value));
            }
            this.#chainCode.fill(0);
            this.#chainCode.set(value, 0);
            return this;
        }
        soften() {
            this.#isHard = false;
            return this;
        }
    }

    const RE_JUNCTION = /\/(\/?)([^/]+)/g;
    function keyExtractPath(derivePath) {
        const parts = derivePath.match(RE_JUNCTION);
        const path = [];
        let constructed = '';
        if (parts) {
            constructed = parts.join('');
            for (const p of parts) {
                path.push(DeriveJunction.from(p.substring(1)));
            }
        }
        if (constructed !== derivePath) {
            throw new Error(`Re-constructed path "${constructed}" does not match input`);
        }
        return {
            parts,
            path
        };
    }

    const RE_CAPTURE = /^((0x[a-fA-F0-9]+|[\p{L}\d]+(?: [\p{L}\d]+)*))((\/\/?[^/]+)*)(\/\/\/(.*))?$/u;
    function keyExtractSuri(suri) {
        const normalizedSuri = suri.normalize('NFC');
        const matches = normalizedSuri.match(RE_CAPTURE);
        if (matches === null) {
            throw new Error('Unable to match provided value to a secret URI');
        }
        const [, phrase, , derivePath, , , password] = matches;
        const { path } = keyExtractPath(derivePath);
        return {
            derivePath,
            password,
            path,
            phrase
        };
    }

    const HDKD$2 = util.compactAddLength(util.stringToU8a('Secp256k1HDKD'));
    function secp256k1DeriveHard(seed, chainCode) {
        if (!util.isU8a(chainCode) || chainCode.length !== 32) {
            throw new Error('Invalid chainCode passed to derive');
        }
        return blake2AsU8a(util.u8aConcat(HDKD$2, seed, chainCode), 256);
    }

    const SHA256_K =  Uint32Array.from([
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
    ]);
    const SHA256_W =  new Uint32Array(64);
    class SHA256 extends HashMD {
        constructor(outputLen = 32) {
            super(64, outputLen, 8, false);
            this.A = SHA256_IV[0] | 0;
            this.B = SHA256_IV[1] | 0;
            this.C = SHA256_IV[2] | 0;
            this.D = SHA256_IV[3] | 0;
            this.E = SHA256_IV[4] | 0;
            this.F = SHA256_IV[5] | 0;
            this.G = SHA256_IV[6] | 0;
            this.H = SHA256_IV[7] | 0;
        }
        get() {
            const { A, B, C, D, E, F, G, H } = this;
            return [A, B, C, D, E, F, G, H];
        }
        set(A, B, C, D, E, F, G, H) {
            this.A = A | 0;
            this.B = B | 0;
            this.C = C | 0;
            this.D = D | 0;
            this.E = E | 0;
            this.F = F | 0;
            this.G = G | 0;
            this.H = H | 0;
        }
        process(view, offset) {
            for (let i = 0; i < 16; i++, offset += 4)
                SHA256_W[i] = view.getUint32(offset, false);
            for (let i = 16; i < 64; i++) {
                const W15 = SHA256_W[i - 15];
                const W2 = SHA256_W[i - 2];
                const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
                const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
                SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
            }
            let { A, B, C, D, E, F, G, H } = this;
            for (let i = 0; i < 64; i++) {
                const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
                const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
                const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
                const T2 = (sigma0 + Maj(A, B, C)) | 0;
                H = G;
                G = F;
                F = E;
                E = (D + T1) | 0;
                D = C;
                C = B;
                B = A;
                A = (T1 + T2) | 0;
            }
            A = (A + this.A) | 0;
            B = (B + this.B) | 0;
            C = (C + this.C) | 0;
            D = (D + this.D) | 0;
            E = (E + this.E) | 0;
            F = (F + this.F) | 0;
            G = (G + this.G) | 0;
            H = (H + this.H) | 0;
            this.set(A, B, C, D, E, F, G, H);
        }
        roundClean() {
            clean(SHA256_W);
        }
        destroy() {
            this.set(0, 0, 0, 0, 0, 0, 0, 0);
            clean(this.buffer);
        }
    }
    class SHA224 extends SHA256 {
        constructor() {
            super(28);
            this.A = SHA224_IV[0] | 0;
            this.B = SHA224_IV[1] | 0;
            this.C = SHA224_IV[2] | 0;
            this.D = SHA224_IV[3] | 0;
            this.E = SHA224_IV[4] | 0;
            this.F = SHA224_IV[5] | 0;
            this.G = SHA224_IV[6] | 0;
            this.H = SHA224_IV[7] | 0;
        }
    }
    const K512 =  (() => split([
        '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
        '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
        '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
        '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
        '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
        '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
        '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
        '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
        '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
        '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
        '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
        '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
        '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
        '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
        '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
        '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
        '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
        '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
        '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
        '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
    ].map(n => BigInt(n))))();
    const SHA512_Kh =  (() => K512[0])();
    const SHA512_Kl =  (() => K512[1])();
    const SHA512_W_H =  new Uint32Array(80);
    const SHA512_W_L =  new Uint32Array(80);
    class SHA512 extends HashMD {
        constructor(outputLen = 64) {
            super(128, outputLen, 16, false);
            this.Ah = SHA512_IV[0] | 0;
            this.Al = SHA512_IV[1] | 0;
            this.Bh = SHA512_IV[2] | 0;
            this.Bl = SHA512_IV[3] | 0;
            this.Ch = SHA512_IV[4] | 0;
            this.Cl = SHA512_IV[5] | 0;
            this.Dh = SHA512_IV[6] | 0;
            this.Dl = SHA512_IV[7] | 0;
            this.Eh = SHA512_IV[8] | 0;
            this.El = SHA512_IV[9] | 0;
            this.Fh = SHA512_IV[10] | 0;
            this.Fl = SHA512_IV[11] | 0;
            this.Gh = SHA512_IV[12] | 0;
            this.Gl = SHA512_IV[13] | 0;
            this.Hh = SHA512_IV[14] | 0;
            this.Hl = SHA512_IV[15] | 0;
        }
        get() {
            const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
            return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
        }
        set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
            this.Ah = Ah | 0;
            this.Al = Al | 0;
            this.Bh = Bh | 0;
            this.Bl = Bl | 0;
            this.Ch = Ch | 0;
            this.Cl = Cl | 0;
            this.Dh = Dh | 0;
            this.Dl = Dl | 0;
            this.Eh = Eh | 0;
            this.El = El | 0;
            this.Fh = Fh | 0;
            this.Fl = Fl | 0;
            this.Gh = Gh | 0;
            this.Gl = Gl | 0;
            this.Hh = Hh | 0;
            this.Hl = Hl | 0;
        }
        process(view, offset) {
            for (let i = 0; i < 16; i++, offset += 4) {
                SHA512_W_H[i] = view.getUint32(offset);
                SHA512_W_L[i] = view.getUint32((offset += 4));
            }
            for (let i = 16; i < 80; i++) {
                const W15h = SHA512_W_H[i - 15] | 0;
                const W15l = SHA512_W_L[i - 15] | 0;
                const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
                const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
                const W2h = SHA512_W_H[i - 2] | 0;
                const W2l = SHA512_W_L[i - 2] | 0;
                const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
                const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
                const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
                const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
                SHA512_W_H[i] = SUMh | 0;
                SHA512_W_L[i] = SUMl | 0;
            }
            let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
            for (let i = 0; i < 80; i++) {
                const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
                const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
                const CHIh = (Eh & Fh) ^ (~Eh & Gh);
                const CHIl = (El & Fl) ^ (~El & Gl);
                const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
                const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
                const T1l = T1ll | 0;
                const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
                const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
                const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
                const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
                Hh = Gh | 0;
                Hl = Gl | 0;
                Gh = Fh | 0;
                Gl = Fl | 0;
                Fh = Eh | 0;
                Fl = El | 0;
                ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
                Dh = Ch | 0;
                Dl = Cl | 0;
                Ch = Bh | 0;
                Cl = Bl | 0;
                Bh = Ah | 0;
                Bl = Al | 0;
                const All = add3L(T1l, sigma0l, MAJl);
                Ah = add3H(All, T1h, sigma0h, MAJh);
                Al = All | 0;
            }
            ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
            ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
            ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
            ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
            ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
            ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
            ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
            ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
            this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
        }
        roundClean() {
            clean(SHA512_W_H, SHA512_W_L);
        }
        destroy() {
            clean(this.buffer);
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        }
    }
    class SHA384 extends SHA512 {
        constructor() {
            super(48);
            this.Ah = SHA384_IV[0] | 0;
            this.Al = SHA384_IV[1] | 0;
            this.Bh = SHA384_IV[2] | 0;
            this.Bl = SHA384_IV[3] | 0;
            this.Ch = SHA384_IV[4] | 0;
            this.Cl = SHA384_IV[5] | 0;
            this.Dh = SHA384_IV[6] | 0;
            this.Dl = SHA384_IV[7] | 0;
            this.Eh = SHA384_IV[8] | 0;
            this.El = SHA384_IV[9] | 0;
            this.Fh = SHA384_IV[10] | 0;
            this.Fl = SHA384_IV[11] | 0;
            this.Gh = SHA384_IV[12] | 0;
            this.Gl = SHA384_IV[13] | 0;
            this.Hh = SHA384_IV[14] | 0;
            this.Hl = SHA384_IV[15] | 0;
        }
    }
    const T224_IV =  Uint32Array.from([
        0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
        0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
    ]);
    const T256_IV =  Uint32Array.from([
        0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
        0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
    ]);
    class SHA512_224 extends SHA512 {
        constructor() {
            super(28);
            this.Ah = T224_IV[0] | 0;
            this.Al = T224_IV[1] | 0;
            this.Bh = T224_IV[2] | 0;
            this.Bl = T224_IV[3] | 0;
            this.Ch = T224_IV[4] | 0;
            this.Cl = T224_IV[5] | 0;
            this.Dh = T224_IV[6] | 0;
            this.Dl = T224_IV[7] | 0;
            this.Eh = T224_IV[8] | 0;
            this.El = T224_IV[9] | 0;
            this.Fh = T224_IV[10] | 0;
            this.Fl = T224_IV[11] | 0;
            this.Gh = T224_IV[12] | 0;
            this.Gl = T224_IV[13] | 0;
            this.Hh = T224_IV[14] | 0;
            this.Hl = T224_IV[15] | 0;
        }
    }
    class SHA512_256 extends SHA512 {
        constructor() {
            super(32);
            this.Ah = T256_IV[0] | 0;
            this.Al = T256_IV[1] | 0;
            this.Bh = T256_IV[2] | 0;
            this.Bl = T256_IV[3] | 0;
            this.Ch = T256_IV[4] | 0;
            this.Cl = T256_IV[5] | 0;
            this.Dh = T256_IV[6] | 0;
            this.Dl = T256_IV[7] | 0;
            this.Eh = T256_IV[8] | 0;
            this.El = T256_IV[9] | 0;
            this.Fh = T256_IV[10] | 0;
            this.Fl = T256_IV[11] | 0;
            this.Gh = T256_IV[12] | 0;
            this.Gl = T256_IV[13] | 0;
            this.Hh = T256_IV[14] | 0;
            this.Hl = T256_IV[15] | 0;
        }
    }
    const sha256$1 =  createHasher$1(() => new SHA256());
    createHasher$1(() => new SHA224());
    const sha512$1 =  createHasher$1(() => new SHA512());
    createHasher$1(() => new SHA384());
    createHasher$1(() => new SHA512_256());
    createHasher$1(() => new SHA512_224());

    class HMAC extends Hash {
        constructor(hash, _key) {
            super();
            this.finished = false;
            this.destroyed = false;
            ahash(hash);
            const key = toBytes(_key);
            this.iHash = hash.create();
            if (typeof this.iHash.update !== 'function')
                throw new Error('Expected instance of class which extends utils.Hash');
            this.blockLen = this.iHash.blockLen;
            this.outputLen = this.iHash.outputLen;
            const blockLen = this.blockLen;
            const pad = new Uint8Array(blockLen);
            pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
            for (let i = 0; i < pad.length; i++)
                pad[i] ^= 0x36;
            this.iHash.update(pad);
            this.oHash = hash.create();
            for (let i = 0; i < pad.length; i++)
                pad[i] ^= 0x36 ^ 0x5c;
            this.oHash.update(pad);
            clean(pad);
        }
        update(buf) {
            aexists(this);
            this.iHash.update(buf);
            return this;
        }
        digestInto(out) {
            aexists(this);
            abytes$1(out, this.outputLen);
            this.finished = true;
            this.iHash.digestInto(out);
            this.oHash.update(out);
            this.oHash.digestInto(out);
            this.destroy();
        }
        digest() {
            const out = new Uint8Array(this.oHash.outputLen);
            this.digestInto(out);
            return out;
        }
        _cloneInto(to) {
            to || (to = Object.create(Object.getPrototypeOf(this), {}));
            const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
            to = to;
            to.finished = finished;
            to.destroyed = destroyed;
            to.blockLen = blockLen;
            to.outputLen = outputLen;
            to.oHash = oHash._cloneInto(to.oHash);
            to.iHash = iHash._cloneInto(to.iHash);
            return to;
        }
        clone() {
            return this._cloneInto();
        }
        destroy() {
            this.destroyed = true;
            this.oHash.destroy();
            this.iHash.destroy();
        }
    }
    const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
    hmac.create = (hash, key) => new HMAC(hash, key);

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$9 =  BigInt(0);
    const _1n$8 =  BigInt(1);
    function _abool2(value, title = '') {
        if (typeof value !== 'boolean') {
            const prefix = title && `"${title}"`;
            throw new Error(prefix + 'expected boolean, got type=' + typeof value);
        }
        return value;
    }
    function _abytes2(value, length, title = '') {
        const bytes = isBytes$1(value);
        const len = value?.length;
        const needsLen = length !== undefined;
        if (!bytes || (needsLen && len !== length)) {
            const prefix = title && `"${title}" `;
            const ofLen = needsLen ? ` of length ${length}` : '';
            const got = bytes ? `length=${len}` : `type=${typeof value}`;
            throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
        }
        return value;
    }
    function numberToHexUnpadded(num) {
        const hex = num.toString(16);
        return hex.length & 1 ? '0' + hex : hex;
    }
    function hexToNumber(hex) {
        if (typeof hex !== 'string')
            throw new Error('hex string expected, got ' + typeof hex);
        return hex === '' ? _0n$9 : BigInt('0x' + hex);
    }
    function bytesToNumberBE(bytes) {
        return hexToNumber(bytesToHex(bytes));
    }
    function bytesToNumberLE$1(bytes) {
        abytes$1(bytes);
        return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
    }
    function numberToBytesBE(n, len) {
        return hexToBytes(n.toString(16).padStart(len * 2, '0'));
    }
    function numberToBytesLE$1(n, len) {
        return numberToBytesBE(n, len).reverse();
    }
    function ensureBytes(title, hex, expectedLength) {
        let res;
        if (typeof hex === 'string') {
            try {
                res = hexToBytes(hex);
            }
            catch (e) {
                throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
            }
        }
        else if (isBytes$1(hex)) {
            res = Uint8Array.from(hex);
        }
        else {
            throw new Error(title + ' must be hex string or Uint8Array');
        }
        const len = res.length;
        if (typeof expectedLength === 'number' && len !== expectedLength)
            throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
        return res;
    }
    function equalBytes(a, b) {
        if (a.length !== b.length)
            return false;
        let diff = 0;
        for (let i = 0; i < a.length; i++)
            diff |= a[i] ^ b[i];
        return diff === 0;
    }
    function copyBytes(bytes) {
        return Uint8Array.from(bytes);
    }
    const isPosBig = (n) => typeof n === 'bigint' && _0n$9 <= n;
    function inRange(n, min, max) {
        return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
    }
    function aInRange$1(title, n, min, max) {
        if (!inRange(n, min, max))
            throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
    }
    function bitLen(n) {
        let len;
        for (len = 0; n > _0n$9; n >>= _1n$8, len += 1)
            ;
        return len;
    }
    const bitMask$1 = (n) => (_1n$8 << BigInt(n)) - _1n$8;
    function createHmacDrbg(hashLen, qByteLen, hmacFn) {
        if (typeof hashLen !== 'number' || hashLen < 2)
            throw new Error('hashLen must be a number');
        if (typeof qByteLen !== 'number' || qByteLen < 2)
            throw new Error('qByteLen must be a number');
        if (typeof hmacFn !== 'function')
            throw new Error('hmacFn must be a function');
        const u8n = (len) => new Uint8Array(len);
        const u8of = (byte) => Uint8Array.of(byte);
        let v = u8n(hashLen);
        let k = u8n(hashLen);
        let i = 0;
        const reset = () => {
            v.fill(1);
            k.fill(0);
            i = 0;
        };
        const h = (...b) => hmacFn(k, v, ...b);
        const reseed = (seed = u8n(0)) => {
            k = h(u8of(0x00), seed);
            v = h();
            if (seed.length === 0)
                return;
            k = h(u8of(0x01), seed);
            v = h();
        };
        const gen = () => {
            if (i++ >= 1000)
                throw new Error('drbg: tried 1000 values');
            let len = 0;
            const out = [];
            while (len < qByteLen) {
                v = h();
                const sl = v.slice();
                out.push(sl);
                len += v.length;
            }
            return concatBytes(...out);
        };
        const genUntil = (seed, pred) => {
            reset();
            reseed(seed);
            let res = undefined;
            while (!(res = pred(gen())))
                reseed();
            reset();
            return res;
        };
        return genUntil;
    }
    function isHash(val) {
        return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
    }
    function _validateObject(object, fields, optFields = {}) {
        if (!object || typeof object !== 'object')
            throw new Error('expected valid options object');
        function checkField(fieldName, expectedType, isOpt) {
            const val = object[fieldName];
            if (isOpt && val === undefined)
                return;
            const current = typeof val;
            if (current !== expectedType || val === null)
                throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
        }
        Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
        Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
    }
    const notImplemented = () => {
        throw new Error('not implemented');
    };
    function memoized(fn) {
        const map = new WeakMap();
        return (arg, ...args) => {
            const val = map.get(arg);
            if (val !== undefined)
                return val;
            const computed = fn(arg, ...args);
            map.set(arg, computed);
            return computed;
        };
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$8 = BigInt(0), _1n$7 = BigInt(1), _2n$6 =  BigInt(2), _3n$3 =  BigInt(3);
    const _4n$1 =  BigInt(4), _5n$1 =  BigInt(5), _7n$2 =  BigInt(7);
    const _8n$2 =  BigInt(8), _9n =  BigInt(9), _16n$1 =  BigInt(16);
    function mod(a, b) {
        const result = a % b;
        return result >= _0n$8 ? result : b + result;
    }
    function pow2(x, power, modulo) {
        let res = x;
        while (power-- > _0n$8) {
            res *= res;
            res %= modulo;
        }
        return res;
    }
    function invert(number, modulo) {
        if (number === _0n$8)
            throw new Error('invert: expected non-zero number');
        if (modulo <= _0n$8)
            throw new Error('invert: expected positive modulus, got ' + modulo);
        let a = mod(number, modulo);
        let b = modulo;
        let x = _0n$8, u = _1n$7;
        while (a !== _0n$8) {
            const q = b / a;
            const r = b % a;
            const m = x - u * q;
            b = a, a = r, x = u, u = m;
        }
        const gcd = b;
        if (gcd !== _1n$7)
            throw new Error('invert: does not exist');
        return mod(x, modulo);
    }
    function assertIsSquare(Fp, root, n) {
        if (!Fp.eql(Fp.sqr(root), n))
            throw new Error('Cannot find square root');
    }
    function sqrt3mod4(Fp, n) {
        const p1div4 = (Fp.ORDER + _1n$7) / _4n$1;
        const root = Fp.pow(n, p1div4);
        assertIsSquare(Fp, root, n);
        return root;
    }
    function sqrt5mod8(Fp, n) {
        const p5div8 = (Fp.ORDER - _5n$1) / _8n$2;
        const n2 = Fp.mul(n, _2n$6);
        const v = Fp.pow(n2, p5div8);
        const nv = Fp.mul(n, v);
        const i = Fp.mul(Fp.mul(nv, _2n$6), v);
        const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
        assertIsSquare(Fp, root, n);
        return root;
    }
    function sqrt9mod16(P) {
        const Fp_ = Field(P);
        const tn = tonelliShanks(P);
        const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
        const c2 = tn(Fp_, c1);
        const c3 = tn(Fp_, Fp_.neg(c1));
        const c4 = (P + _7n$2) / _16n$1;
        return (Fp, n) => {
            let tv1 = Fp.pow(n, c4);
            let tv2 = Fp.mul(tv1, c1);
            const tv3 = Fp.mul(tv1, c2);
            const tv4 = Fp.mul(tv1, c3);
            const e1 = Fp.eql(Fp.sqr(tv2), n);
            const e2 = Fp.eql(Fp.sqr(tv3), n);
            tv1 = Fp.cmov(tv1, tv2, e1);
            tv2 = Fp.cmov(tv4, tv3, e2);
            const e3 = Fp.eql(Fp.sqr(tv2), n);
            const root = Fp.cmov(tv1, tv2, e3);
            assertIsSquare(Fp, root, n);
            return root;
        };
    }
    function tonelliShanks(P) {
        if (P < _3n$3)
            throw new Error('sqrt is not defined for small field');
        let Q = P - _1n$7;
        let S = 0;
        while (Q % _2n$6 === _0n$8) {
            Q /= _2n$6;
            S++;
        }
        let Z = _2n$6;
        const _Fp = Field(P);
        while (FpLegendre(_Fp, Z) === 1) {
            if (Z++ > 1000)
                throw new Error('Cannot find square root: probably non-prime P');
        }
        if (S === 1)
            return sqrt3mod4;
        let cc = _Fp.pow(Z, Q);
        const Q1div2 = (Q + _1n$7) / _2n$6;
        return function tonelliSlow(Fp, n) {
            if (Fp.is0(n))
                return n;
            if (FpLegendre(Fp, n) !== 1)
                throw new Error('Cannot find square root');
            let M = S;
            let c = Fp.mul(Fp.ONE, cc);
            let t = Fp.pow(n, Q);
            let R = Fp.pow(n, Q1div2);
            while (!Fp.eql(t, Fp.ONE)) {
                if (Fp.is0(t))
                    return Fp.ZERO;
                let i = 1;
                let t_tmp = Fp.sqr(t);
                while (!Fp.eql(t_tmp, Fp.ONE)) {
                    i++;
                    t_tmp = Fp.sqr(t_tmp);
                    if (i === M)
                        throw new Error('Cannot find square root');
                }
                const exponent = _1n$7 << BigInt(M - i - 1);
                const b = Fp.pow(c, exponent);
                M = i;
                c = Fp.sqr(b);
                t = Fp.mul(t, c);
                R = Fp.mul(R, b);
            }
            return R;
        };
    }
    function FpSqrt(P) {
        if (P % _4n$1 === _3n$3)
            return sqrt3mod4;
        if (P % _8n$2 === _5n$1)
            return sqrt5mod8;
        if (P % _16n$1 === _9n)
            return sqrt9mod16(P);
        return tonelliShanks(P);
    }
    const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$7) === _1n$7;
    const FIELD_FIELDS = [
        'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
        'eql', 'add', 'sub', 'mul', 'pow', 'div',
        'addN', 'subN', 'mulN', 'sqrN'
    ];
    function validateField(field) {
        const initial = {
            ORDER: 'bigint',
            MASK: 'bigint',
            BYTES: 'number',
            BITS: 'number',
        };
        const opts = FIELD_FIELDS.reduce((map, val) => {
            map[val] = 'function';
            return map;
        }, initial);
        _validateObject(field, opts);
        return field;
    }
    function FpPow(Fp, num, power) {
        if (power < _0n$8)
            throw new Error('invalid exponent, negatives unsupported');
        if (power === _0n$8)
            return Fp.ONE;
        if (power === _1n$7)
            return num;
        let p = Fp.ONE;
        let d = num;
        while (power > _0n$8) {
            if (power & _1n$7)
                p = Fp.mul(p, d);
            d = Fp.sqr(d);
            power >>= _1n$7;
        }
        return p;
    }
    function FpInvertBatch(Fp, nums, passZero = false) {
        const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
        const multipliedAcc = nums.reduce((acc, num, i) => {
            if (Fp.is0(num))
                return acc;
            inverted[i] = acc;
            return Fp.mul(acc, num);
        }, Fp.ONE);
        const invertedAcc = Fp.inv(multipliedAcc);
        nums.reduceRight((acc, num, i) => {
            if (Fp.is0(num))
                return acc;
            inverted[i] = Fp.mul(acc, inverted[i]);
            return Fp.mul(acc, num);
        }, invertedAcc);
        return inverted;
    }
    function FpLegendre(Fp, n) {
        const p1mod2 = (Fp.ORDER - _1n$7) / _2n$6;
        const powered = Fp.pow(n, p1mod2);
        const yes = Fp.eql(powered, Fp.ONE);
        const zero = Fp.eql(powered, Fp.ZERO);
        const no = Fp.eql(powered, Fp.neg(Fp.ONE));
        if (!yes && !zero && !no)
            throw new Error('invalid Legendre symbol result');
        return yes ? 1 : zero ? 0 : -1;
    }
    function nLength(n, nBitLength) {
        if (nBitLength !== undefined)
            anumber(nBitLength);
        const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
        const nByteLength = Math.ceil(_nBitLength / 8);
        return { nBitLength: _nBitLength, nByteLength };
    }
    function Field(ORDER, bitLenOrOpts,
    isLE = false, opts = {}) {
        if (ORDER <= _0n$8)
            throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
        let _nbitLength = undefined;
        let _sqrt = undefined;
        let modFromBytes = false;
        let allowedLengths = undefined;
        if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
            if (opts.sqrt || isLE)
                throw new Error('cannot specify opts in two arguments');
            const _opts = bitLenOrOpts;
            if (_opts.BITS)
                _nbitLength = _opts.BITS;
            if (_opts.sqrt)
                _sqrt = _opts.sqrt;
            if (typeof _opts.isLE === 'boolean')
                isLE = _opts.isLE;
            if (typeof _opts.modFromBytes === 'boolean')
                modFromBytes = _opts.modFromBytes;
            allowedLengths = _opts.allowedLengths;
        }
        else {
            if (typeof bitLenOrOpts === 'number')
                _nbitLength = bitLenOrOpts;
            if (opts.sqrt)
                _sqrt = opts.sqrt;
        }
        const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
        if (BYTES > 2048)
            throw new Error('invalid field: expected ORDER of <= 2048 bytes');
        let sqrtP;
        const f = Object.freeze({
            ORDER,
            isLE,
            BITS,
            BYTES,
            MASK: bitMask$1(BITS),
            ZERO: _0n$8,
            ONE: _1n$7,
            allowedLengths: allowedLengths,
            create: (num) => mod(num, ORDER),
            isValid: (num) => {
                if (typeof num !== 'bigint')
                    throw new Error('invalid field element: expected bigint, got ' + typeof num);
                return _0n$8 <= num && num < ORDER;
            },
            is0: (num) => num === _0n$8,
            isValidNot0: (num) => !f.is0(num) && f.isValid(num),
            isOdd: (num) => (num & _1n$7) === _1n$7,
            neg: (num) => mod(-num, ORDER),
            eql: (lhs, rhs) => lhs === rhs,
            sqr: (num) => mod(num * num, ORDER),
            add: (lhs, rhs) => mod(lhs + rhs, ORDER),
            sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
            mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
            pow: (num, power) => FpPow(f, num, power),
            div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
            sqrN: (num) => num * num,
            addN: (lhs, rhs) => lhs + rhs,
            subN: (lhs, rhs) => lhs - rhs,
            mulN: (lhs, rhs) => lhs * rhs,
            inv: (num) => invert(num, ORDER),
            sqrt: _sqrt ||
                ((n) => {
                    if (!sqrtP)
                        sqrtP = FpSqrt(ORDER);
                    return sqrtP(f, n);
                }),
            toBytes: (num) => (isLE ? numberToBytesLE$1(num, BYTES) : numberToBytesBE(num, BYTES)),
            fromBytes: (bytes, skipValidation = true) => {
                if (allowedLengths) {
                    if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                        throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                    }
                    const padded = new Uint8Array(BYTES);
                    padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                    bytes = padded;
                }
                if (bytes.length !== BYTES)
                    throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
                let scalar = isLE ? bytesToNumberLE$1(bytes) : bytesToNumberBE(bytes);
                if (modFromBytes)
                    scalar = mod(scalar, ORDER);
                if (!skipValidation)
                    if (!f.isValid(scalar))
                        throw new Error('invalid field element: outside of range 0..ORDER');
                return scalar;
            },
            invertBatch: (lst) => FpInvertBatch(f, lst),
            cmov: (a, b, c) => (c ? b : a),
        });
        return Object.freeze(f);
    }
    function FpSqrtEven(Fp, elm) {
        if (!Fp.isOdd)
            throw new Error("Field doesn't have isOdd");
        const root = Fp.sqrt(elm);
        return Fp.isOdd(root) ? Fp.neg(root) : root;
    }
    function getFieldBytesLength(fieldOrder) {
        if (typeof fieldOrder !== 'bigint')
            throw new Error('field order must be bigint');
        const bitLength = fieldOrder.toString(2).length;
        return Math.ceil(bitLength / 8);
    }
    function getMinHashLength(fieldOrder) {
        const length = getFieldBytesLength(fieldOrder);
        return length + Math.ceil(length / 2);
    }
    function mapHashToField(key, fieldOrder, isLE = false) {
        const len = key.length;
        const fieldLen = getFieldBytesLength(fieldOrder);
        const minLen = getMinHashLength(fieldOrder);
        if (len < 16 || len < minLen || len > 1024)
            throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
        const num = isLE ? bytesToNumberLE$1(key) : bytesToNumberBE(key);
        const reduced = mod(num, fieldOrder - _1n$7) + _1n$7;
        return isLE ? numberToBytesLE$1(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$7 = BigInt(0);
    const _1n$6 = BigInt(1);
    function negateCt(condition, item) {
        const neg = item.negate();
        return condition ? neg : item;
    }
    function normalizeZ(c, points) {
        const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
        return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
    }
    function validateW(W, bits) {
        if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
            throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
    }
    function calcWOpts(W, scalarBits) {
        validateW(W, scalarBits);
        const windows = Math.ceil(scalarBits / W) + 1;
        const windowSize = 2 ** (W - 1);
        const maxNumber = 2 ** W;
        const mask = bitMask$1(W);
        const shiftBy = BigInt(W);
        return { windows, windowSize, mask, maxNumber, shiftBy };
    }
    function calcOffsets(n, window, wOpts) {
        const { windowSize, mask, maxNumber, shiftBy } = wOpts;
        let wbits = Number(n & mask);
        let nextN = n >> shiftBy;
        if (wbits > windowSize) {
            wbits -= maxNumber;
            nextN += _1n$6;
        }
        const offsetStart = window * windowSize;
        const offset = offsetStart + Math.abs(wbits) - 1;
        const isZero = wbits === 0;
        const isNeg = wbits < 0;
        const isNegF = window % 2 !== 0;
        const offsetF = offsetStart;
        return { nextN, offset, isZero, isNeg, isNegF, offsetF };
    }
    function validateMSMPoints(points, c) {
        if (!Array.isArray(points))
            throw new Error('array expected');
        points.forEach((p, i) => {
            if (!(p instanceof c))
                throw new Error('invalid point at index ' + i);
        });
    }
    function validateMSMScalars(scalars, field) {
        if (!Array.isArray(scalars))
            throw new Error('array of scalars expected');
        scalars.forEach((s, i) => {
            if (!field.isValid(s))
                throw new Error('invalid scalar at index ' + i);
        });
    }
    const pointPrecomputes = new WeakMap();
    const pointWindowSizes = new WeakMap();
    function getW(P) {
        return pointWindowSizes.get(P) || 1;
    }
    function assert0(n) {
        if (n !== _0n$7)
            throw new Error('invalid wNAF');
    }
    class wNAF {
        constructor(Point, bits) {
            this.BASE = Point.BASE;
            this.ZERO = Point.ZERO;
            this.Fn = Point.Fn;
            this.bits = bits;
        }
        _unsafeLadder(elm, n, p = this.ZERO) {
            let d = elm;
            while (n > _0n$7) {
                if (n & _1n$6)
                    p = p.add(d);
                d = d.double();
                n >>= _1n$6;
            }
            return p;
        }
        precomputeWindow(point, W) {
            const { windows, windowSize } = calcWOpts(W, this.bits);
            const points = [];
            let p = point;
            let base = p;
            for (let window = 0; window < windows; window++) {
                base = p;
                points.push(base);
                for (let i = 1; i < windowSize; i++) {
                    base = base.add(p);
                    points.push(base);
                }
                p = base.double();
            }
            return points;
        }
        wNAF(W, precomputes, n) {
            if (!this.Fn.isValid(n))
                throw new Error('invalid scalar');
            let p = this.ZERO;
            let f = this.BASE;
            const wo = calcWOpts(W, this.bits);
            for (let window = 0; window < wo.windows; window++) {
                const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
                n = nextN;
                if (isZero) {
                    f = f.add(negateCt(isNegF, precomputes[offsetF]));
                }
                else {
                    p = p.add(negateCt(isNeg, precomputes[offset]));
                }
            }
            assert0(n);
            return { p, f };
        }
        wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
            const wo = calcWOpts(W, this.bits);
            for (let window = 0; window < wo.windows; window++) {
                if (n === _0n$7)
                    break;
                const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
                n = nextN;
                if (isZero) {
                    continue;
                }
                else {
                    const item = precomputes[offset];
                    acc = acc.add(isNeg ? item.negate() : item);
                }
            }
            assert0(n);
            return acc;
        }
        getPrecomputes(W, point, transform) {
            let comp = pointPrecomputes.get(point);
            if (!comp) {
                comp = this.precomputeWindow(point, W);
                if (W !== 1) {
                    if (typeof transform === 'function')
                        comp = transform(comp);
                    pointPrecomputes.set(point, comp);
                }
            }
            return comp;
        }
        cached(point, scalar, transform) {
            const W = getW(point);
            return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
        }
        unsafe(point, scalar, transform, prev) {
            const W = getW(point);
            if (W === 1)
                return this._unsafeLadder(point, scalar, prev);
            return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
        }
        createCache(P, W) {
            validateW(W, this.bits);
            pointWindowSizes.set(P, W);
            pointPrecomputes.delete(P);
        }
        hasCache(elm) {
            return getW(elm) !== 1;
        }
    }
    function mulEndoUnsafe(Point, point, k1, k2) {
        let acc = point;
        let p1 = Point.ZERO;
        let p2 = Point.ZERO;
        while (k1 > _0n$7 || k2 > _0n$7) {
            if (k1 & _1n$6)
                p1 = p1.add(acc);
            if (k2 & _1n$6)
                p2 = p2.add(acc);
            acc = acc.double();
            k1 >>= _1n$6;
            k2 >>= _1n$6;
        }
        return { p1, p2 };
    }
    function pippenger(c, fieldN, points, scalars) {
        validateMSMPoints(points, c);
        validateMSMScalars(scalars, fieldN);
        const plength = points.length;
        const slength = scalars.length;
        if (plength !== slength)
            throw new Error('arrays of points and scalars must have equal length');
        const zero = c.ZERO;
        const wbits = bitLen(BigInt(plength));
        let windowSize = 1;
        if (wbits > 12)
            windowSize = wbits - 3;
        else if (wbits > 4)
            windowSize = wbits - 2;
        else if (wbits > 0)
            windowSize = 2;
        const MASK = bitMask$1(windowSize);
        const buckets = new Array(Number(MASK) + 1).fill(zero);
        const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
        let sum = zero;
        for (let i = lastBits; i >= 0; i -= windowSize) {
            buckets.fill(zero);
            for (let j = 0; j < slength; j++) {
                const scalar = scalars[j];
                const wbits = Number((scalar >> BigInt(i)) & MASK);
                buckets[wbits] = buckets[wbits].add(points[j]);
            }
            let resI = zero;
            for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
                sumI = sumI.add(buckets[j]);
                resI = resI.add(sumI);
            }
            sum = sum.add(resI);
            if (i !== 0)
                for (let j = 0; j < windowSize; j++)
                    sum = sum.double();
        }
        return sum;
    }
    function createField(order, field, isLE) {
        if (field) {
            if (field.ORDER !== order)
                throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
            validateField(field);
            return field;
        }
        else {
            return Field(order, { isLE });
        }
    }
    function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
        if (FpFnLE === undefined)
            FpFnLE = type === 'edwards';
        if (!CURVE || typeof CURVE !== 'object')
            throw new Error(`expected valid ${type} CURVE object`);
        for (const p of ['p', 'n', 'h']) {
            const val = CURVE[p];
            if (!(typeof val === 'bigint' && val > _0n$7))
                throw new Error(`CURVE.${p} must be positive bigint`);
        }
        const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
        const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
        const _b = type === 'weierstrass' ? 'b' : 'd';
        const params = ['Gx', 'Gy', 'a', _b];
        for (const p of params) {
            if (!Fp.isValid(CURVE[p]))
                throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
        }
        CURVE = Object.freeze(Object.assign({}, CURVE));
        return { CURVE, Fp, Fn };
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n$5) / den;
    function _splitEndoScalar(k, basis, n) {
        const [[a1, b1], [a2, b2]] = basis;
        const c1 = divNearest(b2 * k, n);
        const c2 = divNearest(-b1 * k, n);
        let k1 = k - c1 * a1 - c2 * a2;
        let k2 = -c1 * b1 - c2 * b2;
        const k1neg = k1 < _0n$6;
        const k2neg = k2 < _0n$6;
        if (k1neg)
            k1 = -k1;
        if (k2neg)
            k2 = -k2;
        const MAX_NUM = bitMask$1(Math.ceil(bitLen(n) / 2)) + _1n$5;
        if (k1 < _0n$6 || k1 >= MAX_NUM || k2 < _0n$6 || k2 >= MAX_NUM) {
            throw new Error('splitScalar (endomorphism): failed, k=' + k);
        }
        return { k1neg, k1, k2neg, k2 };
    }
    function validateSigFormat(format) {
        if (!['compact', 'recovered', 'der'].includes(format))
            throw new Error('Signature format must be "compact", "recovered", or "der"');
        return format;
    }
    function validateSigOpts(opts, def) {
        const optsn = {};
        for (let optName of Object.keys(def)) {
            optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
        }
        _abool2(optsn.lowS, 'lowS');
        _abool2(optsn.prehash, 'prehash');
        if (optsn.format !== undefined)
            validateSigFormat(optsn.format);
        return optsn;
    }
    class DERErr extends Error {
        constructor(m = '') {
            super(m);
        }
    }
    const DER = {
        Err: DERErr,
        _tlv: {
            encode: (tag, data) => {
                const { Err: E } = DER;
                if (tag < 0 || tag > 256)
                    throw new E('tlv.encode: wrong tag');
                if (data.length & 1)
                    throw new E('tlv.encode: unpadded data');
                const dataLen = data.length / 2;
                const len = numberToHexUnpadded(dataLen);
                if ((len.length / 2) & 128)
                    throw new E('tlv.encode: long form length too big');
                const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
                const t = numberToHexUnpadded(tag);
                return t + lenLen + len + data;
            },
            decode(tag, data) {
                const { Err: E } = DER;
                let pos = 0;
                if (tag < 0 || tag > 256)
                    throw new E('tlv.encode: wrong tag');
                if (data.length < 2 || data[pos++] !== tag)
                    throw new E('tlv.decode: wrong tlv');
                const first = data[pos++];
                const isLong = !!(first & 128);
                let length = 0;
                if (!isLong)
                    length = first;
                else {
                    const lenLen = first & 127;
                    if (!lenLen)
                        throw new E('tlv.decode(long): indefinite length not supported');
                    if (lenLen > 4)
                        throw new E('tlv.decode(long): byte length is too big');
                    const lengthBytes = data.subarray(pos, pos + lenLen);
                    if (lengthBytes.length !== lenLen)
                        throw new E('tlv.decode: length bytes not complete');
                    if (lengthBytes[0] === 0)
                        throw new E('tlv.decode(long): zero leftmost byte');
                    for (const b of lengthBytes)
                        length = (length << 8) | b;
                    pos += lenLen;
                    if (length < 128)
                        throw new E('tlv.decode(long): not minimal encoding');
                }
                const v = data.subarray(pos, pos + length);
                if (v.length !== length)
                    throw new E('tlv.decode: wrong value length');
                return { v, l: data.subarray(pos + length) };
            },
        },
        _int: {
            encode(num) {
                const { Err: E } = DER;
                if (num < _0n$6)
                    throw new E('integer: negative integers are not allowed');
                let hex = numberToHexUnpadded(num);
                if (Number.parseInt(hex[0], 16) & 0b1000)
                    hex = '00' + hex;
                if (hex.length & 1)
                    throw new E('unexpected DER parsing assertion: unpadded hex');
                return hex;
            },
            decode(data) {
                const { Err: E } = DER;
                if (data[0] & 128)
                    throw new E('invalid signature integer: negative');
                if (data[0] === 0x00 && !(data[1] & 128))
                    throw new E('invalid signature integer: unnecessary leading zero');
                return bytesToNumberBE(data);
            },
        },
        toSig(hex) {
            const { Err: E, _int: int, _tlv: tlv } = DER;
            const data = ensureBytes('signature', hex);
            const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
            if (seqLeftBytes.length)
                throw new E('invalid signature: left bytes after parsing');
            const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
            const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
            if (sLeftBytes.length)
                throw new E('invalid signature: left bytes after parsing');
            return { r: int.decode(rBytes), s: int.decode(sBytes) };
        },
        hexFromSig(sig) {
            const { _tlv: tlv, _int: int } = DER;
            const rs = tlv.encode(0x02, int.encode(sig.r));
            const ss = tlv.encode(0x02, int.encode(sig.s));
            const seq = rs + ss;
            return tlv.encode(0x30, seq);
        },
    };
    const _0n$6 = BigInt(0), _1n$5 = BigInt(1), _2n$5 = BigInt(2), _3n$2 = BigInt(3), _4n = BigInt(4);
    function _normFnElement(Fn, key) {
        const { BYTES: expected } = Fn;
        let num;
        if (typeof key === 'bigint') {
            num = key;
        }
        else {
            let bytes = ensureBytes('private key', key);
            try {
                num = Fn.fromBytes(bytes);
            }
            catch (error) {
                throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
            }
        }
        if (!Fn.isValidNot0(num))
            throw new Error('invalid private key: out of range [1..N-1]');
        return num;
    }
    function weierstrassN(params, extraOpts = {}) {
        const validated = _createCurveFields('weierstrass', params, extraOpts);
        const { Fp, Fn } = validated;
        let CURVE = validated.CURVE;
        const { h: cofactor, n: CURVE_ORDER } = CURVE;
        _validateObject(extraOpts, {}, {
            allowInfinityPoint: 'boolean',
            clearCofactor: 'function',
            isTorsionFree: 'function',
            fromBytes: 'function',
            toBytes: 'function',
            endo: 'object',
            wrapPrivateKey: 'boolean',
        });
        const { endo } = extraOpts;
        if (endo) {
            if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
                throw new Error('invalid endo: expected "beta": bigint and "basises": array');
            }
        }
        const lengths = getWLengths(Fp, Fn);
        function assertCompressionIsSupported() {
            if (!Fp.isOdd)
                throw new Error('compression is not supported: Field does not have .isOdd()');
        }
        function pointToBytes(_c, point, isCompressed) {
            const { x, y } = point.toAffine();
            const bx = Fp.toBytes(x);
            _abool2(isCompressed, 'isCompressed');
            if (isCompressed) {
                assertCompressionIsSupported();
                const hasEvenY = !Fp.isOdd(y);
                return concatBytes(pprefix(hasEvenY), bx);
            }
            else {
                return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
            }
        }
        function pointFromBytes(bytes) {
            _abytes2(bytes, undefined, 'Point');
            const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
            const length = bytes.length;
            const head = bytes[0];
            const tail = bytes.subarray(1);
            if (length === comp && (head === 0x02 || head === 0x03)) {
                const x = Fp.fromBytes(tail);
                if (!Fp.isValid(x))
                    throw new Error('bad point: is not on curve, wrong x');
                const y2 = weierstrassEquation(x);
                let y;
                try {
                    y = Fp.sqrt(y2);
                }
                catch (sqrtError) {
                    const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                    throw new Error('bad point: is not on curve, sqrt error' + err);
                }
                assertCompressionIsSupported();
                const isYOdd = Fp.isOdd(y);
                const isHeadOdd = (head & 1) === 1;
                if (isHeadOdd !== isYOdd)
                    y = Fp.neg(y);
                return { x, y };
            }
            else if (length === uncomp && head === 0x04) {
                const L = Fp.BYTES;
                const x = Fp.fromBytes(tail.subarray(0, L));
                const y = Fp.fromBytes(tail.subarray(L, L * 2));
                if (!isValidXY(x, y))
                    throw new Error('bad point: is not on curve');
                return { x, y };
            }
            else {
                throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
            }
        }
        const encodePoint = extraOpts.toBytes || pointToBytes;
        const decodePoint = extraOpts.fromBytes || pointFromBytes;
        function weierstrassEquation(x) {
            const x2 = Fp.sqr(x);
            const x3 = Fp.mul(x2, x);
            return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
        }
        function isValidXY(x, y) {
            const left = Fp.sqr(y);
            const right = weierstrassEquation(x);
            return Fp.eql(left, right);
        }
        if (!isValidXY(CURVE.Gx, CURVE.Gy))
            throw new Error('bad curve params: generator point');
        const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n$2), _4n);
        const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
        if (Fp.is0(Fp.add(_4a3, _27b2)))
            throw new Error('bad curve params: a or b');
        function acoord(title, n, banZero = false) {
            if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
                throw new Error(`bad point coordinate ${title}`);
            return n;
        }
        function aprjpoint(other) {
            if (!(other instanceof Point))
                throw new Error('ProjectivePoint expected');
        }
        function splitEndoScalarN(k) {
            if (!endo || !endo.basises)
                throw new Error('no endo');
            return _splitEndoScalar(k, endo.basises, Fn.ORDER);
        }
        const toAffineMemo = memoized((p, iz) => {
            const { X, Y, Z } = p;
            if (Fp.eql(Z, Fp.ONE))
                return { x: X, y: Y };
            const is0 = p.is0();
            if (iz == null)
                iz = is0 ? Fp.ONE : Fp.inv(Z);
            const x = Fp.mul(X, iz);
            const y = Fp.mul(Y, iz);
            const zz = Fp.mul(Z, iz);
            if (is0)
                return { x: Fp.ZERO, y: Fp.ZERO };
            if (!Fp.eql(zz, Fp.ONE))
                throw new Error('invZ was invalid');
            return { x, y };
        });
        const assertValidMemo = memoized((p) => {
            if (p.is0()) {
                if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                    return;
                throw new Error('bad point: ZERO');
            }
            const { x, y } = p.toAffine();
            if (!Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('bad point: x or y not field elements');
            if (!isValidXY(x, y))
                throw new Error('bad point: equation left != right');
            if (!p.isTorsionFree())
                throw new Error('bad point: not in prime-order subgroup');
            return true;
        });
        function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
            k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
            k1p = negateCt(k1neg, k1p);
            k2p = negateCt(k2neg, k2p);
            return k1p.add(k2p);
        }
        class Point {
            constructor(X, Y, Z) {
                this.X = acoord('x', X);
                this.Y = acoord('y', Y, true);
                this.Z = acoord('z', Z);
                Object.freeze(this);
            }
            static CURVE() {
                return CURVE;
            }
            static fromAffine(p) {
                const { x, y } = p || {};
                if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                    throw new Error('invalid affine point');
                if (p instanceof Point)
                    throw new Error('projective point not allowed');
                if (Fp.is0(x) && Fp.is0(y))
                    return Point.ZERO;
                return new Point(x, y, Fp.ONE);
            }
            static fromBytes(bytes) {
                const P = Point.fromAffine(decodePoint(_abytes2(bytes, undefined, 'point')));
                P.assertValidity();
                return P;
            }
            static fromHex(hex) {
                return Point.fromBytes(ensureBytes('pointHex', hex));
            }
            get x() {
                return this.toAffine().x;
            }
            get y() {
                return this.toAffine().y;
            }
            precompute(windowSize = 8, isLazy = true) {
                wnaf.createCache(this, windowSize);
                if (!isLazy)
                    this.multiply(_3n$2);
                return this;
            }
            assertValidity() {
                assertValidMemo(this);
            }
            hasEvenY() {
                const { y } = this.toAffine();
                if (!Fp.isOdd)
                    throw new Error("Field doesn't support isOdd");
                return !Fp.isOdd(y);
            }
            equals(other) {
                aprjpoint(other);
                const { X: X1, Y: Y1, Z: Z1 } = this;
                const { X: X2, Y: Y2, Z: Z2 } = other;
                const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
                const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
                return U1 && U2;
            }
            negate() {
                return new Point(this.X, Fp.neg(this.Y), this.Z);
            }
            double() {
                const { a, b } = CURVE;
                const b3 = Fp.mul(b, _3n$2);
                const { X: X1, Y: Y1, Z: Z1 } = this;
                let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
                let t0 = Fp.mul(X1, X1);
                let t1 = Fp.mul(Y1, Y1);
                let t2 = Fp.mul(Z1, Z1);
                let t3 = Fp.mul(X1, Y1);
                t3 = Fp.add(t3, t3);
                Z3 = Fp.mul(X1, Z1);
                Z3 = Fp.add(Z3, Z3);
                X3 = Fp.mul(a, Z3);
                Y3 = Fp.mul(b3, t2);
                Y3 = Fp.add(X3, Y3);
                X3 = Fp.sub(t1, Y3);
                Y3 = Fp.add(t1, Y3);
                Y3 = Fp.mul(X3, Y3);
                X3 = Fp.mul(t3, X3);
                Z3 = Fp.mul(b3, Z3);
                t2 = Fp.mul(a, t2);
                t3 = Fp.sub(t0, t2);
                t3 = Fp.mul(a, t3);
                t3 = Fp.add(t3, Z3);
                Z3 = Fp.add(t0, t0);
                t0 = Fp.add(Z3, t0);
                t0 = Fp.add(t0, t2);
                t0 = Fp.mul(t0, t3);
                Y3 = Fp.add(Y3, t0);
                t2 = Fp.mul(Y1, Z1);
                t2 = Fp.add(t2, t2);
                t0 = Fp.mul(t2, t3);
                X3 = Fp.sub(X3, t0);
                Z3 = Fp.mul(t2, t1);
                Z3 = Fp.add(Z3, Z3);
                Z3 = Fp.add(Z3, Z3);
                return new Point(X3, Y3, Z3);
            }
            add(other) {
                aprjpoint(other);
                const { X: X1, Y: Y1, Z: Z1 } = this;
                const { X: X2, Y: Y2, Z: Z2 } = other;
                let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
                const a = CURVE.a;
                const b3 = Fp.mul(CURVE.b, _3n$2);
                let t0 = Fp.mul(X1, X2);
                let t1 = Fp.mul(Y1, Y2);
                let t2 = Fp.mul(Z1, Z2);
                let t3 = Fp.add(X1, Y1);
                let t4 = Fp.add(X2, Y2);
                t3 = Fp.mul(t3, t4);
                t4 = Fp.add(t0, t1);
                t3 = Fp.sub(t3, t4);
                t4 = Fp.add(X1, Z1);
                let t5 = Fp.add(X2, Z2);
                t4 = Fp.mul(t4, t5);
                t5 = Fp.add(t0, t2);
                t4 = Fp.sub(t4, t5);
                t5 = Fp.add(Y1, Z1);
                X3 = Fp.add(Y2, Z2);
                t5 = Fp.mul(t5, X3);
                X3 = Fp.add(t1, t2);
                t5 = Fp.sub(t5, X3);
                Z3 = Fp.mul(a, t4);
                X3 = Fp.mul(b3, t2);
                Z3 = Fp.add(X3, Z3);
                X3 = Fp.sub(t1, Z3);
                Z3 = Fp.add(t1, Z3);
                Y3 = Fp.mul(X3, Z3);
                t1 = Fp.add(t0, t0);
                t1 = Fp.add(t1, t0);
                t2 = Fp.mul(a, t2);
                t4 = Fp.mul(b3, t4);
                t1 = Fp.add(t1, t2);
                t2 = Fp.sub(t0, t2);
                t2 = Fp.mul(a, t2);
                t4 = Fp.add(t4, t2);
                t0 = Fp.mul(t1, t4);
                Y3 = Fp.add(Y3, t0);
                t0 = Fp.mul(t5, t4);
                X3 = Fp.mul(t3, X3);
                X3 = Fp.sub(X3, t0);
                t0 = Fp.mul(t3, t1);
                Z3 = Fp.mul(t5, Z3);
                Z3 = Fp.add(Z3, t0);
                return new Point(X3, Y3, Z3);
            }
            subtract(other) {
                return this.add(other.negate());
            }
            is0() {
                return this.equals(Point.ZERO);
            }
            multiply(scalar) {
                const { endo } = extraOpts;
                if (!Fn.isValidNot0(scalar))
                    throw new Error('invalid scalar: out of range');
                let point, fake;
                const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
                if (endo) {
                    const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                    const { p: k1p, f: k1f } = mul(k1);
                    const { p: k2p, f: k2f } = mul(k2);
                    fake = k1f.add(k2f);
                    point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
                }
                else {
                    const { p, f } = mul(scalar);
                    point = p;
                    fake = f;
                }
                return normalizeZ(Point, [point, fake])[0];
            }
            multiplyUnsafe(sc) {
                const { endo } = extraOpts;
                const p = this;
                if (!Fn.isValid(sc))
                    throw new Error('invalid scalar: out of range');
                if (sc === _0n$6 || p.is0())
                    return Point.ZERO;
                if (sc === _1n$5)
                    return p;
                if (wnaf.hasCache(this))
                    return this.multiply(sc);
                if (endo) {
                    const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                    const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
                    return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
                }
                else {
                    return wnaf.unsafe(p, sc);
                }
            }
            multiplyAndAddUnsafe(Q, a, b) {
                const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
                return sum.is0() ? undefined : sum;
            }
            toAffine(invertedZ) {
                return toAffineMemo(this, invertedZ);
            }
            isTorsionFree() {
                const { isTorsionFree } = extraOpts;
                if (cofactor === _1n$5)
                    return true;
                if (isTorsionFree)
                    return isTorsionFree(Point, this);
                return wnaf.unsafe(this, CURVE_ORDER).is0();
            }
            clearCofactor() {
                const { clearCofactor } = extraOpts;
                if (cofactor === _1n$5)
                    return this;
                if (clearCofactor)
                    return clearCofactor(Point, this);
                return this.multiplyUnsafe(cofactor);
            }
            isSmallOrder() {
                return this.multiplyUnsafe(cofactor).is0();
            }
            toBytes(isCompressed = true) {
                _abool2(isCompressed, 'isCompressed');
                this.assertValidity();
                return encodePoint(Point, this, isCompressed);
            }
            toHex(isCompressed = true) {
                return bytesToHex(this.toBytes(isCompressed));
            }
            toString() {
                return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
            }
            get px() {
                return this.X;
            }
            get py() {
                return this.X;
            }
            get pz() {
                return this.Z;
            }
            toRawBytes(isCompressed = true) {
                return this.toBytes(isCompressed);
            }
            _setWindowSize(windowSize) {
                this.precompute(windowSize);
            }
            static normalizeZ(points) {
                return normalizeZ(Point, points);
            }
            static msm(points, scalars) {
                return pippenger(Point, Fn, points, scalars);
            }
            static fromPrivateKey(privateKey) {
                return Point.BASE.multiply(_normFnElement(Fn, privateKey));
            }
        }
        Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
        Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
        Point.Fp = Fp;
        Point.Fn = Fn;
        const bits = Fn.BITS;
        const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
        Point.BASE.precompute(8);
        return Point;
    }
    function pprefix(hasEvenY) {
        return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
    }
    function SWUFpSqrtRatio(Fp, Z) {
        const q = Fp.ORDER;
        let l = _0n$6;
        for (let o = q - _1n$5; o % _2n$5 === _0n$6; o /= _2n$5)
            l += _1n$5;
        const c1 = l;
        const _2n_pow_c1_1 = _2n$5 << (c1 - _1n$5 - _1n$5);
        const _2n_pow_c1 = _2n_pow_c1_1 * _2n$5;
        const c2 = (q - _1n$5) / _2n_pow_c1;
        const c3 = (c2 - _1n$5) / _2n$5;
        const c4 = _2n_pow_c1 - _1n$5;
        const c5 = _2n_pow_c1_1;
        const c6 = Fp.pow(Z, c2);
        const c7 = Fp.pow(Z, (c2 + _1n$5) / _2n$5);
        let sqrtRatio = (u, v) => {
            let tv1 = c6;
            let tv2 = Fp.pow(v, c4);
            let tv3 = Fp.sqr(tv2);
            tv3 = Fp.mul(tv3, v);
            let tv5 = Fp.mul(u, tv3);
            tv5 = Fp.pow(tv5, c3);
            tv5 = Fp.mul(tv5, tv2);
            tv2 = Fp.mul(tv5, v);
            tv3 = Fp.mul(tv5, u);
            let tv4 = Fp.mul(tv3, tv2);
            tv5 = Fp.pow(tv4, c5);
            let isQR = Fp.eql(tv5, Fp.ONE);
            tv2 = Fp.mul(tv3, c7);
            tv5 = Fp.mul(tv4, tv1);
            tv3 = Fp.cmov(tv2, tv3, isQR);
            tv4 = Fp.cmov(tv5, tv4, isQR);
            for (let i = c1; i > _1n$5; i--) {
                let tv5 = i - _2n$5;
                tv5 = _2n$5 << (tv5 - _1n$5);
                let tvv5 = Fp.pow(tv4, tv5);
                const e1 = Fp.eql(tvv5, Fp.ONE);
                tv2 = Fp.mul(tv3, tv1);
                tv1 = Fp.mul(tv1, tv1);
                tvv5 = Fp.mul(tv4, tv1);
                tv3 = Fp.cmov(tv2, tv3, e1);
                tv4 = Fp.cmov(tvv5, tv4, e1);
            }
            return { isValid: isQR, value: tv3 };
        };
        if (Fp.ORDER % _4n === _3n$2) {
            const c1 = (Fp.ORDER - _3n$2) / _4n;
            const c2 = Fp.sqrt(Fp.neg(Z));
            sqrtRatio = (u, v) => {
                let tv1 = Fp.sqr(v);
                const tv2 = Fp.mul(u, v);
                tv1 = Fp.mul(tv1, tv2);
                let y1 = Fp.pow(tv1, c1);
                y1 = Fp.mul(y1, tv2);
                const y2 = Fp.mul(y1, c2);
                const tv3 = Fp.mul(Fp.sqr(y1), v);
                const isQR = Fp.eql(tv3, u);
                let y = Fp.cmov(y2, y1, isQR);
                return { isValid: isQR, value: y };
            };
        }
        return sqrtRatio;
    }
    function mapToCurveSimpleSWU(Fp, opts) {
        validateField(Fp);
        const { A, B, Z } = opts;
        if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
            throw new Error('mapToCurveSimpleSWU: invalid opts');
        const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
        if (!Fp.isOdd)
            throw new Error('Field does not have .isOdd()');
        return (u) => {
            let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
            tv1 = Fp.sqr(u);
            tv1 = Fp.mul(tv1, Z);
            tv2 = Fp.sqr(tv1);
            tv2 = Fp.add(tv2, tv1);
            tv3 = Fp.add(tv2, Fp.ONE);
            tv3 = Fp.mul(tv3, B);
            tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
            tv4 = Fp.mul(tv4, A);
            tv2 = Fp.sqr(tv3);
            tv6 = Fp.sqr(tv4);
            tv5 = Fp.mul(tv6, A);
            tv2 = Fp.add(tv2, tv5);
            tv2 = Fp.mul(tv2, tv3);
            tv6 = Fp.mul(tv6, tv4);
            tv5 = Fp.mul(tv6, B);
            tv2 = Fp.add(tv2, tv5);
            x = Fp.mul(tv1, tv3);
            const { isValid, value } = sqrtRatio(tv2, tv6);
            y = Fp.mul(tv1, u);
            y = Fp.mul(y, value);
            x = Fp.cmov(x, tv3, isValid);
            y = Fp.cmov(y, value, isValid);
            const e1 = Fp.isOdd(u) === Fp.isOdd(y);
            y = Fp.cmov(Fp.neg(y), y, e1);
            const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
            x = Fp.mul(x, tv4_inv);
            return { x, y };
        };
    }
    function getWLengths(Fp, Fn) {
        return {
            secretKey: Fn.BYTES,
            publicKey: 1 + Fp.BYTES,
            publicKeyUncompressed: 1 + 2 * Fp.BYTES,
            publicKeyHasPrefix: true,
            signature: 2 * Fn.BYTES,
        };
    }
    function ecdh(Point, ecdhOpts = {}) {
        const { Fn } = Point;
        const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
        const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
        function isValidSecretKey(secretKey) {
            try {
                return !!_normFnElement(Fn, secretKey);
            }
            catch (error) {
                return false;
            }
        }
        function isValidPublicKey(publicKey, isCompressed) {
            const { publicKey: comp, publicKeyUncompressed } = lengths;
            try {
                const l = publicKey.length;
                if (isCompressed === true && l !== comp)
                    return false;
                if (isCompressed === false && l !== publicKeyUncompressed)
                    return false;
                return !!Point.fromBytes(publicKey);
            }
            catch (error) {
                return false;
            }
        }
        function randomSecretKey(seed = randomBytes_(lengths.seed)) {
            return mapHashToField(_abytes2(seed, lengths.seed, 'seed'), Fn.ORDER);
        }
        function getPublicKey(secretKey, isCompressed = true) {
            return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
        }
        function keygen(seed) {
            const secretKey = randomSecretKey(seed);
            return { secretKey, publicKey: getPublicKey(secretKey) };
        }
        function isProbPub(item) {
            if (typeof item === 'bigint')
                return false;
            if (item instanceof Point)
                return true;
            const { secretKey, publicKey, publicKeyUncompressed } = lengths;
            if (Fn.allowedLengths || secretKey === publicKey)
                return undefined;
            const l = ensureBytes('key', item).length;
            return l === publicKey || l === publicKeyUncompressed;
        }
        function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
            if (isProbPub(secretKeyA) === true)
                throw new Error('first arg must be private key');
            if (isProbPub(publicKeyB) === false)
                throw new Error('second arg must be public key');
            const s = _normFnElement(Fn, secretKeyA);
            const b = Point.fromHex(publicKeyB);
            return b.multiply(s).toBytes(isCompressed);
        }
        const utils = {
            isValidSecretKey,
            isValidPublicKey,
            randomSecretKey,
            isValidPrivateKey: isValidSecretKey,
            randomPrivateKey: randomSecretKey,
            normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
            precompute(windowSize = 8, point = Point.BASE) {
                return point.precompute(windowSize, false);
            },
        };
        return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
    }
    function ecdsa(Point, hash, ecdsaOpts = {}) {
        ahash(hash);
        _validateObject(ecdsaOpts, {}, {
            hmac: 'function',
            lowS: 'boolean',
            randomBytes: 'function',
            bits2int: 'function',
            bits2int_modN: 'function',
        });
        const randomBytes$1 = ecdsaOpts.randomBytes || randomBytes;
        const hmac$1 = ecdsaOpts.hmac ||
            ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs)));
        const { Fp, Fn } = Point;
        const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
        const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
        const defaultSigOpts = {
            prehash: false,
            lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
            format: undefined,
            extraEntropy: false,
        };
        const defaultSigOpts_format = 'compact';
        function isBiggerThanHalfOrder(number) {
            const HALF = CURVE_ORDER >> _1n$5;
            return number > HALF;
        }
        function validateRS(title, num) {
            if (!Fn.isValidNot0(num))
                throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
            return num;
        }
        function validateSigLength(bytes, format) {
            validateSigFormat(format);
            const size = lengths.signature;
            const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
            return _abytes2(bytes, sizer, `${format} signature`);
        }
        class Signature {
            constructor(r, s, recovery) {
                this.r = validateRS('r', r);
                this.s = validateRS('s', s);
                if (recovery != null)
                    this.recovery = recovery;
                Object.freeze(this);
            }
            static fromBytes(bytes, format = defaultSigOpts_format) {
                validateSigLength(bytes, format);
                let recid;
                if (format === 'der') {
                    const { r, s } = DER.toSig(_abytes2(bytes));
                    return new Signature(r, s);
                }
                if (format === 'recovered') {
                    recid = bytes[0];
                    format = 'compact';
                    bytes = bytes.subarray(1);
                }
                const L = Fn.BYTES;
                const r = bytes.subarray(0, L);
                const s = bytes.subarray(L, L * 2);
                return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
            }
            static fromHex(hex, format) {
                return this.fromBytes(hexToBytes(hex), format);
            }
            addRecoveryBit(recovery) {
                return new Signature(this.r, this.s, recovery);
            }
            recoverPublicKey(messageHash) {
                const FIELD_ORDER = Fp.ORDER;
                const { r, s, recovery: rec } = this;
                if (rec == null || ![0, 1, 2, 3].includes(rec))
                    throw new Error('recovery id invalid');
                const hasCofactor = CURVE_ORDER * _2n$5 < FIELD_ORDER;
                if (hasCofactor && rec > 1)
                    throw new Error('recovery id is ambiguous for h>1 curve');
                const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
                if (!Fp.isValid(radj))
                    throw new Error('recovery id 2 or 3 invalid');
                const x = Fp.toBytes(radj);
                const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
                const ir = Fn.inv(radj);
                const h = bits2int_modN(ensureBytes('msgHash', messageHash));
                const u1 = Fn.create(-h * ir);
                const u2 = Fn.create(s * ir);
                const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
                if (Q.is0())
                    throw new Error('point at infinify');
                Q.assertValidity();
                return Q;
            }
            hasHighS() {
                return isBiggerThanHalfOrder(this.s);
            }
            toBytes(format = defaultSigOpts_format) {
                validateSigFormat(format);
                if (format === 'der')
                    return hexToBytes(DER.hexFromSig(this));
                const r = Fn.toBytes(this.r);
                const s = Fn.toBytes(this.s);
                if (format === 'recovered') {
                    if (this.recovery == null)
                        throw new Error('recovery bit must be present');
                    return concatBytes(Uint8Array.of(this.recovery), r, s);
                }
                return concatBytes(r, s);
            }
            toHex(format) {
                return bytesToHex(this.toBytes(format));
            }
            assertValidity() { }
            static fromCompact(hex) {
                return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
            }
            static fromDER(hex) {
                return Signature.fromBytes(ensureBytes('sig', hex), 'der');
            }
            normalizeS() {
                return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
            }
            toDERRawBytes() {
                return this.toBytes('der');
            }
            toDERHex() {
                return bytesToHex(this.toBytes('der'));
            }
            toCompactRawBytes() {
                return this.toBytes('compact');
            }
            toCompactHex() {
                return bytesToHex(this.toBytes('compact'));
            }
        }
        const bits2int = ecdsaOpts.bits2int ||
            function bits2int_def(bytes) {
                if (bytes.length > 8192)
                    throw new Error('input is too large');
                const num = bytesToNumberBE(bytes);
                const delta = bytes.length * 8 - fnBits;
                return delta > 0 ? num >> BigInt(delta) : num;
            };
        const bits2int_modN = ecdsaOpts.bits2int_modN ||
            function bits2int_modN_def(bytes) {
                return Fn.create(bits2int(bytes));
            };
        const ORDER_MASK = bitMask$1(fnBits);
        function int2octets(num) {
            aInRange$1('num < 2^' + fnBits, num, _0n$6, ORDER_MASK);
            return Fn.toBytes(num);
        }
        function validateMsgAndHash(message, prehash) {
            _abytes2(message, undefined, 'message');
            return prehash ? _abytes2(hash(message), undefined, 'prehashed message') : message;
        }
        function prepSig(message, privateKey, opts) {
            if (['recovered', 'canonical'].some((k) => k in opts))
                throw new Error('sign() legacy options not supported');
            const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
            message = validateMsgAndHash(message, prehash);
            const h1int = bits2int_modN(message);
            const d = _normFnElement(Fn, privateKey);
            const seedArgs = [int2octets(d), int2octets(h1int)];
            if (extraEntropy != null && extraEntropy !== false) {
                const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
                seedArgs.push(ensureBytes('extraEntropy', e));
            }
            const seed = concatBytes(...seedArgs);
            const m = h1int;
            function k2sig(kBytes) {
                const k = bits2int(kBytes);
                if (!Fn.isValidNot0(k))
                    return;
                const ik = Fn.inv(k);
                const q = Point.BASE.multiply(k).toAffine();
                const r = Fn.create(q.x);
                if (r === _0n$6)
                    return;
                const s = Fn.create(ik * Fn.create(m + r * d));
                if (s === _0n$6)
                    return;
                let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$5);
                let normS = s;
                if (lowS && isBiggerThanHalfOrder(s)) {
                    normS = Fn.neg(s);
                    recovery ^= 1;
                }
                return new Signature(r, normS, recovery);
            }
            return { seed, k2sig };
        }
        function sign(message, secretKey, opts = {}) {
            message = ensureBytes('message', message);
            const { seed, k2sig } = prepSig(message, secretKey, opts);
            const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac$1);
            const sig = drbg(seed, k2sig);
            return sig;
        }
        function tryParsingSig(sg) {
            let sig = undefined;
            const isHex = typeof sg === 'string' || isBytes$1(sg);
            const isObj = !isHex &&
                sg !== null &&
                typeof sg === 'object' &&
                typeof sg.r === 'bigint' &&
                typeof sg.s === 'bigint';
            if (!isHex && !isObj)
                throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
            if (isObj) {
                sig = new Signature(sg.r, sg.s);
            }
            else if (isHex) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
                }
                catch (derError) {
                    if (!(derError instanceof DER.Err))
                        throw derError;
                }
                if (!sig) {
                    try {
                        sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                    }
                    catch (error) {
                        return false;
                    }
                }
            }
            if (!sig)
                return false;
            return sig;
        }
        function verify(signature, message, publicKey, opts = {}) {
            const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
            publicKey = ensureBytes('publicKey', publicKey);
            message = validateMsgAndHash(ensureBytes('message', message), prehash);
            if ('strict' in opts)
                throw new Error('options.strict was renamed to lowS');
            const sig = format === undefined
                ? tryParsingSig(signature)
                : Signature.fromBytes(ensureBytes('sig', signature), format);
            if (sig === false)
                return false;
            try {
                const P = Point.fromBytes(publicKey);
                if (lowS && sig.hasHighS())
                    return false;
                const { r, s } = sig;
                const h = bits2int_modN(message);
                const is = Fn.inv(s);
                const u1 = Fn.create(h * is);
                const u2 = Fn.create(r * is);
                const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
                if (R.is0())
                    return false;
                const v = Fn.create(R.x);
                return v === r;
            }
            catch (e) {
                return false;
            }
        }
        function recoverPublicKey(signature, message, opts = {}) {
            const { prehash } = validateSigOpts(opts, defaultSigOpts);
            message = validateMsgAndHash(message, prehash);
            return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
        }
        return Object.freeze({
            keygen,
            getPublicKey,
            getSharedSecret,
            utils,
            lengths,
            Point,
            sign,
            verify,
            recoverPublicKey,
            Signature,
            hash,
        });
    }
    function _weierstrass_legacy_opts_to_new(c) {
        const CURVE = {
            a: c.a,
            b: c.b,
            p: c.Fp.ORDER,
            n: c.n,
            h: c.h,
            Gx: c.Gx,
            Gy: c.Gy,
        };
        const Fp = c.Fp;
        let allowedLengths = c.allowedPrivateKeyLengths
            ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
            : undefined;
        const Fn = Field(CURVE.n, {
            BITS: c.nBitLength,
            allowedLengths: allowedLengths,
            modFromBytes: c.wrapPrivateKey,
        });
        const curveOpts = {
            Fp,
            Fn,
            allowInfinityPoint: c.allowInfinityPoint,
            endo: c.endo,
            isTorsionFree: c.isTorsionFree,
            clearCofactor: c.clearCofactor,
            fromBytes: c.fromBytes,
            toBytes: c.toBytes,
        };
        return { CURVE, curveOpts };
    }
    function _ecdsa_legacy_opts_to_new(c) {
        const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
        const ecdsaOpts = {
            hmac: c.hmac,
            randomBytes: c.randomBytes,
            lowS: c.lowS,
            bits2int: c.bits2int,
            bits2int_modN: c.bits2int_modN,
        };
        return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
    }
    function _ecdsa_new_output_to_legacy(c, _ecdsa) {
        const Point = _ecdsa.Point;
        return Object.assign({}, _ecdsa, {
            ProjectivePoint: Point,
            CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
        });
    }
    function weierstrass(c) {
        const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
        const Point = weierstrassN(CURVE, curveOpts);
        const signs = ecdsa(Point, hash, ecdsaOpts);
        return _ecdsa_new_output_to_legacy(c, signs);
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    function createCurve(curveDef, defHash) {
        const create = (hash) => weierstrass({ ...curveDef, hash: hash });
        return { ...create(defHash), create };
    }

    const os2ip = bytesToNumberBE;
    function i2osp(value, length) {
        anum(value);
        anum(length);
        if (value < 0 || value >= 1 << (8 * length))
            throw new Error('invalid I2OSP input: ' + value);
        const res = Array.from({ length }).fill(0);
        for (let i = length - 1; i >= 0; i--) {
            res[i] = value & 0xff;
            value >>>= 8;
        }
        return new Uint8Array(res);
    }
    function strxor(a, b) {
        const arr = new Uint8Array(a.length);
        for (let i = 0; i < a.length; i++) {
            arr[i] = a[i] ^ b[i];
        }
        return arr;
    }
    function anum(item) {
        if (!Number.isSafeInteger(item))
            throw new Error('number expected');
    }
    function normDST(DST) {
        if (!isBytes$1(DST) && typeof DST !== 'string')
            throw new Error('DST must be Uint8Array or string');
        return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
    }
    function expand_message_xmd(msg, DST, lenInBytes, H) {
        abytes$1(msg);
        anum(lenInBytes);
        DST = normDST(DST);
        if (DST.length > 255)
            DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
        const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
        const ell = Math.ceil(lenInBytes / b_in_bytes);
        if (lenInBytes > 65535 || ell > 255)
            throw new Error('expand_message_xmd: invalid lenInBytes');
        const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
        const Z_pad = i2osp(0, r_in_bytes);
        const l_i_b_str = i2osp(lenInBytes, 2);
        const b = new Array(ell);
        const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
        b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
        for (let i = 1; i <= ell; i++) {
            const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
            b[i] = H(concatBytes(...args));
        }
        const pseudo_random_bytes = concatBytes(...b);
        return pseudo_random_bytes.slice(0, lenInBytes);
    }
    function expand_message_xof(msg, DST, lenInBytes, k, H) {
        abytes$1(msg);
        anum(lenInBytes);
        DST = normDST(DST);
        if (DST.length > 255) {
            const dkLen = Math.ceil((2 * k) / 8);
            DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
        }
        if (lenInBytes > 65535 || DST.length > 255)
            throw new Error('expand_message_xof: invalid lenInBytes');
        return (H.create({ dkLen: lenInBytes })
            .update(msg)
            .update(i2osp(lenInBytes, 2))
            .update(DST)
            .update(i2osp(DST.length, 1))
            .digest());
    }
    function hash_to_field(msg, count, options) {
        _validateObject(options, {
            p: 'bigint',
            m: 'number',
            k: 'number',
            hash: 'function',
        });
        const { p, k, m, hash, expand, DST } = options;
        if (!isHash(options.hash))
            throw new Error('expected valid hash');
        abytes$1(msg);
        anum(count);
        const log2p = p.toString(2).length;
        const L = Math.ceil((log2p + k) / 8);
        const len_in_bytes = count * m * L;
        let prb;
        if (expand === 'xmd') {
            prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
        }
        else if (expand === 'xof') {
            prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
        }
        else if (expand === '_internal_pass') {
            prb = msg;
        }
        else {
            throw new Error('expand must be "xmd" or "xof"');
        }
        const u = new Array(count);
        for (let i = 0; i < count; i++) {
            const e = new Array(m);
            for (let j = 0; j < m; j++) {
                const elm_offset = L * (j + i * m);
                const tv = prb.subarray(elm_offset, elm_offset + L);
                e[j] = mod(os2ip(tv), p);
            }
            u[i] = e;
        }
        return u;
    }
    function isogenyMap(field, map) {
        const coeff = map.map((i) => Array.from(i).reverse());
        return (x, y) => {
            const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
            const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
            x = field.mul(xn, xd_inv);
            y = field.mul(y, field.mul(yn, yd_inv));
            return { x, y };
        };
    }
    const _DST_scalar = utf8ToBytes('HashToScalar-');
    function createHasher(Point, mapToCurve, defaults) {
        if (typeof mapToCurve !== 'function')
            throw new Error('mapToCurve() must be defined');
        function map(num) {
            return Point.fromAffine(mapToCurve(num));
        }
        function clear(initial) {
            const P = initial.clearCofactor();
            if (P.equals(Point.ZERO))
                return Point.ZERO;
            P.assertValidity();
            return P;
        }
        return {
            defaults,
            hashToCurve(msg, options) {
                const opts = Object.assign({}, defaults, options);
                const u = hash_to_field(msg, 2, opts);
                const u0 = map(u[0]);
                const u1 = map(u[1]);
                return clear(u0.add(u1));
            },
            encodeToCurve(msg, options) {
                const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
                const opts = Object.assign({}, defaults, optsDst, options);
                const u = hash_to_field(msg, 1, opts);
                const u0 = map(u[0]);
                return clear(u0);
            },
            mapToCurve(scalars) {
                if (!Array.isArray(scalars))
                    throw new Error('expected array of bigints');
                for (const i of scalars)
                    if (typeof i !== 'bigint')
                        throw new Error('expected array of bigints');
                return clear(map(scalars));
            },
            hashToScalar(msg, options) {
                const N = Point.Fn.ORDER;
                const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
                return hash_to_field(msg, 1, opts)[0][0];
            },
        };
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const secp256k1_CURVE = {
        p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
        n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
        h: BigInt(1),
        a: BigInt(0),
        b: BigInt(7),
        Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
        Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
    };
    const secp256k1_ENDO = {
        beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
        basises: [
            [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
            [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
        ],
    };
    const _0n$5 =  BigInt(0);
    const _1n$4 =  BigInt(1);
    const _2n$4 =  BigInt(2);
    function sqrtMod(y) {
        const P = secp256k1_CURVE.p;
        const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
        const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
        const b2 = (y * y * y) % P;
        const b3 = (b2 * b2 * y) % P;
        const b6 = (pow2(b3, _3n, P) * b3) % P;
        const b9 = (pow2(b6, _3n, P) * b3) % P;
        const b11 = (pow2(b9, _2n$4, P) * b2) % P;
        const b22 = (pow2(b11, _11n, P) * b11) % P;
        const b44 = (pow2(b22, _22n, P) * b22) % P;
        const b88 = (pow2(b44, _44n, P) * b44) % P;
        const b176 = (pow2(b88, _88n, P) * b88) % P;
        const b220 = (pow2(b176, _44n, P) * b44) % P;
        const b223 = (pow2(b220, _3n, P) * b3) % P;
        const t1 = (pow2(b223, _23n, P) * b22) % P;
        const t2 = (pow2(t1, _6n, P) * b2) % P;
        const root = pow2(t2, _2n$4, P);
        if (!Fpk1.eql(Fpk1.sqr(root), y))
            throw new Error('Cannot find square root');
        return root;
    }
    const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
    const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256$1);
    const TAGGED_HASH_PREFIXES = {};
    function taggedHash(tag, ...messages) {
        let tagP = TAGGED_HASH_PREFIXES[tag];
        if (tagP === undefined) {
            const tagH = sha256$1(utf8ToBytes(tag));
            tagP = concatBytes(tagH, tagH);
            TAGGED_HASH_PREFIXES[tag] = tagP;
        }
        return sha256$1(concatBytes(tagP, ...messages));
    }
    const pointToBytes = (point) => point.toBytes(true).slice(1);
    const Pointk1 =  (() => secp256k1.Point)();
    const hasEven = (y) => y % _2n$4 === _0n$5;
    function schnorrGetExtPubKey(priv) {
        const { Fn, BASE } = Pointk1;
        const d_ = _normFnElement(Fn, priv);
        const p = BASE.multiply(d_);
        const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
        return { scalar, bytes: pointToBytes(p) };
    }
    function lift_x(x) {
        const Fp = Fpk1;
        if (!Fp.isValidNot0(x))
            throw new Error('invalid x: Fail if x ≥ p');
        const xx = Fp.create(x * x);
        const c = Fp.create(xx * x + BigInt(7));
        let y = Fp.sqrt(c);
        if (!hasEven(y))
            y = Fp.neg(y);
        const p = Pointk1.fromAffine({ x, y });
        p.assertValidity();
        return p;
    }
    const num = bytesToNumberBE;
    function challenge(...args) {
        return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
    }
    function schnorrGetPublicKey(secretKey) {
        return schnorrGetExtPubKey(secretKey).bytes;
    }
    function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
        const { Fn } = Pointk1;
        const m = ensureBytes('message', message);
        const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey);
        const a = ensureBytes('auxRand', auxRand, 32);
        const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));
        const rand = taggedHash('BIP0340/nonce', t, px, m);
        const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
        const e = challenge(rx, px, m);
        const sig = new Uint8Array(64);
        sig.set(rx, 0);
        sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
        if (!schnorrVerify(sig, m, px))
            throw new Error('sign: Invalid signature produced');
        return sig;
    }
    function schnorrVerify(signature, message, publicKey) {
        const { Fn, BASE } = Pointk1;
        const sig = ensureBytes('signature', signature, 64);
        const m = ensureBytes('message', message);
        const pub = ensureBytes('publicKey', publicKey, 32);
        try {
            const P = lift_x(num(pub));
            const r = num(sig.subarray(0, 32));
            if (!inRange(r, _1n$4, secp256k1_CURVE.p))
                return false;
            const s = num(sig.subarray(32, 64));
            if (!inRange(s, _1n$4, secp256k1_CURVE.n))
                return false;
            const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
            const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
            const { x, y } = R.toAffine();
            if (R.is0() || !hasEven(y) || x !== r)
                return false;
            return true;
        }
        catch (error) {
            return false;
        }
    }
    (() => {
        const size = 32;
        const seedLength = 48;
        const randomSecretKey = (seed = randomBytes(seedLength)) => {
            return mapHashToField(seed, secp256k1_CURVE.n);
        };
        secp256k1.utils.randomSecretKey;
        function keygen(seed) {
            const secretKey = randomSecretKey(seed);
            return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
        }
        return {
            keygen,
            getPublicKey: schnorrGetPublicKey,
            sign: schnorrSign,
            verify: schnorrVerify,
            Point: Pointk1,
            utils: {
                randomSecretKey: randomSecretKey,
                randomPrivateKey: randomSecretKey,
                taggedHash,
                lift_x,
                pointToBytes,
                numberToBytesBE,
                bytesToNumberBE,
                mod,
            },
            lengths: {
                secretKey: size,
                publicKey: size,
                publicKeyHasPrefix: false,
                signature: size * 2,
                seed: seedLength,
            },
        };
    })();
    const isoMap =  (() => isogenyMap(Fpk1, [
        [
            '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
            '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
            '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
            '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
        ],
        [
            '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
            '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
            '0x0000000000000000000000000000000000000000000000000000000000000001',
        ],
        [
            '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
            '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
            '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
            '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
        ],
        [
            '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
            '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
            '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
            '0x0000000000000000000000000000000000000000000000000000000000000001',
        ],
    ].map((i) => i.map((j) => BigInt(j)))))();
    const mapSWU =  (() => mapToCurveSimpleSWU(Fpk1, {
        A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
        B: BigInt('1771'),
        Z: Fpk1.create(BigInt('-11')),
    }))();
    (() => createHasher(secp256k1.Point, (scalars) => {
        const { x, y } = mapSWU(Fpk1.create(scalars[0]));
        return isoMap(x, y);
    }, {
        DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
        encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
        p: Fpk1.ORDER,
        m: 1,
        k: 128,
        expand: 'xmd',
        hash: sha256$1,
    }))();

    function secp256k1PairFromSeed(seed, onlyJs) {
        if (seed.length !== 32) {
            throw new Error('Expected valid 32-byte private key as a seed');
        }
        if (!util.hasBigInt || (!onlyJs && isReady())) {
            const full = secp256k1FromSeed(seed);
            const publicKey = full.slice(32);
            if (util.u8aEmpty(publicKey)) {
                throw new Error('Invalid publicKey generated from WASM interface');
            }
            return {
                publicKey,
                secretKey: full.slice(0, 32)
            };
        }
        return {
            publicKey: secp256k1.getPublicKey(seed, true),
            secretKey: seed
        };
    }

    function createSeedDeriveFn(fromSeed, derive) {
        return (keypair, { chainCode, isHard }) => {
            if (!isHard) {
                throw new Error('A soft key was found in the path and is not supported');
            }
            return fromSeed(derive(keypair.secretKey.subarray(0, 32), chainCode));
        };
    }

    const keyHdkdEcdsa =  createSeedDeriveFn(secp256k1PairFromSeed, secp256k1DeriveHard);

    const HDKD$1 = util.compactAddLength(util.stringToU8a('Ed25519HDKD'));
    function ed25519DeriveHard(seed, chainCode) {
        if (!util.isU8a(chainCode) || chainCode.length !== 32) {
            throw new Error('Invalid chainCode passed to derive');
        }
        return blake2AsU8a(util.u8aConcat(HDKD$1, seed, chainCode));
    }

    function randomAsU8a(length = 32) {
        return browser.getRandomValues(new Uint8Array(length));
    }
    const randomAsHex =  createAsHex(randomAsU8a);

    const BN_53 = new util.BN(0b11111111111111111111111111111111111111111111111111111);
    function randomAsNumber() {
        return util.hexToBn(randomAsHex(8)).and(BN_53).toNumber();
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$4 = BigInt(0), _1n$3 = BigInt(1), _2n$3 = BigInt(2), _8n$1 = BigInt(8);
    function isEdValidXY(Fp, CURVE, x, y) {
        const x2 = Fp.sqr(x);
        const y2 = Fp.sqr(y);
        const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
        const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
        return Fp.eql(left, right);
    }
    function edwards(params, extraOpts = {}) {
        const validated = _createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);
        const { Fp, Fn } = validated;
        let CURVE = validated.CURVE;
        const { h: cofactor } = CURVE;
        _validateObject(extraOpts, {}, { uvRatio: 'function' });
        const MASK = _2n$3 << (BigInt(Fn.BYTES * 8) - _1n$3);
        const modP = (n) => Fp.create(n);
        const uvRatio = extraOpts.uvRatio ||
            ((u, v) => {
                try {
                    return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
                }
                catch (e) {
                    return { isValid: false, value: _0n$4 };
                }
            });
        if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
            throw new Error('bad curve params: generator point');
        function acoord(title, n, banZero = false) {
            const min = banZero ? _1n$3 : _0n$4;
            aInRange$1('coordinate ' + title, n, min, MASK);
            return n;
        }
        function aextpoint(other) {
            if (!(other instanceof Point))
                throw new Error('ExtendedPoint expected');
        }
        const toAffineMemo = memoized((p, iz) => {
            const { X, Y, Z } = p;
            const is0 = p.is0();
            if (iz == null)
                iz = is0 ? _8n$1 : Fp.inv(Z);
            const x = modP(X * iz);
            const y = modP(Y * iz);
            const zz = Fp.mul(Z, iz);
            if (is0)
                return { x: _0n$4, y: _1n$3 };
            if (zz !== _1n$3)
                throw new Error('invZ was invalid');
            return { x, y };
        });
        const assertValidMemo = memoized((p) => {
            const { a, d } = CURVE;
            if (p.is0())
                throw new Error('bad point: ZERO');
            const { X, Y, Z, T } = p;
            const X2 = modP(X * X);
            const Y2 = modP(Y * Y);
            const Z2 = modP(Z * Z);
            const Z4 = modP(Z2 * Z2);
            const aX2 = modP(X2 * a);
            const left = modP(Z2 * modP(aX2 + Y2));
            const right = modP(Z4 + modP(d * modP(X2 * Y2)));
            if (left !== right)
                throw new Error('bad point: equation left != right (1)');
            const XY = modP(X * Y);
            const ZT = modP(Z * T);
            if (XY !== ZT)
                throw new Error('bad point: equation left != right (2)');
            return true;
        });
        class Point {
            constructor(X, Y, Z, T) {
                this.X = acoord('x', X);
                this.Y = acoord('y', Y);
                this.Z = acoord('z', Z, true);
                this.T = acoord('t', T);
                Object.freeze(this);
            }
            static CURVE() {
                return CURVE;
            }
            static fromAffine(p) {
                if (p instanceof Point)
                    throw new Error('extended point not allowed');
                const { x, y } = p || {};
                acoord('x', x);
                acoord('y', y);
                return new Point(x, y, _1n$3, modP(x * y));
            }
            static fromBytes(bytes, zip215 = false) {
                const len = Fp.BYTES;
                const { a, d } = CURVE;
                bytes = copyBytes(_abytes2(bytes, len, 'point'));
                _abool2(zip215, 'zip215');
                const normed = copyBytes(bytes);
                const lastByte = bytes[len - 1];
                normed[len - 1] = lastByte & -129;
                const y = bytesToNumberLE$1(normed);
                const max = zip215 ? MASK : Fp.ORDER;
                aInRange$1('point.y', y, _0n$4, max);
                const y2 = modP(y * y);
                const u = modP(y2 - _1n$3);
                const v = modP(d * y2 - a);
                let { isValid, value: x } = uvRatio(u, v);
                if (!isValid)
                    throw new Error('bad point: invalid y coordinate');
                const isXOdd = (x & _1n$3) === _1n$3;
                const isLastByteOdd = (lastByte & 0x80) !== 0;
                if (!zip215 && x === _0n$4 && isLastByteOdd)
                    throw new Error('bad point: x=0 and x_0=1');
                if (isLastByteOdd !== isXOdd)
                    x = modP(-x);
                return Point.fromAffine({ x, y });
            }
            static fromHex(bytes, zip215 = false) {
                return Point.fromBytes(ensureBytes('point', bytes), zip215);
            }
            get x() {
                return this.toAffine().x;
            }
            get y() {
                return this.toAffine().y;
            }
            precompute(windowSize = 8, isLazy = true) {
                wnaf.createCache(this, windowSize);
                if (!isLazy)
                    this.multiply(_2n$3);
                return this;
            }
            assertValidity() {
                assertValidMemo(this);
            }
            equals(other) {
                aextpoint(other);
                const { X: X1, Y: Y1, Z: Z1 } = this;
                const { X: X2, Y: Y2, Z: Z2 } = other;
                const X1Z2 = modP(X1 * Z2);
                const X2Z1 = modP(X2 * Z1);
                const Y1Z2 = modP(Y1 * Z2);
                const Y2Z1 = modP(Y2 * Z1);
                return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
            }
            is0() {
                return this.equals(Point.ZERO);
            }
            negate() {
                return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
            }
            double() {
                const { a } = CURVE;
                const { X: X1, Y: Y1, Z: Z1 } = this;
                const A = modP(X1 * X1);
                const B = modP(Y1 * Y1);
                const C = modP(_2n$3 * modP(Z1 * Z1));
                const D = modP(a * A);
                const x1y1 = X1 + Y1;
                const E = modP(modP(x1y1 * x1y1) - A - B);
                const G = D + B;
                const F = G - C;
                const H = D - B;
                const X3 = modP(E * F);
                const Y3 = modP(G * H);
                const T3 = modP(E * H);
                const Z3 = modP(F * G);
                return new Point(X3, Y3, Z3, T3);
            }
            add(other) {
                aextpoint(other);
                const { a, d } = CURVE;
                const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
                const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
                const A = modP(X1 * X2);
                const B = modP(Y1 * Y2);
                const C = modP(T1 * d * T2);
                const D = modP(Z1 * Z2);
                const E = modP((X1 + Y1) * (X2 + Y2) - A - B);
                const F = D - C;
                const G = D + C;
                const H = modP(B - a * A);
                const X3 = modP(E * F);
                const Y3 = modP(G * H);
                const T3 = modP(E * H);
                const Z3 = modP(F * G);
                return new Point(X3, Y3, Z3, T3);
            }
            subtract(other) {
                return this.add(other.negate());
            }
            multiply(scalar) {
                if (!Fn.isValidNot0(scalar))
                    throw new Error('invalid scalar: expected 1 <= sc < curve.n');
                const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
                return normalizeZ(Point, [p, f])[0];
            }
            multiplyUnsafe(scalar, acc = Point.ZERO) {
                if (!Fn.isValid(scalar))
                    throw new Error('invalid scalar: expected 0 <= sc < curve.n');
                if (scalar === _0n$4)
                    return Point.ZERO;
                if (this.is0() || scalar === _1n$3)
                    return this;
                return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
            }
            isSmallOrder() {
                return this.multiplyUnsafe(cofactor).is0();
            }
            isTorsionFree() {
                return wnaf.unsafe(this, CURVE.n).is0();
            }
            toAffine(invertedZ) {
                return toAffineMemo(this, invertedZ);
            }
            clearCofactor() {
                if (cofactor === _1n$3)
                    return this;
                return this.multiplyUnsafe(cofactor);
            }
            toBytes() {
                const { x, y } = this.toAffine();
                const bytes = Fp.toBytes(y);
                bytes[bytes.length - 1] |= x & _1n$3 ? 0x80 : 0;
                return bytes;
            }
            toHex() {
                return bytesToHex(this.toBytes());
            }
            toString() {
                return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
            }
            get ex() {
                return this.X;
            }
            get ey() {
                return this.Y;
            }
            get ez() {
                return this.Z;
            }
            get et() {
                return this.T;
            }
            static normalizeZ(points) {
                return normalizeZ(Point, points);
            }
            static msm(points, scalars) {
                return pippenger(Point, Fn, points, scalars);
            }
            _setWindowSize(windowSize) {
                this.precompute(windowSize);
            }
            toRawBytes() {
                return this.toBytes();
            }
        }
        Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$3, modP(CURVE.Gx * CURVE.Gy));
        Point.ZERO = new Point(_0n$4, _1n$3, _1n$3, _0n$4);
        Point.Fp = Fp;
        Point.Fn = Fn;
        const wnaf = new wNAF(Point, Fn.BITS);
        Point.BASE.precompute(8);
        return Point;
    }
    class PrimeEdwardsPoint {
        constructor(ep) {
            this.ep = ep;
        }
        static fromBytes(_bytes) {
            notImplemented();
        }
        static fromHex(_hex) {
            notImplemented();
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        clearCofactor() {
            return this;
        }
        assertValidity() {
            this.ep.assertValidity();
        }
        toAffine(invertedZ) {
            return this.ep.toAffine(invertedZ);
        }
        toHex() {
            return bytesToHex(this.toBytes());
        }
        toString() {
            return this.toHex();
        }
        isTorsionFree() {
            return true;
        }
        isSmallOrder() {
            return false;
        }
        add(other) {
            this.assertSame(other);
            return this.init(this.ep.add(other.ep));
        }
        subtract(other) {
            this.assertSame(other);
            return this.init(this.ep.subtract(other.ep));
        }
        multiply(scalar) {
            return this.init(this.ep.multiply(scalar));
        }
        multiplyUnsafe(scalar) {
            return this.init(this.ep.multiplyUnsafe(scalar));
        }
        double() {
            return this.init(this.ep.double());
        }
        negate() {
            return this.init(this.ep.negate());
        }
        precompute(windowSize, isLazy) {
            return this.init(this.ep.precompute(windowSize, isLazy));
        }
        toRawBytes() {
            return this.toBytes();
        }
    }
    function eddsa(Point, cHash, eddsaOpts = {}) {
        if (typeof cHash !== 'function')
            throw new Error('"hash" function param is required');
        _validateObject(eddsaOpts, {}, {
            adjustScalarBytes: 'function',
            randomBytes: 'function',
            domain: 'function',
            prehash: 'function',
            mapToCurve: 'function',
        });
        const { prehash } = eddsaOpts;
        const { BASE, Fp, Fn } = Point;
        const randomBytes$1 = eddsaOpts.randomBytes || randomBytes;
        const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
        const domain = eddsaOpts.domain ||
            ((data, ctx, phflag) => {
                _abool2(phflag, 'phflag');
                if (ctx.length || phflag)
                    throw new Error('Contexts/pre-hash are not supported');
                return data;
            });
        function modN_LE(hash) {
            return Fn.create(bytesToNumberLE$1(hash));
        }
        function getPrivateScalar(key) {
            const len = lengths.secretKey;
            key = ensureBytes('private key', key, len);
            const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);
            const head = adjustScalarBytes(hashed.slice(0, len));
            const prefix = hashed.slice(len, 2 * len);
            const scalar = modN_LE(head);
            return { head, prefix, scalar };
        }
        function getExtendedPublicKey(secretKey) {
            const { head, prefix, scalar } = getPrivateScalar(secretKey);
            const point = BASE.multiply(scalar);
            const pointBytes = point.toBytes();
            return { head, prefix, scalar, point, pointBytes };
        }
        function getPublicKey(secretKey) {
            return getExtendedPublicKey(secretKey).pointBytes;
        }
        function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
            const msg = concatBytes(...msgs);
            return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));
        }
        function sign(msg, secretKey, options = {}) {
            msg = ensureBytes('message', msg);
            if (prehash)
                msg = prehash(msg);
            const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
            const r = hashDomainToScalar(options.context, prefix, msg);
            const R = BASE.multiply(r).toBytes();
            const k = hashDomainToScalar(options.context, R, pointBytes, msg);
            const s = Fn.create(r + k * scalar);
            if (!Fn.isValid(s))
                throw new Error('sign failed: invalid s');
            const rs = concatBytes(R, Fn.toBytes(s));
            return _abytes2(rs, lengths.signature, 'result');
        }
        const verifyOpts = { zip215: true };
        function verify(sig, msg, publicKey, options = verifyOpts) {
            const { context, zip215 } = options;
            const len = lengths.signature;
            sig = ensureBytes('signature', sig, len);
            msg = ensureBytes('message', msg);
            publicKey = ensureBytes('publicKey', publicKey, lengths.publicKey);
            if (zip215 !== undefined)
                _abool2(zip215, 'zip215');
            if (prehash)
                msg = prehash(msg);
            const mid = len / 2;
            const r = sig.subarray(0, mid);
            const s = bytesToNumberLE$1(sig.subarray(mid, len));
            let A, R, SB;
            try {
                A = Point.fromBytes(publicKey, zip215);
                R = Point.fromBytes(r, zip215);
                SB = BASE.multiplyUnsafe(s);
            }
            catch (error) {
                return false;
            }
            if (!zip215 && A.isSmallOrder())
                return false;
            const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
            const RkA = R.add(A.multiplyUnsafe(k));
            return RkA.subtract(SB).clearCofactor().is0();
        }
        const _size = Fp.BYTES;
        const lengths = {
            secretKey: _size,
            publicKey: _size,
            signature: 2 * _size,
            seed: _size,
        };
        function randomSecretKey(seed = randomBytes$1(lengths.seed)) {
            return _abytes2(seed, lengths.seed, 'seed');
        }
        function keygen(seed) {
            const secretKey = utils.randomSecretKey(seed);
            return { secretKey, publicKey: getPublicKey(secretKey) };
        }
        function isValidSecretKey(key) {
            return isBytes$1(key) && key.length === Fn.BYTES;
        }
        function isValidPublicKey(key, zip215) {
            try {
                return !!Point.fromBytes(key, zip215);
            }
            catch (error) {
                return false;
            }
        }
        const utils = {
            getExtendedPublicKey,
            randomSecretKey,
            isValidSecretKey,
            isValidPublicKey,
            toMontgomery(publicKey) {
                const { y } = Point.fromBytes(publicKey);
                const size = lengths.publicKey;
                const is25519 = size === 32;
                if (!is25519 && size !== 57)
                    throw new Error('only defined for 25519 and 448');
                const u = is25519 ? Fp.div(_1n$3 + y, _1n$3 - y) : Fp.div(y - _1n$3, y + _1n$3);
                return Fp.toBytes(u);
            },
            toMontgomerySecret(secretKey) {
                const size = lengths.secretKey;
                _abytes2(secretKey, size);
                const hashed = cHash(secretKey.subarray(0, size));
                return adjustScalarBytes(hashed).subarray(0, size);
            },
            randomPrivateKey: randomSecretKey,
            precompute(windowSize = 8, point = Point.BASE) {
                return point.precompute(windowSize, false);
            },
        };
        return Object.freeze({
            keygen,
            getPublicKey,
            sign,
            verify,
            utils,
            Point,
            lengths,
        });
    }
    function _eddsa_legacy_opts_to_new(c) {
        const CURVE = {
            a: c.a,
            d: c.d,
            p: c.Fp.ORDER,
            n: c.n,
            h: c.h,
            Gx: c.Gx,
            Gy: c.Gy,
        };
        const Fp = c.Fp;
        const Fn = Field(CURVE.n, c.nBitLength, true);
        const curveOpts = { Fp, Fn, uvRatio: c.uvRatio };
        const eddsaOpts = {
            randomBytes: c.randomBytes,
            adjustScalarBytes: c.adjustScalarBytes,
            domain: c.domain,
            prehash: c.prehash,
            mapToCurve: c.mapToCurve,
        };
        return { CURVE, curveOpts, hash: c.hash, eddsaOpts };
    }
    function _eddsa_new_output_to_legacy(c, eddsa) {
        const Point = eddsa.Point;
        const legacy = Object.assign({}, eddsa, {
            ExtendedPoint: Point,
            CURVE: c,
            nBitLength: Point.Fn.BITS,
            nByteLength: Point.Fn.BYTES,
        });
        return legacy;
    }
    function twistedEdwards(c) {
        const { CURVE, curveOpts, hash, eddsaOpts } = _eddsa_legacy_opts_to_new(c);
        const Point = edwards(CURVE, curveOpts);
        const EDDSA = eddsa(Point, hash, eddsaOpts);
        return _eddsa_new_output_to_legacy(c, EDDSA);
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$3 = BigInt(0);
    const _1n$2 = BigInt(1);
    const _2n$2 = BigInt(2);
    function validateOpts(curve) {
        _validateObject(curve, {
            adjustScalarBytes: 'function',
            powPminus2: 'function',
        });
        return Object.freeze({ ...curve });
    }
    function montgomery(curveDef) {
        const CURVE = validateOpts(curveDef);
        const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;
        const is25519 = type === 'x25519';
        if (!is25519 && type !== 'x448')
            throw new Error('invalid type');
        const randomBytes_ = rand || randomBytes;
        const montgomeryBits = is25519 ? 255 : 448;
        const fieldLen = is25519 ? 32 : 56;
        const Gu = is25519 ? BigInt(9) : BigInt(5);
        const a24 = is25519 ? BigInt(121665) : BigInt(39081);
        const minScalar = is25519 ? _2n$2 ** BigInt(254) : _2n$2 ** BigInt(447);
        const maxAdded = is25519
            ? BigInt(8) * _2n$2 ** BigInt(251) - _1n$2
            : BigInt(4) * _2n$2 ** BigInt(445) - _1n$2;
        const maxScalar = minScalar + maxAdded + _1n$2;
        const modP = (n) => mod(n, P);
        const GuBytes = encodeU(Gu);
        function encodeU(u) {
            return numberToBytesLE$1(modP(u), fieldLen);
        }
        function decodeU(u) {
            const _u = ensureBytes('u coordinate', u, fieldLen);
            if (is25519)
                _u[31] &= 127;
            return modP(bytesToNumberLE$1(_u));
        }
        function decodeScalar(scalar) {
            return bytesToNumberLE$1(adjustScalarBytes(ensureBytes('scalar', scalar, fieldLen)));
        }
        function scalarMult(scalar, u) {
            const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));
            if (pu === _0n$3)
                throw new Error('invalid private or public key received');
            return encodeU(pu);
        }
        function scalarMultBase(scalar) {
            return scalarMult(scalar, GuBytes);
        }
        function cswap(swap, x_2, x_3) {
            const dummy = modP(swap * (x_2 - x_3));
            x_2 = modP(x_2 - dummy);
            x_3 = modP(x_3 + dummy);
            return { x_2, x_3 };
        }
        function montgomeryLadder(u, scalar) {
            aInRange$1('u', u, _0n$3, P);
            aInRange$1('scalar', scalar, minScalar, maxScalar);
            const k = scalar;
            const x_1 = u;
            let x_2 = _1n$2;
            let z_2 = _0n$3;
            let x_3 = u;
            let z_3 = _1n$2;
            let swap = _0n$3;
            for (let t = BigInt(montgomeryBits - 1); t >= _0n$3; t--) {
                const k_t = (k >> t) & _1n$2;
                swap ^= k_t;
                ({ x_2, x_3 } = cswap(swap, x_2, x_3));
                ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
                swap = k_t;
                const A = x_2 + z_2;
                const AA = modP(A * A);
                const B = x_2 - z_2;
                const BB = modP(B * B);
                const E = AA - BB;
                const C = x_3 + z_3;
                const D = x_3 - z_3;
                const DA = modP(D * A);
                const CB = modP(C * B);
                const dacb = DA + CB;
                const da_cb = DA - CB;
                x_3 = modP(dacb * dacb);
                z_3 = modP(x_1 * modP(da_cb * da_cb));
                x_2 = modP(AA * BB);
                z_2 = modP(E * (AA + modP(a24 * E)));
            }
            ({ x_2, x_3 } = cswap(swap, x_2, x_3));
            ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));
            const z2 = powPminus2(z_2);
            return modP(x_2 * z2);
        }
        const lengths = {
            secretKey: fieldLen,
            publicKey: fieldLen,
            seed: fieldLen,
        };
        const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
            abytes$1(seed, lengths.seed);
            return seed;
        };
        function keygen(seed) {
            const secretKey = randomSecretKey(seed);
            return { secretKey, publicKey: scalarMultBase(secretKey) };
        }
        const utils = {
            randomSecretKey,
            randomPrivateKey: randomSecretKey,
        };
        return {
            keygen,
            getSharedSecret: (secretKey, publicKey) => scalarMult(secretKey, publicKey),
            getPublicKey: (secretKey) => scalarMultBase(secretKey),
            scalarMult,
            scalarMultBase,
            utils,
            GuBytes: GuBytes.slice(),
            lengths,
        };
    }

    /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
    const _0n$2 =  BigInt(0), _1n$1 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3);
    const _5n = BigInt(5), _8n = BigInt(8);
    const ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');
    const ed25519_CURVE =  (() => ({
        p: ed25519_CURVE_p,
        n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),
        h: _8n,
        a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),
        d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),
        Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),
        Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),
    }))();
    function ed25519_pow_2_252_3(x) {
        const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
        const P = ed25519_CURVE_p;
        const x2 = (x * x) % P;
        const b2 = (x2 * x) % P;
        const b4 = (pow2(b2, _2n$1, P) * b2) % P;
        const b5 = (pow2(b4, _1n$1, P) * x) % P;
        const b10 = (pow2(b5, _5n, P) * b5) % P;
        const b20 = (pow2(b10, _10n, P) * b10) % P;
        const b40 = (pow2(b20, _20n, P) * b20) % P;
        const b80 = (pow2(b40, _40n, P) * b40) % P;
        const b160 = (pow2(b80, _80n, P) * b80) % P;
        const b240 = (pow2(b160, _80n, P) * b80) % P;
        const b250 = (pow2(b240, _10n, P) * b10) % P;
        const pow_p_5_8 = (pow2(b250, _2n$1, P) * x) % P;
        return { pow_p_5_8, b2 };
    }
    function adjustScalarBytes(bytes) {
        bytes[0] &= 248;
        bytes[31] &= 127;
        bytes[31] |= 64;
        return bytes;
    }
    const ED25519_SQRT_M1 =  BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
    function uvRatio(u, v) {
        const P = ed25519_CURVE_p;
        const v3 = mod(v * v * v, P);
        const v7 = mod(v3 * v3 * v, P);
        const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
        let x = mod(u * v3 * pow, P);
        const vx2 = mod(v * x * x, P);
        const root1 = x;
        const root2 = mod(x * ED25519_SQRT_M1, P);
        const useRoot1 = vx2 === u;
        const useRoot2 = vx2 === mod(-u, P);
        const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
        if (useRoot1)
            x = root1;
        if (useRoot2 || noRoot)
            x = root2;
        if (isNegativeLE(x, P))
            x = mod(-x, P);
        return { isValid: useRoot1 || useRoot2, value: x };
    }
    const Fp =  (() => Field(ed25519_CURVE.p, { isLE: true }))();
    const Fn =  (() => Field(ed25519_CURVE.n, { isLE: true }))();
    const ed25519Defaults =  (() => ({
        ...ed25519_CURVE,
        Fp,
        hash: sha512$1,
        adjustScalarBytes,
        uvRatio,
    }))();
    const ed25519 =  (() => twistedEdwards(ed25519Defaults))();
    function ed25519_domain(data, ctx, phflag) {
        if (ctx.length > 255)
            throw new Error('Context is too big');
        return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
    }
    (() => twistedEdwards({
        ...ed25519Defaults,
        domain: ed25519_domain,
    }))();
    (() => twistedEdwards(Object.assign({}, ed25519Defaults, {
        domain: ed25519_domain,
        prehash: sha512$1,
    })))();
    (() => {
        const P = Fp.ORDER;
        return montgomery({
            P,
            type: 'x25519',
            powPminus2: (x) => {
                const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
                return mod(pow2(pow_p_5_8, _3n$1, P) * b2, P);
            },
            adjustScalarBytes,
        });
    })();
    const ELL2_C1 =  (() => (ed25519_CURVE_p + _3n$1) / _8n)();
    const ELL2_C2 =  (() => Fp.pow(_2n$1, ELL2_C1))();
    const ELL2_C3 =  (() => Fp.sqrt(Fp.neg(Fp.ONE)))();
    function map_to_curve_elligator2_curve25519(u) {
        const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n;
        const ELL2_J = BigInt(486662);
        let tv1 = Fp.sqr(u);
        tv1 = Fp.mul(tv1, _2n$1);
        let xd = Fp.add(tv1, Fp.ONE);
        let x1n = Fp.neg(ELL2_J);
        let tv2 = Fp.sqr(xd);
        let gxd = Fp.mul(tv2, xd);
        let gx1 = Fp.mul(tv1, ELL2_J);
        gx1 = Fp.mul(gx1, x1n);
        gx1 = Fp.add(gx1, tv2);
        gx1 = Fp.mul(gx1, x1n);
        let tv3 = Fp.sqr(gxd);
        tv2 = Fp.sqr(tv3);
        tv3 = Fp.mul(tv3, gxd);
        tv3 = Fp.mul(tv3, gx1);
        tv2 = Fp.mul(tv2, tv3);
        let y11 = Fp.pow(tv2, ELL2_C4);
        y11 = Fp.mul(y11, tv3);
        let y12 = Fp.mul(y11, ELL2_C3);
        tv2 = Fp.sqr(y11);
        tv2 = Fp.mul(tv2, gxd);
        let e1 = Fp.eql(tv2, gx1);
        let y1 = Fp.cmov(y12, y11, e1);
        let x2n = Fp.mul(x1n, tv1);
        let y21 = Fp.mul(y11, u);
        y21 = Fp.mul(y21, ELL2_C2);
        let y22 = Fp.mul(y21, ELL2_C3);
        let gx2 = Fp.mul(gx1, tv1);
        tv2 = Fp.sqr(y21);
        tv2 = Fp.mul(tv2, gxd);
        let e2 = Fp.eql(tv2, gx2);
        let y2 = Fp.cmov(y22, y21, e2);
        tv2 = Fp.sqr(y1);
        tv2 = Fp.mul(tv2, gxd);
        let e3 = Fp.eql(tv2, gx1);
        let xn = Fp.cmov(x2n, x1n, e3);
        let y = Fp.cmov(y2, y1, e3);
        let e4 = Fp.isOdd(y);
        y = Fp.cmov(y, Fp.neg(y), e3 !== e4);
        return { xMn: xn, xMd: xd, yMn: y, yMd: _1n$1 };
    }
    const ELL2_C1_EDWARDS =  (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();
    function map_to_curve_elligator2_edwards25519(u) {
        const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u);
        let xn = Fp.mul(xMn, yMd);
        xn = Fp.mul(xn, ELL2_C1_EDWARDS);
        let xd = Fp.mul(xMd, yMn);
        let yn = Fp.sub(xMn, xMd);
        let yd = Fp.add(xMn, xMd);
        let tv1 = Fp.mul(xd, yd);
        let e = Fp.eql(tv1, Fp.ZERO);
        xn = Fp.cmov(xn, Fp.ZERO, e);
        xd = Fp.cmov(xd, Fp.ONE, e);
        yn = Fp.cmov(yn, Fp.ONE, e);
        yd = Fp.cmov(yd, Fp.ONE, e);
        const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true);
        return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) };
    }
    (() => createHasher(ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
        DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',
        encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',
        p: ed25519_CURVE_p,
        m: 1,
        k: 128,
        expand: 'xmd',
        hash: sha512$1,
    }))();
    const SQRT_M1 = ED25519_SQRT_M1;
    const SQRT_AD_MINUS_ONE =  BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
    const INVSQRT_A_MINUS_D =  BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
    const ONE_MINUS_D_SQ =  BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
    const D_MINUS_ONE_SQ =  BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
    const invertSqrt = (number) => uvRatio(_1n$1, number);
    const MAX_255B =  BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
    const bytes255ToNumberLE = (bytes) => ed25519.Point.Fp.create(bytesToNumberLE$1(bytes) & MAX_255B);
    function calcElligatorRistrettoMap(r0) {
        const { d } = ed25519_CURVE;
        const P = ed25519_CURVE_p;
        const mod = (n) => Fp.create(n);
        const r = mod(SQRT_M1 * r0 * r0);
        const Ns = mod((r + _1n$1) * ONE_MINUS_D_SQ);
        let c = BigInt(-1);
        const D = mod((c - d * r) * mod(r + d));
        let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
        let s_ = mod(s * r0);
        if (!isNegativeLE(s_, P))
            s_ = mod(-s_);
        if (!Ns_D_is_sq)
            s = s_;
        if (!Ns_D_is_sq)
            c = r;
        const Nt = mod(c * (r - _1n$1) * D_MINUS_ONE_SQ - D);
        const s2 = s * s;
        const W0 = mod((s + s) * D);
        const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
        const W2 = mod(_1n$1 - s2);
        const W3 = mod(_1n$1 + s2);
        return new ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
    }
    function ristretto255_map(bytes) {
        abytes$1(bytes, 64);
        const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
        const R1 = calcElligatorRistrettoMap(r1);
        const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
        const R2 = calcElligatorRistrettoMap(r2);
        return new _RistrettoPoint(R1.add(R2));
    }
    class _RistrettoPoint extends PrimeEdwardsPoint {
        constructor(ep) {
            super(ep);
        }
        static fromAffine(ap) {
            return new _RistrettoPoint(ed25519.Point.fromAffine(ap));
        }
        assertSame(other) {
            if (!(other instanceof _RistrettoPoint))
                throw new Error('RistrettoPoint expected');
        }
        init(ep) {
            return new _RistrettoPoint(ep);
        }
        static hashToCurve(hex) {
            return ristretto255_map(ensureBytes('ristrettoHash', hex, 64));
        }
        static fromBytes(bytes) {
            abytes$1(bytes, 32);
            const { a, d } = ed25519_CURVE;
            const P = ed25519_CURVE_p;
            const mod = (n) => Fp.create(n);
            const s = bytes255ToNumberLE(bytes);
            if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))
                throw new Error('invalid ristretto255 encoding 1');
            const s2 = mod(s * s);
            const u1 = mod(_1n$1 + a * s2);
            const u2 = mod(_1n$1 - a * s2);
            const u1_2 = mod(u1 * u1);
            const u2_2 = mod(u2 * u2);
            const v = mod(a * d * u1_2 - u2_2);
            const { isValid, value: I } = invertSqrt(mod(v * u2_2));
            const Dx = mod(I * u2);
            const Dy = mod(I * Dx * v);
            let x = mod((s + s) * Dx);
            if (isNegativeLE(x, P))
                x = mod(-x);
            const y = mod(u1 * Dy);
            const t = mod(x * y);
            if (!isValid || isNegativeLE(t, P) || y === _0n$2)
                throw new Error('invalid ristretto255 encoding 2');
            return new _RistrettoPoint(new ed25519.Point(x, y, _1n$1, t));
        }
        static fromHex(hex) {
            return _RistrettoPoint.fromBytes(ensureBytes('ristrettoHex', hex, 32));
        }
        static msm(points, scalars) {
            return pippenger(_RistrettoPoint, ed25519.Point.Fn, points, scalars);
        }
        toBytes() {
            let { X, Y, Z, T } = this.ep;
            const P = ed25519_CURVE_p;
            const mod = (n) => Fp.create(n);
            const u1 = mod(mod(Z + Y) * mod(Z - Y));
            const u2 = mod(X * Y);
            const u2sq = mod(u2 * u2);
            const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));
            const D1 = mod(invsqrt * u1);
            const D2 = mod(invsqrt * u2);
            const zInv = mod(D1 * D2 * T);
            let D;
            if (isNegativeLE(T * zInv, P)) {
                let _x = mod(Y * SQRT_M1);
                let _y = mod(X * SQRT_M1);
                X = _x;
                Y = _y;
                D = mod(D1 * INVSQRT_A_MINUS_D);
            }
            else {
                D = D2;
            }
            if (isNegativeLE(X * zInv, P))
                Y = mod(-Y);
            let s = mod((Z - Y) * D);
            if (isNegativeLE(s, P))
                s = mod(-s);
            return Fp.toBytes(s);
        }
        equals(other) {
            this.assertSame(other);
            const { X: X1, Y: Y1 } = this.ep;
            const { X: X2, Y: Y2 } = other.ep;
            const mod = (n) => Fp.create(n);
            const one = mod(X1 * Y2) === mod(Y1 * X2);
            const two = mod(Y1 * Y2) === mod(X1 * X2);
            return one || two;
        }
        is0() {
            return this.equals(_RistrettoPoint.ZERO);
        }
    }
    _RistrettoPoint.BASE =
     (() => new _RistrettoPoint(ed25519.Point.BASE))();
    _RistrettoPoint.ZERO =
     (() => new _RistrettoPoint(ed25519.Point.ZERO))();
    _RistrettoPoint.Fp =
     (() => Fp)();
    _RistrettoPoint.Fn =
     (() => Fn)();
    const RistrettoPoint = _RistrettoPoint;

    function ed25519PairFromSeed(seed, onlyJs) {
        if (!util.hasBigInt || (!onlyJs && isReady())) {
            const full = ed25519KeypairFromSeed(seed);
            return {
                publicKey: full.slice(32),
                secretKey: full.slice(0, 64)
            };
        }
        const publicKey = ed25519.getPublicKey(seed);
        return {
            publicKey,
            secretKey: util.u8aConcatStrict([seed, publicKey])
        };
    }

    function ed25519PairFromRandom() {
        return ed25519PairFromSeed(randomAsU8a());
    }

    function ed25519PairFromSecret(secretKey) {
        if (secretKey.length !== 64) {
            throw new Error('Invalid secretKey provided');
        }
        return {
            publicKey: secretKey.slice(32),
            secretKey
        };
    }

    function ed25519PairFromString(value) {
        return ed25519PairFromSeed(blake2AsU8a(util.stringToU8a(value)));
    }

    function ed25519Sign(message, { publicKey, secretKey }, onlyJs) {
        if (!secretKey) {
            throw new Error('Expected a valid secretKey');
        }
        else if (!publicKey) {
            throw new Error('Expected a valid publicKey');
        }
        const messageU8a = util.u8aToU8a(message);
        const privateU8a = secretKey.subarray(0, 32);
        return !util.hasBigInt || (!onlyJs && isReady())
            ? ed25519Sign$1(publicKey, privateU8a, messageU8a)
            : ed25519.sign(messageU8a, privateU8a);
    }

    function ed25519Verify(message, signature, publicKey, onlyJs) {
        const messageU8a = util.u8aToU8a(message);
        const publicKeyU8a = util.u8aToU8a(publicKey);
        const signatureU8a = util.u8aToU8a(signature);
        if (publicKeyU8a.length !== 32) {
            throw new Error(`Invalid publicKey, received ${publicKeyU8a.length}, expected 32`);
        }
        else if (signatureU8a.length !== 64) {
            throw new Error(`Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
        }
        try {
            return !util.hasBigInt || (!onlyJs && isReady())
                ? ed25519Verify$1(signatureU8a, messageU8a, publicKeyU8a)
                : ed25519.verify(signatureU8a, messageU8a, publicKeyU8a);
        }
        catch {
            return false;
        }
    }

    const keyHdkdEd25519 =  createSeedDeriveFn(ed25519PairFromSeed, ed25519DeriveHard);

    const isBytes = isBytes$1;
    const bytesToNumberLE = bytesToNumberLE$1;
    const numberToBytesLE = numberToBytesLE$1;
    const aInRange = aInRange$1;
    const bitMask = bitMask$1;

    const _0n$1 = BigInt(0);
    const _1n = BigInt(1);
    const _2n = BigInt(2);
    const _7n$1 = BigInt(7);
    const _256n$1 = BigInt(256);
    const _0x71n = BigInt(0x71);
    const SHA3_PI = [];
    const SHA3_ROTL = [];
    const _SHA3_IOTA = [];
    for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
        [x, y] = [y, (2 * x + 3 * y) % 5];
        SHA3_PI.push(2 * (5 * y + x));
        SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
        let t = _0n$1;
        for (let j = 0; j < 7; j++) {
            R = ((R << _1n) ^ ((R >> _7n$1) * _0x71n)) % _256n$1;
            if (R & _2n)
                t ^= _1n << ((_1n <<  BigInt(j)) - _1n);
        }
        _SHA3_IOTA.push(t);
    }
    const IOTAS = split(_SHA3_IOTA, true);
    const SHA3_IOTA_H = IOTAS[0];
    const SHA3_IOTA_L = IOTAS[1];
    const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
    const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
    function keccakP(s, rounds = 24) {
        const B = new Uint32Array(5 * 2);
        for (let round = 24 - rounds; round < 24; round++) {
            for (let x = 0; x < 10; x++)
                B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
            for (let x = 0; x < 10; x += 2) {
                const idx1 = (x + 8) % 10;
                const idx0 = (x + 2) % 10;
                const B0 = B[idx0];
                const B1 = B[idx0 + 1];
                const Th = rotlH(B0, B1, 1) ^ B[idx1];
                const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
                for (let y = 0; y < 50; y += 10) {
                    s[x + y] ^= Th;
                    s[x + y + 1] ^= Tl;
                }
            }
            let curH = s[2];
            let curL = s[3];
            for (let t = 0; t < 24; t++) {
                const shift = SHA3_ROTL[t];
                const Th = rotlH(curH, curL, shift);
                const Tl = rotlL(curH, curL, shift);
                const PI = SHA3_PI[t];
                curH = s[PI];
                curL = s[PI + 1];
                s[PI] = Th;
                s[PI + 1] = Tl;
            }
            for (let y = 0; y < 50; y += 10) {
                for (let x = 0; x < 10; x++)
                    B[x] = s[y + x];
                for (let x = 0; x < 10; x++)
                    s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
            }
            s[0] ^= SHA3_IOTA_H[round];
            s[1] ^= SHA3_IOTA_L[round];
        }
        clean(B);
    }
    class Keccak extends Hash {
        constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
            super();
            this.pos = 0;
            this.posOut = 0;
            this.finished = false;
            this.destroyed = false;
            this.enableXOF = false;
            this.blockLen = blockLen;
            this.suffix = suffix;
            this.outputLen = outputLen;
            this.enableXOF = enableXOF;
            this.rounds = rounds;
            anumber(outputLen);
            if (!(0 < blockLen && blockLen < 200))
                throw new Error('only keccak-f1600 function is supported');
            this.state = new Uint8Array(200);
            this.state32 = u32(this.state);
        }
        clone() {
            return this._cloneInto();
        }
        keccak() {
            swap32IfBE(this.state32);
            keccakP(this.state32, this.rounds);
            swap32IfBE(this.state32);
            this.posOut = 0;
            this.pos = 0;
        }
        update(data) {
            aexists(this);
            data = toBytes(data);
            abytes$1(data);
            const { blockLen, state } = this;
            const len = data.length;
            for (let pos = 0; pos < len;) {
                const take = Math.min(blockLen - this.pos, len - pos);
                for (let i = 0; i < take; i++)
                    state[this.pos++] ^= data[pos++];
                if (this.pos === blockLen)
                    this.keccak();
            }
            return this;
        }
        finish() {
            if (this.finished)
                return;
            this.finished = true;
            const { state, suffix, pos, blockLen } = this;
            state[pos] ^= suffix;
            if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
                this.keccak();
            state[blockLen - 1] ^= 0x80;
            this.keccak();
        }
        writeInto(out) {
            aexists(this, false);
            abytes$1(out);
            this.finish();
            const bufferOut = this.state;
            const { blockLen } = this;
            for (let pos = 0, len = out.length; pos < len;) {
                if (this.posOut >= blockLen)
                    this.keccak();
                const take = Math.min(blockLen - this.posOut, len - pos);
                out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
                this.posOut += take;
                pos += take;
            }
            return out;
        }
        xofInto(out) {
            if (!this.enableXOF)
                throw new Error('XOF is not possible for this instance');
            return this.writeInto(out);
        }
        xof(bytes) {
            anumber(bytes);
            return this.xofInto(new Uint8Array(bytes));
        }
        digestInto(out) {
            aoutput(out, this);
            if (this.finished)
                throw new Error('digest() was already called');
            this.writeInto(out);
            this.destroy();
            return out;
        }
        digest() {
            return this.digestInto(new Uint8Array(this.outputLen));
        }
        destroy() {
            this.destroyed = true;
            clean(this.state);
        }
        _cloneInto(to) {
            const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
            to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
            to.state32.set(this.state32);
            to.pos = this.pos;
            to.posOut = this.posOut;
            to.finished = this.finished;
            to.rounds = rounds;
            to.suffix = suffix;
            to.outputLen = outputLen;
            to.enableXOF = enableXOF;
            to.destroyed = this.destroyed;
            return to;
        }
    }
    const gen = (suffix, blockLen, outputLen) => createHasher$1(() => new Keccak(blockLen, suffix, outputLen));
    (() => gen(0x06, 144, 224 / 8))();
    (() => gen(0x06, 136, 256 / 8))();
    (() => gen(0x06, 104, 384 / 8))();
    (() => gen(0x06, 72, 512 / 8))();
    (() => gen(0x01, 144, 224 / 8))();
    const keccak_256 =  (() => gen(0x01, 136, 256 / 8))();
    (() => gen(0x01, 104, 384 / 8))();
    const keccak_512 =  (() => gen(0x01, 72, 512 / 8))();
    const genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
    (() => genShake(0x1f, 168, 128 / 8))();
    (() => genShake(0x1f, 136, 256 / 8))();

    const sha512 = sha512$1;

    const _0n = BigInt(0), _3n = BigInt(3);
    function toData(d) {
        if (typeof d === 'string')
            return utf8ToBytes(d);
        if (isBytes(d))
            return d;
        throw new Error('Wrong data');
    }
    function abytes(title, b, ...lengths) {
        if (!isBytes(b))
            throw new Error(`${title}: Uint8Array expected`);
        if (lengths.length && !lengths.includes(b.length))
            throw new Error(`${title}: Uint8Array expected of length ${lengths}, not of length=${b.length}`);
    }
    function checkU32(title, n) {
        if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
            throw new Error(`${title}: wrong u32 integer: ${n}`);
        return n;
    }
    function cleanBytes(...list) {
        for (const t of list)
            t.fill(0);
    }
    const EMPTY = Uint8Array.of();
    const CURVE_ORDER = ed25519.CURVE.n;
    function parseScalar(title, bytes) {
        abytes(title, bytes, 32);
        const n = bytesToNumberLE(bytes);
        aInRange(title, n, _0n, CURVE_ORDER);
        return n;
    }
    const modN = (n) => mod(n, CURVE_ORDER);
    const STROBE_R = 166;
    const Flags = {
        I: 1,
        A: 1 << 1,
        C: 1 << 2,
        T: 1 << 3,
        M: 1 << 4,
        K: 1 << 5,
    };
    class Strobe128 {
        constructor(protocolLabel) {
            this.state = new Uint8Array(200);
            this.pos = 0;
            this.posBegin = 0;
            this.curFlags = 0;
            this.state.set([1, STROBE_R + 2, 1, 0, 1, 96], 0);
            this.state.set(utf8ToBytes('STROBEv1.0.2'), 6);
            this.state32 = u32(this.state);
            this.keccakF1600();
            this.metaAD(protocolLabel, false);
        }
        keccakF1600() {
            keccakP(this.state32);
        }
        runF() {
            this.state[this.pos] ^= this.posBegin;
            this.state[this.pos + 1] ^= 0x04;
            this.state[STROBE_R + 1] ^= 0x80;
            this.keccakF1600();
            this.pos = 0;
            this.posBegin = 0;
        }
        absorb(data) {
            for (let i = 0; i < data.length; i++) {
                this.state[this.pos++] ^= data[i];
                if (this.pos === STROBE_R)
                    this.runF();
            }
        }
        squeeze(len) {
            const data = new Uint8Array(len);
            for (let i = 0; i < data.length; i++) {
                data[i] = this.state[this.pos];
                this.state[this.pos++] = 0;
                if (this.pos === STROBE_R)
                    this.runF();
            }
            return data;
        }
        overwrite(data) {
            for (let i = 0; i < data.length; i++) {
                this.state[this.pos++] = data[i];
                if (this.pos === STROBE_R)
                    this.runF();
            }
        }
        beginOp(flags, more) {
            if (more) {
                if (this.curFlags !== flags) {
                    throw new Error(`Continued op with changed flags from ${this.curFlags.toString(2)} to ${flags.toString(2)}`);
                }
                return;
            }
            if ((flags & Flags.T) !== 0)
                throw new Error('T flag is not supported');
            const oldBegin = this.posBegin;
            this.posBegin = this.pos + 1;
            this.curFlags = flags;
            this.absorb(new Uint8Array([oldBegin, flags]));
            const forceF = (flags & (Flags.C | Flags.K)) !== 0;
            if (forceF && this.pos !== 0)
                this.runF();
        }
        metaAD(data, more) {
            this.beginOp(Flags.M | Flags.A, more);
            this.absorb(toData(data));
        }
        AD(data, more) {
            this.beginOp(Flags.A, more);
            this.absorb(toData(data));
        }
        PRF(len, more) {
            this.beginOp(Flags.I | Flags.A | Flags.C, more);
            return this.squeeze(len);
        }
        KEY(data, more) {
            this.beginOp(Flags.A | Flags.C, more);
            this.overwrite(toData(data));
        }
        clone() {
            const n = new Strobe128('0');
            n.pos = this.pos;
            n.posBegin = this.posBegin;
            n.state.set(this.state);
            n.curFlags = this.curFlags;
            return n;
        }
        clean() {
            this.state.fill(0);
            this.pos = 0;
            this.curFlags = 0;
            this.posBegin = 0;
        }
    }
    class Merlin {
        constructor(label) {
            this.strobe = new Strobe128('Merlin v1.0');
            this.appendMessage('dom-sep', label);
        }
        appendMessage(label, message) {
            this.strobe.metaAD(label, false);
            checkU32('Merlin.appendMessage', message.length);
            this.strobe.metaAD(numberToBytesLE(message.length, 4), true);
            this.strobe.AD(message, false);
        }
        challengeBytes(label, len) {
            this.strobe.metaAD(label, false);
            checkU32('Merlin.challengeBytes', len);
            this.strobe.metaAD(numberToBytesLE(len, 4), true);
            return this.strobe.PRF(len, false);
        }
        clean() {
            this.strobe.clean();
        }
    }
    class SigningContext extends Merlin {
        constructor(name, rng = randomBytes) {
            super(name);
            this.rng = rng;
        }
        label(label) {
            this.appendMessage('', label);
        }
        bytes(bytes) {
            this.appendMessage('sign-bytes', bytes);
            return this;
        }
        protoName(label) {
            this.appendMessage('proto-name', label);
        }
        commitPoint(label, point) {
            this.appendMessage(label, point.toRawBytes());
        }
        challengeScalar(label) {
            return modN(bytesToNumberLE(this.challengeBytes(label, 64)));
        }
        witnessScalar(label, nonceSeeds = []) {
            return modN(bytesToNumberLE(this.witnessBytes(label, 64, nonceSeeds)));
        }
        witnessBytes(label, len, nonceSeeds = []) {
            checkU32('SigningContext.witnessBytes', len);
            const strobeRng = this.strobe.clone();
            for (const ns of nonceSeeds) {
                strobeRng.metaAD(label, false);
                checkU32('SigningContext.witnessBytes nonce length', ns.length);
                strobeRng.metaAD(numberToBytesLE(ns.length, 4), true);
                strobeRng.KEY(ns, false);
            }
            const random = this.rng(32);
            strobeRng.metaAD('rng', false);
            strobeRng.KEY(random, false);
            strobeRng.metaAD(numberToBytesLE(len, 4), false);
            return strobeRng.PRF(len, false);
        }
    }
    const MASK = bitMask(256);
    const encodeScalar = (n) => numberToBytesLE((n << _3n) & MASK, 32);
    const decodeScalar = (n) => bytesToNumberLE(n) >> _3n;
    function getPublicKey(secretKey) {
        abytes('secretKey', secretKey, 64);
        const scalar = decodeScalar(secretKey.subarray(0, 32));
        return RistrettoPoint.BASE.multiply(scalar).toRawBytes();
    }
    function secretFromSeed(seed) {
        abytes('seed', seed, 32);
        const r = sha512(seed);
        r[0] &= 248;
        r[31] &= 63;
        r[31] |= 64;
        const key = encodeScalar(decodeScalar(r.subarray(0, 32)));
        const nonce = r.subarray(32, 64);
        const res = concatBytes(key, nonce);
        cleanBytes(key, nonce, r);
        return res;
    }
    const SUBSTRATE_CONTEXT = utf8ToBytes('substrate');
    function sign(secretKey, message, rng = randomBytes) {
        abytes('message', message);
        abytes('secretKey', secretKey, 64);
        const t = new SigningContext('SigningContext', rng);
        t.label(SUBSTRATE_CONTEXT);
        t.bytes(message);
        const keyScalar = decodeScalar(secretKey.subarray(0, 32));
        const nonce = secretKey.subarray(32, 64);
        const pubPoint = RistrettoPoint.fromHex(getPublicKey(secretKey));
        t.protoName('Schnorr-sig');
        t.commitPoint('sign:pk', pubPoint);
        const r = t.witnessScalar('signing', [nonce]);
        const R = RistrettoPoint.BASE.multiply(r);
        t.commitPoint('sign:R', R);
        const k = t.challengeScalar('sign:c');
        const s = modN(k * keyScalar + r);
        const res = concatBytes(R.toRawBytes(), numberToBytesLE(s, 32));
        res[63] |= 128;
        t.clean();
        return res;
    }
    function verify(message, signature, publicKey) {
        abytes('message', message);
        abytes('signature', signature, 64);
        abytes('publicKey', publicKey, 32);
        if ((signature[63] & 128) === 0)
            throw new Error('Schnorrkel marker missing');
        const sBytes = Uint8Array.from(signature.subarray(32, 64));
        sBytes[31] &= 127;
        const R = RistrettoPoint.fromHex(signature.subarray(0, 32));
        const s = bytesToNumberLE(sBytes);
        aInRange('s', s, _0n, CURVE_ORDER);
        const t = new SigningContext('SigningContext');
        t.label(SUBSTRATE_CONTEXT);
        t.bytes(message);
        const pubPoint = RistrettoPoint.fromHex(publicKey);
        if (pubPoint.equals(RistrettoPoint.ZERO))
            return false;
        t.protoName('Schnorr-sig');
        t.commitPoint('sign:pk', pubPoint);
        t.commitPoint('sign:R', R);
        const k = t.challengeScalar('sign:c');
        const sP = RistrettoPoint.BASE.multiply(s);
        const RR = pubPoint.negate().multiply(k).add(sP);
        t.clean();
        cleanBytes(sBytes);
        return RR.equals(R);
    }
    function getSharedSecret(secretKey, publicKey) {
        abytes('secretKey', secretKey, 64);
        abytes('publicKey', publicKey, 32);
        const keyScalar = decodeScalar(secretKey.subarray(0, 32));
        const pubPoint = RistrettoPoint.fromHex(publicKey);
        if (pubPoint.equals(RistrettoPoint.ZERO))
            throw new Error('wrong public key (infinity)');
        return pubPoint.multiply(keyScalar).toRawBytes();
    }
    const HDKD = {
        secretSoft(secretKey, chainCode, rng = randomBytes) {
            abytes('secretKey', secretKey, 64);
            abytes('chainCode', chainCode, 32);
            const masterScalar = decodeScalar(secretKey.subarray(0, 32));
            const masterNonce = secretKey.subarray(32, 64);
            const pubPoint = RistrettoPoint.fromHex(getPublicKey(secretKey));
            const t = new SigningContext('SchnorrRistrettoHDKD', rng);
            t.bytes(EMPTY);
            t.appendMessage('chain-code', chainCode);
            t.commitPoint('public-key', pubPoint);
            const scalar = t.challengeScalar('HDKD-scalar');
            const hdkdChainCode = t.challengeBytes('HDKD-chaincode', 32);
            const nonceSeed = concatBytes(numberToBytesLE(masterScalar, 32), masterNonce);
            const nonce = t.witnessBytes('HDKD-nonce', 32, [masterNonce, nonceSeed]);
            const key = encodeScalar(modN(masterScalar + scalar));
            const res = concatBytes(key, nonce);
            cleanBytes(key, nonce, nonceSeed, hdkdChainCode);
            t.clean();
            return res;
        },
        publicSoft(publicKey, chainCode) {
            abytes('publicKey', publicKey, 32);
            abytes('chainCode', chainCode, 32);
            const pubPoint = RistrettoPoint.fromHex(publicKey);
            const t = new SigningContext('SchnorrRistrettoHDKD');
            t.bytes(EMPTY);
            t.appendMessage('chain-code', chainCode);
            t.commitPoint('public-key', pubPoint);
            const scalar = t.challengeScalar('HDKD-scalar');
            t.challengeBytes('HDKD-chaincode', 32);
            t.clean();
            return pubPoint.add(RistrettoPoint.BASE.multiply(scalar)).toRawBytes();
        },
        secretHard(secretKey, chainCode) {
            abytes('secretKey', secretKey, 64);
            abytes('chainCode', chainCode, 32);
            const key = numberToBytesLE(decodeScalar(secretKey.subarray(0, 32)), 32);
            const t = new SigningContext('SchnorrRistrettoHDKD');
            t.bytes(EMPTY);
            t.appendMessage('chain-code', chainCode);
            t.appendMessage('secret-key', key);
            const msk = t.challengeBytes('HDKD-hard', 32);
            const hdkdChainCode = t.challengeBytes('HDKD-chaincode', 32);
            t.clean();
            const res = secretFromSeed(msk);
            cleanBytes(key, msk, hdkdChainCode);
            t.clean();
            return res;
        },
    };
    const dleq = {
        proove(keyScalar, nonce, pubPoint, t, input, output) {
            t.protoName('DLEQProof');
            t.commitPoint('vrf:h', input);
            const r = t.witnessScalar(`proving${'\0'}0`, [nonce]);
            const R = RistrettoPoint.BASE.multiply(r);
            t.commitPoint('vrf:R=g^r', R);
            const Hr = input.multiply(r);
            t.commitPoint('vrf:h^r', Hr);
            t.commitPoint('vrf:pk', pubPoint);
            t.commitPoint('vrf:h^sk', output);
            const c = t.challengeScalar('prove');
            const s = modN(r - c * keyScalar);
            return { proof: { c, s }, proofBatchable: { R, Hr, s } };
        },
        verify(pubPoint, t, input, output, proof) {
            if (pubPoint.equals(RistrettoPoint.ZERO))
                return false;
            t.protoName('DLEQProof');
            t.commitPoint('vrf:h', input);
            const R = pubPoint.multiply(proof.c).add(RistrettoPoint.BASE.multiply(proof.s));
            t.commitPoint('vrf:R=g^r', R);
            const Hr = output.multiply(proof.c).add(input.multiply(proof.s));
            t.commitPoint('vrf:h^r', Hr);
            t.commitPoint('vrf:pk', pubPoint);
            t.commitPoint('vrf:h^sk', output);
            const realC = t.challengeScalar('prove');
            if (proof.c === realC)
                return { R, Hr, s: proof.s };
            return false;
        },
    };
    function initVRF(ctx, msg, extra, pubPoint, rng = randomBytes) {
        const t = new SigningContext('SigningContext', rng);
        t.label(ctx);
        t.bytes(msg);
        t.commitPoint('vrf-nm-pk', pubPoint);
        const hash = t.challengeBytes('VRFHash', 64);
        const input = RistrettoPoint.hashToCurve(hash);
        const transcript = new SigningContext('VRF', rng);
        if (extra.length)
            transcript.label(extra);
        t.clean();
        cleanBytes(hash);
        return { input, t: transcript };
    }
    const vrf = {
        sign(msg, secretKey, ctx = EMPTY, extra = EMPTY, rng = randomBytes) {
            abytes('msg', msg);
            abytes('secretKey', secretKey, 64);
            abytes('ctx', ctx);
            abytes('extra', extra);
            const keyScalar = decodeScalar(secretKey.subarray(0, 32));
            const nonce = secretKey.subarray(32, 64);
            const pubPoint = RistrettoPoint.fromHex(getPublicKey(secretKey));
            const { input, t } = initVRF(ctx, msg, extra, pubPoint, rng);
            const output = input.multiply(keyScalar);
            const p = { output };
            const { proof } = dleq.proove(keyScalar, nonce, pubPoint, t, input, output);
            const cBytes = numberToBytesLE(proof.c, 32);
            const sBytes = numberToBytesLE(proof.s, 32);
            const res = concatBytes(p.output.toRawBytes(), cBytes, sBytes);
            cleanBytes(nonce, cBytes, sBytes);
            return res;
        },
        verify(msg, signature, publicKey, ctx = EMPTY, extra = EMPTY, rng = randomBytes) {
            abytes('msg', msg);
            abytes('signature', signature, 96);
            abytes('pubkey', publicKey, 32);
            abytes('ctx', ctx);
            abytes('extra', extra);
            const pubPoint = RistrettoPoint.fromHex(publicKey);
            if (pubPoint.equals(RistrettoPoint.ZERO))
                return false;
            const proof = {
                c: parseScalar('signature.c', signature.subarray(32, 64)),
                s: parseScalar('signature.s', signature.subarray(64, 96)),
            };
            const { input, t } = initVRF(ctx, msg, extra, pubPoint, rng);
            const output = RistrettoPoint.fromHex(signature.subarray(0, 32));
            if (output.equals(RistrettoPoint.ZERO))
                throw new Error('vrf.verify: wrong output point (identity)');
            const proofBatchable = dleq.verify(pubPoint, t, input, output, proof);
            return proofBatchable === false ? false : true;
        },
    };

    function createDeriveFn(derive) {
        return (keypair, chainCode) => {
            if (!util.isU8a(chainCode) || chainCode.length !== 32) {
                throw new Error('Invalid chainCode passed to derive');
            }
            const secretKey = derive(keypair.secretKey, chainCode);
            const publicKey = getPublicKey(secretKey);
            return { publicKey, secretKey };
        };
    }

    const sr25519DeriveHard =  createDeriveFn(HDKD.secretHard);

    const sr25519DeriveSoft =  createDeriveFn(HDKD.secretSoft);

    function keyHdkdSr25519(keypair, { chainCode, isSoft }) {
        return isSoft
            ? sr25519DeriveSoft(keypair, chainCode)
            : sr25519DeriveHard(keypair, chainCode);
    }

    const generators = {
        ecdsa: keyHdkdEcdsa,
        ed25519: keyHdkdEd25519,
        ethereum: keyHdkdEcdsa,
        sr25519: keyHdkdSr25519
    };
    function keyFromPath(pair, path, type) {
        const keyHdkd = generators[type];
        let result = pair;
        for (const junction of path) {
            result = keyHdkd(result, junction);
        }
        return result;
    }

    function sr25519Agreement(secretKey, publicKey) {
        const secretKeyU8a = util.u8aToU8a(secretKey);
        const publicKeyU8a = util.u8aToU8a(publicKey);
        if (publicKeyU8a.length !== 32) {
            throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
        }
        else if (secretKeyU8a.length !== 64) {
            throw new Error(`Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
        }
        return getSharedSecret(secretKeyU8a, publicKeyU8a);
    }

    function sr25519DerivePublic(publicKey, chainCode) {
        const publicKeyU8a = util.u8aToU8a(publicKey);
        if (!util.isU8a(chainCode) || chainCode.length !== 32) {
            throw new Error('Invalid chainCode passed to derive');
        }
        else if (publicKeyU8a.length !== 32) {
            throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
        }
        return HDKD.publicSoft(publicKeyU8a, chainCode);
    }

    function sr25519PairFromSeed(seed) {
        const seedU8a = util.u8aToU8a(seed);
        if (seedU8a.length !== 32) {
            throw new Error(`Expected a seed matching 32 bytes, found ${seedU8a.length}`);
        }
        const sec = secretFromSeed(seedU8a);
        const pub = getPublicKey(sec);
        return {
            publicKey: pub,
            secretKey: sec
        };
    }

    function sr25519Sign(message, { publicKey, secretKey }) {
        if (publicKey?.length !== 32) {
            throw new Error('Expected a valid publicKey, 32-bytes');
        }
        else if (secretKey?.length !== 64) {
            throw new Error('Expected a valid secretKey, 64-bytes');
        }
        return sign(secretKey, util.u8aToU8a(message));
    }

    function sr25519Verify(message, signature, publicKey) {
        const publicKeyU8a = util.u8aToU8a(publicKey);
        const signatureU8a = util.u8aToU8a(signature);
        if (publicKeyU8a.length !== 32) {
            throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
        }
        else if (signatureU8a.length !== 64) {
            throw new Error(`Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
        }
        return verify(util.u8aToU8a(message), signatureU8a, publicKeyU8a);
    }

    const EMPTY_U8A$1 = new Uint8Array();
    function sr25519VrfSign(message, { secretKey }, context = EMPTY_U8A$1, extra = EMPTY_U8A$1) {
        if (secretKey?.length !== 64) {
            throw new Error('Invalid secretKey, expected 64-bytes');
        }
        return vrf.sign(util.u8aToU8a(message), secretKey, util.u8aToU8a(context), util.u8aToU8a(extra), randomBytes);
    }

    const EMPTY_U8A = new Uint8Array();
    function sr25519VrfVerify(message, signOutput, publicKey, context = EMPTY_U8A, extra = EMPTY_U8A) {
        const publicKeyU8a = util.u8aToU8a(publicKey);
        const proofU8a = util.u8aToU8a(signOutput);
        if (publicKeyU8a.length !== 32) {
            throw new Error('Invalid publicKey, expected 32-bytes');
        }
        else if (proofU8a.length !== 96) {
            throw new Error('Invalid vrfSign output, expected 96 bytes');
        }
        return vrf.verify(util.u8aToU8a(message), proofU8a, publicKeyU8a, util.u8aToU8a(context), util.u8aToU8a(extra));
    }

    function encodeAddress(key, ss58Format = defaults.prefix) {
        const u8a = decodeAddress(key);
        if ((ss58Format < 0) || (ss58Format > 16383 && !ss58Exceptions.includes(ss58Format)) || [46, 47].includes(ss58Format)) {
            throw new Error('Out of range ss58Format specified');
        }
        else if (!defaults.allowedDecodedLengths.includes(u8a.length)) {
            throw new Error(`Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
        }
        const input = util.u8aConcat(ss58Format < 64
            ? [ss58Format]
            : [
                ((ss58Format & 0b0000_0000_1111_1100) >> 2) | 0b0100_0000,
                (ss58Format >> 8) | ((ss58Format & 0b0000_0000_0000_0011) << 6)
            ], u8a);
        return base58Encode(util.u8aConcat(input, sshash(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1)));
    }
    const ss58Exceptions = [29972];

    function filterHard({ isHard }) {
        return isHard;
    }
    function deriveAddress(who, suri, ss58Format) {
        const { path } = keyExtractPath(suri);
        if (!path.length || path.every(filterHard)) {
            throw new Error('Expected suri to contain a combination of non-hard paths');
        }
        let publicKey = decodeAddress(who);
        for (const { chainCode } of path) {
            publicKey = sr25519DerivePublic(publicKey, chainCode);
        }
        return encodeAddress(publicKey, ss58Format);
    }

    const PREFIX$1 = util.stringToU8a('modlpy/utilisuba');
    function createKeyDerived(who, index) {
        return blake2AsU8a(util.u8aConcat(PREFIX$1, decodeAddress(who), util.bnToU8a(index, BN_LE_16_OPTS)));
    }

    function encodeDerivedAddress(who, index, ss58Format) {
        return encodeAddress(createKeyDerived(decodeAddress(who), index), ss58Format);
    }

    function addressToU8a(who) {
        return decodeAddress(who);
    }

    const PREFIX = util.stringToU8a('modlpy/utilisuba');
    function createKeyMulti(who, threshold) {
        return blake2AsU8a(util.u8aConcat(PREFIX, util.compactToU8a(who.length), ...util.u8aSorted(who.map(addressToU8a)), util.bnToU8a(threshold, BN_LE_16_OPTS)));
    }

    function encodeMultiAddress(who, threshold, ss58Format) {
        return encodeAddress(createKeyMulti(who, threshold), ss58Format);
    }

    function addressEq(a, b) {
        return util.u8aEq(decodeAddress(a), decodeAddress(b));
    }

    const keccakAsU8a =  createDualHasher({ 256: keccak256, 512: keccak512 }, { 256: keccak_256, 512: keccak_512 });
    const keccak256AsU8a =  createBitHasher(256, keccakAsU8a);
    const keccak512AsU8a =  createBitHasher(512, keccakAsU8a);
    const keccakAsHex =  createAsHex(keccakAsU8a);

    function hasher(hashType, data, onlyJs) {
        return hashType === 'keccak'
            ? keccakAsU8a(data, undefined, onlyJs)
            : blake2AsU8a(data, undefined, undefined, onlyJs);
    }

    function evmToAddress(evmAddress, ss58Format, hashType = 'blake2') {
        const message = util.u8aConcat('evm:', evmAddress);
        if (message.length !== 24) {
            throw new Error(`Converting ${evmAddress}: Invalid evm address length`);
        }
        return encodeAddress(hasher(hashType, message), ss58Format);
    }

    function validateAddress(encoded, ignoreChecksum, ss58Format) {
        return !!decodeAddress(encoded, ignoreChecksum, ss58Format);
    }

    function isAddress(address, ignoreChecksum, ss58Format) {
        try {
            return validateAddress(address, ignoreChecksum, ss58Format);
        }
        catch {
            return false;
        }
    }

    function sortAddresses(addresses, ss58Format) {
        const u8aToAddress = (u8a) => encodeAddress(u8a, ss58Format);
        return util.u8aSorted(addresses.map(addressToU8a)).map(u8aToAddress);
    }

    const l = util.logger('setSS58Format');
    function setSS58Format(prefix) {
        l.warn('Global setting of the ss58Format is deprecated and not recommended. Set format on the keyring (if used) or as part of the address encode function');
        defaults.prefix = prefix;
    }

    const chars = 'abcdefghijklmnopqrstuvwxyz234567';
    const config$1 = {
        chars,
        coder: utils.chain(
        utils.radix2(5), utils.alphabet(chars), {
            decode: (input) => input.split(''),
            encode: (input) => input.join('')
        }),
        ipfs: 'b',
        type: 'base32'
    };
    const base32Validate =  createValidate(config$1);
    const isBase32 =  createIs(base32Validate);
    const base32Decode =  createDecode(config$1, base32Validate);
    const base32Encode =  createEncode(config$1);

    const config = {
        chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
        coder: base64,
        type: 'base64',
        withPadding: true
    };
    const base64Validate =  createValidate(config);
    const isBase64 =  createIs(base64Validate);
    const base64Decode =  createDecode(config, base64Validate);
    const base64Encode =  createEncode(config);

    function base64Pad(value) {
        return value.padEnd(value.length + (value.length % 4), '=');
    }

    function base64Trim(value) {
        while (value.length && value.endsWith('=')) {
            value = value.slice(0, -1);
        }
        return value;
    }

    function secp256k1Compress(publicKey, onlyJs) {
        if (![33, 65].includes(publicKey.length)) {
            throw new Error(`Invalid publicKey provided, received ${publicKey.length} bytes input`);
        }
        if (publicKey.length === 33) {
            return publicKey;
        }
        return !util.hasBigInt || (!onlyJs && isReady())
            ? secp256k1Compress$1(publicKey)
            : secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(true);
    }

    function secp256k1Expand(publicKey, onlyJs) {
        if (![33, 65].includes(publicKey.length)) {
            throw new Error(`Invalid publicKey provided, received ${publicKey.length} bytes input`);
        }
        if (publicKey.length === 65) {
            return publicKey.subarray(1);
        }
        if (!util.hasBigInt || (!onlyJs && isReady())) {
            return secp256k1Expand$1(publicKey).subarray(1);
        }
        const { px, py } = secp256k1.ProjectivePoint.fromHex(publicKey);
        return util.u8aConcat(util.bnToU8a(px, BN_BE_256_OPTS), util.bnToU8a(py, BN_BE_256_OPTS));
    }

    function secp256k1Recover(msgHash, signature, recovery, hashType = 'blake2', onlyJs) {
        const sig = util.u8aToU8a(signature).subarray(0, 64);
        const msg = util.u8aToU8a(msgHash);
        const publicKey = !util.hasBigInt || (!onlyJs && isReady())
            ? secp256k1Recover$1(msg, sig, recovery)
            : secp256k1.Signature
                .fromCompact(sig)
                .addRecoveryBit(recovery)
                .recoverPublicKey(msg)
                .toRawBytes();
        if (!publicKey) {
            throw new Error('Unable to recover publicKey from signature');
        }
        return hashType === 'keccak'
            ? secp256k1Expand(publicKey, onlyJs)
            : secp256k1Compress(publicKey, onlyJs);
    }

    function secp256k1Sign(message, { secretKey }, hashType = 'blake2', onlyJs) {
        if (secretKey?.length !== 32) {
            throw new Error('Expected valid secp256k1 secretKey, 32-bytes');
        }
        const data = hasher(hashType, message, onlyJs);
        if (!util.hasBigInt || (!onlyJs && isReady())) {
            return secp256k1Sign$1(data, secretKey);
        }
        const signature = secp256k1.sign(data, secretKey, { lowS: true });
        return util.u8aConcat(util.bnToU8a(signature.r, BN_BE_256_OPTS), util.bnToU8a(signature.s, BN_BE_256_OPTS), new Uint8Array([signature.recovery || 0]));
    }

    const N = 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141'.replace(/ /g, '');
    const N_BI = BigInt$1(`0x${N}`);
    const N_BN = new util.BN(N, 'hex');
    function addBi(seckey, tweak) {
        let res = util.u8aToBigInt(tweak, BN_BE_OPTS);
        if (res >= N_BI) {
            throw new Error('Tweak parameter is out of range');
        }
        res += util.u8aToBigInt(seckey, BN_BE_OPTS);
        if (res >= N_BI) {
            res -= N_BI;
        }
        if (res === util._0n) {
            throw new Error('Invalid resulting private key');
        }
        return util.nToU8a(res, BN_BE_256_OPTS);
    }
    function addBn(seckey, tweak) {
        const res = new util.BN(tweak);
        if (res.cmp(N_BN) >= 0) {
            throw new Error('Tweak parameter is out of range');
        }
        res.iadd(new util.BN(seckey));
        if (res.cmp(N_BN) >= 0) {
            res.isub(N_BN);
        }
        if (res.isZero()) {
            throw new Error('Invalid resulting private key');
        }
        return util.bnToU8a(res, BN_BE_256_OPTS);
    }
    function secp256k1PrivateKeyTweakAdd(seckey, tweak, onlyBn) {
        if (!util.isU8a(seckey) || seckey.length !== 32) {
            throw new Error('Expected seckey to be an Uint8Array with length 32');
        }
        else if (!util.isU8a(tweak) || tweak.length !== 32) {
            throw new Error('Expected tweak to be an Uint8Array with length 32');
        }
        return !util.hasBigInt || onlyBn
            ? addBn(seckey, tweak)
            : addBi(seckey, tweak);
    }

    function secp256k1Verify(msgHash, signature, address, hashType = 'blake2', onlyJs) {
        const sig = util.u8aToU8a(signature);
        if (sig.length !== 65) {
            throw new Error(`Expected signature with 65 bytes, ${sig.length} found instead`);
        }
        const publicKey = secp256k1Recover(hasher(hashType, msgHash), sig, sig[64], hashType, onlyJs);
        const signerAddr = hasher(hashType, publicKey, onlyJs);
        const inputAddr = util.u8aToU8a(address);
        return util.u8aEq(publicKey, inputAddr) || (hashType === 'keccak'
            ? util.u8aEq(signerAddr.slice(-20), inputAddr.slice(-20))
            : util.u8aEq(signerAddr, inputAddr));
    }

    function getH160(u8a) {
        if ([33, 65].includes(u8a.length)) {
            u8a = keccakAsU8a(secp256k1Expand(u8a));
        }
        return u8a.slice(-20);
    }
    function ethereumEncode(addressOrPublic) {
        if (!addressOrPublic) {
            return '0x';
        }
        const u8aAddress = util.u8aToU8a(addressOrPublic);
        if (![20, 32, 33, 65].includes(u8aAddress.length)) {
            throw new Error(`Invalid address or publicKey provided, received ${u8aAddress.length} bytes input`);
        }
        const address = util.u8aToHex(getH160(u8aAddress), -1, false);
        const hash = util.u8aToHex(keccakAsU8a(address), -1, false);
        let result = '';
        for (let i = 0; i < 40; i++) {
            result = `${result}${parseInt(hash[i], 16) > 7 ? address[i].toUpperCase() : address[i]}`;
        }
        return `0x${result}`;
    }

    function isInvalidChar(char, byte) {
        return char !== (byte > 7
            ? char.toUpperCase()
            : char.toLowerCase());
    }
    function isEthereumChecksum(_address) {
        const address = _address.replace('0x', '');
        const hash = util.u8aToHex(keccakAsU8a(address.toLowerCase()), -1, false);
        for (let i = 0; i < 40; i++) {
            if (isInvalidChar(address[i], parseInt(hash[i], 16))) {
                return false;
            }
        }
        return true;
    }

    function isEthereumAddress(address) {
        if (!address || address.length !== 42 || !util.isHex(address)) {
            return false;
        }
        else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
            return true;
        }
        return isEthereumChecksum(address);
    }

    const sha256 = sha256$1;

    const JS_HASH = {
        256: sha256,
        512: sha512
    };
    const WA_MHAC = {
        256: hmacSha256,
        512: hmacSha512
    };
    function createSha(bitLength) {
        return (key, data, onlyJs) => hmacShaAsU8a(key, data, bitLength, onlyJs);
    }
    function hmacShaAsU8a(key, data, bitLength = 256, onlyJs) {
        const u8aKey = util.u8aToU8a(key);
        return !util.hasBigInt || (!onlyJs && isReady())
            ? WA_MHAC[bitLength](u8aKey, data)
            : hmac(JS_HASH[bitLength], u8aKey, data);
    }
    const hmacSha256AsU8a =  createSha(256);
    const hmacSha512AsU8a =  createSha(512);

    const HARDENED = 0x80000000;
    function hdValidatePath(path) {
        if (!path.startsWith('m/')) {
            return false;
        }
        const parts = path.split('/').slice(1);
        for (const p of parts) {
            const n = /^\d+'?$/.test(p)
                ? parseInt(p.replace(/'$/, ''), 10)
                : Number.NaN;
            if (isNaN(n) || (n >= HARDENED) || (n < 0)) {
                return false;
            }
        }
        return true;
    }

    const MASTER_SECRET = util.stringToU8a('Bitcoin seed');
    function createCoded(secretKey, chainCode) {
        return {
            chainCode,
            publicKey: secp256k1PairFromSeed(secretKey).publicKey,
            secretKey
        };
    }
    function deriveChild(hd, index) {
        const indexBuffer = util.bnToU8a(index, BN_BE_32_OPTS);
        const data = index >= HARDENED
            ? util.u8aConcat(new Uint8Array(1), hd.secretKey, indexBuffer)
            : util.u8aConcat(hd.publicKey, indexBuffer);
        try {
            const I = hmacShaAsU8a(hd.chainCode, data, 512);
            return createCoded(secp256k1PrivateKeyTweakAdd(hd.secretKey, I.slice(0, 32)), I.slice(32));
        }
        catch {
            return deriveChild(hd, index + 1);
        }
    }
    function hdEthereum(seed, path = '') {
        const I = hmacShaAsU8a(MASTER_SECRET, seed, 512);
        let hd = createCoded(I.slice(0, 32), I.slice(32));
        if (!path || path === 'm' || path === 'M' || path === "m'" || path === "M'") {
            return hd;
        }
        if (!hdValidatePath(path)) {
            throw new Error('Invalid derivation path');
        }
        const parts = path.split('/').slice(1);
        for (const p of parts) {
            hd = deriveChild(hd, parseInt(p, 10) + ((p.length > 1) && p.endsWith("'")
                ? HARDENED
                : 0));
        }
        return hd;
    }

    function pbkdf2Init(hash, _password, _salt, _opts) {
        ahash(hash);
        const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
        const { c, dkLen, asyncTick } = opts;
        anumber(c);
        anumber(dkLen);
        anumber(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);
        const PRFSalt = PRF._cloneInto().update(salt);
        return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
    }
    function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
        PRF.destroy();
        PRFSalt.destroy();
        if (prfW)
            prfW.destroy();
        clean(u);
        return DK;
    }
    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);
    }

    function pbkdf2Encode(passphrase, salt = randomAsU8a(), rounds = 2048, onlyJs) {
        const u8aPass = util.u8aToU8a(passphrase);
        const u8aSalt = util.u8aToU8a(salt);
        return {
            password: !util.hasBigInt || (!onlyJs && isReady())
                ? pbkdf2$1(u8aPass, u8aSalt, rounds)
                : pbkdf2(sha512, u8aPass, u8aSalt, { c: rounds, dkLen: 64 }),
            rounds,
            salt
        };
    }

    const shaAsU8a =  createDualHasher({ 256: sha256$2, 512: sha512$2 }, { 256: sha256, 512: sha512 });
    const sha256AsU8a =  createBitHasher(256, shaAsU8a);
    const sha512AsU8a =  createBitHasher(512, shaAsU8a);

    const DEFAULT_WORDLIST = 'abandon|ability|able|about|above|absent|absorb|abstract|absurd|abuse|access|accident|account|accuse|achieve|acid|acoustic|acquire|across|act|action|actor|actress|actual|adapt|add|addict|address|adjust|admit|adult|advance|advice|aerobic|affair|afford|afraid|again|age|agent|agree|ahead|aim|air|airport|aisle|alarm|album|alcohol|alert|alien|all|alley|allow|almost|alone|alpha|already|also|alter|always|amateur|amazing|among|amount|amused|analyst|anchor|ancient|anger|angle|angry|animal|ankle|announce|annual|another|answer|antenna|antique|anxiety|any|apart|apology|appear|apple|approve|april|arch|arctic|area|arena|argue|arm|armed|armor|army|around|arrange|arrest|arrive|arrow|art|artefact|artist|artwork|ask|aspect|assault|asset|assist|assume|asthma|athlete|atom|attack|attend|attitude|attract|auction|audit|august|aunt|author|auto|autumn|average|avocado|avoid|awake|aware|away|awesome|awful|awkward|axis|baby|bachelor|bacon|badge|bag|balance|balcony|ball|bamboo|banana|banner|bar|barely|bargain|barrel|base|basic|basket|battle|beach|bean|beauty|because|become|beef|before|begin|behave|behind|believe|below|belt|bench|benefit|best|betray|better|between|beyond|bicycle|bid|bike|bind|biology|bird|birth|bitter|black|blade|blame|blanket|blast|bleak|bless|blind|blood|blossom|blouse|blue|blur|blush|board|boat|body|boil|bomb|bone|bonus|book|boost|border|boring|borrow|boss|bottom|bounce|box|boy|bracket|brain|brand|brass|brave|bread|breeze|brick|bridge|brief|bright|bring|brisk|broccoli|broken|bronze|broom|brother|brown|brush|bubble|buddy|budget|buffalo|build|bulb|bulk|bullet|bundle|bunker|burden|burger|burst|bus|business|busy|butter|buyer|buzz|cabbage|cabin|cable|cactus|cage|cake|call|calm|camera|camp|can|canal|cancel|candy|cannon|canoe|canvas|canyon|capable|capital|captain|car|carbon|card|cargo|carpet|carry|cart|case|cash|casino|castle|casual|cat|catalog|catch|category|cattle|caught|cause|caution|cave|ceiling|celery|cement|census|century|cereal|certain|chair|chalk|champion|change|chaos|chapter|charge|chase|chat|cheap|check|cheese|chef|cherry|chest|chicken|chief|child|chimney|choice|choose|chronic|chuckle|chunk|churn|cigar|cinnamon|circle|citizen|city|civil|claim|clap|clarify|claw|clay|clean|clerk|clever|click|client|cliff|climb|clinic|clip|clock|clog|close|cloth|cloud|clown|club|clump|cluster|clutch|coach|coast|coconut|code|coffee|coil|coin|collect|color|column|combine|come|comfort|comic|common|company|concert|conduct|confirm|congress|connect|consider|control|convince|cook|cool|copper|copy|coral|core|corn|correct|cost|cotton|couch|country|couple|course|cousin|cover|coyote|crack|cradle|craft|cram|crane|crash|crater|crawl|crazy|cream|credit|creek|crew|cricket|crime|crisp|critic|crop|cross|crouch|crowd|crucial|cruel|cruise|crumble|crunch|crush|cry|crystal|cube|culture|cup|cupboard|curious|current|curtain|curve|cushion|custom|cute|cycle|dad|damage|damp|dance|danger|daring|dash|daughter|dawn|day|deal|debate|debris|decade|december|decide|decline|decorate|decrease|deer|defense|define|defy|degree|delay|deliver|demand|demise|denial|dentist|deny|depart|depend|deposit|depth|deputy|derive|describe|desert|design|desk|despair|destroy|detail|detect|develop|device|devote|diagram|dial|diamond|diary|dice|diesel|diet|differ|digital|dignity|dilemma|dinner|dinosaur|direct|dirt|disagree|discover|disease|dish|dismiss|disorder|display|distance|divert|divide|divorce|dizzy|doctor|document|dog|doll|dolphin|domain|donate|donkey|donor|door|dose|double|dove|draft|dragon|drama|drastic|draw|dream|dress|drift|drill|drink|drip|drive|drop|drum|dry|duck|dumb|dune|during|dust|dutch|duty|dwarf|dynamic|eager|eagle|early|earn|earth|easily|east|easy|echo|ecology|economy|edge|edit|educate|effort|egg|eight|either|elbow|elder|electric|elegant|element|elephant|elevator|elite|else|embark|embody|embrace|emerge|emotion|employ|empower|empty|enable|enact|end|endless|endorse|enemy|energy|enforce|engage|engine|enhance|enjoy|enlist|enough|enrich|enroll|ensure|enter|entire|entry|envelope|episode|equal|equip|era|erase|erode|erosion|error|erupt|escape|essay|essence|estate|eternal|ethics|evidence|evil|evoke|evolve|exact|example|excess|exchange|excite|exclude|excuse|execute|exercise|exhaust|exhibit|exile|exist|exit|exotic|expand|expect|expire|explain|expose|express|extend|extra|eye|eyebrow|fabric|face|faculty|fade|faint|faith|fall|false|fame|family|famous|fan|fancy|fantasy|farm|fashion|fat|fatal|father|fatigue|fault|favorite|feature|february|federal|fee|feed|feel|female|fence|festival|fetch|fever|few|fiber|fiction|field|figure|file|film|filter|final|find|fine|finger|finish|fire|firm|first|fiscal|fish|fit|fitness|fix|flag|flame|flash|flat|flavor|flee|flight|flip|float|flock|floor|flower|fluid|flush|fly|foam|focus|fog|foil|fold|follow|food|foot|force|forest|forget|fork|fortune|forum|forward|fossil|foster|found|fox|fragile|frame|frequent|fresh|friend|fringe|frog|front|frost|frown|frozen|fruit|fuel|fun|funny|furnace|fury|future|gadget|gain|galaxy|gallery|game|gap|garage|garbage|garden|garlic|garment|gas|gasp|gate|gather|gauge|gaze|general|genius|genre|gentle|genuine|gesture|ghost|giant|gift|giggle|ginger|giraffe|girl|give|glad|glance|glare|glass|glide|glimpse|globe|gloom|glory|glove|glow|glue|goat|goddess|gold|good|goose|gorilla|gospel|gossip|govern|gown|grab|grace|grain|grant|grape|grass|gravity|great|green|grid|grief|grit|grocery|group|grow|grunt|guard|guess|guide|guilt|guitar|gun|gym|habit|hair|half|hammer|hamster|hand|happy|harbor|hard|harsh|harvest|hat|have|hawk|hazard|head|health|heart|heavy|hedgehog|height|hello|helmet|help|hen|hero|hidden|high|hill|hint|hip|hire|history|hobby|hockey|hold|hole|holiday|hollow|home|honey|hood|hope|horn|horror|horse|hospital|host|hotel|hour|hover|hub|huge|human|humble|humor|hundred|hungry|hunt|hurdle|hurry|hurt|husband|hybrid|ice|icon|idea|identify|idle|ignore|ill|illegal|illness|image|imitate|immense|immune|impact|impose|improve|impulse|inch|include|income|increase|index|indicate|indoor|industry|infant|inflict|inform|inhale|inherit|initial|inject|injury|inmate|inner|innocent|input|inquiry|insane|insect|inside|inspire|install|intact|interest|into|invest|invite|involve|iron|island|isolate|issue|item|ivory|jacket|jaguar|jar|jazz|jealous|jeans|jelly|jewel|job|join|joke|journey|joy|judge|juice|jump|jungle|junior|junk|just|kangaroo|keen|keep|ketchup|key|kick|kid|kidney|kind|kingdom|kiss|kit|kitchen|kite|kitten|kiwi|knee|knife|knock|know|lab|label|labor|ladder|lady|lake|lamp|language|laptop|large|later|latin|laugh|laundry|lava|law|lawn|lawsuit|layer|lazy|leader|leaf|learn|leave|lecture|left|leg|legal|legend|leisure|lemon|lend|length|lens|leopard|lesson|letter|level|liar|liberty|library|license|life|lift|light|like|limb|limit|link|lion|liquid|list|little|live|lizard|load|loan|lobster|local|lock|logic|lonely|long|loop|lottery|loud|lounge|love|loyal|lucky|luggage|lumber|lunar|lunch|luxury|lyrics|machine|mad|magic|magnet|maid|mail|main|major|make|mammal|man|manage|mandate|mango|mansion|manual|maple|marble|march|margin|marine|market|marriage|mask|mass|master|match|material|math|matrix|matter|maximum|maze|meadow|mean|measure|meat|mechanic|medal|media|melody|melt|member|memory|mention|menu|mercy|merge|merit|merry|mesh|message|metal|method|middle|midnight|milk|million|mimic|mind|minimum|minor|minute|miracle|mirror|misery|miss|mistake|mix|mixed|mixture|mobile|model|modify|mom|moment|monitor|monkey|monster|month|moon|moral|more|morning|mosquito|mother|motion|motor|mountain|mouse|move|movie|much|muffin|mule|multiply|muscle|museum|mushroom|music|must|mutual|myself|mystery|myth|naive|name|napkin|narrow|nasty|nation|nature|near|neck|need|negative|neglect|neither|nephew|nerve|nest|net|network|neutral|never|news|next|nice|night|noble|noise|nominee|noodle|normal|north|nose|notable|note|nothing|notice|novel|now|nuclear|number|nurse|nut|oak|obey|object|oblige|obscure|observe|obtain|obvious|occur|ocean|october|odor|off|offer|office|often|oil|okay|old|olive|olympic|omit|once|one|onion|online|only|open|opera|opinion|oppose|option|orange|orbit|orchard|order|ordinary|organ|orient|original|orphan|ostrich|other|outdoor|outer|output|outside|oval|oven|over|own|owner|oxygen|oyster|ozone|pact|paddle|page|pair|palace|palm|panda|panel|panic|panther|paper|parade|parent|park|parrot|party|pass|patch|path|patient|patrol|pattern|pause|pave|payment|peace|peanut|pear|peasant|pelican|pen|penalty|pencil|people|pepper|perfect|permit|person|pet|phone|photo|phrase|physical|piano|picnic|picture|piece|pig|pigeon|pill|pilot|pink|pioneer|pipe|pistol|pitch|pizza|place|planet|plastic|plate|play|please|pledge|pluck|plug|plunge|poem|poet|point|polar|pole|police|pond|pony|pool|popular|portion|position|possible|post|potato|pottery|poverty|powder|power|practice|praise|predict|prefer|prepare|present|pretty|prevent|price|pride|primary|print|priority|prison|private|prize|problem|process|produce|profit|program|project|promote|proof|property|prosper|protect|proud|provide|public|pudding|pull|pulp|pulse|pumpkin|punch|pupil|puppy|purchase|purity|purpose|purse|push|put|puzzle|pyramid|quality|quantum|quarter|question|quick|quit|quiz|quote|rabbit|raccoon|race|rack|radar|radio|rail|rain|raise|rally|ramp|ranch|random|range|rapid|rare|rate|rather|raven|raw|razor|ready|real|reason|rebel|rebuild|recall|receive|recipe|record|recycle|reduce|reflect|reform|refuse|region|regret|regular|reject|relax|release|relief|rely|remain|remember|remind|remove|render|renew|rent|reopen|repair|repeat|replace|report|require|rescue|resemble|resist|resource|response|result|retire|retreat|return|reunion|reveal|review|reward|rhythm|rib|ribbon|rice|rich|ride|ridge|rifle|right|rigid|ring|riot|ripple|risk|ritual|rival|river|road|roast|robot|robust|rocket|romance|roof|rookie|room|rose|rotate|rough|round|route|royal|rubber|rude|rug|rule|run|runway|rural|sad|saddle|sadness|safe|sail|salad|salmon|salon|salt|salute|same|sample|sand|satisfy|satoshi|sauce|sausage|save|say|scale|scan|scare|scatter|scene|scheme|school|science|scissors|scorpion|scout|scrap|screen|script|scrub|sea|search|season|seat|second|secret|section|security|seed|seek|segment|select|sell|seminar|senior|sense|sentence|series|service|session|settle|setup|seven|shadow|shaft|shallow|share|shed|shell|sheriff|shield|shift|shine|ship|shiver|shock|shoe|shoot|shop|short|shoulder|shove|shrimp|shrug|shuffle|shy|sibling|sick|side|siege|sight|sign|silent|silk|silly|silver|similar|simple|since|sing|siren|sister|situate|six|size|skate|sketch|ski|skill|skin|skirt|skull|slab|slam|sleep|slender|slice|slide|slight|slim|slogan|slot|slow|slush|small|smart|smile|smoke|smooth|snack|snake|snap|sniff|snow|soap|soccer|social|sock|soda|soft|solar|soldier|solid|solution|solve|someone|song|soon|sorry|sort|soul|sound|soup|source|south|space|spare|spatial|spawn|speak|special|speed|spell|spend|sphere|spice|spider|spike|spin|spirit|split|spoil|sponsor|spoon|sport|spot|spray|spread|spring|spy|square|squeeze|squirrel|stable|stadium|staff|stage|stairs|stamp|stand|start|state|stay|steak|steel|stem|step|stereo|stick|still|sting|stock|stomach|stone|stool|story|stove|strategy|street|strike|strong|struggle|student|stuff|stumble|style|subject|submit|subway|success|such|sudden|suffer|sugar|suggest|suit|summer|sun|sunny|sunset|super|supply|supreme|sure|surface|surge|surprise|surround|survey|suspect|sustain|swallow|swamp|swap|swarm|swear|sweet|swift|swim|swing|switch|sword|symbol|symptom|syrup|system|table|tackle|tag|tail|talent|talk|tank|tape|target|task|taste|tattoo|taxi|teach|team|tell|ten|tenant|tennis|tent|term|test|text|thank|that|theme|then|theory|there|they|thing|this|thought|three|thrive|throw|thumb|thunder|ticket|tide|tiger|tilt|timber|time|tiny|tip|tired|tissue|title|toast|tobacco|today|toddler|toe|together|toilet|token|tomato|tomorrow|tone|tongue|tonight|tool|tooth|top|topic|topple|torch|tornado|tortoise|toss|total|tourist|toward|tower|town|toy|track|trade|traffic|tragic|train|transfer|trap|trash|travel|tray|treat|tree|trend|trial|tribe|trick|trigger|trim|trip|trophy|trouble|truck|true|truly|trumpet|trust|truth|try|tube|tuition|tumble|tuna|tunnel|turkey|turn|turtle|twelve|twenty|twice|twin|twist|two|type|typical|ugly|umbrella|unable|unaware|uncle|uncover|under|undo|unfair|unfold|unhappy|uniform|unique|unit|universe|unknown|unlock|until|unusual|unveil|update|upgrade|uphold|upon|upper|upset|urban|urge|usage|use|used|useful|useless|usual|utility|vacant|vacuum|vague|valid|valley|valve|van|vanish|vapor|various|vast|vault|vehicle|velvet|vendor|venture|venue|verb|verify|version|very|vessel|veteran|viable|vibrant|vicious|victory|video|view|village|vintage|violin|virtual|virus|visa|visit|visual|vital|vivid|vocal|voice|void|volcano|volume|vote|voyage|wage|wagon|wait|walk|wall|walnut|want|warfare|warm|warrior|wash|wasp|waste|water|wave|way|wealth|weapon|wear|weasel|weather|web|wedding|weekend|weird|welcome|west|wet|whale|what|wheat|wheel|when|where|whip|whisper|wide|width|wife|wild|will|win|window|wine|wing|wink|winner|winter|wire|wisdom|wise|wish|witness|wolf|woman|wonder|wood|wool|word|work|world|worry|worth|wrap|wreck|wrestle|wrist|write|wrong|yard|year|yellow|you|young|youth|zebra|zero|zone|zoo'.split('|');

    const INVALID_MNEMONIC = 'Invalid mnemonic';
    const INVALID_ENTROPY = 'Invalid entropy';
    const INVALID_CHECKSUM = 'Invalid mnemonic checksum';
    function normalize(str) {
        return (str || '').normalize('NFKD');
    }
    function binaryToByte(bin) {
        return parseInt(bin, 2);
    }
    function bytesToBinary(bytes) {
        return bytes.map((x) => x.toString(2).padStart(8, '0')).join('');
    }
    function deriveChecksumBits(entropyBuffer) {
        return bytesToBinary(Array.from(sha256AsU8a(entropyBuffer))).slice(0, (entropyBuffer.length * 8) / 32);
    }
    function mnemonicToSeedSync(mnemonic, password) {
        return pbkdf2Encode(util.stringToU8a(normalize(mnemonic)), util.stringToU8a(`mnemonic${normalize(password)}`)).password;
    }
    function mnemonicToEntropy$1(mnemonic, wordlist = DEFAULT_WORDLIST) {
        const words = normalize(mnemonic).split(' ');
        if (words.length % 3 !== 0) {
            throw new Error(INVALID_MNEMONIC);
        }
        const bits = words
            .map((word) => {
            const index = wordlist.indexOf(word);
            if (index === -1) {
                throw new Error(INVALID_MNEMONIC);
            }
            return index.toString(2).padStart(11, '0');
        })
            .join('');
        const dividerIndex = Math.floor(bits.length / 33) * 32;
        const entropyBits = bits.slice(0, dividerIndex);
        const checksumBits = bits.slice(dividerIndex);
        const matched = entropyBits.match(/(.{1,8})/g);
        const entropyBytes = matched?.map(binaryToByte);
        if (!entropyBytes || (entropyBytes.length % 4 !== 0) || (entropyBytes.length < 16) || (entropyBytes.length > 32)) {
            throw new Error(INVALID_ENTROPY);
        }
        const entropy = util.u8aToU8a(entropyBytes);
        if (deriveChecksumBits(entropy) !== checksumBits) {
            throw new Error(INVALID_CHECKSUM);
        }
        return entropy;
    }
    function entropyToMnemonic(entropy, wordlist = DEFAULT_WORDLIST) {
        if ((entropy.length % 4 !== 0) || (entropy.length < 16) || (entropy.length > 32)) {
            throw new Error(INVALID_ENTROPY);
        }
        const matched = `${bytesToBinary(Array.from(entropy))}${deriveChecksumBits(entropy)}`.match(/(.{1,11})/g);
        const mapped = matched?.map((b) => wordlist[binaryToByte(b)]);
        if (!mapped || (mapped.length < 12)) {
            throw new Error('Unable to map entropy to mnemonic');
        }
        return mapped.join(' ');
    }
    function generateMnemonic(numWords, wordlist) {
        return entropyToMnemonic(randomAsU8a((numWords / 3) * 4), wordlist);
    }
    function validateMnemonic(mnemonic, wordlist) {
        try {
            mnemonicToEntropy$1(mnemonic, wordlist);
        }
        catch {
            return false;
        }
        return true;
    }

    function mnemonicGenerate(numWords = 12, wordlist, onlyJs) {
        return !util.hasBigInt || (!wordlist && !onlyJs && isReady())
            ? bip39Generate(numWords)
            : generateMnemonic(numWords, wordlist);
    }

    function mnemonicToEntropy(mnemonic, wordlist, onlyJs) {
        return !util.hasBigInt || (!wordlist && !onlyJs && isReady())
            ? bip39ToEntropy(mnemonic)
            : mnemonicToEntropy$1(mnemonic, wordlist);
    }

    function mnemonicValidate(mnemonic, wordlist, onlyJs) {
        return !util.hasBigInt || (!wordlist && !onlyJs && isReady())
            ? bip39Validate(mnemonic)
            : validateMnemonic(mnemonic, wordlist);
    }

    function mnemonicToLegacySeed(mnemonic, password = '', onlyJs, byteLength = 32) {
        if (!mnemonicValidate(mnemonic)) {
            throw new Error('Invalid bip39 mnemonic specified');
        }
        else if (![32, 64].includes(byteLength)) {
            throw new Error(`Invalid seed length ${byteLength}, expected 32 or 64`);
        }
        return byteLength === 32
            ? !util.hasBigInt || (!onlyJs && isReady())
                ? bip39ToSeed(mnemonic, password)
                : mnemonicToSeedSync(mnemonic, password).subarray(0, 32)
            : mnemonicToSeedSync(mnemonic, password);
    }

    function mnemonicToMiniSecret(mnemonic, password = '', wordlist, onlyJs) {
        if (!mnemonicValidate(mnemonic, wordlist, onlyJs)) {
            throw new Error('Invalid bip39 mnemonic specified');
        }
        else if (!wordlist && !onlyJs && isReady()) {
            return bip39ToMiniSecret(mnemonic, password);
        }
        const entropy = mnemonicToEntropy(mnemonic, wordlist);
        const salt = util.stringToU8a(`mnemonic${password}`);
        return pbkdf2Encode(entropy, salt).password.slice(0, 32);
    }

    function ledgerDerivePrivate(xprv, index) {
        const kl = xprv.subarray(0, 32);
        const kr = xprv.subarray(32, 64);
        const cc = xprv.subarray(64, 96);
        const data = util.u8aConcat([0], kl, kr, util.bnToU8a(index, BN_LE_32_OPTS));
        const z = hmacShaAsU8a(cc, data, 512);
        data[0] = 0x01;
        return util.u8aConcat(util.bnToU8a(util.u8aToBn(kl, BN_LE_OPTS).iadd(util.u8aToBn(z.subarray(0, 28), BN_LE_OPTS).imul(util.BN_EIGHT)), BN_LE_512_OPTS).subarray(0, 32), util.bnToU8a(util.u8aToBn(kr, BN_LE_OPTS).iadd(util.u8aToBn(z.subarray(32, 64), BN_LE_OPTS)), BN_LE_512_OPTS).subarray(0, 32), hmacShaAsU8a(cc, data, 512).subarray(32, 64));
    }

    const ED25519_CRYPTO = 'ed25519 seed';
    function ledgerMaster(mnemonic, password) {
        const seed = mnemonicToSeedSync(mnemonic, password);
        const chainCode = hmacShaAsU8a(ED25519_CRYPTO, new Uint8Array([1, ...seed]), 256);
        let priv;
        while (!priv || (priv[31] & 0b0010_0000)) {
            priv = hmacShaAsU8a(ED25519_CRYPTO, priv || seed, 512);
        }
        priv[0] &= 0b1111_1000;
        priv[31] &= 0b0111_1111;
        priv[31] |= 0b0100_0000;
        return util.u8aConcat(priv, chainCode);
    }

    function hdLedger(_mnemonic, path) {
        const words = _mnemonic
            .split(' ')
            .map((s) => s.trim())
            .filter((s) => s);
        if (![12, 24, 25].includes(words.length)) {
            throw new Error('Expected a mnemonic with 24 words (or 25 including a password)');
        }
        const [mnemonic, password] = words.length === 25
            ? [words.slice(0, 24).join(' '), words[24]]
            : [words.join(' '), ''];
        if (!mnemonicValidate(mnemonic)) {
            throw new Error('Invalid mnemonic passed to ledger derivation');
        }
        else if (!hdValidatePath(path)) {
            throw new Error('Invalid derivation path');
        }
        const parts = path.split('/').slice(1);
        let seed = ledgerMaster(mnemonic, password);
        for (const p of parts) {
            const n = parseInt(p.replace(/'$/, ''), 10);
            seed = ledgerDerivePrivate(seed, (n < HARDENED) ? (n + HARDENED) : n);
        }
        return ed25519PairFromSeed(seed.slice(0, 32));
    }

    function L32(x, c) { return (x << c) | (x >>> (32 - c)); }
    function ld32(x, i) {
        let u = x[i + 3] & 0xff;
        u = (u << 8) | (x[i + 2] & 0xff);
        u = (u << 8) | (x[i + 1] & 0xff);
        return (u << 8) | (x[i + 0] & 0xff);
    }
    function st32(x, j, u) {
        for (let i = 0; i < 4; i++) {
            x[j + i] = u & 255;
            u >>>= 8;
        }
    }
    function vn(x, xi, y, yi, n) {
        let d = 0;
        for (let i = 0; i < n; i++)
            d |= x[xi + i] ^ y[yi + i];
        return (1 & ((d - 1) >>> 8)) - 1;
    }
    function core(out, inp, k, c, h) {
        const w = new Uint32Array(16), x = new Uint32Array(16), y = new Uint32Array(16), t = new Uint32Array(4);
        let i, j, m;
        for (i = 0; i < 4; i++) {
            x[5 * i] = ld32(c, 4 * i);
            x[1 + i] = ld32(k, 4 * i);
            x[6 + i] = ld32(inp, 4 * i);
            x[11 + i] = ld32(k, 16 + 4 * i);
        }
        for (i = 0; i < 16; i++)
            y[i] = x[i];
        for (i = 0; i < 20; i++) {
            for (j = 0; j < 4; j++) {
                for (m = 0; m < 4; m++)
                    t[m] = x[(5 * j + 4 * m) % 16];
                t[1] ^= L32((t[0] + t[3]) | 0, 7);
                t[2] ^= L32((t[1] + t[0]) | 0, 9);
                t[3] ^= L32((t[2] + t[1]) | 0, 13);
                t[0] ^= L32((t[3] + t[2]) | 0, 18);
                for (m = 0; m < 4; m++)
                    w[4 * j + (j + m) % 4] = t[m];
            }
            for (m = 0; m < 16; m++)
                x[m] = w[m];
        }
        if (h) {
            for (i = 0; i < 16; i++)
                x[i] = (x[i] + y[i]) | 0;
            for (i = 0; i < 4; i++) {
                x[5 * i] = (x[5 * i] - ld32(c, 4 * i)) | 0;
                x[6 + i] = (x[6 + i] - ld32(inp, 4 * i)) | 0;
            }
            for (i = 0; i < 4; i++) {
                st32(out, 4 * i, x[5 * i]);
                st32(out, 16 + 4 * i, x[6 + i]);
            }
        }
        else {
            for (i = 0; i < 16; i++)
                st32(out, 4 * i, (x[i] + y[i]) | 0);
        }
    }
    const sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
    function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
        const z = new Uint8Array(16), x = new Uint8Array(64);
        let u, i;
        if (!b)
            return 0;
        for (i = 0; i < 16; i++)
            z[i] = 0;
        for (i = 0; i < 8; i++)
            z[i] = n[i];
        while (b >= 64) {
            core(x, z, k, sigma, false);
            for (i = 0; i < 64; i++)
                c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
            u = 1;
            for (i = 8; i < 16; i++) {
                u = u + (z[i] & 0xff) | 0;
                z[i] = u & 0xff;
                u >>>= 8;
            }
            b -= 64;
            cpos += 64;
            if (m)
                mpos += 64;
        }
        if (b > 0) {
            core(x, z, k, sigma, false);
            for (i = 0; i < b; i++)
                c[cpos + i] = (m ? m[mpos + i] : 0) ^ x[i];
        }
        return 0;
    }
    function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
        const s = new Uint8Array(32);
        core(s, n, k, sigma, true);
        return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, n.subarray(16), s);
    }
    function add1305(h, c) {
        let u = 0;
        for (let j = 0; j < 17; j++) {
            u = (u + ((h[j] + c[j]) | 0)) | 0;
            h[j] = u & 255;
            u >>>= 8;
        }
    }
    const minusp = new Uint32Array([5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252]);
    function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
        let i, j, u;
        const x = new Uint32Array(17), r = new Uint32Array(17), h = new Uint32Array(17), c = new Uint32Array(17), g = new Uint32Array(17);
        for (j = 0; j < 17; j++)
            r[j] = h[j] = 0;
        for (j = 0; j < 16; j++)
            r[j] = k[j];
        r[3] &= 15;
        r[4] &= 252;
        r[7] &= 15;
        r[8] &= 252;
        r[11] &= 15;
        r[12] &= 252;
        r[15] &= 15;
        while (n > 0) {
            for (j = 0; j < 17; j++)
                c[j] = 0;
            for (j = 0; (j < 16) && (j < n); ++j)
                c[j] = m[mpos + j];
            c[j] = 1;
            mpos += j;
            n -= j;
            add1305(h, c);
            for (i = 0; i < 17; i++) {
                x[i] = 0;
                for (j = 0; j < 17; j++)
                    x[i] = (x[i] + (h[j] * ((j <= i) ? r[i - j] : ((320 * r[i + 17 - j]) | 0))) | 0) | 0;
            }
            for (i = 0; i < 17; i++)
                h[i] = x[i];
            u = 0;
            for (j = 0; j < 16; j++) {
                u = (u + h[j]) | 0;
                h[j] = u & 255;
                u >>>= 8;
            }
            u = (u + h[16]) | 0;
            h[16] = u & 3;
            u = (5 * (u >>> 2)) | 0;
            for (j = 0; j < 16; j++) {
                u = (u + h[j]) | 0;
                h[j] = u & 255;
                u >>>= 8;
            }
            u = (u + h[16]) | 0;
            h[16] = u;
        }
        for (j = 0; j < 17; j++)
            g[j] = h[j];
        add1305(h, minusp);
        const s = (-(h[16] >>> 7) | 0);
        for (j = 0; j < 17; j++)
            h[j] ^= s & (g[j] ^ h[j]);
        for (j = 0; j < 16; j++)
            c[j] = k[j + 16];
        c[16] = 0;
        add1305(h, c);
        for (j = 0; j < 16; j++)
            out[outpos + j] = h[j];
        return 0;
    }
    function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
        const x = new Uint8Array(16);
        crypto_onetimeauth(x, 0, m, mpos, n, k);
        return vn(h, hpos, x, 0, 16);
    }
    function crypto_secretbox(c, m, d, n, k) {
        if (d < 32)
            return -1;
        crypto_stream_xor(c, 0, m, 0, d, n, k);
        crypto_onetimeauth(c, 16, c, 32, d - 32, c);
        for (let i = 0; i < 16; i++)
            c[i] = 0;
        return 0;
    }
    function crypto_secretbox_open(m, c, d, n, k) {
        const x = new Uint8Array(32);
        if (d < 32)
            return -1;
        crypto_stream_xor(x, 0, null, 0, 32, n, k);
        if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0)
            return -1;
        crypto_stream_xor(m, 0, c, 0, d, n, k);
        for (let i = 0; i < 32; i++)
            m[i] = 0;
        return 0;
    }
    const crypto_secretbox_KEYBYTES = 32;
    const crypto_secretbox_NONCEBYTES = 24;
    const crypto_secretbox_ZEROBYTES = 32;
    const crypto_secretbox_BOXZEROBYTES = 16;
    function checkLengths(k, n) {
        if (k.length !== crypto_secretbox_KEYBYTES)
            throw new Error('bad key size');
        if (n.length !== crypto_secretbox_NONCEBYTES)
            throw new Error('bad nonce size');
    }
    function checkArrayTypes(...args) {
        for (let i = 0, count = args.length; i < count; i++) {
            if (!(args[i] instanceof Uint8Array))
                throw new TypeError('unexpected type, use Uint8Array');
        }
    }
    function naclSecretbox(msg, nonce, key) {
        checkArrayTypes(msg, nonce, key);
        checkLengths(key, nonce);
        const m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
        const c = new Uint8Array(m.length);
        for (let i = 0; i < msg.length; i++)
            m[i + crypto_secretbox_ZEROBYTES] = msg[i];
        crypto_secretbox(c, m, m.length, nonce, key);
        return c.subarray(crypto_secretbox_BOXZEROBYTES);
    }
    function naclSecretboxOpen(box, nonce, key) {
        checkArrayTypes(box, nonce, key);
        checkLengths(key, nonce);
        const c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
        const m = new Uint8Array(c.length);
        for (let i = 0; i < box.length; i++)
            c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
        if (c.length < 32)
            return null;
        if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0)
            return null;
        return m.subarray(crypto_secretbox_ZEROBYTES);
    }

    function naclDecrypt(encrypted, nonce, secret) {
        return naclSecretboxOpen(encrypted, nonce, secret);
    }

    function naclEncrypt(message, secret, nonce = randomAsU8a(24)) {
        return {
            encrypted: naclSecretbox(message, nonce, secret),
            nonce
        };
    }

    function XorAndSalsa(prev, pi, input, ii, out, oi) {
        let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
        let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
        let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
        let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
        let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
        let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
        let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
        let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
        let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
        for (let i = 0; i < 8; i += 2) {
            x04 ^= rotl$1(x00 + x12 | 0, 7);
            x08 ^= rotl$1(x04 + x00 | 0, 9);
            x12 ^= rotl$1(x08 + x04 | 0, 13);
            x00 ^= rotl$1(x12 + x08 | 0, 18);
            x09 ^= rotl$1(x05 + x01 | 0, 7);
            x13 ^= rotl$1(x09 + x05 | 0, 9);
            x01 ^= rotl$1(x13 + x09 | 0, 13);
            x05 ^= rotl$1(x01 + x13 | 0, 18);
            x14 ^= rotl$1(x10 + x06 | 0, 7);
            x02 ^= rotl$1(x14 + x10 | 0, 9);
            x06 ^= rotl$1(x02 + x14 | 0, 13);
            x10 ^= rotl$1(x06 + x02 | 0, 18);
            x03 ^= rotl$1(x15 + x11 | 0, 7);
            x07 ^= rotl$1(x03 + x15 | 0, 9);
            x11 ^= rotl$1(x07 + x03 | 0, 13);
            x15 ^= rotl$1(x11 + x07 | 0, 18);
            x01 ^= rotl$1(x00 + x03 | 0, 7);
            x02 ^= rotl$1(x01 + x00 | 0, 9);
            x03 ^= rotl$1(x02 + x01 | 0, 13);
            x00 ^= rotl$1(x03 + x02 | 0, 18);
            x06 ^= rotl$1(x05 + x04 | 0, 7);
            x07 ^= rotl$1(x06 + x05 | 0, 9);
            x04 ^= rotl$1(x07 + x06 | 0, 13);
            x05 ^= rotl$1(x04 + x07 | 0, 18);
            x11 ^= rotl$1(x10 + x09 | 0, 7);
            x08 ^= rotl$1(x11 + x10 | 0, 9);
            x09 ^= rotl$1(x08 + x11 | 0, 13);
            x10 ^= rotl$1(x09 + x08 | 0, 18);
            x12 ^= rotl$1(x15 + x14 | 0, 7);
            x13 ^= rotl$1(x12 + x15 | 0, 9);
            x14 ^= rotl$1(x13 + x12 | 0, 13);
            x15 ^= rotl$1(x14 + x13 | 0, 18);
        }
        out[oi++] = (y00 + x00) | 0;
        out[oi++] = (y01 + x01) | 0;
        out[oi++] = (y02 + x02) | 0;
        out[oi++] = (y03 + x03) | 0;
        out[oi++] = (y04 + x04) | 0;
        out[oi++] = (y05 + x05) | 0;
        out[oi++] = (y06 + x06) | 0;
        out[oi++] = (y07 + x07) | 0;
        out[oi++] = (y08 + x08) | 0;
        out[oi++] = (y09 + x09) | 0;
        out[oi++] = (y10 + x10) | 0;
        out[oi++] = (y11 + x11) | 0;
        out[oi++] = (y12 + x12) | 0;
        out[oi++] = (y13 + x13) | 0;
        out[oi++] = (y14 + x14) | 0;
        out[oi++] = (y15 + x15) | 0;
    }
    function BlockMix(input, ii, out, oi, r) {
        let head = oi + 0;
        let tail = oi + 16 * r;
        for (let i = 0; i < 16; i++)
            out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
        for (let i = 0; i < r; i++, head += 16, ii += 16) {
            XorAndSalsa(out, tail, input, ii, out, head);
            if (i > 0)
                tail += 16;
            XorAndSalsa(out, head, input, (ii += 16), out, tail);
        }
    }
    function scryptInit(password, salt, _opts) {
        const opts = checkOpts({
            dkLen: 32,
            asyncTick: 10,
            maxmem: 1024 ** 3 + 1024,
        }, _opts);
        const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
        anumber(N);
        anumber(r);
        anumber(p);
        anumber(dkLen);
        anumber(asyncTick);
        anumber(maxmem);
        if (onProgress !== undefined && typeof onProgress !== 'function')
            throw new Error('progressCb should be function');
        const blockSize = 128 * r;
        const blockSize32 = blockSize / 4;
        const pow32 = Math.pow(2, 32);
        if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
            throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
        }
        if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
            throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
        }
        if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
            throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
        }
        const memUsed = blockSize * (N + p);
        if (memUsed > maxmem) {
            throw new Error('Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem);
        }
        const B = pbkdf2(sha256$1, password, salt, { c: 1, dkLen: blockSize * p });
        const B32 = u32(B);
        const V = u32(new Uint8Array(blockSize * N));
        const tmp = u32(new Uint8Array(blockSize));
        let blockMixCb = () => { };
        if (onProgress) {
            const totalBlockMix = 2 * N * p;
            const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
            let blockMixCnt = 0;
            blockMixCb = () => {
                blockMixCnt++;
                if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
                    onProgress(blockMixCnt / totalBlockMix);
            };
        }
        return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
    }
    function scryptOutput(password, dkLen, B, V, tmp) {
        const res = pbkdf2(sha256$1, password, B, { c: 1, dkLen });
        clean(B, V, tmp);
        return res;
    }
    function scrypt(password, salt, opts) {
        const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
        swap32IfBE(B32);
        for (let pi = 0; pi < p; pi++) {
            const Pi = blockSize32 * pi;
            for (let i = 0; i < blockSize32; i++)
                V[i] = B32[Pi + i];
            for (let i = 0, pos = 0; i < N - 1; i++) {
                BlockMix(V, pos, V, (pos += blockSize32), r);
                blockMixCb();
            }
            BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
            blockMixCb();
            for (let i = 0; i < N; i++) {
                const j = B32[Pi + blockSize32 - 16] % N;
                for (let k = 0; k < blockSize32; k++)
                    tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
                BlockMix(tmp, 0, B32, Pi, r);
                blockMixCb();
            }
        }
        swap32IfBE(B32);
        return scryptOutput(password, dkLen, B, V, tmp);
    }

    const ALLOWED_PARAMS = [
        { N: 1 << 13, p: 10, r: 8 },
        { N: 1 << 14, p: 5, r: 8 },
        { N: 1 << 15, p: 3, r: 8 },
        { N: 1 << 15, p: 1, r: 8 },
        { N: 1 << 16, p: 2, r: 8 },
        { N: 1 << 17, p: 1, r: 8 }
    ];
    const DEFAULT_PARAMS = {
        N: 1 << 17,
        p: 1,
        r: 8
    };

    function scryptEncode(passphrase, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs) {
        const u8a = util.u8aToU8a(passphrase);
        return {
            params,
            password: !util.hasBigInt || (!onlyJs && isReady())
                ? scrypt$1(u8a, salt, Math.log2(params.N), params.r, params.p)
                : scrypt(u8a, salt, util.objectSpread({ dkLen: 64 }, params)),
            salt
        };
    }

    function scryptFromU8a(data) {
        if (!(data instanceof Uint8Array)) {
            throw new Error('Expected input to be a Uint8Array');
        }
        if (data.length < 32 + 12) {
            throw new Error(`Invalid input length: expected 44 bytes, found ${data.length}`);
        }
        const salt = data.subarray(0, 32);
        const N = util.u8aToBn(data.subarray(32, 36), BN_LE_OPTS).toNumber();
        const p = util.u8aToBn(data.subarray(36, 40), BN_LE_OPTS).toNumber();
        const r = util.u8aToBn(data.subarray(40, 44), BN_LE_OPTS).toNumber();
        if (N > (1 << 20) || p > 4 || r > 16) {
            throw new Error('Scrypt parameters exceed safe limits');
        }
        const isAllowed = ALLOWED_PARAMS.some((preset) => preset.N === N && preset.p === p && preset.r === r);
        if (!isAllowed) {
            throw new Error('Invalid injected scrypt params found');
        }
        return { params: { N, p, r }, salt };
    }

    function scryptToU8a(salt, { N, p, r }) {
        return util.u8aConcat(salt, util.bnToU8a(N, BN_LE_32_OPTS), util.bnToU8a(p, BN_LE_32_OPTS), util.bnToU8a(r, BN_LE_32_OPTS));
    }

    const ENCODING = ['scrypt', 'xsalsa20-poly1305'];
    const ENCODING_NONE = ['none'];
    const ENCODING_VERSION = '3';
    const NONCE_LENGTH = 24;
    const SCRYPT_LENGTH = 32 + (3 * 4);

    function jsonDecryptData(encrypted, passphrase, encType = ENCODING) {
        if (!encrypted) {
            throw new Error('No encrypted data available to decode');
        }
        else if (encType.includes('xsalsa20-poly1305') && !passphrase) {
            throw new Error('Password required to decode encrypted data');
        }
        let encoded = encrypted;
        if (passphrase) {
            let password;
            if (encType.includes('scrypt')) {
                const { params, salt } = scryptFromU8a(encrypted);
                password = scryptEncode(passphrase, salt, params).password;
                encrypted = encrypted.subarray(SCRYPT_LENGTH);
            }
            else {
                password = util.stringToU8a(passphrase);
            }
            encoded = naclDecrypt(encrypted.subarray(NONCE_LENGTH), encrypted.subarray(0, NONCE_LENGTH), util.u8aFixLength(password, 256, true));
        }
        if (!encoded) {
            throw new Error('Unable to decode using the supplied passphrase');
        }
        return encoded;
    }

    function jsonDecrypt({ encoded, encoding }, passphrase) {
        if (!encoded) {
            throw new Error('No encrypted data available to decode');
        }
        return jsonDecryptData(util.isHex(encoded)
            ? util.hexToU8a(encoded)
            : base64Decode(encoded), passphrase, Array.isArray(encoding.type)
            ? encoding.type
            : [encoding.type]);
    }

    function jsonEncryptFormat(encoded, contentType, isEncrypted) {
        return {
            encoded: base64Encode(encoded),
            encoding: {
                content: contentType,
                type: isEncrypted
                    ? ENCODING
                    : ENCODING_NONE,
                version: ENCODING_VERSION
            }
        };
    }

    function jsonEncrypt(data, contentType, passphrase) {
        let isEncrypted = false;
        let encoded = data;
        if (passphrase) {
            const { params, password, salt } = scryptEncode(passphrase);
            const { encrypted, nonce } = naclEncrypt(encoded, password.subarray(0, 32));
            isEncrypted = true;
            encoded = util.u8aConcat(scryptToU8a(salt, params), nonce, encrypted);
        }
        return jsonEncryptFormat(encoded, contentType, isEncrypted);
    }

    const secp256k1VerifyHasher = (hashType) => (message, signature, publicKey) => secp256k1Verify(message, signature, publicKey, hashType, true);
    const VERIFIERS_ECDSA = [
        ['ecdsa', secp256k1VerifyHasher('blake2')],
        ['ethereum', secp256k1VerifyHasher('keccak')]
    ];
    const VERIFIERS = [
        ['ed25519', ed25519Verify],
        ['sr25519', sr25519Verify]
    ];
    function verifyDetect(result, { message, publicKey, signature }, verifiers = [...VERIFIERS, ...VERIFIERS_ECDSA]) {
        result.isValid = verifiers.some(([crypto, verify]) => {
            try {
                if (verify(message, signature, publicKey)) {
                    result.crypto = crypto;
                    return true;
                }
            }
            catch {
            }
            return false;
        });
        return result;
    }
    function verifyMultisig(result, { message, publicKey, signature }) {
        if (![0, 1, 2].includes(signature[0]) || ![65, 66].includes(signature.length)) {
            throw new Error(`Unknown crypto type, expected signature prefix [0..2], found ${signature[0]}`);
        }
        if (signature.length === 66) {
            result = verifyDetect(result, { message, publicKey, signature: signature.subarray(1) }, VERIFIERS_ECDSA);
        }
        else {
            result = verifyDetect(result, { message, publicKey, signature: signature.subarray(1) }, VERIFIERS);
            if (!result.isValid) {
                result = verifyDetect(result, { message, publicKey, signature }, VERIFIERS_ECDSA);
            }
            if (!result.isValid) {
                result.crypto = 'none';
            }
        }
        return result;
    }
    function getVerifyFn(signature) {
        return [0, 1, 2].includes(signature[0]) && [65, 66].includes(signature.length)
            ? verifyMultisig
            : verifyDetect;
    }
    function signatureVerify(message, signature, addressOrPublicKey) {
        const signatureU8a = util.u8aToU8a(signature);
        if (![64, 65, 66].includes(signatureU8a.length)) {
            throw new Error(`Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
        }
        const publicKey = decodeAddress(addressOrPublicKey);
        const input = { message: util.u8aToU8a(message), publicKey, signature: signatureU8a };
        const result = { crypto: 'none', isValid: false, isWrapped: util.u8aIsWrapped(input.message, true), publicKey };
        const isWrappedBytes = util.u8aIsWrapped(input.message, false);
        const verifyFn = getVerifyFn(signatureU8a);
        verifyFn(result, input);
        if (result.crypto !== 'none' || (result.isWrapped && !isWrappedBytes)) {
            return result;
        }
        input.message = isWrappedBytes
            ? util.u8aUnwrapBytes(input.message)
            : util.u8aWrapBytes(input.message);
        return verifyFn(result, input);
    }

    const P64_1 = BigInt$1('11400714785074694791');
    const P64_2 = BigInt$1('14029467366897019727');
    const P64_3 = BigInt$1('1609587929392839161');
    const P64_4 = BigInt$1('9650029242287828579');
    const P64_5 = BigInt$1('2870177450012600261');
    const U64 = BigInt$1('0xffffffffffffffff');
    const _7n = BigInt$1(7);
    const _11n = BigInt$1(11);
    const _12n = BigInt$1(12);
    const _16n = BigInt$1(16);
    const _18n = BigInt$1(18);
    const _23n = BigInt$1(23);
    const _27n = BigInt$1(27);
    const _29n = BigInt$1(29);
    const _31n = BigInt$1(31);
    const _32n = BigInt$1(32);
    const _33n = BigInt$1(33);
    const _64n = BigInt$1(64);
    const _256n = BigInt$1(256);
    function rotl(a, b) {
        const c = a & U64;
        return ((c << b) | (c >> (_64n - b))) & U64;
    }
    function fromU8a(u8a, p, count) {
        const bigints = new Array(count);
        let offset = 0;
        for (let i = 0; i < count; i++, offset += 2) {
            bigints[i] = BigInt$1(u8a[p + offset] | (u8a[p + 1 + offset] << 8));
        }
        let result = util._0n;
        for (let i = count - 1; i >= 0; i--) {
            result = (result << _16n) + bigints[i];
        }
        return result;
    }
    function init(seed, input) {
        const state = {
            seed,
            u8a: new Uint8Array(32),
            u8asize: 0,
            v1: seed + P64_1 + P64_2,
            v2: seed + P64_2,
            v3: seed,
            v4: seed - P64_1
        };
        if (input.length < 32) {
            state.u8a.set(input);
            state.u8asize = input.length;
            return state;
        }
        const limit = input.length - 32;
        let p = 0;
        if (limit >= 0) {
            const adjustV = (v) => P64_1 * rotl(v + P64_2 * fromU8a(input, p, 4), _31n);
            do {
                state.v1 = adjustV(state.v1);
                p += 8;
                state.v2 = adjustV(state.v2);
                p += 8;
                state.v3 = adjustV(state.v3);
                p += 8;
                state.v4 = adjustV(state.v4);
                p += 8;
            } while (p <= limit);
        }
        if (p < input.length) {
            state.u8a.set(input.subarray(p, input.length));
            state.u8asize = input.length - p;
        }
        return state;
    }
    function xxhash64(input, initSeed) {
        const { seed, u8a, u8asize, v1, v2, v3, v4 } = init(BigInt$1(initSeed), input);
        let p = 0;
        let h64 = U64 & (BigInt$1(input.length) + (input.length >= 32
            ? (((((((((rotl(v1, util._1n) + rotl(v2, _7n) + rotl(v3, _12n) + rotl(v4, _18n)) ^ (P64_1 * rotl(v1 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v2 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v3 * P64_2, _31n))) * P64_1 + P64_4) ^ (P64_1 * rotl(v4 * P64_2, _31n))) * P64_1 + P64_4)
            : (seed + P64_5)));
        while (p <= (u8asize - 8)) {
            h64 = U64 & (P64_4 + P64_1 * rotl(h64 ^ (P64_1 * rotl(P64_2 * fromU8a(u8a, p, 4), _31n)), _27n));
            p += 8;
        }
        if ((p + 4) <= u8asize) {
            h64 = U64 & (P64_3 + P64_2 * rotl(h64 ^ (P64_1 * fromU8a(u8a, p, 2)), _23n));
            p += 4;
        }
        while (p < u8asize) {
            h64 = U64 & (P64_1 * rotl(h64 ^ (P64_5 * BigInt$1(u8a[p++])), _11n));
        }
        h64 = U64 & (P64_2 * (h64 ^ (h64 >> _33n)));
        h64 = U64 & (P64_3 * (h64 ^ (h64 >> _29n)));
        h64 = U64 & (h64 ^ (h64 >> _32n));
        const result = new Uint8Array(8);
        for (let i = 7; i >= 0; i--) {
            result[i] = Number(h64 % _256n);
            h64 = h64 / _256n;
        }
        return result;
    }

    function xxhashAsU8a(data, bitLength = 64, onlyJs) {
        const rounds = Math.ceil(bitLength / 64);
        const u8a = util.u8aToU8a(data);
        if (!util.hasBigInt || (!onlyJs && isReady())) {
            return twox(u8a, rounds);
        }
        const result = new Uint8Array(rounds * 8);
        for (let seed = 0; seed < rounds; seed++) {
            result.set(xxhash64(u8a, seed).reverse(), seed * 8);
        }
        return result;
    }
    const xxhashAsHex =  createAsHex(xxhashAsU8a);

    exports.addressEq = addressEq;
    exports.addressToEvm = addressToEvm;
    exports.allNetworks = allNetworks;
    exports.availableNetworks = availableNetworks;
    exports.base32Decode = base32Decode;
    exports.base32Encode = base32Encode;
    exports.base32Validate = base32Validate;
    exports.base58Decode = base58Decode;
    exports.base58Encode = base58Encode;
    exports.base58Validate = base58Validate;
    exports.base64Decode = base64Decode;
    exports.base64Encode = base64Encode;
    exports.base64Pad = base64Pad;
    exports.base64Trim = base64Trim;
    exports.base64Validate = base64Validate;
    exports.blake2AsHex = blake2AsHex;
    exports.blake2AsU8a = blake2AsU8a;
    exports.checkAddress = checkAddress;
    exports.checkAddressChecksum = checkAddressChecksum;
    exports.createKeyDerived = createKeyDerived;
    exports.createKeyMulti = createKeyMulti;
    exports.cryptoIsReady = cryptoIsReady;
    exports.cryptoWaitReady = cryptoWaitReady;
    exports.decodeAddress = decodeAddress;
    exports.deriveAddress = deriveAddress;
    exports.ed25519DeriveHard = ed25519DeriveHard;
    exports.ed25519PairFromRandom = ed25519PairFromRandom;
    exports.ed25519PairFromSecret = ed25519PairFromSecret;
    exports.ed25519PairFromSeed = ed25519PairFromSeed;
    exports.ed25519PairFromString = ed25519PairFromString;
    exports.ed25519Sign = ed25519Sign;
    exports.ed25519Verify = ed25519Verify;
    exports.encodeAddress = encodeAddress;
    exports.encodeDerivedAddress = encodeDerivedAddress;
    exports.encodeMultiAddress = encodeMultiAddress;
    exports.ethereumEncode = ethereumEncode;
    exports.evmToAddress = evmToAddress;
    exports.hdEthereum = hdEthereum;
    exports.hdLedger = hdLedger;
    exports.hdValidatePath = hdValidatePath;
    exports.hmacSha256AsU8a = hmacSha256AsU8a;
    exports.hmacSha512AsU8a = hmacSha512AsU8a;
    exports.hmacShaAsU8a = hmacShaAsU8a;
    exports.isAddress = isAddress;
    exports.isBase32 = isBase32;
    exports.isBase58 = isBase58;
    exports.isBase64 = isBase64;
    exports.isEthereumAddress = isEthereumAddress;
    exports.isEthereumChecksum = isEthereumChecksum;
    exports.jsonDecrypt = jsonDecrypt;
    exports.jsonDecryptData = jsonDecryptData;
    exports.jsonEncrypt = jsonEncrypt;
    exports.jsonEncryptFormat = jsonEncryptFormat;
    exports.keccak256AsU8a = keccak256AsU8a;
    exports.keccak512AsU8a = keccak512AsU8a;
    exports.keccakAsHex = keccakAsHex;
    exports.keccakAsU8a = keccakAsU8a;
    exports.keyExtractPath = keyExtractPath;
    exports.keyExtractSuri = keyExtractSuri;
    exports.keyFromPath = keyFromPath;
    exports.keyHdkdEcdsa = keyHdkdEcdsa;
    exports.keyHdkdEd25519 = keyHdkdEd25519;
    exports.keyHdkdSr25519 = keyHdkdSr25519;
    exports.mnemonicGenerate = mnemonicGenerate;
    exports.mnemonicToEntropy = mnemonicToEntropy;
    exports.mnemonicToLegacySeed = mnemonicToLegacySeed;
    exports.mnemonicToMiniSecret = mnemonicToMiniSecret;
    exports.mnemonicValidate = mnemonicValidate;
    exports.naclDecrypt = naclDecrypt;
    exports.naclEncrypt = naclEncrypt;
    exports.packageInfo = packageInfo;
    exports.pbkdf2Encode = pbkdf2Encode;
    exports.randomAsHex = randomAsHex;
    exports.randomAsNumber = randomAsNumber;
    exports.randomAsU8a = randomAsU8a;
    exports.scryptEncode = scryptEncode;
    exports.scryptFromU8a = scryptFromU8a;
    exports.scryptToU8a = scryptToU8a;
    exports.secp256k1Compress = secp256k1Compress;
    exports.secp256k1Expand = secp256k1Expand;
    exports.secp256k1PairFromSeed = secp256k1PairFromSeed;
    exports.secp256k1PrivateKeyTweakAdd = secp256k1PrivateKeyTweakAdd;
    exports.secp256k1Recover = secp256k1Recover;
    exports.secp256k1Sign = secp256k1Sign;
    exports.secp256k1Verify = secp256k1Verify;
    exports.selectableNetworks = selectableNetworks;
    exports.setSS58Format = setSS58Format;
    exports.sha256AsU8a = sha256AsU8a;
    exports.sha512AsU8a = sha512AsU8a;
    exports.shaAsU8a = shaAsU8a;
    exports.signatureVerify = signatureVerify;
    exports.sortAddresses = sortAddresses;
    exports.sr25519Agreement = sr25519Agreement;
    exports.sr25519DeriveHard = sr25519DeriveHard;
    exports.sr25519DerivePublic = sr25519DerivePublic;
    exports.sr25519DeriveSoft = sr25519DeriveSoft;
    exports.sr25519PairFromSeed = sr25519PairFromSeed;
    exports.sr25519Sign = sr25519Sign;
    exports.sr25519Verify = sr25519Verify;
    exports.sr25519VrfSign = sr25519VrfSign;
    exports.sr25519VrfVerify = sr25519VrfVerify;
    exports.validateAddress = validateAddress;
    exports.xxhashAsHex = xxhashAsHex;
    exports.xxhashAsU8a = xxhashAsU8a;

}));
