/**
 * Rayon thread bootstrap for the multithreaded zkir.
 *
 * The build replaces the generated pool import with this file. Relative worker
 * imports preserve the existing shared memory. Each startup failure rejects, so
 * `threads.ts` can use the single-threaded prover.
 */

const INIT = 'wasm_bindgen_worker_init';
const READY = 'wasm_bindgen_worker_ready';
const FAILED = 'wasm_bindgen_worker_failed';

/**
 * Firefox collects shared-memory workers that have no live `Worker` reference
 * (bugzilla.mozilla.org/show_bug.cgi?id=1702191), so the pool is retained here.
 * One WASM instance creates one pool, so keep the pool reference here.
 */
let pool;

function retainPool(nextPool) {
  pool = nextPool;
  return pool
}

function spawn(workerInit) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL(/* @vite-ignore */ ""+new URL('assets/thread-worker-NVxCik9R.js', import.meta.url).href+"", import.meta.url), { type: 'module' });
    const stop = () => {
      worker.removeEventListener('message', onMessage);
      worker.removeEventListener('error', onError);
      worker.removeEventListener('messageerror', onError);
    };
    const fail = (reason) => {
      stop();
      worker.terminate();
      reject(new Error(`proof thread failed to start: ${reason}`));
    };
    const onMessage = ({ data }) => {
      if (data?.type === READY) {
        stop();
        resolve(worker);
      } else if (data?.type === FAILED) {
        fail(data.message);
      }
    };
    // Listen for startup errors. After READY, the Rust worker loop does not stop.
    const onError = (event) => { fail(event.message ?? 'worker message error'); };
    worker.addEventListener('message', onMessage);
    worker.addEventListener('error', onError);
    worker.addEventListener('messageerror', onError);
    worker.postMessage(workerInit);
  })
}

/**
 * Start the pool for `initThreadPool`. Reject the promise when startup fails.
 */
async function startWorkers(module, memory, builder) {
  const threads = builder.numThreads();
  if (threads === 0) {
    builder.free();
    throw new Error('num_threads must be > 0.')
  }
  // All workers use one module, memory, receiver, and Rayon queue.
  const workerInit = {
    type: INIT,
    init: { module_or_path: module, memory },
    receiver: builder.receiver(),
  };
  const started = await Promise.allSettled(Array.from({ length: threads }, () => spawn(workerInit)));
  const failed = started.find((result) => result.status === 'rejected');
  if (failed !== undefined) {
    // Rayon requires the requested thread count. Stop a partial pool.
    for (const result of started) if (result.status === 'fulfilled') result.value.terminate();
    builder.free();
    throw failed.reason
  }
  retainPool(started.map((result) => result.value));
  builder.build();
}

/* @ts-self-types="./midnight_zkir_wasm_mt.d.ts" */


class IntoUnderlyingByteSource {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        IntoUnderlyingByteSourceFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_intounderlyingbytesource_free(ptr, 0);
    }
    /**
     * @returns {number}
     */
    get autoAllocateChunkSize() {
        const ret = wasm.intounderlyingbytesource_autoAllocateChunkSize(this.__wbg_ptr);
        return ret >>> 0;
    }
    cancel() {
        const ptr = this.__destroy_into_raw();
        wasm.intounderlyingbytesource_cancel(ptr);
    }
    /**
     * @param {ReadableByteStreamController} controller
     * @returns {Promise<any>}
     */
    pull(controller) {
        const ret = wasm.intounderlyingbytesource_pull(this.__wbg_ptr, controller);
        return ret;
    }
    /**
     * @param {ReadableByteStreamController} controller
     */
    start(controller) {
        wasm.intounderlyingbytesource_start(this.__wbg_ptr, controller);
    }
    /**
     * @returns {ReadableStreamType}
     */
    get type() {
        const ret = wasm.intounderlyingbytesource_type(this.__wbg_ptr);
        return __wbindgen_enum_ReadableStreamType[ret];
    }
}
if (Symbol.dispose) IntoUnderlyingByteSource.prototype[Symbol.dispose] = IntoUnderlyingByteSource.prototype.free;

class IntoUnderlyingSink {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        IntoUnderlyingSinkFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_intounderlyingsink_free(ptr, 0);
    }
    /**
     * @param {any} reason
     * @returns {Promise<any>}
     */
    abort(reason) {
        const ptr = this.__destroy_into_raw();
        const ret = wasm.intounderlyingsink_abort(ptr, reason);
        return ret;
    }
    /**
     * @returns {Promise<any>}
     */
    close() {
        const ptr = this.__destroy_into_raw();
        const ret = wasm.intounderlyingsink_close(ptr);
        return ret;
    }
    /**
     * @param {any} chunk
     * @returns {Promise<any>}
     */
    write(chunk) {
        const ret = wasm.intounderlyingsink_write(this.__wbg_ptr, chunk);
        return ret;
    }
}
if (Symbol.dispose) IntoUnderlyingSink.prototype[Symbol.dispose] = IntoUnderlyingSink.prototype.free;

class IntoUnderlyingSource {
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        IntoUnderlyingSourceFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_intounderlyingsource_free(ptr, 0);
    }
    cancel() {
        const ptr = this.__destroy_into_raw();
        wasm.intounderlyingsource_cancel(ptr);
    }
    /**
     * @param {ReadableStreamDefaultController} controller
     * @returns {Promise<any>}
     */
    pull(controller) {
        const ret = wasm.intounderlyingsource_pull(this.__wbg_ptr, controller);
        return ret;
    }
}
if (Symbol.dispose) IntoUnderlyingSource.prototype[Symbol.dispose] = IntoUnderlyingSource.prototype.free;

class WrappedProvingProvider {
    static __wrap(ptr) {
        const obj = Object.create(WrappedProvingProvider.prototype);
        obj.__wbg_ptr = ptr;
        WrappedProvingProviderFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
    }
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        WrappedProvingProviderFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_wrappedprovingprovider_free(ptr, 0);
    }
    /**
     * @param {Uint8Array} ser_preimage
     * @param {string} _key_location
     * @returns {Promise<any[]>}
     */
    check(ser_preimage, _key_location) {
        const ptr0 = passStringToWasm0(_key_location, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.wrappedprovingprovider_check(this.__wbg_ptr, ser_preimage, ptr0, len0);
        return ret;
    }
    /**
     * @param {Uint8Array} ser_preimage
     * @param {string} _key_location
     * @param {bigint | null} [overwrite_binding_input]
     * @returns {Promise<Uint8Array>}
     */
    prove(ser_preimage, _key_location, overwrite_binding_input) {
        const ptr0 = passStringToWasm0(_key_location, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.wrappedprovingprovider_prove(this.__wbg_ptr, ser_preimage, ptr0, len0, isLikeNone(overwrite_binding_input) ? 0 : addToExternrefTable0(overwrite_binding_input));
        return ret;
    }
}
if (Symbol.dispose) WrappedProvingProvider.prototype[Symbol.dispose] = WrappedProvingProvider.prototype.free;

class Zkir {
    static __wrap(ptr) {
        const obj = Object.create(Zkir.prototype);
        obj.__wbg_ptr = ptr;
        ZkirFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
    }
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        ZkirFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_zkir_free(ptr, 0);
    }
    /**
     * @param {Uint8Array} bytes
     * @returns {Zkir}
     */
    static deserialize(bytes) {
        const ret = wasm.zkir_deserialize(bytes);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return Zkir.__wrap(ret[0]);
    }
    /**
     * @param {string} json
     * @returns {Zkir}
     */
    static fromJson(json) {
        const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        const ret = wasm.zkir_fromJson(ptr0, len0);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return Zkir.__wrap(ret[0]);
    }
    /**
     * @returns {number}
     */
    getK() {
        const ret = wasm.zkir_getK(this.__wbg_ptr);
        return ret;
    }
    constructor() {
        const ret = wasm.zkir_new();
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        this.__wbg_ptr = ret[0];
        ZkirFinalization.register(this, this.__wbg_ptr, this);
        return this;
    }
    /**
     * @returns {Uint8Array}
     */
    serialize() {
        const ret = wasm.zkir_serialize(this.__wbg_ptr);
        if (ret[2]) {
            throw takeFromExternrefTable0(ret[1]);
        }
        return takeFromExternrefTable0(ret[0]);
    }
}
if (Symbol.dispose) Zkir.prototype[Symbol.dispose] = Zkir.prototype.free;

/**
 * @param {Uint8Array} ser_preimage
 * @param {any} provider
 * @returns {Promise<any[]>}
 */
function check$1(ser_preimage, provider) {
    const ret = wasm.check(ser_preimage, provider);
    return ret;
}

/**
 * @param {number} num_threads
 * @returns {Promise<any>}
 */
function initThreadPool(num_threads) {
    const ret = wasm.initThreadPool(num_threads);
    return ret;
}

/**
 * @param {string} json
 * @returns {Uint8Array}
 */
function jsonIrToBinary(json) {
    const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.jsonIrToBinary(ptr0, len0);
    if (ret[2]) {
        throw takeFromExternrefTable0(ret[1]);
    }
    return takeFromExternrefTable0(ret[0]);
}

/**
 * Decode and retain the expected parameters, then prepare both fixed k=15
 * KZG bases in the shared GPU service before the first transaction proves.
 * The WebGPU hook is a no-op when acceleration was not selected.
 * @param {number} k
 * @param {any} provider
 * @returns {Promise<void>}
 */
function prewarmGpuMsmBases$1(k, provider) {
    const ret = wasm.prewarmGpuMsmBases(k, provider);
    return ret;
}

/**
 * Inflate and initialize one proving key while the application is otherwise
 * warming its first GPU worker. `ProverKey::init` populates the existing
 * content-addressed PK cache, so the later proof gets the identical key and
 * correctness path without paying the synchronous gzip/key decode on demand.
 * @param {string} key_location
 * @param {any} provider
 * @param {Uint8Array | null} [expanded_snapshot]
 * @returns {Promise<any>}
 */
function prewarmProverKey$1(key_location, provider, expanded_snapshot) {
    const ptr0 = passStringToWasm0(key_location, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
    const len0 = WASM_VECTOR_LEN;
    const ret = wasm.prewarmProverKey(ptr0, len0, provider, isLikeNone(expanded_snapshot) ? 0 : addToExternrefTable0(expanded_snapshot));
    return ret;
}

/**
 * @param {Uint8Array} ser_preimage
 * @param {any} provider
 * @param {bigint | null} [overwrite_binding_input]
 * @returns {Promise<Uint8Array>}
 */
function prove$1(ser_preimage, provider, overwrite_binding_input) {
    const ret = wasm.prove(ser_preimage, provider, isLikeNone(overwrite_binding_input) ? 0 : addToExternrefTable0(overwrite_binding_input));
    return ret;
}

/**
 * Same proof as `prove`, with per-stage measurements returned to the worker.
 * Keeping this as a separate export leaves upstream consumers source-compatible.
 * @param {Uint8Array} ser_preimage
 * @param {any} provider
 * @param {bigint | null} [overwrite_binding_input]
 * @returns {Promise<any>}
 */
function proveProfiled$1(ser_preimage, provider, overwrite_binding_input) {
    const ret = wasm.proveProfiled(ser_preimage, provider, isLikeNone(overwrite_binding_input) ? 0 : addToExternrefTable0(overwrite_binding_input));
    return ret;
}

/**
 * @param {any} km_provider
 * @returns {WrappedProvingProvider}
 */
function provingProvider(km_provider) {
    const ret = wasm.provingProvider(km_provider);
    return WrappedProvingProvider.__wrap(ret);
}

class wbg_rayon_PoolBuilder {
    static __wrap(ptr) {
        const obj = Object.create(wbg_rayon_PoolBuilder.prototype);
        obj.__wbg_ptr = ptr;
        wbg_rayon_PoolBuilderFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
    }
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        wbg_rayon_PoolBuilderFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm.__wbg_wbg_rayon_poolbuilder_free(ptr, 0);
    }
    build() {
        wasm.wbg_rayon_poolbuilder_build(this.__wbg_ptr);
    }
    /**
     * @returns {number}
     */
    numThreads() {
        const ret = wasm.wbg_rayon_poolbuilder_numThreads(this.__wbg_ptr);
        return ret >>> 0;
    }
    /**
     * @returns {number}
     */
    receiver() {
        const ret = wasm.wbg_rayon_poolbuilder_receiver(this.__wbg_ptr);
        return ret >>> 0;
    }
}
if (Symbol.dispose) wbg_rayon_PoolBuilder.prototype[Symbol.dispose] = wbg_rayon_PoolBuilder.prototype.free;

/**
 * @param {number} receiver
 */
function wbg_rayon_start_worker(receiver) {
    wasm.wbg_rayon_start_worker(receiver);
}
function __wbg_get_imports(memory) {
    const import0 = {
        __proto__: null,
        __wbg_BigInt_54837260f97b6890: function(arg0) {
            const ret = BigInt(arg0);
            return ret;
        },
        __wbg_Error_408e67f47ca7b58b: function(arg0, arg1) {
            const ret = Error(getStringFromWasm0(arg0, arg1));
            return ret;
        },
        __wbg___oneamCpuMsm_1247fa01803c2c32: function() {
            globalThis.__oneamCpuMsm();
        },
        __wbg___oneamGpuEvaluateH_a862691e736c72c5: function() { return handleError(function (arg0, arg1, arg2, arg3) {
            const ret = globalThis.__oneamGpuEvaluateH(getArrayU8FromWasm0(arg0, arg1), getArrayU8FromWasm0(arg2, arg3));
            return ret;
        }, arguments); },
        __wbg___oneamGpuFftBatch_123372407bb2f68a: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
            const ret = globalThis.__oneamGpuFftBatch(arg0 >>> 0, arg1 !== 0, arg2 >>> 0, getArrayU8FromWasm0(arg3, arg4));
            return ret;
        }, arguments); },
        __wbg___oneamGpuMsmBatch_6ac5a4fb6c45764a: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
            const ret = globalThis.__oneamGpuMsmBatch(arg0 >>> 0, arg1 >>> 0, arg2 >>> 0, arg3 >>> 0, getArrayU8FromWasm0(arg4, arg5), getArrayU8FromWasm0(arg6, arg7), arg8);
            return ret;
        }, arguments); },
        __wbg___oneamGpuMsmDisable_b8eb898815dc9afe: function() { return handleError(function (arg0, arg1) {
            globalThis.__oneamGpuMsmDisable(getStringFromWasm0(arg0, arg1));
        }, arguments); },
        __wbg___oneamGpuMsmEnabled_fd2c4aea14c53613: function() {
            const ret = globalThis.__oneamGpuMsmEnabled();
            return ret;
        },
        __wbg___oneamGpuMsmPrewarm_e8c724178af609d2: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5) {
            globalThis.__oneamGpuMsmPrewarm(arg0 >>> 0, arg1 >>> 0, arg2 >>> 0, getArrayU8FromWasm0(arg3, arg4), arg5);
        }, arguments); },
        __wbg___oneamGpuMsm_0e17f25f95e649ae: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
            const ret = globalThis.__oneamGpuMsm(arg0 >>> 0, arg1 >>> 0, arg2 >>> 0, getArrayU8FromWasm0(arg3, arg4), getArrayU8FromWasm0(arg5, arg6), arg7);
            return ret;
        }, arguments); },
        __wbg___wbindgen_boolean_get_c9c83ebd41b34df3: function(arg0) {
            const v = arg0;
            const ret = typeof(v) === 'boolean' ? v : undefined;
            return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
        },
        __wbg___wbindgen_is_function_5e4570eb24ffa122: function(arg0) {
            const ret = typeof(arg0) === 'function';
            return ret;
        },
        __wbg___wbindgen_is_null_7d13f41e1a2d5140: function(arg0) {
            const ret = arg0 === null;
            return ret;
        },
        __wbg___wbindgen_is_object_a2790eb24c211ea0: function(arg0) {
            const val = arg0;
            const ret = typeof(val) === 'object' && val !== null;
            return ret;
        },
        __wbg___wbindgen_is_string_e6f02f0ea5f20a32: function(arg0) {
            const ret = typeof(arg0) === 'string';
            return ret;
        },
        __wbg___wbindgen_is_undefined_6cff064c44e0d823: function(arg0) {
            const ret = arg0 === undefined;
            return ret;
        },
        __wbg___wbindgen_memory_5dc2a138835b0f8e: function() {
            const ret = wasm.memory;
            return ret;
        },
        __wbg___wbindgen_module_d70c256490b5f616: function() {
            const ret = wasmModule;
            return ret;
        },
        __wbg___wbindgen_rethrow_fbd2dcd7d2b9ac5f: function(arg0) {
            throw arg0;
        },
        __wbg___wbindgen_string_get_d154f1e671052120: function(arg0, arg1) {
            const obj = arg1;
            const ret = typeof(obj) === 'string' ? obj : undefined;
            var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
            var len1 = WASM_VECTOR_LEN;
            getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
            getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
        },
        __wbg___wbindgen_throw_bb96b2010945f0bc: function(arg0, arg1) {
            throw new Error(getStringFromWasm0(arg0, arg1));
        },
        __wbg__wbg_cb_unref_be22cc64ae6946a0: function(arg0) {
            arg0._wbg_cb_unref();
        },
        __wbg_async_a8daea0f547e8eaa: function(arg0) {
            const ret = arg0.async;
            return ret;
        },
        __wbg_buffer_78291c0e094ccf99: function(arg0) {
            const ret = arg0.buffer;
            return ret;
        },
        __wbg_buffer_8117fe4dab119813: function(arg0) {
            const ret = arg0.buffer;
            return ret;
        },
        __wbg_byobRequest_f8b1c89429b77545: function(arg0) {
            const ret = arg0.byobRequest;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_byteLength_336bc7d303511ba0: function(arg0) {
            const ret = arg0.byteLength;
            return ret;
        },
        __wbg_byteOffset_2b1d5b10453ce198: function(arg0) {
            const ret = arg0.byteOffset;
            return ret;
        },
        __wbg_call_1c5886ab9c57d1c7: function() { return handleError(function (arg0, arg1) {
            const ret = arg0.call(arg1);
            return ret;
        }, arguments); },
        __wbg_call_35dba3c747ad7521: function() { return handleError(function (arg0, arg1, arg2) {
            const ret = arg0.call(arg1, arg2);
            return ret;
        }, arguments); },
        __wbg_close_72f69f5f2de2bc73: function() { return handleError(function (arg0) {
            arg0.close();
        }, arguments); },
        __wbg_close_97cdb44c3a7878f6: function() { return handleError(function (arg0) {
            arg0.close();
        }, arguments); },
        __wbg_crypto_38df2bab126b63dc: function(arg0) {
            const ret = arg0.crypto;
            return ret;
        },
        __wbg_data_e8364fec9b39caa4: function(arg0) {
            const ret = arg0.data;
            return ret;
        },
        __wbg_enqueue_7d68a21eda78e72f: function() { return handleError(function (arg0, arg1) {
            arg0.enqueue(arg1);
        }, arguments); },
        __wbg_getRandomValues_c44a50d8cfdaebeb: function() { return handleError(function (arg0, arg1) {
            arg0.getRandomValues(arg1);
        }, arguments); },
        __wbg_get_971a0c45d172643f: function() { return handleError(function (arg0, arg1) {
            const ret = Reflect.get(arg0, arg1);
            return ret;
        }, arguments); },
        __wbg_instanceof_Promise_e6e764b945c3128a: function(arg0) {
            let result;
            try {
                result = arg0 instanceof Promise;
            } catch (_) {
                result = false;
            }
            const ret = result;
            return ret;
        },
        __wbg_instanceof_Uint8Array_f935dbb0aa7cdeed: function(arg0) {
            let result;
            try {
                result = arg0 instanceof Uint8Array;
            } catch (_) {
                result = false;
            }
            const ret = result;
            return ret;
        },
        __wbg_instanceof_Window_5625ff9937037a38: function(arg0) {
            let result;
            try {
                result = arg0 instanceof Window;
            } catch (_) {
                result = false;
            }
            const ret = result;
            return ret;
        },
        __wbg_length_36bd29c6848c2144: function(arg0) {
            const ret = arg0.length;
            return ret;
        },
        __wbg_msCrypto_bd5a034af96bcba6: function(arg0) {
            const ret = arg0.msCrypto;
            return ret;
        },
        __wbg_new_116be93542d39019: function() {
            const ret = new Array();
            return ret;
        },
        __wbg_new_358857d90afd5a2d: function(arg0, arg1) {
            const ret = new Error(getStringFromWasm0(arg0, arg1));
            return ret;
        },
        __wbg_new_418fb92a013d5930: function(arg0, arg1) {
            try {
                var state0 = {a: arg0, b: arg1};
                var cb0 = (arg0, arg1) => {
                    const a = state0.a;
                    state0.a = 0;
                    try {
                        return wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined_______true_(a, state0.b, arg0, arg1);
                    } finally {
                        state0.a = a;
                    }
                };
                const ret = new Promise(cb0);
                return ret;
            } finally {
                state0.a = 0;
            }
        },
        __wbg_new_ebe3e0f6837f0879: function() {
            const ret = new Object();
            return ret;
        },
        __wbg_new_f545e2e1ea609f29: function(arg0) {
            const ret = new Int32Array(arg0);
            return ret;
        },
        __wbg_new_from_slice_3eea173078478cfe: function(arg0, arg1) {
            const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
            return ret;
        },
        __wbg_new_typed_cceaf62d8d95e9f2: function(arg0, arg1) {
            try {
                var state0 = {a: arg0, b: arg1};
                var cb0 = (arg0, arg1) => {
                    const a = state0.a;
                    state0.a = 0;
                    try {
                        return wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined_______true_(a, state0.b, arg0, arg1);
                    } finally {
                        state0.a = a;
                    }
                };
                const ret = new Promise(cb0);
                return ret;
            } finally {
                state0.a = 0;
            }
        },
        __wbg_new_with_byte_offset_and_length_ff6e927f8d72f0c3: function(arg0, arg1, arg2) {
            const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0);
            return ret;
        },
        __wbg_new_with_length_3ffc1c56427c525c: function(arg0) {
            const ret = new Uint8Array(arg0 >>> 0);
            return ret;
        },
        __wbg_new_worker_b0d92a7c5ee3d84d: function(arg0, arg1) {
            const ret = new Worker(getStringFromWasm0(arg0, arg1));
            return ret;
        },
        __wbg_node_84ea875411254db1: function(arg0) {
            const ret = arg0.node;
            return ret;
        },
        __wbg_now_8b265300afd5f2b9: function() {
            const ret = Date.now();
            return ret;
        },
        __wbg_now_e7c6795a7f81e10f: function(arg0) {
            const ret = arg0.now();
            return ret;
        },
        __wbg_of_79747c3f25a53502: function(arg0, arg1, arg2) {
            const ret = Array.of(arg0, arg1, arg2);
            return ret;
        },
        __wbg_performance_3fcf6e32a7e1ed0a: function(arg0) {
            const ret = arg0.performance;
            return ret;
        },
        __wbg_postMessage_99ea49fc49d53c0b: function() { return handleError(function (arg0, arg1) {
            arg0.postMessage(arg1);
        }, arguments); },
        __wbg_process_44c7a14e11e9f69e: function(arg0) {
            const ret = arg0.process;
            return ret;
        },
        __wbg_prototypesetcall_de8e0d9553586985: function(arg0, arg1, arg2) {
            Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
        },
        __wbg_push_adb0107829f02d75: function(arg0, arg1) {
            const ret = arg0.push(arg1);
            return ret;
        },
        __wbg_queueMicrotask_ac694eae12e92dfb: function(arg0) {
            queueMicrotask(arg0);
        },
        __wbg_queueMicrotask_be5fe34a8f4cad4d: function(arg0) {
            const ret = arg0.queueMicrotask;
            return ret;
        },
        __wbg_randomFillSync_6c25eac9869eb53c: function() { return handleError(function (arg0, arg1) {
            arg0.randomFillSync(arg1);
        }, arguments); },
        __wbg_require_b4edbdcf3e2a1ef0: function() { return handleError(function () {
            const ret = module.require;
            return ret;
        }, arguments); },
        __wbg_resolve_020f95d838c6ef25: function(arg0) {
            const ret = Promise.resolve(arg0);
            return ret;
        },
        __wbg_respond_f88cbcebace42068: function() { return handleError(function (arg0, arg1) {
            arg0.respond(arg1 >>> 0);
        }, arguments); },
        __wbg_set_8155bb79a948541b: function() { return handleError(function (arg0, arg1, arg2) {
            const ret = Reflect.set(arg0, arg1, arg2);
            return ret;
        }, arguments); },
        __wbg_set_b9b5b5cb7b495037: function(arg0, arg1, arg2) {
            arg0.set(getArrayU8FromWasm0(arg1, arg2));
        },
        __wbg_set_onmessage_ed4e5288e2e3af6f: function(arg0, arg1) {
            arg0.onmessage = arg1;
        },
        __wbg_startWorkers_8b582d57e92bd2d4: function(arg0, arg1, arg2) {
            const ret = startWorkers(arg0, arg1, wbg_rayon_PoolBuilder.__wrap(arg2));
            return ret;
        },
        __wbg_static_accessor_GLOBAL_THIS_466428f93b4eaa76: function() {
            const ret = typeof globalThis === 'undefined' ? null : globalThis;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_static_accessor_GLOBAL_c7aea38d4de089bc: function() {
            const ret = typeof global === 'undefined' ? null : global;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_static_accessor_SELF_42d4fae05e59267a: function() {
            const ret = typeof self === 'undefined' ? null : self;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_static_accessor_WINDOW_e0db14a0eba6a812: function() {
            const ret = typeof window === 'undefined' ? null : window;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_subarray_a4cc58201c7359fd: function(arg0, arg1, arg2) {
            const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0);
            return ret;
        },
        __wbg_then_03887f33d8da4f96: function(arg0, arg1) {
            const ret = arg0.then(arg1);
            return ret;
        },
        __wbg_then_7026b513a94278a8: function(arg0, arg1) {
            const ret = arg0.then(arg1);
            return ret;
        },
        __wbg_then_72819b8d4e081fb5: function(arg0, arg1, arg2) {
            const ret = arg0.then(arg1, arg2);
            return ret;
        },
        __wbg_timeOrigin_f3d5cb4f4a06c2b7: function(arg0) {
            const ret = arg0.timeOrigin;
            return ret;
        },
        __wbg_toString_033acf19ce89359c: function(arg0) {
            const ret = arg0.toString();
            return ret;
        },
        __wbg_toString_76752bc853683831: function() { return handleError(function (arg0, arg1) {
            const ret = arg0.toString(arg1);
            return ret;
        }, arguments); },
        __wbg_value_542338ffd3de015d: function(arg0) {
            const ret = arg0.value;
            return ret;
        },
        __wbg_versions_276b2795b1c6a219: function(arg0) {
            const ret = arg0.versions;
            return ret;
        },
        __wbg_view_7685fe4b2845c5b6: function(arg0) {
            const ret = arg0.view;
            return isLikeNone(ret) ? 0 : addToExternrefTable0(ret);
        },
        __wbg_waitAsync_442a13a06eeeb381: function() {
            const ret = Atomics.waitAsync;
            return ret;
        },
        __wbg_waitAsync_ea6a3c85af0d1191: function(arg0, arg1, arg2) {
            const ret = Atomics.waitAsync(arg0, arg1 >>> 0, arg2);
            return ret;
        },
        __wbindgen_cast_0000000000000001: function(arg0, arg1) {
            // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 208, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
            const ret = makeMutClosure(arg0, arg1, wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue______true_);
            return ret;
        },
        __wbindgen_cast_0000000000000002: function(arg0, arg1) {
            // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 93, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
            const ret = makeMutClosure(arg0, arg1, wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue__core_3ace8ec9fdfd5aa5___result__Result_____wasm_bindgen_bcb79949e0c72a34___JsError___true_);
            return ret;
        },
        __wbindgen_cast_0000000000000003: function(arg0, arg1) {
            // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 95, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
            const ret = makeMutClosure(arg0, arg1, wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___futures__task__wait_async_polyfill__MessageEvent______true_);
            return ret;
        },
        __wbindgen_cast_0000000000000004: function(arg0) {
            // Cast intrinsic for `F64 -> Externref`.
            const ret = arg0;
            return ret;
        },
        __wbindgen_cast_0000000000000005: function(arg0, arg1) {
            // Cast intrinsic for `Ref(Slice(U8)) -> NamedExternref("Uint8Array")`.
            const ret = getArrayU8FromWasm0(arg0, arg1);
            return ret;
        },
        __wbindgen_cast_0000000000000006: function(arg0, arg1) {
            // Cast intrinsic for `Ref(String) -> Externref`.
            const ret = getStringFromWasm0(arg0, arg1);
            return ret;
        },
        __wbindgen_cast_0000000000000007: function(arg0, arg1) {
            var v0 = getArrayJsValueFromWasm0(arg0, arg1);
            wasm.__wbindgen_free(arg0, arg1 * 4, 4);
            // Cast intrinsic for `Vector(Externref) -> Externref`.
            const ret = v0;
            return ret;
        },
        __wbindgen_init_externref_table: function() {
            const table = wasm.__wbindgen_externrefs;
            const offset = table.grow(4);
            table.set(0, undefined);
            table.set(offset + 0, undefined);
            table.set(offset + 1, null);
            table.set(offset + 2, true);
            table.set(offset + 3, false);
        },
        __wbindgen_link_5a1fa9a05318ea21: function(arg0) {
            const val = `onmessage = function (ev) {
                let [ia, index, value] = ev.data;
                ia = new Int32Array(ia.buffer);
                let result = Atomics.wait(ia, index, value);
                postMessage(result);
            };
            `;
            const ret = typeof URL.createObjectURL === 'undefined' ? "data:application/javascript," + encodeURIComponent(val) : URL.createObjectURL(new Blob([val], { type: "text/javascript" }));
            const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
            const len1 = WASM_VECTOR_LEN;
            getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
            getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
        },
        memory: memory || new WebAssembly.Memory({initial:22,maximum:65536,shared:true}),
    };
    return {
        __proto__: null,
        "./midnight_zkir_wasm_mt_bg.js": import0,
    };
}

function wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue______true_(arg0, arg1, arg2) {
    wasm.wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue______true_(arg0, arg1, arg2);
}

function wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___futures__task__wait_async_polyfill__MessageEvent______true_(arg0, arg1, arg2) {
    wasm.wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___futures__task__wait_async_polyfill__MessageEvent______true_(arg0, arg1, arg2);
}

function wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue__core_3ace8ec9fdfd5aa5___result__Result_____wasm_bindgen_bcb79949e0c72a34___JsError___true_(arg0, arg1, arg2) {
    const ret = wasm.wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___wasm_bindgen_bcb79949e0c72a34___JsValue__core_3ace8ec9fdfd5aa5___result__Result_____wasm_bindgen_bcb79949e0c72a34___JsError___true_(arg0, arg1, arg2);
    if (ret[1]) {
        throw takeFromExternrefTable0(ret[0]);
    }
}

function wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined_______true_(arg0, arg1, arg2, arg3) {
    wasm.wasm_bindgen_bcb79949e0c72a34___convert__closures_____invoke___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined___js_sys_3d2458c8fb275dd1___Function_fn_wasm_bindgen_bcb79949e0c72a34___JsValue_____wasm_bindgen_bcb79949e0c72a34___sys__Undefined_______true_(arg0, arg1, arg2, arg3);
}


const __wbindgen_enum_ReadableStreamType = ["bytes"];
const IntoUnderlyingByteSourceFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingbytesource_free(ptr, 1));
const IntoUnderlyingSinkFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingsink_free(ptr, 1));
const IntoUnderlyingSourceFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_intounderlyingsource_free(ptr, 1));
const WrappedProvingProviderFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_wrappedprovingprovider_free(ptr, 1));
const ZkirFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_zkir_free(ptr, 1));
const wbg_rayon_PoolBuilderFinalization = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(ptr => wasm.__wbg_wbg_rayon_poolbuilder_free(ptr, 1));

function addToExternrefTable0(obj) {
    const idx = wasm.__externref_table_alloc();
    wasm.__wbindgen_externrefs.set(idx, obj);
    return idx;
}

const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')
    ? { register: () => {}, unregister: () => {} }
    : new FinalizationRegistry(state => wasm.__wbindgen_destroy_closure(state.a, state.b));

function getArrayJsValueFromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    const mem = getDataViewMemory0();
    const result = [];
    for (let i = ptr; i < ptr + 4 * len; i += 4) {
        result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true)));
    }
    wasm.__externref_drop_slice(ptr, len);
    return result;
}

function getArrayU8FromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}

let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
    if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
        cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
    }
    return cachedDataViewMemory0;
}

function getStringFromWasm0(ptr, len) {
    return decodeText(ptr >>> 0, len);
}

let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
    if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.buffer !== wasm.memory.buffer) {
        cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
    }
    return cachedUint8ArrayMemory0;
}

function handleError(f, args) {
    try {
        return f.apply(this, args);
    } catch (e) {
        const idx = addToExternrefTable0(e);
        wasm.__wbindgen_exn_store(idx);
    }
}

function isLikeNone(x) {
    return x === undefined || x === null;
}

function makeMutClosure(arg0, arg1, f) {
    const state = { a: arg0, b: arg1, cnt: 1 };
    const real = (...args) => {

        // First up with a closure we increment the internal reference
        // count. This ensures that the Rust closure environment won't
        // be deallocated while we're invoking it.
        state.cnt++;
        const a = state.a;
        state.a = 0;
        try {
            return f(a, state.b, ...args);
        } finally {
            state.a = a;
            real._wbg_cb_unref();
        }
    };
    real._wbg_cb_unref = () => {
        if (--state.cnt === 0) {
            wasm.__wbindgen_destroy_closure(state.a, state.b);
            state.a = 0;
            CLOSURE_DTORS.unregister(state);
        }
    };
    CLOSURE_DTORS.register(real, state, state);
    return real;
}

function passStringToWasm0(arg, malloc, realloc) {
    if (realloc === undefined) {
        const buf = cachedTextEncoder.encode(arg);
        const ptr = malloc(buf.length, 1) >>> 0;
        getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
        WASM_VECTOR_LEN = buf.length;
        return ptr;
    }

    let len = arg.length;
    let ptr = malloc(len, 1) >>> 0;

    const mem = getUint8ArrayMemory0();

    let offset = 0;

    for (; offset < len; offset++) {
        const code = arg.charCodeAt(offset);
        if (code > 0x7F) break;
        mem[ptr + offset] = code;
    }
    if (offset !== len) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
        const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
        const ret = cachedTextEncoder.encodeInto(arg, view);

        offset += ret.written;
        ptr = realloc(ptr, len, offset, 1) >>> 0;
    }

    WASM_VECTOR_LEN = offset;
    return ptr;
}

function takeFromExternrefTable0(idx) {
    const value = wasm.__wbindgen_externrefs.get(idx);
    wasm.__externref_table_dealloc(idx);
    return value;
}

let cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : undefined);
if (cachedTextDecoder) cachedTextDecoder.decode();

const MAX_SAFARI_DECODE_BYTES = 2146435072;
let numBytesDecoded = 0;
function decodeText(ptr, len) {
    numBytesDecoded += len;
    if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
        cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
        cachedTextDecoder.decode();
        numBytesDecoded = len;
    }
    return cachedTextDecoder.decode(getUint8ArrayMemory0().slice(ptr, ptr + len));
}

const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder() : undefined);

if (cachedTextEncoder) {
    cachedTextEncoder.encodeInto = function (arg, view) {
        const buf = cachedTextEncoder.encode(arg);
        view.set(buf);
        return {
            read: arg.length,
            written: buf.length
        };
    };
}

let WASM_VECTOR_LEN = 0;

let wasmModule, wasm;
function __wbg_finalize_init(instance, module, thread_stack_size) {
    wasm = instance.exports;
    wasmModule = module;
    cachedDataViewMemory0 = null;
    cachedUint8ArrayMemory0 = null;
    if (typeof thread_stack_size !== 'undefined' && (typeof thread_stack_size !== 'number' || thread_stack_size === 0 || thread_stack_size % 65536 !== 0)) {
        throw new Error('invalid stack size');
    }

    wasm.__wbindgen_start(thread_stack_size);
    return wasm;
}

async function __wbg_load(module, imports) {
    if (typeof Response === 'function' && module instanceof Response) {
        if (!module.ok) {
            throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
        }

        if (typeof WebAssembly.instantiateStreaming === 'function') {
            try {
                return await WebAssembly.instantiateStreaming(module, imports);
            } catch (e) {
                const validResponse = expectedResponseType(module.type);

                if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
                    console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);

                } else { throw e; }
            }
        }

        const bytes = await module.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);
    } else {
        const instance = await WebAssembly.instantiate(module, imports);

        if (instance instanceof WebAssembly.Instance) {
            return { instance, module };
        } else {
            return instance;
        }
    }

    function expectedResponseType(type) {
        switch (type) {
            case 'basic': case 'cors': case 'default': return true;
        }
        return false;
    }
}

function initSync(module, memory) {
    if (wasm !== undefined) return wasm;

    let thread_stack_size;
    if (module !== undefined) {
        if (Object.getPrototypeOf(module) === Object.prototype) {
            ({module, memory, thread_stack_size} = module);
        } else {
            console.warn('using deprecated parameters for `initSync()`; pass a single object instead');
        }
    }

    const imports = __wbg_get_imports(memory);
    if (!(module instanceof WebAssembly.Module)) {
        module = new WebAssembly.Module(module);
    }
    const instance = new WebAssembly.Instance(module, imports);
    return __wbg_finalize_init(instance, module, thread_stack_size);
}

async function __wbg_init(module_or_path, memory) {
    if (wasm !== undefined) return wasm;

    let thread_stack_size;
    if (module_or_path !== undefined) {
        if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
            ({module_or_path, memory, thread_stack_size} = module_or_path);
        } else {
            console.warn('using deprecated parameters for the initialization function; pass a single object instead');
        }
    }

    if (module_or_path === undefined) {
        module_or_path = new URL(""+new URL('assets/midnight_zkir_wasm_mt_bg.wasm', import.meta.url).href+"", import.meta.url);
    }
    const imports = __wbg_get_imports(memory);

    if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
        module_or_path = fetch(module_or_path);
    }

    const { instance, module } = await __wbg_load(await module_or_path, imports);

    return __wbg_finalize_init(instance, module, thread_stack_size);
}

const variants$1 = {"baseline":{"wasm":"midnight_zkir_wasm_mt_bg.wasm","simd128":false,"wideArithmetic":false,"wasmSha256":"2aa77200952b52ab11aca43ca8cd399eb3cdb7bc8dbcb88868f32d5ff97a7b70"},"wide-arithmetic":{"wasm":"midnight_zkir_wasm_mt_wide_bg.wasm","simd128":false,"wideArithmetic":true,"wasmSha256":"9932c20f3dd0795c2d907f743b4a102a29957cc5e00533e3cdab32d982611c12"}};
const zkirBuildManifest = {
  variants: variants$1,
};

const wideArithmeticModule = (instructions) => {
  const body = [0, 32, 0, 32, 1, ...instructions, 11];
  return Uint8Array.from([
    0,
    97,
    115,
    109,
    1,
    0,
    0,
    0,
    1,
    8,
    1,
    96,
    2,
    126,
    126,
    2,
    126,
    126,
    // type (i64,i64)->(i64,i64)
    3,
    2,
    1,
    0,
    // func 0
    7,
    5,
    1,
    1,
    102,
    0,
    0,
    // export "f"
    10,
    body.length + 2,
    1,
    body.length,
    ...body
    // code
  ]);
};
const I64_MUL_WIDE_U = [252, 22];
const CONTROL_MODULE = wideArithmeticModule([]);
const PROBE_MODULE = wideArithmeticModule(I64_MUL_WIDE_U);
function currentWideArithmeticEnvironment() {
  const wasm = globalThis.WebAssembly;
  return {
    validate: typeof wasm?.validate === "function" ? (bytes) => wasm.validate(bytes) : void 0
  };
}
function detectWideArithmetic(environment = currentWideArithmeticEnvironment()) {
  const { validate } = environment;
  if (!validate) return { supported: false, reason: "probe-unavailable" };
  try {
    if (!validate(CONTROL_MODULE)) {
      return { supported: false, reason: "probe-inconclusive" };
    }
    return validate(PROBE_MODULE) ? { supported: true, reason: "supported" } : { supported: false, reason: "opcode-rejected" };
  } catch (error) {
    return {
      supported: false,
      reason: "probe-inconclusive",
      detail: error instanceof Error ? error.message : String(error)
    };
  }
}
function selectZkirVariant({
  manifest,
  environment,
  override
}) {
  const baseline = {
    variant: "baseline",
    wasm: manifest.baseline,
    reason: "user-disabled"
  };
  if (override === "baseline") return baseline;
  if (override === "wide-arithmetic") {
    return manifest.wideArithmetic === void 0 ? { ...baseline, reason: "variant-absent" } : {
      variant: "wide-arithmetic",
      wasm: manifest.wideArithmetic,
      reason: "supported",
      detail: "forced by override"
    };
  }
  const support = detectWideArithmetic(environment);
  if (!support.supported) {
    return { ...baseline, reason: support.reason, detail: support.detail };
  }
  if (manifest.wideArithmetic === void 0) {
    return { ...baseline, reason: "variant-absent" };
  }
  return {
    variant: "wide-arithmetic",
    wasm: manifest.wideArithmetic,
    reason: "supported"
  };
}

/**
 * Multithreaded replacement for `@midnight-ntwrk/zkir-v2`.
 *
 * wasm-bindgen-rayon does not support the package's `bundler` target. This build
 * uses the `web` target and initializes WASM here. It also exports
 * `initThreadPool`; see `threads.ts`.
 *
 * This file selects the wide-arithmetic binary on the main thread. Rayon
 * threads receive the selected module and its shared memory directly.
 *
 * Built from midnight-ledger `wasm-proving-demos/zkir-mt` at revision 02716c2c.
 * Rebuild with `npm run build:zkir-mt`. The build flags enable threads.
 */


const variants = zkirBuildManifest.variants ?? {};
const baseline = variants.baseline;
if (baseline === undefined) {
  throw new Error('vendor-zkir-mt/build-manifest.json has no baseline variant; rebuild with npm run build:zkir-mt')
}

/** `__1AM_ZKIR_VARIANT` selects a binary for rollback or benchmark tests. */
const choice = selectZkirVariant({
  manifest: { baseline: baseline.wasm, wideArithmetic: variants['wide-arithmetic']?.wasm },
  override: globalThis.__1AM_ZKIR_VARIANT,
});

/**
 * Initialize the baseline without an argument.
 *
 * The generated glue uses the static
 * `new URL('midnight_zkir_wasm_mt_bg.wasm', import.meta.url)`, which Vite
 * Vite rewrites this URL to the emitted asset path. A URL from a variable is not
 * rewritten and points to the wrong directory. Only an optional variant gets an
 * explicit URL because build-proof-worker.mjs copies it beside the worker.
 */
const initArgs = (name) => name === baseline.wasm
  ? undefined
  : { module_or_path: new URL(name, import.meta.url) };

/**
 * The probe validates the instruction, not the complete binary. If the wide
 * binary cannot start, use the baseline. A failed `__wbg_init` leaves its
 * module-level `wasm` unset, so the baseline initialization is safe.
 */
let active = choice;
try {
  await __wbg_init(initArgs(choice.wasm));
} catch (error) {
  if (choice.variant === 'baseline') throw error
  console.warn(
    `zkir: ${choice.variant} binary failed to initialise, falling back to baseline`,
    error,
  );
  active = {
    variant: 'baseline',
    wasm: baseline.wasm,
    reason: 'probe-inconclusive',
    detail: error instanceof Error ? error.message : String(error),
  };
  await __wbg_init(initArgs(baseline.wasm));
}

/** Active binary identity for telemetry and separate binary caches. */
const zkirVariant = Object.freeze({
  ...active,
  wasmSha256: (variants[active.variant] ?? baseline).wasmSha256,
});

const zkir = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  IntoUnderlyingByteSource,
  IntoUnderlyingSink,
  IntoUnderlyingSource,
  WrappedProvingProvider,
  Zkir,
  check: check$1,
  initSync,
  initThreadPool,
  jsonIrToBinary,
  prewarmGpuMsmBases: prewarmGpuMsmBases$1,
  prewarmProverKey: prewarmProverKey$1,
  prove: prove$1,
  proveProfiled: proveProfiled$1,
  provingProvider,
  wbg_rayon_PoolBuilder,
  wbg_rayon_start_worker,
  zkirVariant
}, Symbol.toStringTag, { value: 'Module' }));

// Single source of truth for the extension's network security policy.
//
// Imported by three very different consumers, so this file must stay plain
// ESM JavaScript with zero dependencies:
//   1. wxt.config.ts (vite-node) — builds the manifest CSP and content-script
//      matches from it.
//   2. dev/scripts/verify-manifest.mjs (node) — asserts the packed manifest
//      matches these expectations after every build/zip.
//   3. Browser runtime code (packages/wallet-runtime-browser/src/network/environment.ts) — validates
//      user-supplied custom endpoints against the same allowlist the CSP
//      enforces, so settings can reject a URL *before* the CSP silently
//      blocks it.


// Source for the proving keys used by the browser WASM prover. This bucket has
// no CORS headers, so local builds need a host permission to fetch it. Release
// builds use a CORS-enabled mirror instead.
const ZK_PARAMS_ORIGIN =
  'https://midnight-s3-fileshare-dev-eu-west-1.s3.eu-west-1.amazonaws.com';

const BUNDLED_ZK_PARAMS_PATH = "zk-params";
const DEFAULT_ZK_PARAMS_BASE_URL = typeof self === "undefined" || !self.location?.origin ? ZK_PARAMS_ORIGIN : `${self.location.origin}/${BUNDLED_ZK_PARAMS_PATH}`;
const MAX_BUNDLED_PARAMS_K = 17;
const KEY_MATERIAL_VERSION = 9;
const CACHE_NAME$1 = `oneam-zk-key-material-v${KEY_MATERIAL_VERSION}`;
const KEY_LOCATION_PATHS = {
  "midnight/zswap/spend": `zswap/${KEY_MATERIAL_VERSION}/spend`,
  "midnight/zswap/output": `zswap/${KEY_MATERIAL_VERSION}/output`,
  "midnight/zswap/sign": `zswap/${KEY_MATERIAL_VERSION}/sign`,
  "midnight/dust/spend": `dust/${KEY_MATERIAL_VERSION}/spend`
};
const KNOWN_KEY_LOCATIONS = Object.keys(KEY_LOCATION_PATHS);
const FETCH_ATTEMPTS = 3;
const delay = (ms) => new Promise((resolve) => {
  setTimeout(resolve, ms);
});
async function openCache() {
  if (typeof caches === "undefined") return void 0;
  try {
    return await caches.open(CACHE_NAME$1);
  } catch {
    return void 0;
  }
}
async function fetchWithRetry(url) {
  let lastError;
  for (let attempt = 1; attempt <= FETCH_ATTEMPTS; attempt++) {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      return response;
    } catch (error) {
      lastError = error;
      if (attempt < FETCH_ATTEMPTS) await delay(1e3 * 2 ** attempt);
    }
  }
  throw new Error(
    `Failed to download proving key material from ${url} after ${FETCH_ATTEMPTS} attempts: ${String(lastError)}`
  );
}
function withoutTrailingSlashes(value) {
  let end = value.length;
  while (end > 0 && value[end - 1] === "/") end--;
  return value.slice(0, end);
}
function createCachingKeyMaterialProvider(baseUrl = DEFAULT_ZK_PARAMS_BASE_URL) {
  const memory = /* @__PURE__ */ new Map();
  const normalizedBase = withoutTrailingSlashes(baseUrl);
  const servesBundledParams = normalizedBase !== withoutTrailingSlashes(ZK_PARAMS_ORIGIN);
  const download = async (path) => {
    const url = `${normalizedBase}/${path}`;
    const cache = await openCache();
    const cached = await cache?.match(url);
    if (cached) return new Uint8Array(await cached.arrayBuffer());
    const response = await fetchWithRetry(url);
    await cache?.put(url, response.clone()).catch(() => void 0);
    return new Uint8Array(await response.arrayBuffer());
  };
  const load = (path) => {
    const inFlight = memory.get(path);
    if (inFlight) return inFlight;
    const pending = download(path).catch((error) => {
      memory.delete(path);
      throw error;
    });
    memory.set(path, pending);
    return pending;
  };
  return {
    async lookupKey(keyLocation) {
      const path = KEY_LOCATION_PATHS[keyLocation];
      if (path === void 0) return void 0;
      const [proverKey, verifierKey, ir] = await Promise.all([
        load(`${path}.prover`),
        load(`${path}.verifier`),
        load(`${path}.bzkir`)
      ]);
      return { proverKey, verifierKey, ir };
    },
    getParams(k) {
      if (servesBundledParams && k > MAX_BUNDLED_PARAMS_K) {
        return Promise.reject(
          new Error(
            `This circuit is too large to prove in the browser: it needs BLS setup parameters for k=${k} (2^${k} rows), and the wallet ships up to k=${MAX_BUNDLED_PARAMS_K}. Configure a remote proof server for this dApp.`
          )
        );
      }
      return load(`bls_midnight_2p${k}`);
    }
  };
}

function gpuMsmBaseKey(base) {
  return JSON.stringify([base.ledgerRevision, base.k, base.basis, base.length]);
}
const GPU_MSM_BASE_K_CAPACITY = 4;
class GpuMsmBaseLru {
  constructor(kCapacity = GPU_MSM_BASE_K_CAPACITY) {
    this.kCapacity = kCapacity;
    if (!Number.isInteger(kCapacity) || kCapacity < 1) {
      throw new RangeError("GPU base cache k capacity must be a positive integer");
    }
  }
  kCapacity;
  entries = /* @__PURE__ */ new Map();
  kLru = [];
  get size() {
    return this.entries.size;
  }
  has(base) {
    const found = this.entries.has(gpuMsmBaseKey(base));
    if (found) this.touchK(base.k);
    return found;
  }
  get(base) {
    const entry = this.entries.get(gpuMsmBaseKey(base));
    if (entry) this.touchK(base.k);
    return entry?.value;
  }
  delete(base) {
    const deleted = this.entries.delete(gpuMsmBaseKey(base));
    if (deleted && ![...this.entries.values()].some((entry) => entry.base.k === base.k)) {
      const index = this.kLru.indexOf(base.k);
      if (index >= 0) this.kLru.splice(index, 1);
    }
    return deleted;
  }
  set(base, value) {
    const key = gpuMsmBaseKey(base);
    this.entries.set(key, { base: { ...base }, value });
    this.touchK(base.k);
    const evicted = [];
    while (this.kLru.length > this.kCapacity) {
      const evictedK = this.kLru.shift();
      for (const [candidateKey, entry] of this.entries) {
        if (entry.base.k !== evictedK) continue;
        this.entries.delete(candidateKey);
        evicted.push({ key: candidateKey, base: entry.base, value: entry.value });
      }
    }
    return evicted;
  }
  clear() {
    const evicted = [...this.entries].map(([key, entry]) => ({ key, ...entry }));
    this.entries.clear();
    this.kLru.length = 0;
    return evicted;
  }
  touchK(k) {
    const oldIndex = this.kLru.indexOf(k);
    if (oldIndex >= 0) this.kLru.splice(oldIndex, 1);
    this.kLru.push(k);
  }
}

const GPU_MSM_SCALAR_BYTES = 32;
const GPU_MSM_G1_BYTES = 48;
const GPU_MSM_AFFINE_G1_BYTES = 96;
const COMPLETION_HEADER_WORDS = 18;
const COMPLETION_HEADER_BYTES = COMPLETION_HEADER_WORDS * Int32Array.BYTES_PER_ELEMENT;
const failureCodes = [
  "user-disabled",
  "unsupported-browser",
  "webgpu-unavailable",
  "cross-origin-isolation-unavailable",
  "shared-memory-unavailable",
  "atomics-wait-unavailable",
  "adapter-unavailable",
  "fallback-adapter",
  "initialization-failed",
  "correctness-test-failed",
  "no-profitable-msm-sizes",
  "device-lost",
  "timeout",
  "shader-error",
  "transport-error",
  "point-decoding-error",
  "proof-verification-failed",
  "unknown"
];
new TextEncoder();
const decoder = new TextDecoder();
function createGpuMsmCompletion(payloadCapacity = 1024) {
  return new SharedArrayBuffer(COMPLETION_HEADER_BYTES + payloadCapacity);
}
function gpuMsmCompletionStatus(completion) {
  return new Int32Array(completion, 0, COMPLETION_HEADER_WORDS);
}
function payloadView(completion) {
  return new Uint8Array(completion, COMPLETION_HEADER_BYTES);
}
function readMetrics(words) {
  return {
    initMs: Atomics.load(words, 4 /* InitMicros */) / 1e3,
    affineConversionMs: Atomics.load(words, 8 /* AffineConversionMicros */) / 1e3,
    glvGenerationMs: Atomics.load(words, 9 /* GlvGenerationMicros */) / 1e3,
    cacheReadMs: Atomics.load(words, 10 /* CacheReadMicros */) / 1e3,
    cacheWriteMs: Atomics.load(words, 11 /* CacheWriteMicros */) / 1e3,
    bufferUploadMs: Atomics.load(words, 12 /* BufferUploadMicros */) / 1e3,
    montgomeryConversionMs: Atomics.load(words, 13 /* MontgomeryConversionMicros */) / 1e3,
    baseUploadMs: Atomics.load(words, 5 /* BaseUploadMicros */) / 1e3,
    dispatchMs: Atomics.load(words, 6 /* DispatchMicros */) / 1e3,
    readbackMs: Atomics.load(words, 7 /* ReadbackMicros */) / 1e3,
    fenceMs: Atomics.load(words, 16 /* FenceMicros */) / 1e3,
    scalarDecodeMs: Atomics.load(words, 17 /* ScalarDecodeMicros */) / 1e3,
    fftDispatchMs: Atomics.load(words, 14 /* FftDispatchMicros */) / 1e3,
    fftReadbackMs: Atomics.load(words, 15 /* FftReadbackMicros */) / 1e3
  };
}
function readGpuMsmCompletion(completion) {
  const words = gpuMsmCompletionStatus(completion);
  const status = Atomics.load(words, 0 /* Status */);
  if (status === 0 /* Pending */) return { state: "pending" };
  const metrics = readMetrics(words);
  const payloadLength = Atomics.load(words, 2 /* PayloadLength */);
  const source = payloadView(completion);
  if (payloadLength < 0 || payloadLength > source.byteLength) {
    return {
      state: "failure",
      code: "transport-error",
      message: `Invalid GPU MSM completion length ${payloadLength}`,
      metrics
    };
  }
  const payload = source.slice(0, payloadLength);
  if (status === 2 /* Failure */) {
    const encodedCode = Atomics.load(words, 3 /* FailureCode */);
    return {
      state: "failure",
      code: failureCodes[encodedCode - 1] ?? "unknown",
      message: payload.byteLength > 0 ? decoder.decode(payload) : void 0,
      metrics
    };
  }
  if (status !== 1 /* Success */) {
    return {
      state: "failure",
      code: "transport-error",
      message: `Invalid GPU MSM completion status ${status}`,
      metrics
    };
  }
  const format = Atomics.load(words, 1 /* Format */);
  if (format === 0 /* None */) {
    return { state: "success", format: "none", payload, metrics };
  }
  if (format === 1 /* Bytes */) {
    return { state: "success", format: "bytes", payload, metrics };
  }
  if (format === 2 /* Json */) {
    return { state: "success", format: "json", payload, metrics };
  }
  return {
    state: "failure",
    code: "transport-error",
    message: `Invalid GPU MSM completion format ${format}`,
    metrics
  };
}
function decodeGpuMsmJson(completion) {
  if (completion.format !== "json") throw new Error("Expected a JSON GPU MSM completion");
  return JSON.parse(decoder.decode(completion.payload));
}

function isFallbackGpuAdapter(adapter) {
  if (adapter.isFallbackAdapter === true) return true;
  const identity = [
    adapter.vendor,
    adapter.architecture,
    adapter.device,
    adapter.description
  ].filter((part) => typeof part === "string").join(" ").toLowerCase();
  return ["swiftshader", "llvmpipe", "software", "lavapipe"].some((marker) => identity.includes(marker));
}

function currentGpuMsmEnvironment() {
  const root = globalThis;
  return {
    navigator: root.navigator,
    crossOriginIsolated: root.crossOriginIsolated === true,
    sharedArrayBuffer: typeof SharedArrayBuffer === "function" ? SharedArrayBuffer : void 0,
    atomicsWait: typeof Atomics.wait === "function" ? Atomics.wait.bind(Atomics) : void 0,
    workerScope: !("document" in root)
  };
}
const ineligible = (code, message) => ({ eligible: false, reason: { code, message } });
function isSupportedChrome(nav, allowChromiumForTesting) {
  const ua = nav?.userAgent ?? "";
  const brands = nav?.userAgentData?.brands?.map(({ brand }) => brand) ?? [];
  const forbiddenBrand = brands.some(
    (brand) => /Microsoft Edge|Opera|Brave|Vivaldi/i.test(brand)
  );
  const forbiddenUa = /(?:Edg|EdgA|EdgiOS|OPR|Opera|Brave|Vivaldi|YaBrowser|SamsungBrowser|CriOS|HeadlessChrome)\//i.test(ua);
  const chromeUa = /(?:^|\s)Chrome\/\d+/i.test(ua);
  const vendorMismatch = nav?.vendor !== void 0 && nav.vendor !== "" && nav.vendor !== "Google Inc.";
  const sharedRequirements = !forbiddenBrand && !forbiddenUa && nav?.brave === void 0 && chromeUa;
  const isGoogleChrome = sharedRequirements && !vendorMismatch && (brands.length === 0 || brands.includes("Google Chrome"));
  const isTestChromium = allowChromiumForTesting && sharedRequirements && brands.includes("Chromium");
  return isGoogleChrome || isTestChromium;
}
function detectWebGpuMsmEligibility(mode = "auto", environment = currentGpuMsmEnvironment(), allowChromiumForTesting = false) {
  if (mode === "off") return ineligible("user-disabled");
  const nav = environment.navigator;
  if (!isSupportedChrome(nav, allowChromiumForTesting)) {
    return ineligible("unsupported-browser", "WebGPU MSM is enabled only in Google Chrome");
  }
  if (!nav || nav.gpu === void 0 || nav.gpu === null) return ineligible("webgpu-unavailable");
  if (!environment.crossOriginIsolated) return ineligible("cross-origin-isolation-unavailable");
  if (!environment.sharedArrayBuffer) return ineligible("shared-memory-unavailable");
  if (!environment.workerScope || !environment.atomicsWait) return ineligible("atomics-wait-unavailable");
  try {
    const probe = new Int32Array(new environment.sharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
    const result = environment.atomicsWait(probe, 0, 0, 0);
    if (result !== "timed-out" && result !== "not-equal") {
      return ineligible("atomics-wait-unavailable", `Unexpected Atomics.wait result ${result}`);
    }
  } catch (error) {
    return ineligible(
      "atomics-wait-unavailable",
      error instanceof Error ? error.message : String(error)
    );
  }
  return { eligible: true };
}

const DEFAULT_GPU_MSM_TIMEOUT_MS = 3e4;
function describeWorkerError(event) {
  if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
    const where = event.filename ? ` (${event.filename}:${event.lineno}:${event.colno})` : "";
    const message = event.message || event.error?.message;
    if (message) return `${message}${where}`;
  }
  if (typeof MessageEvent !== "undefined" && event instanceof MessageEvent) {
    return `${event.type}: message could not be deserialized`;
  }
  return event.type;
}
class WebGpuMsmBridgeError extends Error {
  constructor(reason) {
    super(reason.message ? `${reason.code}: ${reason.message}` : reason.code);
    this.reason = reason;
    this.name = "WebGpuMsmBridgeError";
  }
  reason;
}
function decodeCanonicalG1Points(encoded, decode) {
  const points = [];
  try {
    for (let offset = 0; offset < encoded.byteLength; offset += GPU_MSM_G1_BYTES) {
      const point = decode(encoded.slice(offset, offset + GPU_MSM_G1_BYTES));
      if (point === void 0 || point === null) {
        throw new Error("canonical G1 decoder returned no point");
      }
      points.push(point);
    }
    return { ok: true, points };
  } catch (error) {
    return { ok: false, message: error instanceof Error ? error.message : String(error) };
  }
}
class GpuMsmParamsK {
  largest;
  record(k) {
    if (!Number.isFinite(k)) return;
    this.largest = Math.max(this.largest ?? 0, Math.trunc(k));
  }
  observed() {
    return this.largest;
  }
  reset() {
    this.largest = void 0;
  }
}
function msmScalarError(request) {
  if (request.scalars.byteLength === request.base.length * GPU_MSM_SCALAR_BYTES) return void 0;
  return `scalar byte length ${request.scalars.byteLength} does not match ${request.base.length} points`;
}
function msmBatchScalarError(request) {
  if (!Number.isSafeInteger(request.batchItems) || request.batchItems < 1) {
    return `invalid GPU MSM batch item count ${request.batchItems}`;
  }
  const expected = request.batchItems * request.base.length * GPU_MSM_SCALAR_BYTES;
  if (Number.isSafeInteger(expected) && request.scalars.byteLength === expected) return void 0;
  return `batch scalar byte length ${request.scalars.byteLength} does not match ${request.batchItems} x ${request.base.length} points`;
}
function defaultGpuMsmSidecarModuleUrl() {
  const runtimeUrl = globalThis.location?.href;
  return new URL(
    "./webgpu-sidecar/oneam_webgpu_msm_sidecar.js",
    runtimeUrl ?? import.meta.url
  ).href;
}
function freshGpuMsmArrayBuffer(bytes) {
  const copy = new Uint8Array(bytes.byteLength);
  copy.set(bytes);
  return copy.buffer;
}
function finiteGpuMsmDuration(value) {
  return value !== void 0 && Number.isFinite(value) ? Math.max(0, value) : 0;
}
function validGpuMsmBaseDescriptor(base) {
  if (!base.ledgerRevision) return "ledgerRevision must not be empty";
  if (!Number.isInteger(base.k) || base.k < 1) return `invalid k ${base.k}`;
  if (base.basis !== "coefficient" && base.basis !== "lagrange") return `invalid basis ${String(base.basis)}`;
  if (!Number.isSafeInteger(base.length) || base.length < 1) return `invalid base length ${base.length}`;
  return void 0;
}
const GPU_FFT_MIN_LOG_N = 10;
const GPU_FFT_MAX_LOG_N = 20;
function gpuFftBatchIsOffloadable(request) {
  return Number.isSafeInteger(request.logN) && request.logN >= GPU_FFT_MIN_LOG_N && request.logN <= GPU_FFT_MAX_LOG_N;
}
function validGpuFftBatchRequest(request) {
  if (!gpuFftBatchIsOffloadable(request)) {
    return `invalid GPU FFT logN ${request.logN}`;
  }
  if (!Number.isSafeInteger(request.batchItems) || request.batchItems < 1 || request.batchItems > 128) {
    return `invalid GPU FFT batch item count ${request.batchItems}`;
  }
  const expectedBytes = request.batchItems * 2 ** request.logN * GPU_MSM_SCALAR_BYTES;
  if (!Number.isSafeInteger(expectedBytes) || request.values.byteLength !== expectedBytes) {
    return `GPU FFT input has ${request.values.byteLength} bytes; expected ${expectedBytes}`;
  }
  return expectedBytes;
}
function defaultGpuMsmWorker() {
  if (typeof SharedWorker !== "undefined") {
    try {
      const shared = new SharedWorker(new URL(/* @vite-ignore */ ""+new URL('assets/gpu-msm-worker-DscPZVad.js', import.meta.url).href+"", import.meta.url), {
        type: "module",
        name: "oneam-webgpu-msm"
      });
      shared.port.start();
      return {
        shared: true,
        addEventListener: (type, listener) => {
          if (type === "error") shared.addEventListener("error", listener);
          else shared.port.addEventListener("messageerror", listener);
        },
        postMessage: (message, transfer) => shared.port.postMessage(message, transfer ?? []),
        terminate: () => shared.port.close()
      };
    } catch {
    }
  }
  return new Worker(new URL(/* @vite-ignore */ ""+new URL('assets/gpu-msm-worker-DscPZVad.js', import.meta.url).href+"", import.meta.url), {
    type: "module",
    name: "oneam-webgpu-msm"
  });
}
function zeroGpuMsmMetrics() {
  return {
    cpuCalls: 0,
    gpuCalls: 0,
    gpuBatches: 0,
    gpuFftCalls: 0,
    gpuEvaluateHCalls: 0,
    gpuInitMs: 0,
    gpuAffineConversionMs: 0,
    gpuFenceMs: 0,
    gpuScalarDecodeMs: 0,
    gpuGlvGenerationMs: 0,
    gpuCacheReadMs: 0,
    gpuCacheWriteMs: 0,
    gpuBufferUploadMs: 0,
    gpuMontgomeryConversionMs: 0,
    gpuBaseUploadMs: 0,
    gpuDispatchMs: 0,
    gpuReadbackMs: 0,
    gpuFftDispatchMs: 0,
    gpuFftReadbackMs: 0,
    fallbackCount: 0,
    retriedOnCpu: false
  };
}
const EMPTY_GPU_COMPLETION_METRICS = {
  initMs: 0,
  affineConversionMs: 0,
  glvGenerationMs: 0,
  cacheReadMs: 0,
  cacheWriteMs: 0,
  bufferUploadMs: 0,
  montgomeryConversionMs: 0,
  baseUploadMs: 0,
  dispatchMs: 0,
  readbackMs: 0,
  fenceMs: 0,
  scalarDecodeMs: 0,
  fftDispatchMs: 0,
  fftReadbackMs: 0
};
function addGpuMsmCompletionMetrics(totals, metrics) {
  totals.gpuInitMs += metrics.initMs;
  totals.gpuAffineConversionMs += metrics.affineConversionMs;
  totals.gpuGlvGenerationMs += metrics.glvGenerationMs;
  totals.gpuCacheReadMs += metrics.cacheReadMs;
  totals.gpuCacheWriteMs += metrics.cacheWriteMs;
  totals.gpuBufferUploadMs += metrics.bufferUploadMs;
  totals.gpuMontgomeryConversionMs += metrics.montgomeryConversionMs;
  totals.gpuBaseUploadMs += metrics.baseUploadMs;
  totals.gpuDispatchMs += metrics.dispatchMs;
  totals.gpuReadbackMs += metrics.readbackMs;
  totals.gpuFenceMs += metrics.fenceMs;
  totals.gpuScalarDecodeMs += metrics.scalarDecodeMs;
  totals.gpuFftDispatchMs += metrics.fftDispatchMs;
  totals.gpuFftReadbackMs += metrics.fftReadbackMs;
}
function gpuMsmMetricsDelta(current, previous) {
  return {
    cpuCalls: Math.max(0, current.cpuCalls - previous.cpuCalls),
    gpuCalls: Math.max(0, current.gpuCalls - previous.gpuCalls),
    gpuBatches: Math.max(0, (current.gpuBatches ?? 0) - (previous.gpuBatches ?? 0)),
    gpuFftCalls: Math.max(0, current.gpuFftCalls - previous.gpuFftCalls),
    gpuEvaluateHCalls: Math.max(
      0,
      (current.gpuEvaluateHCalls ?? 0) - (previous.gpuEvaluateHCalls ?? 0)
    ),
    gpuInitMs: Math.max(0, current.gpuInitMs - previous.gpuInitMs),
    gpuAffineConversionMs: Math.max(0, current.gpuAffineConversionMs - previous.gpuAffineConversionMs),
    gpuGlvGenerationMs: Math.max(0, current.gpuGlvGenerationMs - previous.gpuGlvGenerationMs),
    gpuCacheReadMs: Math.max(0, current.gpuCacheReadMs - previous.gpuCacheReadMs),
    gpuCacheWriteMs: Math.max(0, current.gpuCacheWriteMs - previous.gpuCacheWriteMs),
    gpuBufferUploadMs: Math.max(0, current.gpuBufferUploadMs - previous.gpuBufferUploadMs),
    gpuMontgomeryConversionMs: Math.max(0, current.gpuMontgomeryConversionMs - previous.gpuMontgomeryConversionMs),
    gpuBaseUploadMs: Math.max(0, current.gpuBaseUploadMs - previous.gpuBaseUploadMs),
    gpuDispatchMs: Math.max(0, current.gpuDispatchMs - previous.gpuDispatchMs),
    gpuReadbackMs: Math.max(0, current.gpuReadbackMs - previous.gpuReadbackMs),
    gpuFenceMs: Math.max(0, current.gpuFenceMs - previous.gpuFenceMs),
    gpuScalarDecodeMs: Math.max(0, current.gpuScalarDecodeMs - previous.gpuScalarDecodeMs),
    gpuFftDispatchMs: Math.max(0, current.gpuFftDispatchMs - previous.gpuFftDispatchMs),
    gpuFftReadbackMs: Math.max(0, current.gpuFftReadbackMs - previous.gpuFftReadbackMs),
    fallbackCount: Math.max(0, current.fallbackCount - previous.fallbackCount),
    fallbackReason: current.fallbackCount > previous.fallbackCount ? current.fallbackReason : void 0,
    retriedOnCpu: current.retriedOnCpu && !previous.retriedOnCpu
  };
}

class WebGpuMsmBridge {
  eligibility;
  residentBases = new GpuMsmBaseLru(GPU_MSM_BASE_K_CAPACITY);
  timeoutMs;
  wait;
  sidecarModuleUrl;
  makeWorker;
  decodeCanonicalG1;
  totals = zeroGpuMsmMetrics();
  paramsK = new GpuMsmParamsK();
  worker;
  initCompletion;
  adapter;
  fallbackReason;
  initialized = false;
  disposed = false;
  constructor(options) {
    const environment = options.environment ?? currentGpuMsmEnvironment();
    this.eligibility = detectWebGpuMsmEligibility(
      options.mode,
      environment,
      options.allowChromiumForTesting
    );
    this.timeoutMs = Math.max(1, Math.floor(options.timeoutMs ?? DEFAULT_GPU_MSM_TIMEOUT_MS));
    this.wait = options.wait ?? environment.atomicsWait ?? Atomics.wait.bind(Atomics);
    this.sidecarModuleUrl = options.sidecarModuleUrl ?? defaultGpuMsmSidecarModuleUrl();
    this.makeWorker = options.createWorker ?? defaultGpuMsmWorker;
    this.decodeCanonicalG1 = options.decodeCanonicalG1;
    if (!this.eligibility.eligible) this.fallbackReason = this.eligibility.reason;
  }
  beginInitialization() {
    if (this.worker || this.fallbackReason || this.disposed) return;
    try {
      const worker = this.makeWorker();
      this.worker = worker;
      worker.addEventListener("error", (event) => {
        this.disable({ code: "transport-error", message: describeWorkerError(event) });
      });
      worker.addEventListener("messageerror", (event) => {
        this.disable({ code: "transport-error", message: describeWorkerError(event) });
      });
      const completion = createGpuMsmCompletion(2048);
      this.initCompletion = completion;
      worker.postMessage({
        op: "init",
        completion,
        sidecarModuleUrl: this.sidecarModuleUrl
      });
    } catch (error) {
      this.disable({
        code: "initialization-failed",
        message: error instanceof Error ? error.message : String(error)
      });
    }
  }
  initialize() {
    this.beginInitialization();
    if (this.fallbackReason) return this.cpuSelection();
    if (this.initialized && this.adapter) return { selectedBackend: "webgpu", adapter: this.adapter };
    const completion = this.initCompletion;
    if (!completion) {
      this.disable({ code: "initialization-failed", message: "GPU MSM initialization was not started" });
      return this.cpuSelection();
    }
    const result = this.waitFor(completion);
    if (result.state === "pending") {
      this.disable({ code: "timeout", message: `GPU initialization exceeded ${this.timeoutMs} ms` });
      return this.cpuSelection();
    }
    if (result.state === "failure") {
      this.addCompletionMetrics(result.metrics);
      this.disable({ code: result.code, message: result.message });
      return this.cpuSelection();
    }
    this.addCompletionMetrics(result.metrics);
    try {
      const payload = decodeGpuMsmJson(result);
      if (typeof payload !== "object" || payload === null || typeof payload.adapter !== "object") {
        throw new Error("GPU MSM initialization returned malformed adapter metadata");
      }
      if (isFallbackGpuAdapter(payload.adapter)) {
        this.disable({ code: "fallback-adapter", message: "Software/fallback WebGPU adapter rejected" });
        return this.cpuSelection();
      }
      this.adapter = { ...payload.adapter };
      this.initialized = true;
      this.initCompletion = void 0;
      return { selectedBackend: "webgpu", adapter: this.adapter };
    } catch (error) {
      this.disable({
        code: "initialization-failed",
        message: error instanceof Error ? error.message : String(error)
      });
      return this.cpuSelection();
    }
  }
  tryMsm(request) {
    this.paramsK.record(request.base.k);
    this.totals.gpuAffineConversionMs += finiteGpuMsmDuration(request.affineConversionMs);
    const selection = this.initialize();
    if (selection.selectedBackend === "cpu") return this.recordFallback(selection.cpuFallbackReason);
    const prepared = this.prepareMsmBase(request, msmScalarError(request));
    if (!prepared.ok) return prepared;
    const { alreadyResident, suppliedBases } = prepared;
    const completion = createGpuMsmCompletion(1024);
    const scalarBuffer = freshGpuMsmArrayBuffer(request.scalars);
    const baseBuffer = !alreadyResident && suppliedBases ? freshGpuMsmArrayBuffer(suppliedBases) : void 0;
    const message = {
      op: "msm",
      completion,
      base: { ...request.base },
      scalars: scalarBuffer,
      bases: baseBuffer
    };
    const transfer = baseBuffer ? [scalarBuffer, baseBuffer] : [scalarBuffer];
    const run = this.runBytesOp(message, transfer, completion, GPU_MSM_G1_BYTES, "GPU MSM");
    if (!run.ok) return run;
    const decoded = this.decodePoint(run.payload);
    if (!decoded.ok) return decoded;
    if (!alreadyResident) {
      this.residentBases.set(request.base, true);
    }
    this.totals.gpuCalls++;
    this.totals.gpuBatches = (this.totals.gpuBatches ?? 0) + 1;
    return { ok: true, point: decoded.point, encoded: run.payload.slice() };
  }
  tryMsmBatch(request) {
    this.paramsK.record(request.base.k);
    this.totals.gpuAffineConversionMs += finiteGpuMsmDuration(request.affineConversionMs);
    const selection = this.initialize();
    if (selection.selectedBackend === "cpu") return this.recordFallback(selection.cpuFallbackReason);
    const prepared = this.prepareMsmBase(request, msmBatchScalarError(request));
    if (!prepared.ok) return prepared;
    const { alreadyResident, suppliedBases } = prepared;
    const expectedResultBytes = request.batchItems * GPU_MSM_G1_BYTES;
    const completion = createGpuMsmCompletion(expectedResultBytes);
    const scalarBuffer = freshGpuMsmArrayBuffer(request.scalars);
    const baseBuffer = !alreadyResident && suppliedBases ? freshGpuMsmArrayBuffer(suppliedBases) : void 0;
    const message = {
      op: "msm-batch",
      completion,
      base: { ...request.base },
      batchItems: request.batchItems,
      scalars: scalarBuffer,
      bases: baseBuffer
    };
    const transfer = baseBuffer ? [scalarBuffer, baseBuffer] : [scalarBuffer];
    const run = this.runBytesOp(message, transfer, completion, expectedResultBytes, "GPU MSM batch");
    if (!run.ok) return run;
    const encoded = run.payload.slice();
    const decoded = this.decodePoints(encoded);
    if (!decoded.ok) return decoded;
    if (!alreadyResident) this.residentBases.set(request.base, true);
    this.totals.gpuCalls += request.batchItems;
    this.totals.gpuBatches = (this.totals.gpuBatches ?? 0) + 1;
    return { ok: true, points: decoded.points, encoded };
  }
  tryFftBatch(request) {
    const selection = this.initialize();
    if (selection.selectedBackend === "cpu") return this.recordFallback(selection.cpuFallbackReason);
    if (!gpuFftBatchIsOffloadable(request)) {
      return this.recordFallback({
        code: "no-profitable-msm-sizes",
        message: `GPU FFT does not serve logN ${request.logN}`
      });
    }
    const validation = validGpuFftBatchRequest(request);
    if (typeof validation === "string") {
      return this.failCurrent({ code: "transport-error", message: validation });
    }
    const expectedBytes = validation;
    const completion = createGpuMsmCompletion(expectedBytes);
    const values = freshGpuMsmArrayBuffer(request.values);
    const message = {
      op: "fft-batch",
      completion,
      logN: request.logN,
      inverse: request.inverse,
      batchItems: request.batchItems,
      values
    };
    const run = this.runBytesOp(message, [values], completion, expectedBytes, "GPU FFT batch");
    if (!run.ok) return run;
    this.totals.gpuFftCalls += request.batchItems;
    return { ok: true, encoded: run.payload.slice() };
  }
  /** Evaluate one `evaluate_h` block on the accelerator. */
  tryEvaluateH(program, columns, rows) {
    const selection = this.initialize();
    if (selection.selectedBackend === "cpu") return this.recordFallback(selection.cpuFallbackReason);
    if (selection.adapter.pipelineProfile === "windows-g1-minimal") {
      return {
        ok: false,
        reason: {
          code: "no-profitable-msm-sizes",
          message: "Windows G1 minimal profile keeps evaluate_h on Rayon CPU"
        }
      };
    }
    const expectedBytes = rows * GPU_MSM_SCALAR_BYTES;
    const completion = createGpuMsmCompletion(expectedBytes);
    const programBuffer = freshGpuMsmArrayBuffer(program);
    const columnBuffer = freshGpuMsmArrayBuffer(columns);
    const message = {
      op: "evaluate-h",
      completion,
      program: programBuffer,
      columns: columnBuffer
    };
    const run = this.runBytesOp(
      message,
      [programBuffer, columnBuffer],
      completion,
      expectedBytes,
      "GPU evaluate_h"
    );
    if (!run.ok) return run;
    this.totals.gpuEvaluateHCalls = (this.totals.gpuEvaluateHCalls ?? 0) + 1;
    return { ok: true, encoded: run.payload.slice() };
  }
  msm(request) {
    const result = this.tryMsm(request);
    if (!result.ok) throw new WebGpuMsmBridgeError(result.reason);
    return result;
  }
  msmBatch(request) {
    const result = this.tryMsmBatch(request);
    if (!result.ok) throw new WebGpuMsmBridgeError(result.reason);
    return result;
  }
  fftBatch(request) {
    const result = this.tryFftBatch(request);
    if (!result.ok) throw new WebGpuMsmBridgeError(result.reason);
    return result;
  }
  recordCpuMsm(count = 1) {
    this.totals.cpuCalls += Math.max(0, Math.floor(count));
  }
  markProofRetriedOnCpu() {
    this.totals.retriedOnCpu = true;
  }
  disable(reason, recordFallback = false) {
    if (!this.fallbackReason) this.fallbackReason = { ...reason };
    if (recordFallback) {
      this.totals.fallbackCount++;
      this.totals.fallbackReason ??= { ...reason };
    }
    this.initialized = false;
    this.adapter = void 0;
    this.initCompletion = void 0;
    this.residentBases.clear();
    this.worker?.terminate();
    this.worker = void 0;
  }
  backendSelection() {
    if (this.initialized && this.adapter) return { selectedBackend: "webgpu", adapter: { ...this.adapter } };
    return this.cpuSelection();
  }
  metricsSnapshot() {
    return {
      ...this.totals,
      fallbackReason: this.totals.fallbackReason ? { ...this.totals.fallbackReason } : void 0
    };
  }
  metricsDelta(previous) {
    return gpuMsmMetricsDelta(this.metricsSnapshot(), previous);
  }
  dispose() {
    if (this.disposed) return;
    this.disposed = true;
    const worker = this.worker;
    if (worker) {
      if (!worker.shared) {
        try {
          const completion = createGpuMsmCompletion(64);
          worker.postMessage({ op: "dispose", completion });
          this.wait(gpuMsmCompletionStatus(completion), 0, 0, Math.min(this.timeoutMs, 1e3));
        } catch {
        }
      }
      worker.terminate();
    }
    this.worker = void 0;
    this.initialized = false;
    this.adapter = void 0;
    this.residentBases.clear();
  }
  waitFor(completion) {
    const words = gpuMsmCompletionStatus(completion);
    const waitResult = this.wait(words, 0, 0, this.timeoutMs);
    if (waitResult === "timed-out") return { state: "pending" };
    return readGpuMsmCompletion(completion);
  }
  addCompletionMetrics(metrics) {
    addGpuMsmCompletionMetrics(this.totals, metrics);
  }
  /** Send one sidecar operation and validate its response. */
  runBytesOp(message, transfer, completion, expectedBytes, label) {
    try {
      this.worker?.postMessage(message, transfer);
    } catch (error) {
      return this.failCurrent({
        code: "transport-error",
        message: error instanceof Error ? error.message : String(error)
      });
    }
    const result = this.waitFor(completion);
    this.addCompletionMetrics(result.state === "pending" ? EMPTY_GPU_COMPLETION_METRICS : result.metrics);
    if (result.state === "failure") {
      return this.failCurrent({ code: result.code, message: result.message });
    }
    if (result.state === "pending") {
      return this.failCurrent({ code: "timeout", message: `${label} exceeded ${this.timeoutMs} ms` });
    }
    if (result.format !== "bytes" || result.payload.byteLength !== expectedBytes) {
      return this.failCurrent({
        code: "transport-error",
        message: `${label} returned ${result.payload.byteLength} bytes instead of ${expectedBytes}`
      });
    }
    return { ok: true, payload: result.payload };
  }
  prepareMsmBase(request, scalarError) {
    const descriptorError = validGpuMsmBaseDescriptor(request.base);
    if (descriptorError) return this.failCurrent({ code: "transport-error", message: descriptorError });
    if (scalarError) return this.failCurrent({ code: "transport-error", message: scalarError });
    const alreadyResident = this.residentBases.has(request.base);
    const suppliedBases = request.bases && request.bases.byteLength > 0 ? request.bases : void 0;
    if (!alreadyResident && !suppliedBases) {
      return this.failCurrent({
        code: "transport-error",
        message: "GPU base cache miss and the prover did not resend trusted affine bases"
      });
    }
    if (suppliedBases && suppliedBases.byteLength !== request.base.length * GPU_MSM_AFFINE_G1_BYTES) {
      return this.failCurrent({
        code: "transport-error",
        message: `affine base byte length ${suppliedBases.byteLength} does not match ${request.base.length} points`
      });
    }
    return { ok: true, alreadyResident, suppliedBases };
  }
  decodePoints(encoded) {
    const decoded = decodeCanonicalG1Points(encoded, this.decodeCanonicalG1);
    if (decoded.ok) return decoded;
    return this.failCurrent({ code: "point-decoding-error", message: decoded.message });
  }
  decodePoint(encoded) {
    const decoded = this.decodePoints(encoded);
    if (!decoded.ok) return decoded;
    const [point] = decoded.points;
    if (point === void 0) {
      return this.failCurrent({ code: "point-decoding-error", message: "GPU returned no point" });
    }
    return { ok: true, point };
  }
  failCurrent(reason) {
    this.disable(reason);
    return this.recordFallback(reason);
  }
  recordFallback(reason) {
    this.totals.fallbackCount++;
    this.totals.fallbackReason ??= { ...reason };
    return { ok: false, reason: { ...reason } };
  }
  cpuSelection() {
    return {
      selectedBackend: "cpu",
      cpuFallbackReason: this.fallbackReason ?? {
        code: "initialization-failed",
        message: "WebGPU MSM bridge is not initialized"
      }
    };
  }
}

function installOneAmGpuMsmImport(bridge, ledgerRevision) {
  const target = globalThis;
  const installedNames = [
    "__oneamGpuMsm",
    "__oneamGpuMsmBatch",
    "__oneamGpuMsmPrewarm",
    "__oneamGpuFftBatch",
    "__oneamGpuEvaluateH",
    "__oneamGpuMsmDisable",
    "__oneamGpuMsmEnabled",
    "__oneamCpuMsm"
  ];
  const snapshot = installedNames.map((name) => [name, target[name]]);
  target.__oneamGpuMsmEnabled = () => bridge.backendSelection().selectedBackend === "webgpu";
  target.__oneamCpuMsm = () => {
    bridge.recordCpuMsm();
  };
  target.__oneamGpuMsm = (k, basis, points, scalars, bases, affineConversionMs) => bridge.msm({
    base: {
      ledgerRevision,
      k,
      basis: basis === 0 ? "coefficient" : "lagrange",
      length: points
    },
    scalars,
    bases,
    affineConversionMs
  }).encoded;
  target.__oneamGpuMsmBatch = (k, basis, points, batchItems, scalars, bases, affineConversionMs) => bridge.msmBatch({
    base: {
      ledgerRevision,
      k,
      basis: basis === 0 ? "coefficient" : "lagrange",
      length: points
    },
    batchItems,
    scalars,
    bases,
    affineConversionMs
  }).encoded;
  target.__oneamGpuMsmPrewarm = (k, basis, points, bases, affineConversionMs) => {
    bridge.msm({
      base: {
        ledgerRevision,
        k,
        basis: basis === 0 ? "coefficient" : "lagrange",
        length: points
      },
      scalars: new Uint8Array(points * GPU_MSM_SCALAR_BYTES),
      bases,
      affineConversionMs
    });
  };
  target.__oneamGpuFftBatch = (logN, inverse, batchItems, values) => bridge.fftBatch({
    logN,
    inverse,
    batchItems,
    values
  }).encoded;
  target.__oneamGpuEvaluateH = (program, columns) => {
    const rows = new DataView(program.buffer, program.byteOffset, program.byteLength).getUint32(8, true);
    const result = bridge.tryEvaluateH(program, columns, rows);
    if (!result.ok) throw new WebGpuMsmBridgeError(result.reason);
    return result.encoded;
  };
  target.__oneamGpuMsmDisable = (code) => {
    bridge.disable({
      code: code === "proof-verification-failed" ? "proof-verification-failed" : "point-decoding-error",
      message: code
    }, true);
  };
  return () => {
    for (const [name, value] of snapshot) {
      if (value) Object.assign(target, { [name]: value });
      else delete target[name];
    }
  };
}

const GPU_CORRECTNESS_PREFIX = "ONEAM_GPU_CORRECTNESS:";
async function proveWithGpuCorrectnessRetry(bridge, prove, cpuCalls, reportBefore = bridge.metricsSnapshot()) {
  const attemptBefore = bridge.metricsSnapshot();
  let result;
  let retriedOnCpu = false;
  try {
    result = await prove();
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    const usedGpu = bridge.metricsDelta(attemptBefore).gpuCalls > 0;
    if (!usedGpu || !message.includes(GPU_CORRECTNESS_PREFIX)) throw error;
    bridge.disable({ code: "proof-verification-failed", message }, true);
    bridge.markProofRetriedOnCpu();
    retriedOnCpu = true;
    result = await prove();
  }
  const msm = bridge.metricsDelta(reportBefore);
  msm.cpuCalls = Math.max(msm.cpuCalls, Math.max(0, Math.floor(cpuCalls(result))));
  msm.retriedOnCpu = retriedOnCpu || msm.retriedOnCpu;
  return { result, msm };
}

const GPU_MSM_PARAM = "gpuMsm";

const PROVER_KEY_SNAPSHOT_FORMAT = "expanded-spend-v1";
const SNAPSHOT_KEY_LOCATION = "midnight/zswap/spend";
const CACHE_NAME = "oneam-prover-key-snapshots";
const CACHE_PATH = "/__oneam_prover_key_snapshot__/";
async function sha256(bytes) {
  const subtle = globalThis.crypto?.subtle;
  if (!subtle) return void 0;
  const digest = new Uint8Array(await subtle.digest("SHA-256", bytes.slice().buffer));
  return [...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function identity(material) {
  const [sourceSha256, verifierSha256, irSha256] = await Promise.all([
    sha256(material.proverKey),
    sha256(material.verifierKey),
    sha256(material.ir)
  ]);
  if (!sourceSha256 || !verifierSha256 || !irSha256) return void 0;
  return { sourceSha256, verifierSha256, irSha256 };
}
function cacheUrl(keyLocation) {
  return new URL(`${CACHE_PATH}${encodeURIComponent(keyLocation)}`, "https://oneam.invalid").href;
}
function createProverKeySnapshotStore(buildSha256, storage = globalThis.caches) {
  const open = async () => {
    try {
      return await storage?.open(CACHE_NAME);
    } catch {
      return void 0;
    }
  };
  return {
    async get(keyLocation, material) {
      if (keyLocation !== SNAPSHOT_KEY_LOCATION) return void 0;
      const sourceIdentity = await identity(material);
      if (!sourceIdentity) return void 0;
      const cache = await open();
      if (!cache) return void 0;
      const url = cacheUrl(keyLocation);
      try {
        const response = await cache.match(url);
        if (!response) return void 0;
        const expectedHeaders = {
          "x-oneam-pk-format": PROVER_KEY_SNAPSHOT_FORMAT,
          "x-oneam-pk-build-sha256": buildSha256,
          "x-oneam-pk-material-version": String(KEY_MATERIAL_VERSION),
          "x-oneam-pk-key-location": keyLocation,
          "x-oneam-pk-source-sha256": sourceIdentity.sourceSha256,
          "x-oneam-pk-verifier-sha256": sourceIdentity.verifierSha256,
          "x-oneam-pk-ir-sha256": sourceIdentity.irSha256
        };
        if (Object.entries(expectedHeaders).some(([name, value]) => response.headers.get(name) !== value)) {
          await cache.delete(url);
          return void 0;
        }
        const bytes = new Uint8Array(await response.arrayBuffer());
        const snapshotSha256 = await sha256(bytes);
        if (!snapshotSha256 || bytes.byteLength !== Number(response.headers.get("x-oneam-pk-snapshot-bytes")) || snapshotSha256 !== response.headers.get("x-oneam-pk-snapshot-sha256")) {
          await cache.delete(url);
          return void 0;
        }
        return { bytes, identity: sourceIdentity };
      } catch {
        await cache.delete(url).catch(() => false);
        return void 0;
      }
    },
    async put(keyLocation, material, bytes) {
      if (keyLocation !== SNAPSHOT_KEY_LOCATION || bytes.byteLength === 0) return false;
      const [sourceIdentity, snapshotSha256] = await Promise.all([identity(material), sha256(bytes)]);
      if (!sourceIdentity || !snapshotSha256) return false;
      const cache = await open();
      if (!cache) return false;
      const url = cacheUrl(keyLocation);
      try {
        await cache.put(url, new Response(bytes.slice().buffer, {
          headers: {
            "content-type": "application/octet-stream",
            "x-oneam-pk-format": PROVER_KEY_SNAPSHOT_FORMAT,
            "x-oneam-pk-build-sha256": buildSha256,
            "x-oneam-pk-material-version": String(KEY_MATERIAL_VERSION),
            "x-oneam-pk-key-location": keyLocation,
            "x-oneam-pk-source-sha256": sourceIdentity.sourceSha256,
            "x-oneam-pk-verifier-sha256": sourceIdentity.verifierSha256,
            "x-oneam-pk-ir-sha256": sourceIdentity.irSha256,
            "x-oneam-pk-snapshot-sha256": snapshotSha256,
            "x-oneam-pk-snapshot-bytes": String(bytes.byteLength)
          }
        }));
        return true;
      } catch {
        return false;
      }
    }
  };
}

const THREADS_PARAM = "threads";
function requestedThreads(workerUrl) {
  const raw = new URL(workerUrl).searchParams.get(THREADS_PARAM);
  const parsed = raw === null ? Number.NaN : Number.parseInt(raw, 10);
  return Number.isFinite(parsed) && parsed >= 1 ? parsed : 1;
}
async function startThreadPool(zkir, threads) {
  if (threads < 2) return 1;
  if (typeof zkir.initThreadPool !== "function") return 1;
  if (!globalThis.crossOriginIsolated) return 1;
  try {
    await zkir.initThreadPool(threads);
    return threads;
  } catch (error) {
    console.warn(
      "[WasmProving] threads unavailable, proving single-threaded:",
      error instanceof Error ? error.message : error
    );
    return 1;
  }
}

const { check, prove } = zkir;
const proveProfiled = proveProfiled$1;
const prewarmGpuMsmBases = prewarmGpuMsmBases$1;
const prewarmProverKey = prewarmProverKey$1;
const LEDGER_REVISION = "02716c2c95d50654aeb3cb63bfd8386046e4ca7d";
const GPU_SPEND_PREWARM_KEY = "midnight/zswap/spend";
const GPU_OUTPUT_PREWARM_KEY = "midnight/zswap/output";
function requestedGpuMsm(workerUrl) {
  return new URL(workerUrl).searchParams.get(GPU_MSM_PARAM) === "auto" ? "auto" : "off";
}
const gpuBridge = new WebGpuMsmBridge({
  mode: requestedGpuMsm(self.location.href),
  allowChromiumForTesting: false,
  decodeCanonicalG1: (encoded) => encoded
});
installOneAmGpuMsmImport(gpuBridge, LEDGER_REVISION);
let gpuMetricsBaseline = {
  cpuCalls: 0,
  gpuCalls: 0,
  gpuBatches: 0,
  gpuFftCalls: 0,
  gpuInitMs: 0,
  gpuAffineConversionMs: 0,
  gpuGlvGenerationMs: 0,
  gpuCacheReadMs: 0,
  gpuCacheWriteMs: 0,
  gpuBufferUploadMs: 0,
  gpuMontgomeryConversionMs: 0,
  gpuBaseUploadMs: 0,
  gpuDispatchMs: 0,
  gpuReadbackMs: 0,
  gpuFenceMs: 0,
  gpuScalarDecodeMs: 0,
  gpuFftDispatchMs: 0,
  gpuFftReadbackMs: 0,
  fallbackCount: 0,
  retriedOnCpu: false
};
const workerScope = self;
let provider;
const activeZkirVariant = zkirVariant;
const proverKeySnapshots = createProverKeySnapshotStore(
  activeZkirVariant?.wasmSha256 ?? zkirBuildManifest.variants.baseline.wasmSha256
);
function keyMaterialProvider(paramsBaseUrl) {
  if (!provider) {
    provider = createCachingKeyMaterialProvider(paramsBaseUrl);
    provider.cacheDecodedParams = new URL(self.location.href).searchParams.get("paramsCache") !== "false";
  }
  return provider;
}
function withSuppliedKeyMaterial(base, supplied) {
  if (!supplied) return base;
  return {
    cacheDecodedParams: base.cacheDecodedParams,
    lookupKey: async (keyLocation) => keyLocation === supplied.keyLocation ? supplied.material : base.lookupKey(keyLocation),
    getParams: (k) => base.getParams(k)
  };
}
function paramsKFromMsmCalls(calls) {
  const widest = calls?.reduce((largest, call) => Math.max(largest, call.points), 0) ?? 0;
  if (widest < 2) return void 0;
  return Math.round(Math.log2(widest));
}
function requestedPrewarmKey(request) {
  if (request.prewarmSpendKey) return GPU_SPEND_PREWARM_KEY;
  if (request.gpuPrewarmK === 14) return GPU_OUTPUT_PREWARM_KEY;
  return void 0;
}
async function handle(request) {
  const km = keyMaterialProvider(request.paramsBaseUrl);
  switch (request.op) {
    case "prove": {
      const material = withSuppliedKeyMaterial(km, request.supplied);
      if (proveProfiled) {
        const reportBefore = gpuMetricsBaseline;
        gpuBridge.paramsK.reset();
        try {
          const { result, msm } = await proveWithGpuCorrectnessRetry(
            gpuBridge,
            () => proveProfiled(
              request.preimage,
              material,
              request.overwriteBindingInput
            ),
            (completed) => completed.msmCalls?.length ?? 0,
            reportBefore
          );
          return {
            id: request.id,
            ok: true,
            op: "prove",
            proof: result.proof,
            timings: result.timings,
            msmCalls: result.msmCalls,
            msm,
            backend: gpuBridge.backendSelection(),
            paramsK: gpuBridge.paramsK.observed() ?? paramsKFromMsmCalls(result.msmCalls)
          };
        } finally {
          gpuMetricsBaseline = gpuBridge.metricsSnapshot();
        }
      }
      gpuBridge.paramsK.reset();
      const proof = await prove(request.preimage, material, request.overwriteBindingInput);
      return {
        id: request.id,
        ok: true,
        op: "prove",
        proof,
        backend: gpuBridge.backendSelection(),
        paramsK: gpuBridge.paramsK.observed()
      };
    }
    case "check": {
      const results = await check(request.preimage, withSuppliedKeyMaterial(km, request.supplied));
      return { id: request.id, ok: true, op: "check", results };
    }
    case "warmup": {
      const reportBefore = gpuMetricsBaseline;
      const prewarmKey = requestedPrewarmKey(request);
      let keyProfile;
      let keySnapshot;
      try {
        await Promise.all([
          ...request.snapshotOnly && prewarmKey ? [km.lookupKey(prewarmKey)] : KNOWN_KEY_LOCATIONS.map((location) => km.lookupKey(location)),
          ...!request.snapshotOnly && request.gpuPrewarmK && prewarmGpuMsmBases && gpuBridge.backendSelection().selectedBackend === "webgpu" ? [prewarmGpuMsmBases(request.gpuPrewarmK, km)] : [],
          ...prewarmKey && prewarmProverKey ? [(async () => {
            const material = await km.lookupKey(prewarmKey);
            if (!material) throw new Error(`failed to resolve key at '${prewarmKey}'`);
            const cached = await proverKeySnapshots.get(prewarmKey, material);
            keySnapshot = cached ? { status: "hit", bytes: cached.bytes.byteLength } : { status: "miss" };
            const profile = await prewarmProverKey(prewarmKey, km, cached?.bytes);
            keyProfile = profile;
            if (cached && !profile.snapshotAccepted) {
              keySnapshot = { status: "miss" };
            }
            if (profile.expandedSnapshot) {
              const written = await proverKeySnapshots.put(
                prewarmKey,
                material,
                profile.expandedSnapshot
              );
              keySnapshot = {
                status: written ? "written" : "unavailable",
                bytes: profile.expandedSnapshot.byteLength
              };
            }
          })()] : []
        ]);
        return {
          id: request.id,
          ok: true,
          op: "warmup",
          timings: keyProfile?.timings,
          keySnapshot,
          msm: gpuBridge.metricsDelta(reportBefore),
          backend: gpuBridge.backendSelection()
        };
      } finally {
        gpuMetricsBaseline = gpuBridge.metricsSnapshot();
      }
    }
  }
}
let requestQueue = Promise.resolve();
workerScope.addEventListener("message", (event) => {
  const request = event.data;
  requestQueue = requestQueue.then(async () => {
    try {
      workerScope.postMessage(await handle(request));
    } catch (error) {
      workerScope.postMessage({
        id: request.id,
        op: "error",
        ok: false,
        message: error instanceof Error ? error.message : String(error)
      });
    }
  });
});
gpuBridge.beginInitialization();
startThreadPool(zkir, requestedThreads(self.location.href)).then((threads) => {
  const backend = gpuBridge.initialize();
  workerScope.postMessage({ op: "ready", threads, ...backend });
}).catch((error) => {
  workerScope.postMessage({
    op: "initialization-error",
    message: error instanceof Error ? error.message : String(error)
  });
});
