{"version":3,"sources":["../src/networks.ts","../src/script/address.ts","../src/utils/timelock.ts","../src/script/tapscript.ts","../src/script/taprootTree.ts","../src/script/base.ts","../src/utils/transaction.ts","../src/utils/unknownFields.ts","../src/providers/eventSource.ts","../package.json","../src/utils/fetch.ts","../src/providers/errors.ts","../src/intent/index.ts","../src/providers/utils.ts","../src/providers/rateGate.ts","../src/providers/ark.ts","../src/providers/availability.ts","../src/contracts/constants.ts","../src/wallet/vtxo.ts"],"names":["NETWORK","TEST_NETWORK","version","bech32m","Script","bip68","ScriptNum","MultisigTapscript","CSVMultisigTapscript","ConditionCSVMultisigTapscript","ConditionMultisigTapscript","CLTVMultisigTapscript","hex","MultisigType","encode","p2tr_ms","decode","TAP_LEAF_VERSION","P","VarBytes","p2tr","taprootNumsKey","Address","leaf","BtcSignerTransaction","PSBTOutput","RawTx","concatBytes","SigHash","ArkPsbtFieldKey","RawWitness","Intent","OP","schnorr","SettlementEventType"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBO,IAAM,UAAA,GAAa,CAAC,OAAA,KAAkC;AACzD,EAAA,MAAM,KAAA,GAAQ,SAAS,OAAO,CAAA;AAG9B,EAAA,IAAI,CAAC,KAAA,EAAO,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,OAAO,CAAA,CAAE,CAAA;AAC7D,EAAA,OAAO,KAAA;AACX;AAEO,IAAM,QAAA,GAAW;AAAA,EACpB,OAAA,EAAS,aAAA,CAAcA,gBAAA,EAAS,KAAA,EAAO,SAAS,CAAA;AAAA,EAChD,OAAA,EAAS,aAAA,CAAcC,qBAAA,EAAc,MAAA,EAAQ,SAAS,CAAA;AAAA,EACtD,MAAA,EAAQ,aAAA,CAAcA,qBAAA,EAAc,MAAA,EAAQ,QAAQ,CAAA;AAAA,EACpD,SAAA,EAAW,aAAA,CAAcA,qBAAA,EAAc,MAAA,EAAQ,WAAW,CAAA;AAAA,EAC1D,OAAA,EAAS,aAAA;AAAA,IACL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,SAAA,KAAc,MAAA,IAAa,EAAE,SAAA,CAAU,OAAA,EAAQ,IAAK,IAAA,CAAK,GAAA,EAAI;AACxF","file":"chunk-DAYCCIRO.cjs","sourcesContent":["import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n\nexport type NetworkName = \"bitcoin\" | \"testnet\" | \"signet\" | \"mutinynet\" | \"regtest\";\n\nexport interface Network {\n    hrp: string;\n    bech32: string;\n    pubKeyHash: number;\n    scriptHash: number;\n    wif: number;\n    /**\n     * Canonical name this network was resolved from, when known.\n     *\n     * `bech32` cannot separate the tb-family — testnet, signet and mutinynet\n     * share every field above — so anything that has to tell them apart (a\n     * per-network timelock floor, for one) has no other handle. Optional\n     * because a hand-built `Network` carries no name: consumers must read a\n     * missing one as \"unknown\" and fall back to their strictest branch rather\n     * than guess at one.\n     */\n    name?: NetworkName;\n}\nexport const getNetwork = (network: NetworkName): Network => {\n    const found = networks[network];\n    // Fail closed: an unknown network must never silently fall through to\n    // mainnet params (e.g. via Address()'s default) when validating addresses.\n    if (!found) throw new Error(`Unsupported network: ${network}`);\n    return found;\n};\n\nexport const networks = {\n    bitcoin: withArkPrefix(NETWORK, \"ark\", \"bitcoin\"),\n    testnet: withArkPrefix(TEST_NETWORK, \"tark\", \"testnet\"),\n    signet: withArkPrefix(TEST_NETWORK, \"tark\", \"signet\"),\n    mutinynet: withArkPrefix(TEST_NETWORK, \"tark\", \"mutinynet\"),\n    regtest: withArkPrefix(\n        {\n            ...TEST_NETWORK,\n            bech32: \"bcrt\",\n            pubKeyHash: 0x6f,\n            scriptHash: 0xc4,\n        },\n        \"tark\",\n        \"regtest\",\n    ),\n};\n\nfunction withArkPrefix(\n    network: Omit<Network, \"hrp\" | \"name\">,\n    prefix: string,\n    name: NetworkName,\n): Network {\n    return {\n        ...network,\n        hrp: prefix,\n        name,\n    };\n}\n\nexport const DEFAULT_ARKADE_SERVER_URL = \"https://arkade.computer\" as const;\nexport const DEFAULT_NETWORK = networks.bitcoin;\nexport const DEFAULT_NETWORK_NAME = \"bitcoin\" as const satisfies NetworkName;\n\n/**\n * 33-byte compressed secp256k1 point, lowercase hex.\n *\n * Compressed rather than the 32-byte x-only form, for two reasons that are not\n * about the covenant leaf. The leaf itself is indifferent:\n * `computeArkadeScriptPublicKey` truncates by length and `lift_x`es, so a\n * compressed key and its x-only tail tweak to the same point — even for an\n * odd-Y (`03`) key like mutinynet's.\n *\n * What decides it is that compressed is the lossless form and the one actually\n * on the wire. The emulator's `/v1/info` returns `signerPubkey` compressed and\n * `Arkade.connect` keeps all 33 bytes of it (unlike the Arkade server key on\n * the line above, which it slices), so a value pinned here in compressed form\n * is byte-identical to what a live fetch yields and can substitute for it\n * directly. Going the other way is a one-way door: x-only can always be\n * recovered by dropping the prefix, but the parity bit cannot be recovered\n * from x-only. Consumers that need 32 bytes — the Arkade Intents offer TLV,\n * for one — already normalize at their own boundary.\n */\nconst COMPRESSED_PUBKEY = /^0[23][0-9a-f]{64}$/;\n\n/** Covenant co-signer (\"emulator\") for the mainnet Arkade deployment. */\nexport const BITCOIN_EMULATOR_PUBKEY =\n    \"0239c196415da47b26456a101daaa12ba9e445bfe153197f1e2b750bf40e52092e\" as const;\n\n/** Covenant co-signer (\"emulator\") for the hosted mutinynet Arkade deployment. */\nexport const MUTINYNET_EMULATOR_PUBKEY =\n    \"03f823b9b2febc81f4af967e77aed2f541cbd3397c6d8f5a72e32eb7b471af889a\" as const;\n\n/** Covenant co-signer (\"emulator\") shipped with the `arkade-regtest` stack. */\nexport const REGTEST_EMULATOR_PUBKEY =\n    \"02999413c46fa10ada5cbc4bcc79a1d09160c2ba3cfc812705d7a13e5e545fb2a9\" as const;\n\n/**\n * The covenant co-signer each network's Arkade deployment runs.\n *\n * This is a property of the NETWORK, not of whoever happens to be talking to\n * it: every participant building a covenant contract on one network co-signs\n * with the same key, so carrying a per-deployment copy of it can only ever\n * introduce disagreement — two peers on one network advertising two keys is a\n * misconfiguration nothing downstream is positioned to catch.\n *\n * `testnet` and `signet` are absent because no emulator is deployed for them;\n * they resolve to a throw rather than to a neighbouring network's key.\n */\nconst EMULATOR_PUBKEYS: Partial<Record<NetworkName, string>> = {\n    bitcoin: BITCOIN_EMULATOR_PUBKEY,\n    mutinynet: MUTINYNET_EMULATOR_PUBKEY,\n    regtest: REGTEST_EMULATOR_PUBKEY,\n};\n\n/**\n * The pinned co-signer key for `network`, as 33-byte compressed lowercase hex.\n *\n * @throws if the network carries no name, or names one with no deployed\n *   emulator. Fail closed on both counts: the return value ends up in a\n *   covenant leaf that decides who can move the funds, so there is no\n *   defensible fallback. Guessing a neighbour's key (the tb-family share every\n *   other field on {@link Network}) would build a leaf co-signed by a service\n *   that will never sign for it — funds locked to a key nobody holds — and\n *   returning an empty string just moves the same failure somewhere harder to\n *   read. A hand-assembled `Network` carries no `name` and lands here too,\n *   matching how the per-network timelock floors treat an unnamed network.\n *\n *   Deliberately NOT falling back to whatever key the emulator reports about\n *   itself: that is the self-report this pin exists to stop trusting, and doing\n *   it only on unpinned networks would make the guarantee depend on\n *   `network.name` with no signal to the caller that it had lapsed. The\n *   unnamed case is the sharp one — a hand-built `Network` can carry\n *   bitcoin-equivalent parameters, so a silent fallback would drop to\n *   \"trust the endpoint\" on exactly the input that looks most like mainnet.\n *   Callers who mean it pass {@link resolveEmulatorPubkey}'s override, which\n *   the thrown message names.\n */\nexport function defaultEmulatorPubkey(network: Network): string {\n    const pinned = network.name ? EMULATOR_PUBKEYS[network.name] : undefined;\n    if (!pinned) {\n        // Name the remedy, not just the refusal. Whoever hits this usually has\n        // a working emulator in front of them, so a bare \"not pinned\" reads as\n        // the SDK being broken rather than as one argument being missing.\n        const cause = network.name\n            ? `no emulator is deployed for ${network.name}`\n            : `this Network carries no name, so it cannot be matched ` +\n              `(build it with getNetwork(...) rather than by hand)`;\n        throw new Error(\n            `No emulator co-signer key is pinned for this network: ${cause}; ` +\n                `pass emulatorPubkey: \"<33-byte compressed hex>\" to Arkade.connect to ` +\n                `co-sign with your own emulator instead. Pinned networks: ` +\n                `${Object.keys(EMULATOR_PUBKEYS).join(\", \")}`,\n        );\n    }\n    return pinned;\n}\n\n/**\n * Resolve the co-signer key for `network`, letting a caller substitute its own.\n *\n * The override is the escape hatch for three situations, and the first is the\n * one that matters operationally:\n *\n * 1. **A network rotated its emulator key and this SDK has not shipped the new\n *    constant yet.** Since `Arkade.connect` no longer asks the service which\n *    key it signs with, a rotation is invisible here until the constant is\n *    updated — covenants keep building against the retired key and fail only\n *    when a claim is attempted. Passing the new key restores service without\n *    waiting for a release, so a rotation is a config change rather than an\n *    outage.\n * 2. A private or self-hosted emulator, including on a network with no pinned\n *    key at all (signet, testnet, a hand-built `Network`).\n * 3. Tests and local stacks.\n *\n * Supplying it means co-signing with a different service: every covenant built\n * from the returned key can be completed by whoever holds it and by no one\n * else, so it is a statement that you trust that operator in place of the\n * network's. Prefer {@link defaultEmulatorPubkey} unless that is deliberate.\n *\n * A malformed override throws rather than being passed through — a typo here\n * would otherwise surface as an unspendable contract long after the fact.\n */\nexport function resolveEmulatorPubkey(network: Network, override?: string): string {\n    if (override === undefined) return defaultEmulatorPubkey(network);\n    if (!COMPRESSED_PUBKEY.test(override)) {\n        throw new Error(\n            `Emulator pubkey override must be 33-byte compressed secp256k1 hex ` +\n                `(66 lowercase chars, 02/03 prefix), got ${JSON.stringify(override)}.`,\n        );\n    }\n    return override;\n}\n","import { bech32m } from \"@scure/base\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { Script } from \"@scure/btc-signer/script.js\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\n/**\n * ArkAddress allows creating and decoding bech32m-encoded Arkade addresses.\n *\n * An Arkade address is composed of:\n * - a human readable prefix (hrp)\n * - a version byte (1 byte)\n * - a server public key (32 bytes)\n * - a vtxo taproot public key (32 bytes)\n *\n * @remarks\n * This is an Arkade-specific address format.\n * It is distinct from the Taproot onchain address returned by `VtxoScript.onchainAddress`.\n *\n * @see VtxoScript\n *\n * @example\n * ```typescript\n * const address = new ArkAddress(\n *     new Uint8Array(32), // server public key\n *     new Uint8Array(32), // vtxo taproot public key\n *     \"ark\"\n * );\n *\n * const encoded = address.encode();\n * console.log(\"address: \", encoded);\n *\n * const decoded = ArkAddress.decode(encoded);\n * ```\n */\nexport class ArkAddress {\n    /**\n     * Create an Arkade address from its server public key, Taproot output key, and prefix.\n     *\n     * @param serverPubKey - 32-byte Arkade server public key\n     * @param vtxoTaprootKey - 32-byte Taproot output key (a.k.a. tweaked public key)\n     * @param hrp - Bech32 human-readable prefix\n     * @param version - Address version byte\n     * @defaultValue `version = 0`\n     * @throws Error if either public key is not 32 bytes long\n     */\n    constructor(\n        readonly serverPubKey: Bytes,\n        readonly vtxoTaprootKey: Bytes,\n        readonly hrp: string = DEFAULT_NETWORK.hrp,\n        readonly version: number = 0,\n    ) {\n        if (serverPubKey.length !== 32) {\n            throw new Error(\n                \"Invalid server public key length, expected 32 bytes, got \" + serverPubKey.length,\n            );\n        }\n        if (vtxoTaprootKey.length !== 32) {\n            throw new Error(\n                \"Invalid vtxo taproot public key length, expected 32 bytes, got \" +\n                    vtxoTaprootKey.length,\n            );\n        }\n    }\n\n    /**\n     * Decode an Arkade address from its bech32m string form.\n     *\n     * @param address - Bech32m-encoded Arkade address\n     * @returns Decoded Arkade address\n     * @throws Error if the address is malformed or has an invalid payload length\n     * @see encode\n     */\n    static decode(address: string): ArkAddress {\n        const decoded = bech32m.decodeUnsafe(address, 1023);\n        if (!decoded) {\n            throw new Error(\"Invalid address\");\n        }\n        const data = new Uint8Array(bech32m.fromWords(decoded.words));\n\n        // First the version byte, then 32 bytes server pubkey, then 32 bytes vtxo taproot public key.\n        if (data.length !== 1 + 32 + 32) {\n            throw new Error(\"Invalid data length, expected 65 bytes, got \" + data.length);\n        }\n\n        const version = data[0];\n        const serverPubKey = data.slice(1, 33);\n        const vtxoTaprootPubKey = data.slice(33, 65);\n\n        return new ArkAddress(serverPubKey, vtxoTaprootPubKey, decoded.prefix, version);\n    }\n\n    /**\n     * Encode the address to its bech32m string form.\n     *\n     * @returns Bech32m-encoded Arkade address\n     * @see decode\n     */\n    encode(): string {\n        // Combine version byte, server pubkey, and vtxo taproot public key.\n        const data = new Uint8Array(1 + 32 + 32);\n        data[0] = this.version;\n        data.set(this.serverPubKey, 1);\n        data.set(this.vtxoTaprootKey, 33);\n\n        const words = bech32m.toWords(data);\n        return bech32m.encode(this.hrp, words, 1023);\n    }\n\n    /** ScriptPubKey used to send non-dust funds to the address. */\n    get pkScript(): Bytes {\n        return Script.encode([\"OP_1\", this.vtxoTaprootKey]);\n    }\n\n    /** ScriptPubKey used to send sub-dust funds to the address. */\n    get subdustPkScript(): Bytes {\n        return Script.encode([\"RETURN\", this.vtxoTaprootKey]);\n    }\n}\n","import * as bip68 from \"bip68\";\nimport type { RelativeTimelock } from \"../script/tapscript\";\n\n/**\n * Convert RelativeTimelock to BIP68 sequence number.\n */\nexport function timelockToSequence(timelock: RelativeTimelock): number {\n    return bip68.encode(\n        timelock.type === \"blocks\"\n            ? { blocks: Number(timelock.value) }\n            : { seconds: Number(timelock.value) },\n    );\n}\n\n/**\n * Convert BIP68 sequence number back to RelativeTimelock.\n */\nexport function sequenceToTimelock(sequence: number): RelativeTimelock {\n    const decoded = bip68.decode(sequence);\n    if (\"blocks\" in decoded && decoded.blocks !== undefined) {\n        return { type: \"blocks\", value: BigInt(decoded.blocks) };\n    }\n    if (\"seconds\" in decoded && decoded.seconds !== undefined) {\n        return { type: \"seconds\", value: BigInt(decoded.seconds) };\n    }\n    throw new Error(`Invalid BIP68 sequence: ${sequence}`);\n}\n","import { Script, ScriptNum, ScriptType, p2tr_ms } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\nimport { sequenceToTimelock, timelockToSequence } from \"../utils/timelock\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n/**\n * RelativeTimelock lets to create timelocked with CHECKSEQUENCEVERIFY script.\n *\n * @example\n * ```typescript\n * const timelock = { value: 144n, type: \"blocks\" }; // 1 day in blocks\n * const timelock = { value: 512n, type: \"seconds\" }; // 8 minutes in seconds\n * ```\n */\nexport type RelativeTimelock = {\n    value: bigint;\n    type: \"seconds\" | \"blocks\";\n};\n\nexport enum TapscriptType {\n    Multisig = \"multisig\",\n    CSVMultisig = \"csv-multisig\",\n    ConditionCSVMultisig = \"condition-csv-multisig\",\n    ConditionMultisig = \"condition-multisig\",\n    CLTVMultisig = \"cltv-multisig\",\n}\n\n/**\n * ArkTapscript is the base element of vtxo scripts.\n * It is used to encode and decode the different types of vtxo scripts.\n */\nexport interface ArkTapscript<T extends TapscriptType, Params> {\n    type: T;\n    params: Params;\n    script: Uint8Array;\n}\n\n/**\n * decodeTapscript is a function that decodes an Arkade tapscript from a raw script.\n *\n * @throws {Error} if the script is not a valid Arkade tapscript\n * @example\n * ```typescript\n * const arkTapscript = decodeTapscript(new Uint8Array(32));\n * console.log(\"type:\", arkTapscript.type);\n * ```\n */\nexport function decodeTapscript(script: Uint8Array): ArkTapscript<TapscriptType, any> {\n    const types = [\n        MultisigTapscript,\n        CSVMultisigTapscript,\n        ConditionCSVMultisigTapscript,\n        ConditionMultisigTapscript,\n        CLTVMultisigTapscript,\n    ];\n\n    for (const type of types) {\n        try {\n            return type.decode(script);\n        } catch (error) {\n            continue;\n        }\n    }\n\n    throw new Error(`Failed to decode: script ${hex.encode(script)} is not a valid tapscript`);\n}\n\n/**\n * Implements a multi-signature tapscript.\n *\n * <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const multisigTapscript = MultisigTapscript.encode({ pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace MultisigTapscript {\n    export type Type = ArkTapscript<TapscriptType.Multisig, Params>;\n\n    export enum MultisigType {\n        CHECKSIG,\n        CHECKSIGADD,\n    }\n\n    export type Params = {\n        pubkeys: Bytes[];\n        type?: MultisigType;\n    };\n\n    /** Encode a plain multisig tapscript. */\n    export function encode(params: Params): Type {\n        if (params.pubkeys.length === 0) {\n            throw new Error(\"At least 1 pubkey is required\");\n        }\n\n        for (const pubkey of params.pubkeys) {\n            if (pubkey.length !== 32) {\n                throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n            }\n        }\n\n        if (!params.type) {\n            params.type = MultisigType.CHECKSIG;\n        }\n\n        if (params.type === MultisigType.CHECKSIGADD) {\n            return {\n                type: TapscriptType.Multisig,\n                params,\n                script: p2tr_ms(params.pubkeys.length, params.pubkeys).script,\n            };\n        }\n\n        const asm: ScriptType = [];\n        for (let i = 0; i < params.pubkeys.length; i++) {\n            asm.push(params.pubkeys[i]);\n\n            // CHECKSIGVERIFY except the last pubkey\n            if (i < params.pubkeys.length - 1) {\n                asm.push(\"CHECKSIGVERIFY\");\n            } else {\n                asm.push(\"CHECKSIG\");\n            }\n        }\n\n        return {\n            type: TapscriptType.Multisig,\n            params,\n            script: Script.encode(asm),\n        };\n    }\n\n    /** Decode a plain multisig tapscript from raw script bytes. */\n    export function decode(script: Uint8Array): Type {\n        if (script.length === 0) {\n            throw new Error(\"Failed to decode: script is empty\");\n        }\n\n        try {\n            // Try decoding as checksigAdd first\n            return decodeChecksigAdd(script);\n        } catch (error) {\n            // If checksigAdd fails, try regular checksig\n            try {\n                return decodeChecksig(script);\n            } catch (error2) {\n                throw new Error(\n                    `Failed to decode script: ${error2 instanceof Error ? error2.message : String(error2)}`,\n                );\n            }\n        }\n    }\n\n    // <pubkey> CHECKSIG <pubkey> CHECKSIGADD <len_keys> NUMEQUAL\n    function decodeChecksigAdd(script: Uint8Array): Type {\n        const asm = Script.decode(script);\n        const pubkeys: Bytes[] = [];\n        let foundNumEqual = false;\n\n        // Parse through ASM operations\n        for (let i = 0; i < asm.length; i++) {\n            const op = asm[i];\n\n            // If it's a data push, it should be a 32-byte pubkey\n            if (typeof op !== \"string\" && typeof op !== \"number\") {\n                if (op.length !== 32) {\n                    throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n                }\n                pubkeys.push(op);\n\n                // Check next operation is CHECKSIGADD or CHECKSIG\n                if (\n                    i + 1 >= asm.length ||\n                    (asm[i + 1] !== \"CHECKSIGADD\" && asm[i + 1] !== \"CHECKSIG\")\n                ) {\n                    throw new Error(\"Expected CHECKSIGADD or CHECKSIG after pubkey\");\n                }\n                i++; // Skip the CHECKSIGADD op\n                continue;\n            }\n\n            // Last operation should be NUMEQUAL\n            if (i === asm.length - 1) {\n                if (op !== \"NUMEQUAL\") {\n                    throw new Error(\"Expected NUMEQUAL at end of script\");\n                }\n                foundNumEqual = true;\n            }\n        }\n\n        if (!foundNumEqual) {\n            throw new Error(\"Missing NUMEQUAL operation\");\n        }\n\n        if (pubkeys.length === 0) {\n            throw new Error(\"Invalid script: must have at least 1 pubkey\");\n        }\n\n        // Verify the script by re-encoding and comparing\n        const reconstructed = encode({\n            pubkeys,\n            type: MultisigType.CHECKSIGADD,\n        });\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.Multisig,\n            params: { pubkeys, type: MultisigType.CHECKSIGADD },\n            script,\n        };\n    }\n\n    // <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n    function decodeChecksig(script: Uint8Array): Type {\n        const asm = Script.decode(script);\n        const pubkeys: Bytes[] = [];\n\n        // Parse through ASM operations\n        for (let i = 0; i < asm.length; i++) {\n            const op = asm[i];\n\n            // If it's a data push, it should be a 32-byte pubkey\n            if (typeof op !== \"string\" && typeof op !== \"number\") {\n                if (op.length !== 32) {\n                    throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n                }\n                pubkeys.push(op);\n\n                // Check next operation\n                if (i + 1 >= asm.length) {\n                    throw new Error(\"Unexpected end of script\");\n                }\n\n                const nextOp = asm[i + 1];\n                if (nextOp !== \"CHECKSIGVERIFY\" && nextOp !== \"CHECKSIG\") {\n                    throw new Error(\"Expected CHECKSIGVERIFY or CHECKSIG after pubkey\");\n                }\n\n                // Last operation must be CHECKSIG, not CHECKSIGVERIFY\n                if (i === asm.length - 2 && nextOp !== \"CHECKSIG\") {\n                    throw new Error(\"Last operation must be CHECKSIG\");\n                }\n\n                i++; // Skip the CHECKSIG/CHECKSIGVERIFY op\n                continue;\n            }\n        }\n\n        if (pubkeys.length === 0) {\n            throw new Error(\"Invalid script: must have at least 1 pubkey\");\n        }\n\n        // Verify the script by re-encoding and comparing\n        const reconstructed = encode({ pubkeys, type: MultisigType.CHECKSIG });\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.Multisig,\n            params: { pubkeys, type: MultisigType.CHECKSIG },\n            script,\n        };\n    }\n\n    /** Return true when the tapscript is a plain multisig tapscript. */\n    export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n        return tapscript.type === TapscriptType.Multisig;\n    }\n}\n\n/**\n * Implements a relative timelock script that requires all specified pubkeys to sign\n * after the relative timelock has expired. The timelock can be specified in blocks or seconds.\n *\n * This is the standard exit closure and it is also used for the sweep closure in vtxo trees.\n *\n * <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const csvMultisigTapscript = CSVMultisigTapscript.encode({ timelock: { type: \"blocks\", value: 144 }, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CSVMultisigTapscript {\n    export type Type = ArkTapscript<TapscriptType.CSVMultisig, Params>;\n\n    export type Params = {\n        timelock: RelativeTimelock;\n    } & MultisigTapscript.Params;\n\n    /** Encode a CSV multisig tapscript. */\n    export function encode(params: Params): Type {\n        for (const pubkey of params.pubkeys) {\n            if (pubkey.length !== 32) {\n                throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n            }\n        }\n\n        const sequence = MinimalScriptNum.encode(BigInt(timelockToSequence(params.timelock)));\n\n        const asm: ScriptType = [\n            sequence.length === 1 ? sequence[0] : sequence,\n            \"CHECKSEQUENCEVERIFY\",\n            \"DROP\",\n        ];\n        const multisigScript = MultisigTapscript.encode(params);\n        const script = new Uint8Array([...Script.encode(asm), ...multisigScript.script]);\n\n        return {\n            type: TapscriptType.CSVMultisig,\n            params,\n            script,\n        };\n    }\n\n    /** Decode a CSV multisig tapscript from raw script bytes. */\n    export function decode(script: Uint8Array): Type {\n        if (script.length === 0) {\n            throw new Error(\"Failed to decode: script is empty\");\n        }\n\n        const isValid = isScriptValid(script);\n        if (isValid instanceof Error) {\n            throw isValid;\n        }\n\n        const asm = Script.decode(script);\n\n        const sequence = asm[0];\n        const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n        let multisig: MultisigTapscript.Type;\n\n        try {\n            multisig = MultisigTapscript.decode(multisigScript);\n        } catch (error) {\n            throw new Error(\n                `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n            );\n        }\n\n        let sequenceNum: number;\n        if (typeof sequence === \"number\") {\n            sequenceNum = sequence;\n        } else {\n            sequenceNum = Number(MinimalScriptNum.decode(sequence as Uint8Array));\n        }\n        const timelock = sequenceToTimelock(sequenceNum);\n\n        const reconstructed = encode({\n            timelock,\n            ...multisig.params,\n        });\n\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.CSVMultisig,\n            params: {\n                timelock,\n                ...multisig.params,\n            },\n            script,\n        };\n    }\n\n    /** Return true when the tapscript is a CSV multisig tapscript. */\n    export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n        return tapscript.type === TapscriptType.CSVMultisig;\n    }\n\n    export function isScriptValid(script: Uint8Array): true | Error {\n        const asm = Script.decode(script);\n\n        if (asm.length < 3) {\n            return new Error(`Invalid script: too short (expected at least 3)`);\n        }\n\n        const sequence = asm[0];\n        if (typeof sequence === \"string\") {\n            return new Error(\"Invalid script: expected sequence number\");\n        }\n\n        if (asm[1] !== \"CHECKSEQUENCEVERIFY\" || asm[2] !== \"DROP\") {\n            return new Error(\"Invalid script: expected CHECKSEQUENCEVERIFY DROP\");\n        }\n\n        return true;\n    }\n}\n\n/**\n * Combines a condition script with an exit closure. The resulting script requires\n * the condition to be met, followed by the standard exit closure requirements\n * (timelock and signatures).\n *\n * <conditionScript> VERIFY <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionCSVMultisigTapscript = ConditionCSVMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionCSVMultisigTapscript {\n    export type Type = ArkTapscript<TapscriptType.ConditionCSVMultisig, Params>;\n\n    export type Params = {\n        conditionScript: Bytes;\n    } & CSVMultisigTapscript.Params;\n\n    /** Encode a condition + CSV multisig tapscript. */\n    export function encode(params: Params): Type {\n        const script = new Uint8Array([\n            ...params.conditionScript,\n            ...Script.encode([\"VERIFY\"]),\n            ...CSVMultisigTapscript.encode(params).script,\n        ]);\n\n        return {\n            type: TapscriptType.ConditionCSVMultisig,\n            params,\n            script,\n        };\n    }\n\n    /** Decode a condition + CSV multisig tapscript from raw script bytes. */\n    export function decode(script: Uint8Array): Type {\n        if (script.length === 0) {\n            throw new Error(\"Failed to decode: script is empty\");\n        }\n\n        const isValid = isScriptValid(script);\n        if (isValid instanceof Error) {\n            throw isValid;\n        }\n\n        const asm = Script.decode(script);\n\n        let verifyIndex = getVerifyIndex(asm);\n\n        if (verifyIndex === -1) {\n            throw Error(\"Invalid script: missing VERIFY operation\");\n        }\n\n        const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n        const csvMultisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n        let csvMultisig: CSVMultisigTapscript.Type;\n        try {\n            csvMultisig = CSVMultisigTapscript.decode(csvMultisigScript);\n        } catch (error) {\n            throw new Error(\n                `Invalid CSV multisig script: ${error instanceof Error ? error.message : String(error)}`,\n            );\n        }\n\n        const reconstructed = encode({\n            conditionScript,\n            ...csvMultisig.params,\n        });\n\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.ConditionCSVMultisig,\n            params: {\n                conditionScript,\n                ...csvMultisig.params,\n            },\n            script,\n        };\n    }\n\n    /** Return true when the tapscript is a condition + CSV multisig tapscript. */\n    export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n        return tapscript.type === TapscriptType.ConditionCSVMultisig;\n    }\n\n    function getVerifyIndex(asm: ScriptType) {\n        let verifyIndex = -1;\n        for (let i = asm.length - 1; i >= 0; i--) {\n            if (asm[i] === \"VERIFY\") {\n                verifyIndex = i;\n                return verifyIndex;\n            }\n        }\n        return verifyIndex;\n    }\n\n    export function isScriptValid(script: Uint8Array): true | Error {\n        const asm = Script.decode(script);\n\n        if (asm.length < 1) {\n            return new Error(`Invalid script: too short (expected at least 1)`);\n        }\n\n        let verifyIndex = getVerifyIndex(asm);\n\n        if (verifyIndex === -1) {\n            return new Error(\"Invalid script: missing VERIFY operation\");\n        }\n\n        return true;\n    }\n}\n\n/**\n * Combines a condition script with a forfeit closure. The resulting script requires\n * the condition to be met, followed by the standard forfeit closure requirements\n * (multi-signature).\n *\n * <conditionScript> VERIFY <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionMultisigTapscript = ConditionMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionMultisigTapscript {\n    export type Type = ArkTapscript<TapscriptType.ConditionMultisig, Params>;\n\n    export type Params = {\n        conditionScript: Bytes;\n    } & MultisigTapscript.Params;\n\n    /** Encode a condition + multisig tapscript. */\n    export function encode(params: Params): Type {\n        const script = new Uint8Array([\n            ...params.conditionScript,\n            ...Script.encode([\"VERIFY\"]),\n            ...MultisigTapscript.encode(params).script,\n        ]);\n\n        return {\n            type: TapscriptType.ConditionMultisig,\n            params,\n            script,\n        };\n    }\n\n    /** Decode a condition + multisig tapscript from raw script bytes. */\n    export function decode(script: Uint8Array): Type {\n        if (script.length === 0) {\n            throw new Error(\"Failed to decode: script is empty\");\n        }\n\n        const isValid = isScriptValid(script);\n        if (isValid instanceof Error) {\n            throw isValid;\n        }\n\n        const asm = Script.decode(script);\n\n        let verifyIndex = getVerifyIndex(asm);\n\n        if (verifyIndex === -1) {\n            throw Error(\"Invalid script: missing VERIFY operation\");\n        }\n\n        const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n        const multisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n        let multisig: MultisigTapscript.Type;\n        try {\n            multisig = MultisigTapscript.decode(multisigScript);\n        } catch (error) {\n            throw new Error(\n                `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n            );\n        }\n\n        const reconstructed = encode({\n            conditionScript,\n            ...multisig.params,\n        });\n\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.ConditionMultisig,\n            params: {\n                conditionScript,\n                ...multisig.params,\n            },\n            script,\n        };\n    }\n\n    /** Return true when the tapscript is a condition + multisig tapscript. */\n    export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n        return tapscript.type === TapscriptType.ConditionMultisig;\n    }\n\n    function getVerifyIndex(asm: ScriptType) {\n        let verifyIndex = -1;\n        for (let i = asm.length - 1; i >= 0; i--) {\n            if (asm[i] === \"VERIFY\") {\n                verifyIndex = i;\n                return verifyIndex;\n            }\n        }\n        return verifyIndex;\n    }\n\n    export function isScriptValid(script: Uint8Array): true | Error {\n        const asm = Script.decode(script);\n\n        if (asm.length < 1) {\n            return new Error(`Invalid script: too short (expected at least 1)`);\n        }\n\n        let verifyIndex = getVerifyIndex(asm);\n\n        if (verifyIndex === -1) {\n            return new Error(\"Invalid script: missing VERIFY operation\");\n        }\n\n        return true;\n    }\n}\n\n/**\n * Implements an absolute timelock (CLTV) script combined with a forfeit closure.\n * The script requires waiting until a specific block height/timestamp before the\n * forfeit closure conditions can be met.\n *\n * <locktime> CHECKLOCKTIMEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const cltvMultisigTapscript = CLTVMultisigTapscript.encode({ absoluteTimelock: 144, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CLTVMultisigTapscript {\n    export type Type = ArkTapscript<TapscriptType.CLTVMultisig, Params>;\n\n    export type Params = {\n        absoluteTimelock: bigint;\n    } & MultisigTapscript.Params;\n\n    /** Encode a CLTV multisig tapscript. */\n    export function encode(params: Params): Type {\n        const locktime = MinimalScriptNum.encode(params.absoluteTimelock);\n        const asm: ScriptType = [\n            locktime.length === 1 ? locktime[0] : locktime,\n            \"CHECKLOCKTIMEVERIFY\",\n            \"DROP\",\n        ];\n        const timelockedScript = Script.encode(asm);\n\n        const script = new Uint8Array([\n            ...timelockedScript,\n            ...MultisigTapscript.encode(params).script,\n        ]);\n\n        return {\n            type: TapscriptType.CLTVMultisig,\n            params,\n            script,\n        };\n    }\n\n    /** Decode a CLTV multisig tapscript from raw script bytes. */\n    export function decode(script: Uint8Array): Type {\n        if (script.length === 0) {\n            throw new Error(\"Failed to decode: script is empty\");\n        }\n\n        const isValid = isScriptValid(script);\n        if (isValid instanceof Error) {\n            throw isValid;\n        }\n\n        const asm = Script.decode(script);\n\n        const locktime = asm[0];\n        if (typeof locktime === \"string\") {\n            throw new Error(\"Invalid script: expected locktime number\");\n        }\n\n        if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n            throw new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n        }\n\n        const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n        let multisig: MultisigTapscript.Type;\n\n        try {\n            multisig = MultisigTapscript.decode(multisigScript);\n        } catch (error) {\n            throw new Error(\n                `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n            );\n        }\n\n        let absoluteTimelock: bigint;\n        if (typeof locktime === \"number\") {\n            absoluteTimelock = BigInt(locktime);\n        } else {\n            absoluteTimelock = MinimalScriptNum.decode(locktime as Bytes);\n        }\n\n        const reconstructed = encode({\n            absoluteTimelock,\n            ...multisig.params,\n        });\n\n        if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n            throw new Error(\"Invalid script format: script reconstruction mismatch\");\n        }\n\n        return {\n            type: TapscriptType.CLTVMultisig,\n            params: {\n                absoluteTimelock,\n                ...multisig.params,\n            },\n            script,\n        };\n    }\n\n    /** Return true when the tapscript is a CLTV multisig tapscript. */\n    export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n        return tapscript.type === TapscriptType.CLTVMultisig;\n    }\n\n    export function isScriptValid(script: Uint8Array): true | Error {\n        const asm = Script.decode(script);\n\n        if (asm.length < 3) {\n            return new Error(`Invalid script: too short (expected at least 3)`);\n        }\n\n        const locktime = asm[0];\n        if (typeof locktime === \"string\") {\n            return new Error(\"Invalid script: expected locktime as number or bytes\");\n        }\n\n        if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n            return new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n        }\n\n        return true;\n    }\n}\n","import { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\n\n/**\n * A leaf node in the Taproot script tree, as consumed by\n * `@scure/btc-signer`'s `p2tr(internalKey, tree, ...)`.\n */\nexport interface TaprootLeaf {\n    script: Bytes;\n    leafVersion: number;\n}\n\n/**\n * Internal tree node shape consumed by `@scure/btc-signer`'s `p2tr`:\n *   - A leaf is `{ script, leafVersion }`\n *   - A branch is a 2-element tuple `[leftNode, rightNode]` of nodes\n */\nexport type TaprootTreeNode = TaprootLeaf | [TaprootTreeNode, TaprootTreeNode];\n\n/**\n * Assemble a Taproot script tree from a flat list of scripts using the\n * exact algorithm arkd's btcd dependency uses\n * (`txscript.AssembleTaprootScriptTree`, see\n * https://github.com/btcsuite/btcd/blob/master/txscript/taproot.go).\n *\n * The algorithm:\n *\n *   Phase 1 — pair leaves left-to-right:\n *     for i := 0; i < len(leaves); i += 2:\n *       if i is the last index (odd leaf at end):\n *         merge with the LAST branch built so far (do NOT pair as a fresh leaf)\n *       else:\n *         create a new branch from (leaves[i], leaves[i+1])\n *\n *   Phase 2 — FIFO-queue merge branches:\n *     while branches has ≥ 2 items:\n *       take front two, combine into a new branch, push to back of queue\n *\n * This matters because `@scure/btc-signer`'s `taprootListToTree` builds a\n * Huffman tree (weight-1 leaves combine by smallest-weight pairs). For\n * power-of-2 leaf counts both algorithms happen to produce the same\n * perfectly-balanced binary tree and agree. For any other count they\n * produce DIFFERENT shapes → different merkle roots → different taproot\n * output keys → arkd rejects spends with `INVALID_PSBT_INPUT`.\n *\n * Reproducing btcd's algorithm here lets the SDK construct taptrees that\n * arkd accepts for arbitrary leaf counts.\n *\n * @param scripts - Raw tapscript bytes for each leaf, in the order they\n *                  should be encoded in the TapTree PSBT field.\n * @returns The nested-tuple form `p2tr` accepts.\n */\nexport function assembleBtcdTaprootTree(scripts: Bytes[]): TaprootTreeNode {\n    if (scripts.length === 0) {\n        throw new Error(\"assembleBtcdTaprootTree: empty scripts list\");\n    }\n\n    const leaves: TaprootLeaf[] = scripts.map((script) => ({\n        script,\n        leafVersion: TAP_LEAF_VERSION,\n    }));\n\n    if (leaves.length === 1) {\n        return leaves[0];\n    }\n\n    // ── Phase 1: pair leaves left-to-right ─────────────────────────────\n    const branches: TaprootTreeNode[] = [];\n    for (let i = 0; i < leaves.length; i += 2) {\n        if (i === leaves.length - 1) {\n            // Odd leaf at end: merge into the LAST branch built so far.\n            // Mirrors btcd's\n            //   branches[len(branches)-1] = NewTapBranch(branchToMerge, leaf)\n            const last = branches.pop();\n            if (last === undefined) {\n                // Defensive — caller should have provided ≥ 2 leaves.\n                throw new Error(\n                    `assembleBtcdTaprootTree: unexpected odd leaf at i=${i} with no prior branch`,\n                );\n            }\n            branches.push([last, leaves[i]]);\n        } else {\n            // Pair two consecutive leaves into a new branch.\n            branches.push([leaves[i], leaves[i + 1]]);\n        }\n    }\n\n    // ── Phase 2: FIFO-queue merge branches ─────────────────────────────\n    // Take front two, combine, push to back. Stops when one branch remains.\n    while (branches.length >= 2) {\n        const left = branches.shift()!;\n        const right = branches.shift()!;\n        branches.push([left, right]);\n    }\n\n    return branches[0];\n}\n\n/**\n * Left-to-right leaf layout of the tree {@link assembleBtcdTaprootTree} builds\n * for `count` leaves: for each position, the leaf's index in the input list\n * and its depth. The shape depends only on the leaf count, never on the\n * scripts, so this also tells where each input leaf lands in any such tree.\n *\n * @param count - Number of leaves\n * @returns One `{ index, depth }` entry per leaf, in left-to-right DFS order\n */\nexport function btcdLeafLayout(count: number): { index: number; depth: number }[] {\n    const placeholders = Array.from({ length: count }, () => new Uint8Array());\n    const indexOf = new Map<Bytes, number>(placeholders.map((script, index) => [script, index]));\n    const layout: { index: number; depth: number }[] = [];\n    const walk = (node: TaprootTreeNode, depth: number): void => {\n        if (Array.isArray(node)) {\n            walk(node[0], depth + 1);\n            walk(node[1], depth + 1);\n        } else {\n            layout.push({ index: indexOf.get(node.script)!, depth });\n        }\n    };\n    walk(assembleBtcdTaprootTree(placeholders), 0);\n    return layout;\n}\n","import { Address, p2tr, taprootNumsKey, NETWORK } from \"@scure/btc-signer\";\nimport { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { PSBTOutput } from \"@scure/btc-signer/psbt.js\";\nimport { VarBytes } from \"@scure/btc-signer/script.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport * as P from \"micro-packed\";\nimport { hex } from \"@scure/base\";\nimport { ArkAddress } from \"./address\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport {\n    CLTVMultisigTapscript,\n    ConditionCSVMultisigTapscript,\n    CSVMultisigTapscript,\n} from \"./tapscript\";\nimport { assembleBtcdTaprootTree, btcdLeafLayout } from \"./taprootTree\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\nexport type TapLeafScript = [\n    {\n        version: number;\n        internalKey: Bytes;\n        merklePath: Bytes[];\n    },\n    Bytes,\n];\n\nexport const TapTreeCoder: (typeof PSBTOutput.tapTree)[2] = P.array(\n    null,\n    P.struct({ depth: P.U8, version: P.U8, script: VarBytes }),\n);\n\nexport function scriptFromTapLeafScript(leaf: TapLeafScript): Bytes {\n    return leaf[1].subarray(0, leaf[1].length - 1); // remove the version byte\n}\n\n/**\n * VtxoScript is a script that contains a list of tapleaf scripts.\n * It is used to create virtual output scripts.\n *\n * @see ArkAddress\n *\n * @example\n * ```typescript\n * const vtxoScript = new VtxoScript([new Uint8Array(32), new Uint8Array(32)]);\n * ```\n */\nexport class VtxoScript {\n    readonly leaves: TapLeafScript[];\n    readonly tweakedPublicKey: Bytes;\n    readonly pkScript: Bytes;\n\n    /**\n     * Decode a virtual output script from an encoded TapTree.\n     *\n     * Leaves are normally read in construction order and their depths\n     * ignored: that covers the {@link encode} form (every depth 1) and the\n     * placeholder depths other writers use, such as arkd's. The exception is\n     * the BIP-371 form {@link toBIP371TapTree} writes, whose leaves are in the\n     * tree's DFS order: for some leaf counts (6, 7, 10, ...) that differs from\n     * construction order. A tree whose depths are exactly the shape\n     * `assembleBtcdTaprootTree` builds is that form, so its leaves are mapped\n     * back to construction order first. No construction-order writer produces\n     * that depth sequence when the two orders differ, so this never reorders\n     * a tree that decoded correctly before.\n     *\n     * Every leaf must carry the base tapscript version: the tree is rebuilt\n     * with {@link TAP_LEAF_VERSION} leaves, so any other version would\n     * silently derive a different taproot key.\n     *\n     * @param tapTree - Encoded TapTree bytes\n     * @returns Decoded virtual output script\n     * @throws Error if the TapTree cannot be decoded into a valid script set\n     *         or a leaf carries a version other than {@link TAP_LEAF_VERSION}\n     * @see encode\n     */\n    static decode(tapTree: Bytes): VtxoScript {\n        const leaves = TapTreeCoder.decode(tapTree);\n        const foreign = leaves.find((leaf) => leaf.version !== TAP_LEAF_VERSION);\n        if (foreign) {\n            throw new Error(`unsupported tap leaf version 0x${foreign.version.toString(16)}`);\n        }\n        const scripts = leaves.map((leaf) => leaf.script);\n        if (leaves.every((leaf) => leaf.depth === 1)) {\n            return new VtxoScript(scripts);\n        }\n        const layout = btcdLeafLayout(leaves.length);\n        if (layout.some((slot, i) => slot.depth !== leaves[i].depth)) {\n            return new VtxoScript(scripts);\n        }\n        const ordered = new Array<Bytes>(leaves.length);\n        layout.forEach((slot, i) => {\n            ordered[slot.index] = scripts[i];\n        });\n        return new VtxoScript(ordered);\n    }\n\n    /**\n     * Create a virtual output script from its tapleaf scripts.\n     *\n     * The Taproot script tree is assembled using btcd's algorithm\n     * (`txscript.AssembleTaprootScriptTree`) so the derived taproot output\n     * key agrees with arkd for any leaf count. `@scure/btc-signer`'s\n     * default `taprootListToTree` is a Huffman builder that only agrees\n     * with arkd for power-of-2 leaf counts.\n     *\n     * @param scripts - Raw tapscript bytes for each leaf\n     * @throws Error if the provided leaves cannot produce a valid Taproot tree\n     */\n    constructor(readonly scripts: Bytes[]) {\n        const tapTree = assembleBtcdTaprootTree(scripts);\n\n        const payment = p2tr(taprootNumsKey(), tapTree, undefined, true);\n\n        if (!payment.tapLeafScript || payment.tapLeafScript.length !== scripts.length) {\n            throw new Error(\"invalid scripts\");\n        }\n\n        this.leaves = payment.tapLeafScript;\n        this.tweakedPublicKey = payment.tweakedPubkey;\n        this.pkScript = payment.script;\n    }\n\n    /**\n     * Encode the virtual output script to a TapTree byte representation.\n     *\n     * @returns Encoded TapTree bytes\n     * @see decode\n     */\n    encode(): Bytes {\n        const tapTree = TapTreeCoder.encode(\n            this.scripts.map((script) => ({\n                depth: 1,\n                version: TAP_LEAF_VERSION,\n                script: script as Uint8Array<ArrayBuffer>,\n            })),\n        );\n        return tapTree;\n    }\n\n    /**\n     * Build the Arkade address corresponding to this virtual output script.\n     *\n     * @param prefix - Bech32 human-readable prefix\n     * @param serverPubKey - 32-byte Arkade server public key\n     * @returns Arkade address for this script\n     * @see ArkAddress\n     */\n    address(prefix: string = DEFAULT_NETWORK.hrp, serverPubKey: Bytes): ArkAddress {\n        return new ArkAddress(serverPubKey, this.tweakedPublicKey, prefix);\n    }\n\n    /**\n     * Build the Taproot onchain address corresponding to this virtual output script.\n     *\n     * @param network - Bitcoin network descriptor\n     * @returns Taproot onchain address\n     * @see address\n     */\n    onchainAddress(network: typeof NETWORK = DEFAULT_NETWORK): string {\n        return Address(network).encode({\n            type: \"tr\",\n            pubkey: this.tweakedPublicKey,\n        });\n    }\n\n    /**\n     * Look up a tapleaf script by its hex-encoded tapscript body.\n     *\n     * @param scriptHex - Hex-encoded tapscript body without the leaf version byte\n     * @returns Matching tapleaf script\n     * @throws Error if no matching leaf exists\n     */\n    findLeaf(scriptHex: string): TapLeafScript {\n        const leaf = this.leaves.find(\n            (leaf) => hex.encode(scriptFromTapLeafScript(leaf)) === scriptHex,\n        )!;\n        if (!leaf) {\n            throw new Error(`leaf '${scriptHex}' not found`);\n        }\n        return leaf;\n    }\n\n    /**\n     * Return all unilateral exit paths embedded in the virtual output script.\n     *\n     * @returns CSV-based exit paths found in the leaves\n     * @see getSequence\n     */\n    exitPaths(): Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> {\n        const paths: Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> = [];\n        for (const leaf of this.leaves) {\n            try {\n                const script = scriptFromTapLeafScript(leaf);\n                if (CSVMultisigTapscript.isScriptValid(script) === true) {\n                    const tapScript = CSVMultisigTapscript.decode(script);\n                    paths.push(tapScript);\n                } else if (ConditionCSVMultisigTapscript.isScriptValid(script) === true) {\n                    const tapScript = ConditionCSVMultisigTapscript.decode(script);\n                    paths.push(tapScript);\n                }\n            } catch (e) {\n                console.debug(\"Failed to decode script\", e);\n            }\n        }\n        return paths;\n    }\n}\n\n/**\n * Convert a `VtxoScript.encode()`-produced TapTree into a BIP-371\n * (`PSBT_OUT_TAP_TREE`) compliant leaf list: entries in left-to-right DFS\n * order, each carrying its *actual* depth in the btcd-assembled tree.\n *\n * `VtxoScript.encode()` stores leaves in the caller's original order with a\n * placeholder `depth: 1` — a format `VtxoScript.decode()` can losslessly\n * invert by re-running `assembleBtcdTaprootTree` over that same order (it\n * decodes this function's output too), but NOT a valid BIP-371 field: for non-power-of-2 leaf counts (e.g. 3, 6) the\n * tree is neither flat nor built in that original order (the algorithm's\n * FIFO merge phase can reorder leaves for counts like 6), so per-index\n * depths cannot be guessed from leaf position. This rebuilds the exact same\n * `VtxoScript` (deterministic from the same script list) to read genuine\n * depths off its `leaves` (populated by `p2tr()` from the real tree), in\n * the tree's true DFS order.\n *\n * @param tapTree - Encoded TapTree bytes from `VtxoScript.encode()`\n * @returns BIP-371-compliant TapTree leaves, ready for a PSBT output's\n *          `tapTree` field\n */\nexport function toBIP371TapTree(tapTree: Bytes): ReturnType<typeof TapTreeCoder.decode> {\n    const scripts = TapTreeCoder.decode(tapTree).map((leaf) => leaf.script);\n    const vtxoScript = new VtxoScript(scripts);\n    return vtxoScript.leaves.map((leaf) => ({\n        depth: leaf[0].merklePath.length,\n        version: TAP_LEAF_VERSION,\n        script: scriptFromTapLeafScript(leaf) as Uint8Array<ArrayBuffer>,\n    }));\n}\n\nexport type EncodedVtxoScript = { tapTree: Bytes };\n\n/**\n * Extract the timelock value encoded in a timelocked tapleaf, if any.\n *\n * The return value is unit-ambiguous: for a CSV leaf it is a BIP-68\n * nSequence (relative timelock); for a CLTV leaf it is an absolute\n * nLockTime. Callers must know which leaf shape they are inspecting to\n * interpret the number correctly, and must not copy a CSV result into\n * `Transaction.lockTime` (or vice versa).\n *\n * @param tapLeafScript - Tapleaf script to inspect\n * @returns The encoded timelock value, or `undefined` when neither a CSV\n *          nor CLTV path is present\n * @see VtxoScript.exitPaths\n */\n// TODO(next-major): return a discriminated union\n// (`{ kind: \"relative\", nSequence } | { kind: \"absolute\", lockTime }`)\n// so callers can't conflate the two. Deferred because changing the\n// return type is a breaking change.\nexport function getSequence(tapLeafScript: TapLeafScript): number | undefined {\n    let sequence: number | undefined = undefined;\n\n    try {\n        const scriptWithLeafVersion = tapLeafScript[1];\n        const script = scriptWithLeafVersion.subarray(0, scriptWithLeafVersion.length - 1);\n        try {\n            const params = CSVMultisigTapscript.decode(script).params;\n            sequence = timelockToSequence(params.timelock);\n        } catch {\n            const params = CLTVMultisigTapscript.decode(script).params;\n            sequence = Number(params.absoluteTimelock);\n        }\n    } catch {}\n\n    return sequence;\n}\n","import { RawTx, SigHash, Transaction as BtcSignerTransaction } from \"@scure/btc-signer\";\nimport { PSBTOutput } from \"@scure/btc-signer/psbt.js\";\nimport { TxOpts } from \"@scure/btc-signer/transaction.js\";\nimport { Bytes, concatBytes } from \"@scure/btc-signer/utils.js\";\nimport { TapTreeCoder, toBIP371TapTree } from \"../script/base\";\n\n/**\n * Transaction is a wrapper around the @scure/btc-signer Transaction class.\n * It adds the Arkade protocol specific options to the transaction.\n */\nexport class Transaction extends BtcSignerTransaction {\n    static ARK_TX_OPTS: TxOpts = {\n        unknown: \"ignore\",\n        allowUnknownOutputs: true,\n        allowUnknownInputs: true,\n    };\n\n    constructor(opts?: TxOpts) {\n        super(withArkOpts(opts));\n    }\n\n    /**\n     * Decode a PSBT. PSBTs carrying a legacy `PSBT_OUT_TAP_TREE` (see\n     * {@link repairLegacyOutputTapTrees}) are repaired and decoded again\n     * instead of being rejected.\n     */\n    static fromPSBT(psbt_: Bytes, opts?: TxOpts): Transaction {\n        try {\n            return BtcSignerTransaction.fromPSBT(psbt_, withArkOpts(opts));\n        } catch (err) {\n            const repaired = repairLegacyOutputTapTrees(psbt_);\n            if (!repaired) throw err;\n            return BtcSignerTransaction.fromPSBT(repaired, withArkOpts(opts));\n        }\n    }\n\n    static fromRaw(raw: Bytes, opts?: TxOpts): Transaction {\n        return BtcSignerTransaction.fromRaw(raw, withArkOpts(opts));\n    }\n}\n\nfunction withArkOpts(opts?: TxOpts): TxOpts {\n    return { ...Transaction.ARK_TX_OPTS, ...opts };\n}\n\nconst PSBT_MAGIC = new Uint8Array([0x70, 0x73, 0x62, 0x74, 0xff]);\nconst PSBT_GLOBAL_UNSIGNED_TX = 0x00;\nconst PSBT_GLOBAL_INPUT_COUNT = 0x04;\nconst PSBT_OUT_TAP_TREE = 0x06;\n\ntype PsbtKeyValue = { key: Uint8Array; value: Uint8Array };\n\n/**\n * Rewrite every `PSBT_OUT_TAP_TREE` written in the legacy\n * `VtxoScript.encode()` form (every leaf at depth 1) into a BIP-371 tree.\n *\n * SDK releases before the scure 2.4 upgrade put `VtxoScript.encode()` bytes\n * straight into this field. For any leaf count other than 2 those depths do\n * not describe a binary tree, which scure >= 2.4 rejects on decode\n * (\"tapTree: tuples must be in DFS order\"). Such transactions are already\n * stored by indexers, so they must stay decodable. Only the PSBT field\n * changes: the txid and every signature are unaffected.\n *\n * @returns The repaired PSBT, or `undefined` if no output needed repair.\n */\nexport function repairLegacyOutputTapTrees(psbt: Bytes): Uint8Array | undefined {\n    let maps: PsbtKeyValue[][];\n    let inputsCount: number;\n    try {\n        maps = readPsbtMaps(psbt);\n        inputsCount = psbtInputsCount(maps[0]);\n    } catch {\n        return undefined;\n    }\n\n    let repaired = false;\n    for (const output of maps.slice(1 + inputsCount)) {\n        for (const kv of output) {\n            if (kv.key.length !== 1 || kv.key[0] !== PSBT_OUT_TAP_TREE) continue;\n            const value = legacyTapTreeToBIP371(kv.value);\n            if (!value) continue;\n            kv.value = value;\n            repaired = true;\n        }\n    }\n    return repaired ? writePsbtMaps(maps) : undefined;\n}\n\nfunction legacyTapTreeToBIP371(value: Uint8Array): Uint8Array | undefined {\n    try {\n        PSBTOutput.tapTree[2].decode(value);\n        return undefined; // already valid\n    } catch {\n        // fall through: only the legacy all-depth-1 form is repaired\n    }\n    let leaves: ReturnType<typeof TapTreeCoder.decode>;\n    try {\n        leaves = TapTreeCoder.decode(value);\n    } catch {\n        return undefined;\n    }\n    if (leaves.length === 0 || leaves.some((leaf) => leaf.depth !== 1)) return undefined;\n    try {\n        return TapTreeCoder.encode(toBIP371TapTree(value));\n    } catch {\n        // Not a tree VtxoScript can rebuild: leave it, so the caller surfaces\n        // the original decode error rather than this one.\n        return undefined;\n    }\n}\n\nfunction psbtInputsCount(global: PsbtKeyValue[]): number {\n    for (const { key, value } of global) {\n        if (key.length !== 1) continue;\n        if (key[0] === PSBT_GLOBAL_UNSIGNED_TX) return RawTx.decode(value).inputs.length;\n        if (key[0] === PSBT_GLOBAL_INPUT_COUNT) return readCompactSize(value, 0)[0];\n    }\n    throw new Error(\"PSBT: missing input count\");\n}\n\n/** Split a PSBT into its raw key-value maps (global, inputs, outputs) without decoding fields. */\nfunction readPsbtMaps(psbt: Bytes): PsbtKeyValue[][] {\n    for (let i = 0; i < PSBT_MAGIC.length; i++) {\n        if (psbt[i] !== PSBT_MAGIC[i]) throw new Error(\"PSBT: invalid magic\");\n    }\n    const maps: PsbtKeyValue[][] = [];\n    let pos = PSBT_MAGIC.length;\n    while (pos < psbt.length) {\n        const map: PsbtKeyValue[] = [];\n        for (;;) {\n            const [keyLen, afterKeyLen] = readCompactSize(psbt, pos);\n            pos = afterKeyLen;\n            if (keyLen === 0) break;\n            const key = readBytes(psbt, pos, keyLen);\n            pos += keyLen;\n            const [valueLen, afterValueLen] = readCompactSize(psbt, pos);\n            pos = afterValueLen;\n            const value = readBytes(psbt, pos, valueLen);\n            pos += valueLen;\n            map.push({ key, value });\n        }\n        maps.push(map);\n    }\n    if (maps.length === 0) throw new Error(\"PSBT: missing global map\");\n    return maps;\n}\n\nfunction writePsbtMaps(maps: PsbtKeyValue[][]): Uint8Array {\n    const parts: Uint8Array[] = [PSBT_MAGIC];\n    for (const map of maps) {\n        for (const { key, value } of map) {\n            parts.push(writeCompactSize(key.length), key, writeCompactSize(value.length), value);\n        }\n        parts.push(new Uint8Array([0]));\n    }\n    return concatBytes(...parts);\n}\n\nfunction readBytes(data: Bytes, pos: number, len: number): Uint8Array {\n    if (pos + len > data.length) throw new Error(\"PSBT: unexpected end of data\");\n    return data.slice(pos, pos + len);\n}\n\n/** @returns [value, position after the compact size] */\nfunction readCompactSize(data: Bytes, pos: number): [number, number] {\n    const first = readBytes(data, pos, 1)[0];\n    if (first < 0xfd) return [first, pos + 1];\n    const width = first === 0xfd ? 2 : first === 0xfe ? 4 : 8;\n    const bytes = readBytes(data, pos + 1, width);\n    let value = 0;\n    for (let i = width - 1; i >= 0; i--) value = value * 256 + bytes[i];\n    if (!Number.isSafeInteger(value)) throw new Error(\"PSBT: compact size too large\");\n    return [value, pos + 1 + width];\n}\n\nfunction writeCompactSize(value: number): Uint8Array {\n    if (value < 0xfd) return new Uint8Array([value]);\n    const width = value <= 0xffff ? 2 : value <= 0xffffffff ? 4 : 8;\n    const out = new Uint8Array(1 + width);\n    out[0] = width === 2 ? 0xfd : width === 4 ? 0xfe : 0xff;\n    for (let i = 0, v = value; i < width; i++, v = Math.floor(v / 256)) out[1 + i] = v % 256;\n    return out;\n}\n\n/** Formats a sighash type as a hex string (e.g., 0x01) */\nexport function formatSighash(type: number): string {\n    return `0x${type.toString(16).padStart(2, \"0\")}`;\n}\n\n/**\n * Reject a PSBT that declares a sighash type outside `allowedSighashTypes` on\n * any input, before it reaches a signer. An input carrying no explicit type is\n * left alone: the signer treats a taproot input as {@link SigHash.DEFAULT}.\n */\nexport function assertAllowedSighashTypes(\n    tx: BtcSignerTransaction,\n    allowedSighashTypes: number[] = [SigHash.DEFAULT],\n): void {\n    for (let i = 0; i < tx.inputsLength; i++) {\n        const declared = tx.getInput(i).sighashType;\n        if (declared === undefined) continue;\n        if (!allowedSighashTypes.includes(declared)) {\n            throw new Error(`Unallowed sighash type ${formatSighash(declared)} for input ${i}.`);\n        }\n    }\n}\n","import { RawWitness, ScriptNum, Transaction } from \"@scure/btc-signer\";\nimport { TransactionInputUpdate } from \"@scure/btc-signer/psbt.js\";\nimport { sequenceToTimelock } from \"./timelock\";\n\n/**\n * ArkPsbtFieldKey are the available key names for the Arkade PSBT custom fields.\n */\nexport enum ArkPsbtFieldKey {\n    VtxoTaprootTree = \"taptree\",\n    VtxoTreeExpiry = \"expiry\",\n    Cosigner = \"cosigner\",\n    ConditionWitness = \"condition\",\n    PrevArkTx = \"prevarktx\",\n    PrevoutTx = \"prevouttx\",\n}\n\n/**\n * ArkPsbtFieldKeyType is the key type of the Arkade PSBT custom field.\n * Every Arkade PSBT field has key type 222.\n */\nexport const ArkPsbtFieldKeyType = 222;\n\n/**\n * ArkPsbtFieldCoder is the coder for the Arkade PSBT custom fields.\n * Each type has its own coder.\n */\nexport interface ArkPsbtFieldCoder<T> {\n    key: ArkPsbtFieldKey;\n    encode: (value: T) => NonNullable<TransactionInputUpdate[\"unknown\"]>[number];\n    decode: (value: NonNullable<TransactionInputUpdate[\"unknown\"]>[number]) => T | null;\n}\n\n/**\n * setArkPsbtField appends a new unknown field to the input at inputIndex\n *\n * @example\n * ```typescript\n * setArkPsbtField(tx, 0, VtxoTaprootTree, myTaprootTree);\n * setArkPsbtField(tx, 0, VtxoTreeExpiry, myVtxoTreeExpiry);\n * ```\n */\nexport function setArkPsbtField<T>(\n    tx: Transaction,\n    inputIndex: number,\n    coder: ArkPsbtFieldCoder<T>,\n    value: T,\n): void {\n    tx.updateInput(inputIndex, {\n        unknown: [...(tx.getInput(inputIndex)?.unknown ?? []), coder.encode(value)],\n    });\n}\n\n/**\n * getArkPsbtFields returns all the values of the given coder for the input at inputIndex\n * Multiple fields of the same type can exist in a single input.\n *\n * @example\n * ```typescript\n * const vtxoTaprootTreeFields = getArkPsbtFields(tx, 0, VtxoTaprootTree);\n * console.log(`input has ${vtxoTaprootTreeFields.length} vtxoTaprootTree fields`);\n */\nexport function getArkPsbtFields<T>(\n    tx: Transaction,\n    inputIndex: number,\n    coder: ArkPsbtFieldCoder<T>,\n): T[] {\n    const unknown = tx.getInput(inputIndex)?.unknown ?? [];\n\n    const fields: T[] = [];\n    for (const u of unknown) {\n        const v = coder.decode(u);\n        if (v !== null) fields.push(v);\n    }\n    return fields;\n}\n\n/**\n * VtxoTaprootTree is set to pass all spending leaves of the vtxo input\n *\n * @example\n * ```typescript\n * const vtxoTaprootTree = VtxoTaprootTree.encode(myTaprootTree);\n */\nexport const VtxoTaprootTree: ArkPsbtFieldCoder<Uint8Array> = {\n    key: ArkPsbtFieldKey.VtxoTaprootTree,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: encodedPsbtFieldKey[ArkPsbtFieldKey.VtxoTaprootTree],\n        },\n        value,\n    ],\n    decode: (value) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(value[0], ArkPsbtFieldKey.VtxoTaprootTree)) return null;\n            return value[1];\n        }),\n};\n\n/**\n * ConditionWitness is set to pass the witness data used to finalize the conditionMultisigClosure\n *\n * @example\n * ```typescript\n * const conditionWitness = ConditionWitness.encode(myConditionWitness);\n */\nexport const ConditionWitness: ArkPsbtFieldCoder<Uint8Array[]> = {\n    key: ArkPsbtFieldKey.ConditionWitness,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: encodedPsbtFieldKey[ArkPsbtFieldKey.ConditionWitness],\n        },\n        RawWitness.encode(value),\n    ],\n    decode: (value) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(value[0], ArkPsbtFieldKey.ConditionWitness)) return null;\n            return RawWitness.decode(value[1]);\n        }),\n};\n\n/**\n * PrevArkTxField carries the serialized raw bitcoin tx of the previous Ark tx\n * spent by an input. Used by OP_INSPECTINPUTSCRIPTPUBKEY on intent proofs and\n * other contexts where the prevout pkScript must be looked up off-chain.\n *\n * Key: [0xde] || \"prevarktx\". Value: serialized wire.MsgTx (NOT a PSBT).\n */\nexport const PrevArkTxField: ArkPsbtFieldCoder<Uint8Array> = {\n    key: ArkPsbtFieldKey.PrevArkTx,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: encodedPsbtFieldKey[ArkPsbtFieldKey.PrevArkTx],\n        },\n        value,\n    ],\n    decode: (value) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(value[0], ArkPsbtFieldKey.PrevArkTx)) return null;\n            return value[1];\n        }),\n};\n\n/**\n * PrevoutTxField carries the serialized raw bitcoin tx that produced the\n * previous output spent by an input. Used by OP_INSPECTINPUTSCRIPTPUBKEY in\n * the SubmitOnchainTx flow, where there is no Ark tx but a plain Bitcoin\n * funding tx whose pkScript must be resolvable.\n *\n * Key: [0xde] || \"prevouttx\". Value: serialized wire.MsgTx (NOT a PSBT).\n */\nexport const PrevoutTxField: ArkPsbtFieldCoder<Uint8Array> = {\n    key: ArkPsbtFieldKey.PrevoutTx,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: encodedPsbtFieldKey[ArkPsbtFieldKey.PrevoutTx],\n        },\n        value,\n    ],\n    decode: (value) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(value[0], ArkPsbtFieldKey.PrevoutTx)) return null;\n            return value[1];\n        }),\n};\n\n/**\n * CosignerPublicKey is set on every TxGraph transactions to identify the musig2 public keys\n *\n * @example\n * ```typescript\n * const cosignerPublicKey = CosignerPublicKey.encode(myCosignerPublicKey);\n */\nexport const CosignerPublicKey: ArkPsbtFieldCoder<{\n    index: number;\n    key: Uint8Array;\n}> = {\n    key: ArkPsbtFieldKey.Cosigner,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: new Uint8Array([...encodedPsbtFieldKey[ArkPsbtFieldKey.Cosigner], value.index]),\n        },\n        value.key,\n    ],\n    decode: (unknown) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(unknown[0], ArkPsbtFieldKey.Cosigner, true)) return null;\n            return {\n                index: unknown[0].key[unknown[0].key.length - 1],\n                key: unknown[1],\n            };\n        }),\n};\n\n/**\n * VtxoTreeExpiry is set to pass the expiry time of the input\n *\n * @example\n * ```typescript\n * const vtxoTreeExpiry = VtxoTreeExpiry.encode(myVtxoTreeExpiry);\n */\nexport const VtxoTreeExpiry: ArkPsbtFieldCoder<{\n    type: \"blocks\" | \"seconds\";\n    value: bigint;\n}> = {\n    key: ArkPsbtFieldKey.VtxoTreeExpiry,\n    encode: (value) => [\n        {\n            type: ArkPsbtFieldKeyType,\n            key: encodedPsbtFieldKey[ArkPsbtFieldKey.VtxoTreeExpiry],\n        },\n        ScriptNum(6, true).encode(value.value === 0n ? 0n : value.value),\n    ],\n    decode: (unknown) =>\n        nullIfCatch(() => {\n            if (!checkKeyMatch(unknown[0], ArkPsbtFieldKey.VtxoTreeExpiry)) return null;\n            const v = ScriptNum(6, true).decode(unknown[1]);\n            if (!v) return null;\n            return sequenceToTimelock(Number(v));\n        }),\n};\n\nconst encodedPsbtFieldKey: Record<string, Uint8Array> = Object.fromEntries(\n    Object.values(ArkPsbtFieldKey).map((key) => [key, new TextEncoder().encode(key)]),\n);\n\nconst nullIfCatch = <T>(fn: () => T): T | null => {\n    try {\n        return fn();\n    } catch {\n        return null;\n    }\n};\n\nfunction checkKeyMatch(\n    key: { type: number; key: Uint8Array },\n    arkPsbtFieldKey: ArkPsbtFieldKey,\n    prefixOnly: boolean = false,\n): boolean {\n    if (key.type !== ArkPsbtFieldKeyType) return false;\n    const expected = encodedPsbtFieldKey[arkPsbtFieldKey];\n    if (key.key.length < expected.length) return false;\n    if (!prefixOnly && key.key.length !== expected.length) return false;\n    for (let i = 0; i < expected.length; i++) {\n        if (key.key[i] !== expected[i]) return false;\n    }\n    return true;\n}\n","/**\n * Where the SDK gets its `EventSource`.\n *\n * Every server-sent-events stream this SDK opens — settlement events, the tx\n * feed, the indexer script subscription — needs one, and until now each site\n * reached for the global. That works in browsers and, via\n * {@link ExpoArkProvider}/{@link ExpoIndexerProvider}, in React Native. It does\n * NOT work in Node, which exposes `EventSource` only behind\n * `--experimental-eventsource` (24.x) — so a CLI, a server-side wallet or a\n * background worker got a `ReferenceError` out of the stream and everything\n * event-driven degraded to whatever polling happened to be running.\n *\n * Resolution order, per call: an explicit per-provider factory, then whatever\n * {@link configureEventSource} was given, then the global. When none answers,\n * {@link resolveEventSource} throws {@link EventSourceUnavailableError} rather\n * than a bare `ReferenceError`, so callers can tell \"this environment has no\n * SSE\" from \"the connection dropped\" — a distinction that matters, because the\n * first is not worth reconnecting for and the second is.\n */\n\n/**\n * The slice of `EventSource` this SDK actually uses.\n *\n * Structural rather than the DOM type on purpose: Node's `eventsource` package\n * and the React Native polyfills are not DOM `EventSource`s, and demanding one\n * made every consumer launder a perfectly capable object through\n * `as unknown as EventSource` — a cast that hides real mismatches as readily as\n * it waves through this one.\n */\nexport interface EventSourceLike {\n    addEventListener(type: \"message\" | \"error\", listener: (event: MessageEvent) => void): void;\n    removeEventListener(type: \"message\" | \"error\", listener: (event: MessageEvent) => void): void;\n    close(): void;\n}\n\n/** Opens an SSE connection to `url`. `new EventSource(url)`, as a value. */\nexport type EventSourceFactory = (url: string) => EventSourceLike;\n\n/** Options shared by every provider that opens an SSE stream. */\nexport interface EventSourceCapable {\n    /**\n     * Where this provider gets its `EventSource`, overriding\n     * {@link configureEventSource} and the global. Use it when one process\n     * needs different transports per connection; otherwise configure once.\n     */\n    eventSource?: EventSourceFactory;\n}\n\nconst GUIDANCE =\n    \"Pass one with configureEventSource(url => new EventSource(url)) — in Node, from the \" +\n    \"`eventsource` package or by running with --experimental-eventsource. In React Native, \" +\n    \"use ExpoArkProvider / ExpoIndexerProvider instead.\";\n\n/**\n * No `EventSource` could be resolved, so no SSE stream can be opened.\n *\n * A property of the environment, not of the connection: retrying cannot fix it,\n * which is why {@link ContractWatcher} reports it once and stops reconnecting\n * instead of looping on it.\n */\nexport class EventSourceUnavailableError extends Error {\n    constructor() {\n        super(`no EventSource is available, so server-sent events cannot be opened. ${GUIDANCE}`);\n        this.name = \"EventSourceUnavailableError\";\n    }\n}\n\n/**\n * Type guard for {@link EventSourceUnavailableError}.\n *\n * Falls back to the `name` because a custom error crossing the service-worker\n * `postMessage` boundary arrives as a plain `Error` — the same reason\n * `ProviderUnavailableError` keeps its state in the message.\n */\nexport function isEventSourceUnavailableError(error: unknown): error is Error {\n    return (\n        error instanceof EventSourceUnavailableError ||\n        (error instanceof Error && error.name === \"EventSourceUnavailableError\")\n    );\n}\n\nlet configured: EventSourceFactory | undefined;\n\n/**\n * Set the `EventSource` every provider uses by default. Call once at startup,\n * before opening a wallet; pass `undefined` to go back to the global.\n *\n * This exists because the provider-level option cannot reach providers the SDK\n * builds for you — `Wallet.create({ arkServerUrl })` constructs both itself.\n *\n * @example\n * ```typescript\n * import { EventSource } from \"eventsource\";\n * configureEventSource((url) => new EventSource(url));\n * ```\n */\nexport function configureEventSource(factory?: EventSourceFactory): void {\n    configured = factory;\n}\n\n/** What {@link configureEventSource} last set, if anything. */\nexport function getConfiguredEventSource(): EventSourceFactory | undefined {\n    return configured;\n}\n\n/**\n * Resolve the factory to open a stream with, or throw\n * {@link EventSourceUnavailableError}.\n *\n * The global is read on every call rather than captured at module load: a test\n * (or a polyfill) that assigns `globalThis.EventSource` after import must still\n * be seen.\n */\nexport function resolveEventSource(override?: EventSourceFactory): EventSourceFactory {\n    const factory =\n        override ??\n        configured ??\n        (typeof EventSource === \"undefined\" ? undefined : (url: string) => new EventSource(url));\n    if (!factory) throw new EventSourceUnavailableError();\n    return factory;\n}\n","{\n    \"name\": \"@arkade-os/sdk\",\n    \"version\": \"0.4.79\",\n    \"description\": \"TypeScript SDK for building Bitcoin wallets using the Arkade protocol\",\n    \"repository\": {\n        \"type\": \"git\",\n        \"url\": \"git+https://github.com/arkade-os/ts-sdk.git\",\n        \"directory\": \"packages/ts-sdk\"\n    },\n    \"type\": \"module\",\n    \"main\": \"./dist/index.cjs\",\n    \"module\": \"./dist/index.js\",\n    \"types\": \"./dist/index.d.ts\",\n    \"sideEffects\": [\n        \"src/index.ts\",\n        \"src/contracts/handlers/index.ts\",\n        \"dist/index.js\",\n        \"dist/index.cjs\",\n        \"dist/contracts/handlers/index.js\",\n        \"dist/contracts/handlers/index.cjs\"\n    ],\n    \"exports\": {\n        \".\": {\n            \"import\": {\n                \"types\": \"./dist/index.d.ts\",\n                \"default\": \"./dist/index.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/index.d.cts\",\n                \"default\": \"./dist/index.cjs\"\n            }\n        },\n        \"./adapters/expo\": {\n            \"import\": {\n                \"types\": \"./dist/adapters/expo.d.ts\",\n                \"default\": \"./dist/adapters/expo.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/adapters/expo.d.cts\",\n                \"default\": \"./dist/adapters/expo.cjs\"\n            }\n        },\n        \"./adapters/localStorage\": {\n            \"import\": {\n                \"types\": \"./dist/adapters/localStorage.d.ts\",\n                \"default\": \"./dist/adapters/localStorage.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/adapters/localStorage.d.cts\",\n                \"default\": \"./dist/adapters/localStorage.cjs\"\n            }\n        },\n        \"./adapters/fileSystem\": {\n            \"import\": {\n                \"types\": \"./dist/adapters/fileSystem.d.ts\",\n                \"default\": \"./dist/adapters/fileSystem.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/adapters/fileSystem.d.cts\",\n                \"default\": \"./dist/adapters/fileSystem.cjs\"\n            }\n        },\n        \"./adapters/indexedDB\": {\n            \"import\": {\n                \"types\": \"./dist/adapters/indexedDB.d.ts\",\n                \"default\": \"./dist/adapters/indexedDB.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/adapters/indexedDB.d.cts\",\n                \"default\": \"./dist/adapters/indexedDB.cjs\"\n            }\n        },\n        \"./adapters/asyncStorage\": {\n            \"import\": {\n                \"types\": \"./dist/adapters/asyncStorage.d.ts\",\n                \"default\": \"./dist/adapters/asyncStorage.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/adapters/asyncStorage.d.cts\",\n                \"default\": \"./dist/adapters/asyncStorage.cjs\"\n            }\n        },\n        \"./repositories/sqlite\": {\n            \"import\": {\n                \"types\": \"./dist/repositories/sqlite/index.d.ts\",\n                \"default\": \"./dist/repositories/sqlite/index.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/repositories/sqlite/index.d.cts\",\n                \"default\": \"./dist/repositories/sqlite/index.cjs\"\n            }\n        },\n        \"./repositories/realm\": {\n            \"import\": {\n                \"types\": \"./dist/repositories/realm/index.d.ts\",\n                \"default\": \"./dist/repositories/realm/index.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/repositories/realm/index.d.cts\",\n                \"default\": \"./dist/repositories/realm/index.cjs\"\n            }\n        },\n        \"./worker/expo\": {\n            \"import\": {\n                \"types\": \"./dist/worker/expo/index.d.ts\",\n                \"default\": \"./dist/worker/expo/index.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/worker/expo/index.d.cts\",\n                \"default\": \"./dist/worker/expo/index.cjs\"\n            }\n        },\n        \"./wallet/expo\": {\n            \"import\": {\n                \"types\": \"./dist/wallet/expo/index.d.ts\",\n                \"default\": \"./dist/wallet/expo/index.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/wallet/expo/index.d.cts\",\n                \"default\": \"./dist/wallet/expo/index.cjs\"\n            }\n        },\n        \"./wallet/expo/background\": {\n            \"import\": {\n                \"types\": \"./dist/wallet/expo/background.d.ts\",\n                \"default\": \"./dist/wallet/expo/background.js\"\n            },\n            \"require\": {\n                \"types\": \"./dist/wallet/expo/background.d.cts\",\n                \"default\": \"./dist/wallet/expo/background.cjs\"\n            }\n        }\n    },\n    \"files\": [\n        \"dist\"\n    ],\n    \"publishConfig\": {\n        \"access\": \"public\",\n        \"registry\": \"https://registry.npmjs.org/\"\n    },\n    \"engines\": {\n        \"node\": \">=22.12.0 <27\"\n    },\n    \"scripts\": {\n        \"build\": \"tsup\",\n        \"smoke:dist\": \"node scripts/smoke-dist.mjs\",\n        \"typecheck\": \"tsc --noEmit\",\n        \"typecheck:types\": \"tsc -p tsconfig.typecheck.json --noEmit\",\n        \"check:vtxo\": \"node scripts/check-virtual-status.mjs && node scripts/check-provider-boundary.mjs\",\n        \"docs:build\": \"pnpm run typecheck && pnpm typedoc\",\n        \"docs:open\": \"open ../../docs/index.html\",\n        \"test\": \"vitest run\",\n        \"test:master\": \"ARK_ENV=master vitest run\",\n        \"test:unit\": \"vitest run --exclude test/e2e\",\n        \"test:setup\": \"node test/setup.mjs\",\n        \"regtest:start\": \"node ./regtest/regtest.mjs start\",\n        \"regtest:stop\": \"node ./regtest/regtest.mjs stop\",\n        \"regtest:clean\": \"node ./regtest/regtest.mjs clean\",\n        \"regtest\": \"pnpm regtest:clean && pnpm regtest:start && pnpm test:setup-docker\",\n        \"test:setup-docker\": \"node test/setup.mjs docker\",\n        \"test:integration\": \"vitest run test/e2e/**\",\n        \"test:integration-docker\": \"ARK_ENV=docker vitest run test/e2e/**\",\n        \"test:watch\": \"vitest\",\n        \"test:coverage\": \"vitest run --coverage\",\n        \"format\": \"biome format --write src test examples\",\n        \"lint\": \"biome format src test examples && pnpm run check:vtxo\",\n        \"audit\": \"pnpm audit\",\n        \"prepack\": \"pnpm run build\",\n        \"prepublishOnly\": \"pnpm run build\"\n    },\n    \"dependencies\": {\n        \"@bitcoinerlab/descriptors-scure\": \"3.1.7\",\n        \"@marcbachmann/cel-js\": \"8.0.0\",\n        \"@noble/curves\": \"2.4.0\",\n        \"@noble/secp256k1\": \"3.0.0\",\n        \"@scure/base\": \"2.4.0\",\n        \"@scure/bip39\": \"2.4.0\",\n        \"@scure/btc-signer\": \"2.4.1\",\n        \"bip68\": \"1.0.4\",\n        \"micro-packed\": \"0.11.1\",\n        \"ws-electrumx-client\": \"1.0.5\"\n    },\n    \"devDependencies\": {\n        \"@types/better-sqlite3\": \"7.6.13\",\n        \"@vitest/coverage-v8\": \"3.2.7\",\n        \"better-sqlite3\": \"12.6.2\",\n        \"tsup\": \"^8.5.0\",\n        \"typedoc\": \"^0.28.19\",\n        \"typescript\": \"5.9.2\"\n    },\n    \"peerDependencies\": {\n        \"@react-native-async-storage/async-storage\": \">=1.0.0\",\n        \"expo\": \">=54.0.0\",\n        \"expo-background-task\": \"~1.0.10 || >=55.0.0\",\n        \"expo-sqlite\": \"~16.0.10 || >=55.0.0\",\n        \"expo-task-manager\": \"~14.0.9 || >=55.0.0\"\n    },\n    \"peerDependenciesMeta\": {\n        \"expo\": {\n            \"optional\": true\n        },\n        \"expo-sqlite\": {\n            \"optional\": true\n        },\n        \"expo-background-task\": {\n            \"optional\": true\n        },\n        \"expo-task-manager\": {\n            \"optional\": true\n        },\n        \"@react-native-async-storage/async-storage\": {\n            \"optional\": true\n        }\n    },\n    \"keywords\": [\n        \"ark\",\n        \"arkade\",\n        \"bip39\",\n        \"bitcoin\",\n        \"btc\",\n        \"crypto\",\n        \"lightning\",\n        \"sdk\",\n        \"stablecoin\",\n        \"taproot\",\n        \"typescript\",\n        \"utxo\",\n        \"vtxo\",\n        \"wallet\"\n    ],\n    \"author\": \"Ark Labs\",\n    \"license\": \"MIT\",\n    \"packageManager\": \"pnpm@10.25.0\"\n}\n","import { version } from \"../../package.json\";\n\nexport const buildVersion = \"0.9.9\";\n\n/**\n * The SDK's own version string, sourced from package.json\n */\nexport const sdkVersion = `ts-sdk/${version}`;\n\n/**\n * The version headers arkd's compatibility guard reads, for callers that need\n * them as data rather than as a wrapper — {@link fetch} sets the same pair, so\n * a header added to one belongs in the other. They go to the Arkade server and\n * nowhere else: another origin rejects them in the CORS preflight.\n */\nexport const ARKADE_VERSION_HEADERS: Readonly<Record<string, string>> = {\n    \"X-Build-Version\": buildVersion,\n    \"X-SDK-VERSION\": sdkVersion,\n};\n\n/**\n * Wraps a transport-level `fetch` rejection (DNS failure, connection refused,\n * TLS or CORS error) with the request method and URL, preserving the original\n * as {@link Error.cause}.\n */\nexport class FetchError extends Error {\n    /** The request URL that failed, when derivable from the `fetch` input. */\n    readonly url?: string;\n    /** The HTTP method of the failed request (defaults to `\"GET\"`). */\n    readonly method?: string;\n\n    constructor(message: string, options: { url?: string; method?: string; cause?: unknown }) {\n        super(message, { cause: options.cause });\n        this.name = \"FetchError\";\n        this.url = options.url;\n        this.method = options.method;\n    }\n}\n\n/**\n * Deadline applied to a read that carries no `AbortSignal` of its own.\n *\n * `fetch` has no default timeout, so a connection the network dropped silently\n * stays pending until the runtime gives up — and every bound built on top of it\n * waits with it. A retry ladder, a bounded queue or a mutex only work if the\n * call underneath them terminates.\n */\nexport const READ_TIMEOUT_MS = 30_000;\n\nlet warnedNoTimeoutSupport = false;\n\n/**\n * The signal bounding this request, or `undefined` to leave it unbounded.\n *\n * Only GET and HEAD get one. A write that is aborted has not necessarily failed\n * — its outcome is unknown — so bounding one converts a stall into a state\n * question its caller may have no way to answer.\n *\n * A `Request` input is always left alone. Every `Request` carries a `signal`\n * whether or not its author supplied one, so \"did the caller bring a signal?\"\n * cannot be read back off it, and guessing wrong would cancel someone's\n * lifetime for them.\n */\nfunction readDeadline(input: RequestInfo | URL, init?: RequestInit): AbortSignal | undefined {\n    if (init?.signal || input instanceof Request) return undefined;\n    const { method } = describeRequest(input, init);\n    const verb = method.toUpperCase();\n    if (verb !== \"GET\" && verb !== \"HEAD\") return undefined;\n    if (typeof AbortSignal !== \"undefined\" && typeof AbortSignal.timeout === \"function\") {\n        return AbortSignal.timeout(READ_TIMEOUT_MS);\n    }\n\n    // `AbortSignal.timeout` is absent on some React Native runtimes while\n    // `AbortController` is not, so fall back rather than silently leaving the\n    // read unbounded — which is the exact state this exists to prevent.\n    if (typeof AbortController === \"function\") {\n        const controller = new AbortController();\n        // Deliberately never cleared, so the bound covers the body read and not\n        // just the headers, matching the native path. Aborting an already\n        // settled request is a no-op; `unref` keeps it from holding Node open.\n        const timer: unknown = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);\n        (timer as { unref?: () => void })?.unref?.();\n        return controller.signal;\n    }\n\n    if (!warnedNoTimeoutSupport) {\n        warnedNoTimeoutSupport = true;\n        console.warn(\n            \"Neither AbortSignal.timeout nor AbortController is available in this runtime: \" +\n                \"provider reads are UNBOUNDED and READ_TIMEOUT_MS is not being applied.\",\n        );\n    }\n    return undefined;\n}\n\n/**\n * Guarded passthrough to the platform `fetch` with no Arkade-specific headers.\n * Use for any service that is NOT the Ark server (delegate, Esplora, …): those\n * origins reject unknown request headers such as `X-Build-Version` in the CORS\n * preflight.\n *\n * Reads without a caller-supplied signal are bounded by {@link READ_TIMEOUT_MS}.\n *\n * **A long-lived request opts out by supplying its own signal — that is the only\n * thing keeping this deadline off a stream.** On web, SSE happens to use\n * `EventSource` and never arrives here at all; on Expo it does arrive here\n * whenever `expo/fetch` fails to import and `getExpoFetch` falls back to this\n * module, and `sseStreamIterator` passing `signal: fetchController.signal` is\n * what prevents a 30-second truncation. That signal is load-bearing, not\n * incidental: a streaming caller that omits one gets cut off here.\n *\n * Transport-level rejections are re-thrown as a {@link FetchError}.\n */\nexport function baseFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n    if (typeof globalThis.fetch !== \"function\") {\n        throw new Error(\"Fetch API is not available in this environment.\");\n    }\n    const signal = readDeadline(input, init);\n    return globalThis.fetch(input, signal ? { ...init, signal } : init).catch((cause) => {\n        const { url, method } = describeRequest(input, init);\n        throw new FetchError(`Network request failed: ${method} ${url}`, { url, method, cause });\n    });\n}\n\n/**\n * `fetch` for the Ark server only: adds the `X-Build-Version` compatibility\n * header that arkd's version guard reads, plus the `X-SDK-VERSION` header\n * carrying this package's own version. Do NOT use it for other origins — they\n * reject these custom headers in CORS preflight.\n */\nexport function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n    const headers = new Headers(init?.headers);\n    headers.set(\"X-Build-Version\", buildVersion);\n    headers.set(\"X-SDK-VERSION\", sdkVersion);\n    return baseFetch(input, { ...init, headers });\n}\n\n/**\n * Derive a human-readable `{ url, method }` for a failed request from the\n * `fetch` arguments, handling the `string | URL | Request` input shapes. The\n * `init.method` wins, then a `Request`'s own method, defaulting to `\"GET\"`.\n */\nfunction describeRequest(\n    input: RequestInfo | URL,\n    init?: RequestInit,\n): { url: string; method: string } {\n    let url: string;\n    if (typeof input === \"string\") {\n        url = input;\n    } else if (input instanceof URL) {\n        url = input.href;\n    } else {\n        url = input.url;\n    }\n\n    let method: string;\n    if (init?.method !== undefined) {\n        method = init.method;\n    } else if (input instanceof Request) {\n        method = input.method;\n    } else {\n        method = \"GET\";\n    }\n\n    return { url, method };\n}\n","import { FetchError } from \"../utils/fetch\";\n\nexport class ArkError extends Error {\n    constructor(\n        readonly code: number,\n        readonly message: string,\n        readonly name: string,\n        readonly metadata?: Record<string, string>,\n    ) {\n        super(message);\n    }\n}\n\n/**\n * Structured arkd error `name`s the SDK branches on, centralized so call sites don't\n * hardcode string literals. Not an exhaustive mirror of the server's codes — only the\n * ones the SDK acts on.\n */\nexport const ArkErrorName = {\n    DIGEST_MISMATCH: \"DIGEST_MISMATCH\",\n    VTXO_ALREADY_SPENT: \"VTXO_ALREADY_SPENT\",\n    INVALID_TX_FILTER: \"INVALID_TX_FILTER\",\n    TX_FILTERS_LIMIT_EXCEEDED: \"TX_FILTERS_LIMIT_EXCEEDED\",\n    /**\n     * A CLTV closure was spent before its absolute locktime matured. Raised only by\n     * `submitTx` (never `finalizeTx`), with metadata\n     * `{ locktime, current_locktime, type: \"height\" | \"time\" }`.\n     *\n     * Self-healing, so defer and retry rather than fail: the server matures a\n     * seconds-locktime against the **chain tip block's timestamp**, not its wall clock,\n     * so a spend attempted promptly at maturity is rejected until a later block lands.\n     */\n    FORFEIT_CLOSURE_LOCKED: \"FORFEIT_CLOSURE_LOCKED\",\n} as const;\n\nexport type ArkErrorName = (typeof ArkErrorName)[keyof typeof ArkErrorName];\n\n/**\n * Type guard for a structured {@link ArkError}, optionally narrowing to a specific\n * `name`. Prefer it over comparing `err.name` literals.\n *\n * `name` accepts only cataloged {@link ArkErrorName} values; to branch on a name the\n * catalog does not cover, either add it there or compare `err.name` after guarding\n * with the one-argument form.\n *\n * @example\n * if (isArkError(maybeArkError(err), ArkErrorName.DIGEST_MISMATCH)) { ... }\n */\nexport function isArkError(error: unknown, name?: ArkErrorName): error is ArkError {\n    return error instanceof ArkError && (name === undefined || error.name === name);\n}\n\n/**\n * Which remote dependency an availability failure refers to. Used to label the\n * {@link ProviderUnavailableError} message and the wallet's\n * `ProviderConnectionState`; it is deliberately *not* carried as a structured\n * field on the error, since custom `Error` own-properties do not survive the\n * service-worker `postMessage` boundary. Structured clone keeps `message`,\n * `stack` and `cause`, drops own-properties, and normalizes a custom `name` to\n * `\"Error\"` — only the built-in error names survive it.\n */\nexport type ProviderKind = \"arkade\" | \"indexer\";\n\n/**\n * A remote provider (Arkade operator or its indexer) is temporarily\n * unreachable. This is a *retryable* condition — transport failure, request\n * timeout, or a 5xx/429-style temporary HTTP response — as opposed to a\n * terminal configuration/authorization/schema error, which stays a plain\n * `Error`/{@link ArkError}. The original low-level error is preserved as\n * {@link Error.cause}.\n */\nexport class ProviderUnavailableError extends Error {\n    /** Always `true`: this error type only ever wraps retryable conditions. */\n    readonly retryable = true;\n\n    constructor(message: string, options?: { cause?: unknown }) {\n        super(message, { cause: options?.cause });\n        this.name = \"ProviderUnavailableError\";\n    }\n}\n\n/**\n * A response does not reconcile with what the SDK submitted or already\n * validated — a checkpoint tx whose txid is not among those submitted, a\n * commitment tx that differs from the one validated at tree signing. Terminal\n * rather than retryable: the two are equal by construction in a well-formed\n * exchange, so the same request would produce the same outcome.\n *\n * Neither own-properties nor a custom `name` cross the service-worker\n * `postMessage` boundary (see {@link ProviderKind}), so `retryable` and `name`\n * are in-process conveniences and every distinguishing detail belongs in\n * `message` — the one field a consumer past the boundary can still branch on.\n */\nexport class ServerResponseMismatchError extends Error {\n    readonly retryable = false;\n\n    constructor(message: string, options?: { cause?: unknown }) {\n        super(message, { cause: options?.cause });\n        this.name = \"ServerResponseMismatchError\";\n    }\n}\n\n/**\n * Throw a typed {@link ProviderUnavailableError} for a temporary HTTP response\n * (429 rate-limit or any 5xx), otherwise return. `fetch()` resolves — rather\n * than rejects — on HTTP error status, so status-code classification has to live\n * at each provider's non-2xx branch, not in the transport wrapper. 4xx and other\n * responses are left to the caller to treat as terminal.\n *\n * Status alone is not enough to classify an arkd response, though: arkd sits\n * behind grpc-gateway, which maps application-level gRPC errors onto HTTP status\n * codes across the whole range — gRPC INTERNAL becomes HTTP 500, for instance. So\n * a 5xx does not by itself mean the operator is unavailable: a 500 whose body\n * carries a structured arkd error (e.g. `INTERNAL_ERROR (0): ...already registered\n * by another intent`) is a deliberate, terminal rejection that must reach the\n * caller as an {@link ArkError}, never be retried. When `body` is provided and\n * decodes to a structured arkd error, this returns without throwing; classify by\n * status only for a bodyless call or a non-structured body (a bare proxy/gateway\n * failure). Mirrors NArk's BuildVersionHandler, which branches on body content,\n * not status.\n */\nexport function throwIfHttpUnavailable(\n    response: Response,\n    kind: ProviderKind,\n    body?: string,\n): void {\n    if (body !== undefined && maybeArkError(new Error(body))) return;\n    if (response.status === 429 || response.status >= 500) {\n        throw new ProviderUnavailableError(\n            `${kind} unavailable: ${response.status} ${response.statusText}`,\n        );\n    }\n}\n\n/**\n * Map a transport-level {@link FetchError} (server unreachable) to a typed\n * {@link ProviderUnavailableError}, preserving the original as `cause`; return\n * any other error unchanged. Returns the error to `throw` rather than throwing,\n * so a `catch` block can `throw toProviderUnavailable(err, kind)`.\n */\nexport function toProviderUnavailable(err: unknown, kind: ProviderKind): unknown {\n    if (err instanceof FetchError) {\n        return new ProviderUnavailableError(`${kind} request failed`, { cause: err });\n    }\n    return err;\n}\n\n/**\n * Try to convert an error to an ArkError class, returning undefined if the error is not an ArkError\n * @param error - The error to parse\n * @returns The parsed ArkError, or undefined if the error is not an ArkError\n */\nexport function maybeArkError(error: any): ArkError | undefined {\n    try {\n        if (!(error instanceof Error)) return undefined;\n        const decoded = JSON.parse(error.message);\n\n        // Preferred: the structured ErrorDetails the server attaches in details[].\n        if (Array.isArray(decoded.details)) {\n            for (const details of decoded.details) {\n                if (!(\"@type\" in details)) continue;\n                const type = details[\"@type\"];\n                if (type !== \"type.googleapis.com/ark.v1.ErrorDetails\") continue;\n\n                if (!(\"code\" in details)) continue;\n\n                const code = details.code;\n\n                if (!(\"message\" in details)) continue;\n                const message = details.message;\n\n                if (!(\"name\" in details)) continue;\n                const name = details.name;\n\n                let metadata: Record<string, string> | undefined;\n                if (\"metadata\" in details && isMetadata(details.metadata)) {\n                    metadata = details.metadata;\n                }\n\n                return new ArkError(code, message, name, metadata);\n            }\n        }\n\n        // Fallback: arkd's guard interceptors (build-version, digest) run outside\n        // the error-detail converter, so their REST errors arrive with an empty\n        // `details[]` and the structured name only in the top-level message, as\n        // \"NAME (code): human message\". Recover the name and code so callers can\n        // still branch on the error name (metadata is unavailable on this path).\n        if (typeof decoded.message === \"string\") {\n            const m = decoded.message.match(/^([A-Z][A-Z0-9_]*) \\((\\d+)\\): ([\\s\\S]*)$/);\n            if (m) return new ArkError(Number(m[2]), m[3], m[1]);\n        }\n\n        return undefined;\n    } catch (e) {\n        return undefined;\n    }\n}\n\nfunction isMetadata(value: any): value is Record<string, string> {\n    return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { OP, Script, SigHash } from \"@scure/btc-signer\";\nimport { PSBTGlobal, TransactionInput, TransactionOutput } from \"@scure/btc-signer/psbt.js\";\nimport type { PSBTKeyMapKeys } from \"@scure/btc-signer/psbt.js\";\nimport { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { Transaction } from \"../utils/transaction\";\nimport { ConditionWitness, PrevArkTxField, VtxoTaprootTree } from \"../utils/unknownFields\";\nimport { hex } from \"@scure/base\";\nimport { getSequence, VtxoScript } from \"../script/base\";\nimport { ExtendedCoin } from \"../wallet\";\nimport type { WithPrevTx } from \"../utils/prevoutTx\";\n\n/**\n * Decoded shape of `Transaction.global`, derived from scure's own\n * `PSBTGlobal` key-map the same way it derives its public\n * `TransactionInput`/`TransactionOutput` types. `Transaction.global` itself\n * is private with no public setter, so writing to it still requires an\n * `as unknown` cast; this type at least ties the cast target to scure's\n * actual field definitions instead of a hand-written guess, so a future\n * rename/removal of a field (e.g. `genericSignedMessage`) breaks the build.\n */\ntype TransactionGlobal = PSBTKeyMapKeys<typeof PSBTGlobal>;\n\n/**\n * A coin an intent proof proves ownership of. `prevTx` carries the raw wire\n * bytes of the transaction that created it — required by emulator v0.0.7+ on\n * every real input of a submitted proof. {@link Intent.create} is synchronous,\n * so the bytes are supplied rather than fetched; `withPrevTxs` fills them in.\n */\nexport type IntentCoin = WithPrevTx<ExtendedCoin>;\n\n/**\n * Intent proof implementation for Bitcoin message signing.\n *\n * Intent proof defines a standard for signing Bitcoin messages as well as proving\n * ownership of outputs.\n *\n * This namespace provides utilities for creating and validating Intent proof.\n *\n * It is greatly inspired by BIP322.\n * @see https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki\n *\n * @example\n * ```typescript\n * // Create a Intent proof\n * const proof = Intent.create(\n *   \"Hello Bitcoin!\",\n *   [input],\n *   [output]\n * );\n *\n * // Sign the proof\n * const signedProof = await identity.sign(proof);\n *\n */\nexport namespace Intent {\n    // Intent proof is a special invalid psbt containing the inputs to prove ownership\n    // signing the proof means signing the psbt as a regular transaction\n    export type Proof = Transaction;\n\n    /**\n     * Creates a new Intent proof unsigned transaction.\n     *\n     * This function constructs a special transaction that can be signed to prove\n     * ownership of onchain and virtual outputs. The proof includes the message to be\n     * signed and the inputs/outputs that demonstrate ownership.\n     *\n     * @param message - The Intent message to be signed, either raw string of Message object\n     * @param ins - Array of transaction inputs to prove ownership of\n     * @param outputs - Optional array of transaction outputs\n     * @returns An unsigned Intent proof transaction\n     */\n    export function create(\n        message: string | Message,\n        ins: (TransactionInput | IntentCoin)[],\n        outputs: TransactionOutput[] = [],\n    ): Proof {\n        if (typeof message !== \"string\") {\n            message = encodeMessage(message);\n        }\n\n        if (ins.length == 0) throw new Error(\"intent proof requires at least one input\");\n        const inputs = ins.map(prepareCoinAsIntentProofInput);\n        if (!validateInputs(inputs)) throw new Error(\"invalid inputs\");\n        if (!validateOutputs(outputs)) throw new Error(\"invalid outputs\");\n\n        // Create the initial transaction to spend.\n        const toSpend = craftToSpendTx(message, inputs[0].witnessUtxo.script);\n\n        // Create the transaction to sign.\n        return craftToSignTx(toSpend, inputs, outputs, message);\n    }\n\n    /**\n     * Compute the fee paid by an intent proof transaction.\n     *\n     * @param proof - Intent proof transaction\n     * @returns The fee in satoshis\n     */\n    export function fee(proof: Proof): number {\n        let sumOfInputs = 0n;\n        for (let i = 0; i < proof.inputsLength; i++) {\n            const input = proof.getInput(i);\n            if (input.witnessUtxo === undefined)\n                throw new Error(\"intent proof input requires witness utxo\");\n            sumOfInputs += input.witnessUtxo.amount;\n        }\n\n        let sumOfOutputs = 0n;\n        for (let i = 0; i < proof.outputsLength; i++) {\n            const output = proof.getOutput(i);\n            if (output.amount === undefined) throw new Error(\"intent proof output requires amount\");\n            sumOfOutputs += output.amount;\n        }\n\n        if (sumOfOutputs > sumOfInputs) {\n            throw new Error(\n                `intent proof output amount is greater than input amount: ${sumOfOutputs} > ${sumOfInputs}`,\n            );\n        }\n\n        return Number(sumOfInputs - sumOfOutputs);\n    }\n\n    export type RegisterMessage = {\n        type: \"register\";\n        onchain_output_indexes: number[];\n        valid_at: number;\n        expire_at: number;\n        cosigners_public_keys: string[];\n    };\n\n    export type DeleteMessage = {\n        type: \"delete\";\n        expire_at: number;\n    };\n\n    export type GetPendingTxMessage = {\n        type: \"get-pending-tx\";\n        expire_at: number;\n    };\n    export type Message = RegisterMessage | DeleteMessage | GetPendingTxMessage;\n\n    /**\n     * Serialize an intent message to the canonical JSON string used for signing.\n     *\n     * @param message - Intent message payload\n     * @returns Canonical string form of the message\n     */\n    export function encodeMessage(message: Message): string {\n        switch (message.type) {\n            case \"register\":\n                return JSON.stringify({\n                    type: \"register\",\n                    onchain_output_indexes: message.onchain_output_indexes,\n                    valid_at: message.valid_at,\n                    expire_at: message.expire_at,\n                    cosigners_public_keys: message.cosigners_public_keys,\n                });\n            case \"delete\":\n                return JSON.stringify({\n                    type: \"delete\",\n                    expire_at: message.expire_at,\n                });\n            case \"get-pending-tx\":\n                return JSON.stringify({\n                    type: \"get-pending-tx\",\n                    expire_at: message.expire_at,\n                });\n        }\n    }\n}\n\nexport const OP_RETURN_EMPTY_PKSCRIPT = new Uint8Array([OP.RETURN]);\nconst ZERO_32 = new Uint8Array(32).fill(0);\nconst MAX_INDEX = 0xffffffff;\nexport const TAG_INTENT_PROOF = \"ark-intent-proof-message\";\n\ntype ValidatedTxInput = TransactionInput & {\n    witnessUtxo: { script: Uint8Array; amount: bigint };\n    index: number;\n    txid: Bytes;\n};\n\ntype ValidatedTxOutput = TransactionOutput & {\n    amount: bigint;\n    script: Uint8Array;\n};\n\nfunction validateInput(input: TransactionInput): input is ValidatedTxInput {\n    if (input.index === undefined) throw new Error(\"intent proof input requires index\");\n    if (input.txid === undefined) throw new Error(\"intent proof input requires txid\");\n    if (input.witnessUtxo === undefined)\n        throw new Error(\"intent proof input requires witness utxo\");\n    return true;\n}\n\nfunction validateInputs(inputs: TransactionInput[]): inputs is ValidatedTxInput[] {\n    inputs.forEach(validateInput);\n    return true;\n}\n\nfunction validateOutput(output: TransactionOutput): output is ValidatedTxOutput {\n    if (output.amount === undefined) throw new Error(\"intent proof output requires amount\");\n    if (output.script === undefined) throw new Error(\"intent proof output requires script\");\n    return true;\n}\n\nfunction validateOutputs(outputs: TransactionOutput[]): outputs is ValidatedTxOutput[] {\n    outputs.forEach(validateOutput);\n    return true;\n}\n\n/**\n * Creates the \"to_spend\" transaction used by both intent proofs and BIP-322.\n *\n * The message is hashed with the given tagged-hash tag before being placed\n * into the scriptSig as `OP_0 <hash>`.\n *\n * @param message - The message to embed\n * @param pkScript - The scriptPubKey of the signer's address\n * @param tag - Tagged-hash tag (defaults to the Arkade intent proof tag)\n */\nexport function craftToSpendTx(\n    message: string,\n    pkScript: Uint8Array,\n    tag: string = TAG_INTENT_PROOF,\n): Transaction {\n    const messageHash = hashMessage(message, tag);\n    const tx = new Transaction({\n        version: 0,\n    });\n\n    // add input with zero hash and max index\n    tx.addInput({\n        txid: ZERO_32, // zero hash\n        index: MAX_INDEX,\n        sequence: 0,\n    });\n\n    // add output with zero value and provided pkScript\n    tx.addOutput({\n        amount: 0n,\n        script: pkScript,\n    });\n\n    tx.updateInput(0, {\n        finalScriptSig: Script.encode([\"OP_0\", messageHash]),\n    });\n\n    return tx;\n}\n\n/**\n * Creates the \"to_sign\" transaction that is signed to produce the proof.\n *\n * The first input references the `toSpend` transaction; the remaining inputs are\n * the ownership inputs being proven. When no outputs are provided a single\n * value-0 OP_RETURN output is added. The BIP-322 `PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE`\n * (`0x09`) global field is set to the UTF-8 message so a verifier can recompute\n * the `toSpend` commitment from PSBT-internal data alone.\n *\n * @param toSpend - The \"to_spend\" transaction whose id the first input references\n * @param inputs - Validated ownership inputs (input[0] is the toSpend reference)\n * @param outputs - Proof outputs; an OP_RETURN placeholder is used when empty\n * @param message - The canonical message the proof commits to\n * @returns The unsigned \"to_sign\" proof transaction\n */\nfunction craftToSignTx(\n    toSpend: Transaction,\n    inputs: ValidatedTxInput[],\n    outputs: ValidatedTxOutput[],\n    message: string,\n): Transaction {\n    const firstInput = inputs[0];\n\n    // Proof tx is never broadcast onchain — toSpend references a zero-hash\n    // outpoint (see BIP-322). The tx exists only as a sighash commitment\n    // the server verifies signatures against; nLockTime and nSequence carry\n    // no consensus meaning here, they only need to match between signer and\n    // verifier. Use lockTime = 0 (BIP-322 convention) and leave each input's\n    // nSequence untouched.\n    const tx = new Transaction({\n        version: 2,\n        lockTime: 0,\n    });\n\n    // add the first \"toSpend\" input\n    const { unknown: _, ...toSpendInput } = firstInput;\n    tx.addInput({\n        ...toSpendInput,\n        txid: toSpend.id,\n        index: 0,\n        witnessUtxo: {\n            script: firstInput.witnessUtxo.script,\n            amount: 0n,\n        },\n        sighashType: SigHash.ALL,\n    });\n\n    // add other inputs\n    for (const [i, input] of inputs.entries()) {\n        tx.addInput({\n            ...input,\n            sighashType: SigHash.ALL,\n        });\n\n        if (input.unknown?.length) {\n            tx.updateInput(i + 1, {\n                unknown: input.unknown,\n            });\n        }\n    }\n\n    // add the special OP_RETURN output if no outputs are provided\n    if (outputs.length === 0) {\n        outputs = [\n            {\n                amount: 0n,\n                script: OP_RETURN_EMPTY_PKSCRIPT,\n            },\n        ];\n    }\n\n    for (const output of outputs) {\n        tx.addOutput({\n            amount: output.amount,\n            script: output.script,\n        });\n    }\n\n    // Set BIP-322's PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE (0x09) to the UTF-8\n    // message being signed. Lets a co-signer recognise a message-signing PSBT\n    // and recompute the to_spend commitment from PSBT-internal data alone.\n    // @scure/btc-signer exposes no public setter for PSBT global fields (and\n    // marks `Transaction.global` private), so write the global entry\n    // directly. `TransactionGlobal` is derived from scure's own `PSBTGlobal`\n    // key-map (the same way it derives its public `TransactionInput`/\n    // `TransactionOutput` types), so a future scure release that renames or\n    // drops `genericSignedMessage` fails this file at compile time instead\n    // of silently writing into/reading from a stale field name.\n    (tx as unknown as { global: TransactionGlobal }).global.genericSignedMessage =\n        new TextEncoder().encode(message);\n\n    return tx;\n}\n\nfunction hashMessage(message: string, tag: string = TAG_INTENT_PROOF): Uint8Array {\n    return schnorr.utils.taggedHash(tag, new TextEncoder().encode(message));\n}\n\nfunction prepareCoinAsIntentProofInput(coin: IntentCoin | TransactionInput): TransactionInput {\n    if (!(\"tapTree\" in coin)) {\n        return coin;\n    }\n    const vtxoScript = VtxoScript.decode(coin.tapTree);\n    const sequence = getSequence(coin.intentTapLeafScript);\n\n    const unknown = [VtxoTaprootTree.encode(coin.tapTree)];\n    if (coin.extraWitness) {\n        unknown.push(ConditionWitness.encode(coin.extraWitness));\n    }\n    // Lands on proof input i+1 via craftToSignTx; the synthetic input 0 needs\n    // no prevout tx, the emulator synthesises one for it.\n    if (coin.prevTx) {\n        unknown.push(PrevArkTxField.encode(coin.prevTx));\n    }\n\n    return {\n        txid: hex.decode(coin.txid),\n        index: coin.vout,\n        witnessUtxo: {\n            amount: BigInt(coin.value),\n            script: vtxoScript.pkScript,\n        },\n        sequence,\n        tapLeafScript: [coin.intentTapLeafScript],\n        unknown,\n    };\n}\n","import type { EventSourceLike } from \"./eventSource\";\n\nexport type ManagedEventSourceIterator = AsyncGenerator<MessageEvent, void, unknown> & {\n    close(): void;\n};\n\nfunction createAbortError(): Error {\n    const error = new Error(\"EventSource closed\");\n    error.name = \"AbortError\";\n    return error;\n}\n\n/**\n * Creates a close-aware EventSource async iterator.\n *\n * Listeners attach eagerly so events are buffered before the first next() call.\n * close() closes the EventSource, removes listeners, and wakes any pending\n * next() even when the browser does not emit an error from EventSource.close().\n */\nexport function eventSourceIterator(eventSource: EventSourceLike): ManagedEventSourceIterator {\n    const messageQueue: MessageEvent[] = [];\n    const errorQueue: Error[] = [];\n    let messageResolve: ((value: MessageEvent) => void) | null = null;\n    let errorResolve: ((error: Error) => void) | null = null;\n    let closed = false;\n    let cleanedUp = false;\n\n    const cleanup = () => {\n        if (cleanedUp) return;\n        cleanedUp = true;\n        eventSource.removeEventListener(\"message\", messageHandler);\n        eventSource.removeEventListener(\"error\", errorHandler);\n    };\n\n    const close = () => {\n        if (closed) return;\n        closed = true;\n        messageQueue.length = 0;\n        errorQueue.length = 0;\n        eventSource.close();\n        cleanup();\n\n        if (errorResolve) {\n            const reject = errorResolve;\n            messageResolve = null;\n            errorResolve = null;\n            reject(createAbortError());\n        }\n    };\n\n    const messageHandler = (event: MessageEvent) => {\n        if (closed) return;\n        if (messageResolve) {\n            const resolve = messageResolve;\n            messageResolve = null;\n            errorResolve = null;\n            resolve(event);\n        } else {\n            messageQueue.push(event);\n        }\n    };\n\n    const errorHandler = () => {\n        if (closed) return;\n        const error = new Error(\"EventSource error\");\n        error.name = \"EventSourceError\";\n        if (errorResolve) {\n            const reject = errorResolve;\n            messageResolve = null;\n            errorResolve = null;\n            reject(error);\n        } else {\n            errorQueue.push(error);\n        }\n    };\n\n    // Attach listeners immediately so events are buffered\n    // even before the caller starts iterating\n    eventSource.addEventListener(\"message\", messageHandler);\n    eventSource.addEventListener(\"error\", errorHandler);\n\n    const gen = (async function* () {\n        try {\n            while (!closed) {\n                // if we have queued messages, yield the first one, remove it from the queue\n                if (messageQueue.length > 0) {\n                    yield messageQueue.shift()!;\n                    continue;\n                }\n\n                // if we have queued errors, throw the first one, remove it from the queue\n                if (errorQueue.length > 0) {\n                    const error = errorQueue.shift()!;\n                    throw error;\n                }\n\n                // wait for the next message or error\n                const result = await new Promise<MessageEvent>((resolve, reject) => {\n                    messageResolve = resolve;\n                    errorResolve = reject;\n                }).finally(() => {\n                    messageResolve = null;\n                    errorResolve = null;\n                });\n\n                if (!closed && result) {\n                    yield result;\n                }\n            }\n        } finally {\n            closed = true;\n            cleanup();\n            eventSource.close();\n        }\n    })();\n\n    const origReturn = gen.return.bind(gen);\n    const managed = gen as ManagedEventSourceIterator;\n    managed.close = close;\n    managed.return = (value?: void | PromiseLike<void>) => {\n        close();\n        return origReturn(value);\n    };\n\n    return managed;\n}\n\nexport function isEventSourceError(error: unknown): error is Error {\n    return error instanceof Error && error.name === \"EventSourceError\";\n}\n","/**\n * Origin-scoped politeness gate for outbound provider requests.\n *\n * Per-request retry alone cannot survive a rate limiter: under a burst every\n * in-flight request gets the same `429` and the same `Retry-After`, sleeps\n * independently, and wakes in unison to re-trip it — while requests queued\n * behind them learn nothing from the `429` at all. So the backoff state is\n * shared, keyed by **origin** (`/v1/info` and `/v1/indexer/*` are one host\n * behind one limiter). Callers use one of two verbs:\n *\n * - **Wait + report** ({@link OriginRateGate.runHttp}) — indexer and operator\n *   reads, where delaying a send is safe. Waiting is separate from retrying:\n *   an indexer POST waits and reports but is not replayed (see `indexerFetch`).\n * - **Report-only** ({@link OriginRateGate.reportRateLimited}) — intent and\n *   settlement POSTs, which feed the shared signal but never wait or retry:\n *   batch sessions have deadlines, and these POSTs are not idempotent at the\n *   application level, so a certain missed round beats a possible `429`.\n */\n\n/** Per-origin in-flight cap on the wait+report path (the browser per-host cap). */\nconst DEFAULT_MAX_CONCURRENT = 6;\n\n/** Cooldown applied to a `429` that carries no usable `Retry-After`. */\nconst DEFAULT_COOLDOWN_MS = 5_000;\n\n/** Ceiling on a single cooldown, so a bogus `Retry-After` can't wedge the wallet. */\nconst MAX_COOLDOWN_MS = 60_000;\n\n/** Upper bound of the random delay decorrelating waiters released together. */\nconst DEFAULT_JITTER_MS = 500;\n\nexport interface RateGateOptions {\n    maxConcurrent?: number;\n    defaultCooldownMs?: number;\n    maxCooldownMs?: number;\n    jitterMs?: number;\n}\n\ninterface OriginState {\n    /** Epoch ms before which no gated request to this origin may be sent. */\n    blockedUntil: number;\n    /** In-flight gated requests. */\n    active: number;\n    /** FIFO of waiters parked on the concurrency cap. */\n    queue: (() => void)[];\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Parse a `Retry-After` header into milliseconds, in either spec encoding\n * (delta-seconds or HTTP-date). `undefined` when absent or unparseable.\n */\nexport function parseRetryAfterMs(header: string | null | undefined): number | undefined {\n    if (header === null || header === undefined) return undefined;\n    const trimmed = header.trim();\n    // Checked before Number(), which maps \"\" to 0.\n    if (trimmed === \"\") return undefined;\n\n    const seconds = Number(trimmed);\n    // A negative delta is malformed — delta-seconds is non-negative — so there\n    // is no valid reading of it. Fall back to the caller's default instead of\n    // clamping to 0, which would mean \"no cooldown at all\".\n    if (Number.isFinite(seconds)) return seconds < 0 ? undefined : seconds * 1000;\n\n    // Unlike a negative delta, a past HTTP-date is well-formed and does mean\n    // \"retry now\", so it clamps rather than falling back.\n    const at = Date.parse(trimmed);\n    if (!Number.isNaN(at)) return Math.max(0, at - Date.now());\n\n    return undefined;\n}\n\n/** Derive the origin key for a `fetch` input, tolerating the three input shapes. */\nexport function requestOrigin(input: RequestInfo | URL): string {\n    let url: string;\n    if (typeof input === \"string\") {\n        url = input;\n    } else if (input instanceof URL) {\n        url = input.href;\n    } else {\n        url = input.url;\n    }\n    try {\n        return new URL(url).origin;\n    } catch {\n        // Unparseable (e.g. relative): key on the raw string. Grouping is then\n        // wrong, but only ever over- or under-shares a cooldown.\n        return url;\n    }\n}\n\n/** Shared cooldown + concurrency state, keyed by origin. */\nexport class OriginRateGate {\n    private readonly states = new Map<string, OriginState>();\n    private readonly maxConcurrent: number;\n    private readonly defaultCooldownMs: number;\n    private readonly maxCooldownMs: number;\n    private readonly jitterMs: number;\n\n    constructor(options?: RateGateOptions) {\n        this.maxConcurrent = options?.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;\n        this.defaultCooldownMs = options?.defaultCooldownMs ?? DEFAULT_COOLDOWN_MS;\n        this.maxCooldownMs = options?.maxCooldownMs ?? MAX_COOLDOWN_MS;\n        this.jitterMs = options?.jitterMs ?? DEFAULT_JITTER_MS;\n    }\n\n    /**\n     * Run `fn` under the origin's concurrency cap and behind any active\n     * cooldown. Put only the request in `fn`: the slot is released as soon as\n     * it settles, so body parsing doesn't hold one.\n     */\n    async run<T>(input: RequestInfo | URL, fn: () => Promise<T>): Promise<T> {\n        const state = this.stateFor(requestOrigin(input));\n        await this.acquire(state);\n        try {\n            // Re-checked after each sleep, so a `429` seen by another request\n            // while this one waits extends the wait instead of slipping through.\n            for (;;) {\n                const remaining = state.blockedUntil - Date.now();\n                if (remaining <= 0) break;\n                await sleep(remaining + Math.random() * this.jitterMs);\n            }\n            return await fn();\n        } finally {\n            this.release(state);\n        }\n    }\n\n    /**\n     * {@link run} for a request whose response the gate should inspect: a `429`\n     * is recorded *before* the slot is released. Reporting after `run()` resolves\n     * is too late — `release()` hands the slot to the next queued waiter, which\n     * resumes, sees no cooldown, and sends into the limiter that just refused us.\n     *\n     * Prefer this over `run` for anything returning a `Response`.\n     */\n    runHttp(input: RequestInfo | URL, fn: () => Promise<Response>): Promise<Response> {\n        return this.run(input, async () => {\n            const response = await fn();\n            if (response.status === 429) {\n                this.reportRateLimited(input, response.headers?.get(\"retry-after\"));\n            }\n            return response;\n        });\n    }\n\n    /**\n     * Record an observed `429`, pausing every gated request to that origin.\n     * Monotonic: a shorter cooldown never shortens one already in effect.\n     */\n    reportRateLimited(input: RequestInfo | URL, retryAfterHeader?: string | null): void {\n        const cooldown = Math.min(\n            parseRetryAfterMs(retryAfterHeader) ?? this.defaultCooldownMs,\n            this.maxCooldownMs,\n        );\n        const state = this.stateFor(requestOrigin(input));\n        state.blockedUntil = Math.max(state.blockedUntil, Date.now() + cooldown);\n    }\n\n    /** Milliseconds left on `input` origin's cooldown; `0` when not cooling down. */\n    cooldownRemainingMs(input: RequestInfo | URL): number {\n        const state = this.states.get(requestOrigin(input));\n        if (!state) return 0;\n        return Math.max(0, state.blockedUntil - Date.now());\n    }\n\n    /**\n     * Drop all per-origin state, so test suites don't inherit each other's\n     * cooldowns. Waiters queued on the discarded state still drain normally.\n     */\n    reset(): void {\n        this.states.clear();\n    }\n\n    private stateFor(origin: string): OriginState {\n        let state = this.states.get(origin);\n        if (!state) {\n            state = { blockedUntil: 0, active: 0, queue: [] };\n            this.states.set(origin, state);\n        }\n        return state;\n    }\n\n    private acquire(state: OriginState): Promise<void> {\n        if (state.active < this.maxConcurrent) {\n            state.active += 1;\n            return Promise.resolve();\n        }\n        return new Promise<void>((resolve) => {\n            state.queue.push(() => {\n                state.active += 1;\n                resolve();\n            });\n        });\n    }\n\n    private release(state: OriginState): void {\n        state.active -= 1;\n        const next = state.queue.shift();\n        if (next) next();\n    }\n}\n\n/**\n * Process-wide gate shared by every provider fetch path. Origin keying keeps\n * embedders on several operators from cross-throttling each other.\n */\nexport const rateGate = new OriginRateGate();\n","import { TxTreeNode } from \"../tree/txTree\";\nimport { TreeNonces, TreePartialSigs } from \"../tree/signingSession\";\nimport { hex } from \"@scure/base\";\nimport { Vtxo } from \"./indexer\";\nimport type { Outpoint } from \"../wallet\";\nimport { eventSourceIterator, isEventSourceError } from \"./utils\";\nimport {\n    isEventSourceUnavailableError,\n    resolveEventSource,\n    type EventSourceCapable,\n    type EventSourceFactory,\n} from \"./eventSource\";\nimport {\n    ArkErrorName,\n    isArkError,\n    maybeArkError,\n    throwIfHttpUnavailable,\n    toProviderUnavailable,\n} from \"./errors\";\nimport type { IntentFeeConfig } from \"../arkfee\";\nimport { Intent } from \"../intent\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\nimport { fetch } from \"../utils/fetch\";\nimport { rateGate } from \"./rateGate\";\n\n/**\n * Thrown by {@link RestArkProvider} when arkd rejects a request with\n * `DIGEST_MISMATCH` — the client's cached server info was stale (e.g. an\n * operator signer rotation). By the time this surfaces the provider has already\n * refreshed its info and fired `onServerInfoChanged`; the caller should rebuild\n * the request under the fresh server info and retry. Mirrors NArk's\n * `DigestMismatchException` (dotnet-sdk #131): the SDK never silently retries.\n */\nexport class DigestMismatchError extends Error {\n    constructor(message: string) {\n        super(message);\n        this.name = \"DigestMismatchError\";\n    }\n}\n\n/** Output requested during settlement or transaction submission. */\nexport type Output = {\n    /** Destination address, either onchain or Arkade (offchain). */\n    address: string;\n\n    /** Amount to send in satoshis. */\n    amount: bigint;\n};\n\nexport enum SettlementEventType {\n    BatchStarted = \"batch_started\",\n    BatchFinalization = \"batch_finalization\",\n    BatchFinalized = \"batch_finalized\",\n    BatchFailed = \"batch_failed\",\n    TreeSigningStarted = \"tree_signing_started\",\n    TreeNonces = \"tree_nonces\",\n    TreeTx = \"tree_tx\",\n    TreeSignature = \"tree_signature\",\n    StreamStarted = \"stream_started\",\n}\n\nexport type BatchFinalizationEvent = {\n    type: SettlementEventType.BatchFinalization;\n    id: string;\n    commitmentTx: string;\n};\n\nexport type BatchFinalizedEvent = {\n    type: SettlementEventType.BatchFinalized;\n    id: string;\n    commitmentTxid: string;\n};\n\nexport type BatchFailedEvent = {\n    type: SettlementEventType.BatchFailed;\n    id: string;\n    reason: string;\n};\n\nexport type TreeSigningStartedEvent = {\n    type: SettlementEventType.TreeSigningStarted;\n    id: string;\n    cosignersPublicKeys: string[];\n    unsignedCommitmentTx: string;\n};\n\nexport type TreeNoncesEvent = {\n    type: SettlementEventType.TreeNonces;\n    id: string;\n    topic: string[];\n    txid: string;\n    /** Musig2 public nonces keyed by cosigner public key. */\n    nonces: TreeNonces;\n};\n\nexport type BatchStartedEvent = {\n    type: SettlementEventType.BatchStarted;\n    id: string;\n    intentIdHashes: string[];\n    batchExpiry: bigint;\n};\n\nexport type TreeTxEvent = {\n    type: SettlementEventType.TreeTx;\n    id: string;\n    topic: string[];\n    batchIndex: number;\n    chunk: TxTreeNode;\n};\n\nexport type TreeSignatureEvent = {\n    type: SettlementEventType.TreeSignature;\n    id: string;\n    topic: string[];\n    batchIndex: number;\n    txid: string;\n    signature: string;\n};\n\nexport type StreamStartedEvent = {\n    type: SettlementEventType.StreamStarted;\n    id: string;\n};\n\nexport type SettlementEvent =\n    | BatchFinalizationEvent\n    | BatchFinalizedEvent\n    | BatchFailedEvent\n    | TreeSigningStartedEvent\n    | TreeNoncesEvent\n    | BatchStartedEvent\n    | TreeTxEvent\n    | TreeSignatureEvent\n    | StreamStartedEvent;\n\nexport interface ScheduledSession {\n    duration: bigint;\n    fees: FeeInfo;\n    nextEndTime: bigint;\n    nextStartTime: bigint;\n    period: bigint;\n}\n\nexport interface FeeInfo {\n    intentFee: IntentFeeConfig;\n    txFeeRate: string;\n}\n\nexport interface PendingTx {\n    arkTxid: string;\n    finalArkTx: string;\n    signedCheckpointTxs: string[];\n}\n\nexport interface DeprecatedSigner {\n    /**\n     * Unix timestamp (seconds) after which the server no longer accepts this\n     * signer's VTXOs as cooperative-migration inputs. arkd advertises this as a\n     * non-nullable field, so it is always present: `0n` is the sentinel for \"no\n     * cutoff advertised\" — the deprecated signer is due for migration\n     * immediately ({@link classifyContractSigner} maps `0n` to `DUE_NOW`). A\n     * positive value is a real deadline (`MIGRATABLE` until it passes, then\n     * `EXPIRED`).\n     */\n    cutoffDate: bigint;\n    pubkey: string;\n}\n\nexport type ServiceStatus = Record<string, string>;\n\nexport interface ArkInfo {\n    boardingExitDelay: bigint;\n    checkpointTapscript: string;\n    deprecatedSigners: DeprecatedSigner[];\n    digest: string;\n    dust: bigint;\n    fees: FeeInfo;\n    forfeitAddress: string;\n    forfeitPubkey: string;\n    network: string;\n    scheduledSession?: ScheduledSession;\n    serviceStatus: ServiceStatus;\n    sessionDuration: bigint;\n    signerPubkey: string;\n    unilateralExitDelay: bigint;\n    /**\n     * Sweep delay the operator advertises for the shared batch output.\n     * `undefined` when not advertised — never coerce to `0n`, which would\n     * satisfy any floor comparison.\n     */\n    vtxoTreeExpiry?: bigint;\n    /**\n     * Weight budget an ark transaction must stay under; the server answers\n     * `TX_TOO_LARGE` past it.\n     *\n     * `undefined` when not advertised — a server that omits the field and one\n     * that sends `0` both mean \"no limit stated\". Never `0n`, which would read\n     * as a server that accepts no transaction at all.\n     */\n    maxTxWeight?: bigint;\n    /**\n     * Maximum OP_RETURN outputs the server accepts per transaction.\n     *\n     * `undefined` when not advertised — a server that omits the field and one\n     * that sends `0` both mean \"no limit stated\". Never `0n`, which would read\n     * as a server that forbids them outright.\n     */\n    maxOpReturnOutputs?: bigint;\n    /**\n     * Maximum boarding input amount.\n     *\n     * @remarks\n     * `-1` means unlimited, while `0` disables boarding.\n     */\n    utxoMaxAmount: bigint;\n    utxoMinAmount: bigint;\n    version: string;\n    /**\n     * Maximum virtual output amount.\n     *\n     * @remarks\n     * `-1` means unlimited.\n     */\n    vtxoMaxAmount: bigint;\n    vtxoMinAmount: bigint;\n}\n\n/** Signed intent payload sent to the Arkade server. */\nexport interface SignedIntent<T extends Intent.Message> {\n    /** Base64-encoded signed proof transaction. */\n    proof: string;\n\n    /** Intent message payload associated with the proof. */\n    message: T;\n}\n\n/** Transaction notification emitted by the Arkade server stream. */\nexport interface TxNotification {\n    /** Transaction id. */\n    txid: string;\n\n    /** Raw transaction payload. */\n    tx: string;\n\n    /** Virtual outputs spent by the transaction. */\n    spentVtxos: Vtxo[];\n\n    /** Virtual outputs made spendable by the transaction. */\n    spendableVtxos: Vtxo[];\n\n    /** Optional checkpoint transactions associated with the notification. */\n    checkpointTxs?: Record<string, { txid: string; tx: string }>;\n}\n\n/**\n * A `sweepTx` notification. Only a sweep carries swept outpoints, so only this\n * arm declares them: reading `sweptVtxos` off another arm is a type error, and\n * a sweep handler never has to narrow the field it came for.\n */\nexport interface SweepTxNotification extends TxNotification {\n    /**\n     * Outpoints the transaction swept — outpoints rather than virtual outputs,\n     * because a swept output is gone: the server has nothing left to describe\n     * beyond where it was. Empty when the sweep touched none of them.\n     */\n    sweptVtxos: Outpoint[];\n}\n\n/**\n * One frame of {@link ArkProvider.getTransactionsStream}. Exactly one arm is\n * set; an unrecognized frame is dropped rather than yielded.\n */\nexport interface TxNotificationEvent {\n    commitmentTx?: TxNotification;\n    arkTx?: TxNotification;\n    sweepTx?: SweepTxNotification;\n}\n\nexport interface ArkProvider {\n    /** Fetch Arkade server configuration and fee settings. */\n    getInfo(): Promise<ArkInfo>;\n\n    /** Submit a signed Arkade transaction and its checkpoint transactions. */\n    submitTx(\n        signedArkTx: string,\n        checkpointTxs: string[],\n    ): Promise<{\n        arkTxid: string;\n        finalArkTx: string;\n        signedCheckpointTxs: string[];\n    }>;\n\n    /** Finalize a previously submitted Arkade transaction. */\n    finalizeTx(arkTxid: string, finalCheckpointTxs: string[]): Promise<void>;\n\n    /** Register a signed intent with the Arkade server. */\n    registerIntent(intent: SignedIntent<Intent.RegisterMessage>): Promise<string>;\n\n    /** Delete a previously registered intent. */\n    deleteIntent(intent: SignedIntent<Intent.DeleteMessage>): Promise<void>;\n\n    /** Confirm an already registered intent id. */\n    confirmRegistration(intentId: string): Promise<void>;\n\n    /** Submit musig2 tree nonces for a batch signing session. */\n    submitTreeNonces(batchId: string, pubkey: string, nonces: TreeNonces): Promise<void>;\n\n    /** Submit musig2 partial signatures for a batch signing session. */\n    submitTreeSignatures(\n        batchId: string,\n        pubkey: string,\n        signatures: TreePartialSigs,\n    ): Promise<void>;\n\n    /** Submit signed forfeit transactions for cooperative settlement. */\n    submitSignedForfeitTxs(signedForfeitTxs: string[], signedCommitmentTx?: string): Promise<void>;\n\n    /** Open the settlement event stream for the given topics. */\n    getEventStream(signal: AbortSignal, topics: string[]): AsyncIterableIterator<SettlementEvent>;\n\n    /** Stream transaction notifications emitted by the Arkade server. */\n    getTransactionsStream(signal: AbortSignal): AsyncIterableIterator<TxNotificationEvent>;\n\n    /** Fetch pending transactions for a signed get-pending-tx intent. */\n    getPendingTxs(intent: SignedIntent<Intent.GetPendingTxMessage>): Promise<PendingTx[]>;\n}\n\n/**\n * Reads a transaction limit the operator advertises on `GetInfo`.\n *\n * `max_tx_weight` and `max_op_return_outputs` are non-optional `int64` in\n * `GetInfoResponse`, and the gateway marshals with EmitUnpopulated, so an arkd\n * carrying the fields but not configuring them sends `\"0\"` instead of omitting\n * them. Field absent (an arkd predating them) and field zero are the same\n * statement — the operator did not advertise a limit — so both answer\n * `undefined`. `0n` would read as a server that accepts no transaction at all\n * and forbids OP_RETURN outright, which is the opposite of \"did not say\".\n * NArk reads the same zero as unset (`SpendingService.GetMaxOpReturnOutputs`).\n */\nfunction advertisedLimit(fromServer: unknown): bigint | undefined {\n    if (fromServer == null) return undefined;\n    const limit = BigInt(fromServer as string | number | bigint);\n    return limit > 0n ? limit : undefined;\n}\n\n/**\n * REST-based Arkade provider implementation.\n *\n * @see https://buf.build/arkade-os/arkd/docs/main:ark.v1#ark.v1.ArkService\n * @example\n * ```typescript\n * const provider = new RestArkProvider('https://arkade.computer');\n * const info = await provider.getInfo();\n * ```\n */\nexport class RestArkProvider implements ArkProvider {\n    /** Overrides {@link configureEventSource} for this provider's streams. */\n    protected readonly eventSource?: EventSourceFactory;\n\n    constructor(\n        public serverUrl: string = DEFAULT_ARKADE_SERVER_URL,\n        options: EventSourceCapable = {},\n    ) {\n        this.eventSource = options.eventSource;\n    }\n\n    /**\n     * Last server-info digest seen from {@link getInfo}. Sent as `X-Digest`\n     * so arkd can reject stale client configuration.\n     */\n    private _digest = \"\";\n    private _hasServerInfo = false;\n    private _suppressNextGetInfoChangeEmit = false;\n\n    private _serverInfoListeners = new Set<(info: ArkInfo) => void>();\n\n    /**\n     * Subscribe to server-info changes. Fired after a stale-info\n     * `DIGEST_MISMATCH` refresh or when {@link getInfo} observes a changed digest.\n     * Returns an unsubscribe function.\n     */\n    onServerInfoChanged(listener: (info: ArkInfo) => void): () => void {\n        this._serverInfoListeners.add(listener);\n        return () => {\n            this._serverInfoListeners.delete(listener);\n        };\n    }\n\n    private emitServerInfoChanged(info: ArkInfo): void {\n        for (const listener of this._serverInfoListeners) {\n            try {\n                listener(info);\n            } catch (e) {\n                console.warn(\"onServerInfoChanged listener threw\", e);\n            }\n        }\n    }\n\n    /**\n     * `fetch` wrapper for arkd requests that participates in server-info digest\n     * negotiation. Sends the cached `X-Digest`; when arkd rejects a request with\n     * `DIGEST_MISMATCH`, refreshes {@link getInfo} (updating the digest), fires\n     * {@link onServerInfoChanged}, and THROWS {@link DigestMismatchError} — it\n     * never silently retries, since the in-flight request was built against the\n     * now-stale config. Dormant until arkd returns the error — then it is the\n     * instant, event-driven signer-rotation trigger. {@link getInfo} itself never\n     * routes through here: it is the refresh path and must not be digest-gated.\n     */\n    private async authedFetch(url: string, init: RequestInit): Promise<Response> {\n        // Read the cached digest once, in the method body where `this` is\n        // unambiguously the provider, and build the header set imperatively. A\n        // prior nested-arrow form (`() => this._digest ? ... : init`) read\n        // `this._digest` as empty on some CI runners and dropped the header.\n        const digest = this._digest;\n        const headers: Record<string, string> = {\n            ...(init.headers as Record<string, string> | undefined),\n        };\n        if (digest) headers[\"X-Digest\"] = digest;\n        let response: Response;\n        try {\n            response = await fetch(url, { ...init, headers });\n        } catch (err) {\n            // Server unreachable: surface a typed retryable unavailable error so\n            // cooperative flows fail with it rather than leaking a raw FetchError.\n            throw toProviderUnavailable(err, \"arkade\");\n        }\n        if (response.ok) return response;\n        // Report-only (see rateGate): this POST is never delayed or retried.\n        if (response.status === 429) {\n            rateGate.reportRateLimited(url, response.headers?.get(\"retry-after\"));\n        }\n        // Read the body first: error classification must branch on its content,\n        // not just the HTTP status. arkd is behind grpc-gateway, which renders\n        // application-level errors across the 4xx AND 5xx range (gRPC INTERNAL ->\n        // HTTP 500), so status alone can't tell a terminal rejection apart from a\n        // genuine availability failure.\n        let body: string;\n        try {\n            body = await response.clone().text();\n        } catch (e) {\n            // Couldn't read the body to classify it (e.g. the connection dropped\n            // mid-body). Fall back to status-only classification so a genuine\n            // 429/5xx still surfaces as retryable; digest detection is only\n            // deferred to the next getInfo(), not lost.\n            console.warn(\"authedFetch could not read response body for digest check\", e);\n            throwIfHttpUnavailable(response, \"arkade\");\n            return response;\n        }\n        // Only arkd's *structured* digest error counts: a grpc-gateway\n        // ErrorDetails whose name is DIGEST_MISMATCH (arkd's X-Digest guard,\n        // v0.9.9-rc.1 #1104), parsed via the shared maybeArkError. A raw\n        // substring match would let an unrelated error body that merely mentions\n        // the token trigger a spurious refresh + signer rotation.\n        const arkError = maybeArkError(new Error(body));\n        // A structured arkd error means the operator is up and deliberately\n        // rejecting the request — terminal, even when grpc-gateway renders it as a\n        // 5xx. Only a non-structured 429/5xx (a bare proxy/gateway failure) is a\n        // retryable availability condition.\n        if (!arkError) throwIfHttpUnavailable(response, \"arkade\");\n        if (!isArkError(arkError, ArkErrorName.DIGEST_MISMATCH)) return response;\n        // arkd rejected this request because our cached server info is stale\n        // (e.g. the operator rotated its signer). Mirror NArk's BuildVersionHandler\n        // (dotnet-sdk #131): clear the digest, refetch info, fire onServerInfoChanged\n        // so the wallet re-derives signer-dependent state, then THROW. The SDK does\n        // NOT silently retry — the in-flight request was built against the old config,\n        // so the caller must rebuild and retry it under the refreshed server info.\n        this._digest = \"\";\n        this._suppressNextGetInfoChangeEmit = true;\n        let info: ArkInfo;\n        try {\n            info = await this.getInfo();\n        } finally {\n            this._suppressNextGetInfoChangeEmit = false;\n        }\n        this.emitServerInfoChanged(info);\n        throw new DigestMismatchError(\n            \"Arkade server reported a configuration digest mismatch; server info was \" +\n                \"refreshed. Rebuild and retry the request under the new server info.\",\n        );\n    }\n\n    async getInfo(): Promise<ArkInfo> {\n        const url = `${this.serverUrl}/v1/info`;\n        // Wait + report (see rateGate): shares an origin, and a limiter, with\n        // the indexer.\n        const response = await rateGate.runHttp(url, () => fetch(url));\n        if (!response.ok) {\n            const errorText = await response.text();\n            // A 429 or 5xx means the operator is up but temporarily unable to\n            // serve — a retryable availability failure, not a config/auth error.\n            // Surface it as a typed unavailable error so wallet boot can fall\n            // back to a cached server-info snapshot. Pass the body so a 5xx that\n            // actually carries a structured arkd error (grpc-gateway maps gRPC\n            // INTERNAL -> HTTP 500) stays terminal instead. `fetch` transport\n            // failures (server unreachable) are already surfaced as FetchError\n            // upstream.\n            throwIfHttpUnavailable(response, \"arkade\", errorText);\n            handleError(errorText, `Failed to get server info: ${response.statusText}`);\n        }\n        const fromServer = await response.json();\n        const info: ArkInfo = {\n            boardingExitDelay: BigInt(fromServer.boardingExitDelay ?? 0),\n            checkpointTapscript: fromServer.checkpointTapscript ?? \"\",\n            deprecatedSigners:\n                fromServer.deprecatedSigners?.map((signer: any) => ({\n                    // arkd advertises `cutoffDate` as a non-nullable field, so it\n                    // is always a bigint here — `0n` is the sentinel for \"no\n                    // cutoff\" (the classifier maps it to DUE_NOW). The grpc-gateway\n                    // marshals with EmitUnpopulated, so an unset `cutoff_date`\n                    // already arrives as `\"0\"`; a genuinely missing field defaults\n                    // to `0n` too. Never collapse to `undefined`.\n                    cutoffDate: BigInt(signer.cutoffDate ?? 0),\n                    pubkey: signer.pubkey ?? \"\",\n                })) ?? [],\n            digest: fromServer.digest ?? \"\",\n            dust: BigInt(fromServer.dust ?? 0),\n            fees: {\n                intentFee: fromServer.fees?.intentFee ?? {},\n                txFeeRate: fromServer?.fees?.txFeeRate ?? \"\",\n            },\n            forfeitAddress: fromServer.forfeitAddress ?? \"\",\n            forfeitPubkey: fromServer.forfeitPubkey ?? \"\",\n            network: fromServer.network ?? \"\",\n            scheduledSession:\n                \"scheduledSession\" in fromServer && fromServer.scheduledSession != null\n                    ? {\n                          duration: BigInt(fromServer.scheduledSession.duration ?? 0),\n                          nextStartTime: BigInt(fromServer.scheduledSession.nextStartTime ?? 0),\n                          nextEndTime: BigInt(fromServer.scheduledSession.nextEndTime ?? 0),\n                          period: BigInt(fromServer.scheduledSession.period ?? 0),\n                          fees: fromServer.scheduledSession.fees ?? {},\n                      }\n                    : undefined,\n            serviceStatus: fromServer.serviceStatus ?? {},\n            sessionDuration: BigInt(fromServer.sessionDuration ?? 0),\n            signerPubkey: fromServer.signerPubkey ?? \"\",\n            unilateralExitDelay: BigInt(fromServer.unilateralExitDelay ?? 0),\n            vtxoTreeExpiry:\n                fromServer.vtxoTreeExpiry != null ? BigInt(fromServer.vtxoTreeExpiry) : undefined,\n            maxTxWeight: advertisedLimit(fromServer.maxTxWeight),\n            maxOpReturnOutputs: advertisedLimit(fromServer.maxOpReturnOutputs),\n            utxoMaxAmount: BigInt(fromServer.utxoMaxAmount ?? -1),\n            utxoMinAmount: BigInt(fromServer.utxoMinAmount ?? 0),\n            version: fromServer.version ?? \"\",\n            vtxoMaxAmount: BigInt(fromServer.vtxoMaxAmount ?? -1),\n            vtxoMinAmount: BigInt(fromServer.vtxoMinAmount ?? 0),\n        };\n        const previousDigest = this._digest;\n        const hadServerInfo = this._hasServerInfo;\n        this._digest = info.digest;\n        this._hasServerInfo = true;\n        // A refresh can observe server-info changes before any digest-gated\n        // request fails. `_hasServerInfo` makes an empty previous digest count\n        // as a real value; `DIGEST_MISMATCH` emits separately after its refetch.\n        if (\n            hadServerInfo &&\n            previousDigest !== info.digest &&\n            !this._suppressNextGetInfoChangeEmit\n        ) {\n            this.emitServerInfoChanged(info);\n        }\n        return info;\n    }\n\n    async submitTx(\n        signedArkTx: string,\n        checkpointTxs: string[],\n    ): Promise<{\n        arkTxid: string;\n        finalArkTx: string;\n        signedCheckpointTxs: string[];\n    }> {\n        const url = `${this.serverUrl}/v1/tx/submit`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                signedArkTx,\n                checkpointTxs,\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to submit virtual transaction: ${errorText}`);\n        }\n\n        const data = await response.json();\n        return {\n            arkTxid: data.arkTxid,\n            finalArkTx: data.finalArkTx,\n            signedCheckpointTxs: data.signedCheckpointTxs,\n        };\n    }\n\n    async finalizeTx(arkTxid: string, finalCheckpointTxs: string[]): Promise<void> {\n        const url = `${this.serverUrl}/v1/tx/finalize`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                arkTxid,\n                finalCheckpointTxs,\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to finalize offchain transaction: ${errorText}`);\n        }\n    }\n\n    async registerIntent(intent: SignedIntent<Intent.RegisterMessage>): Promise<string> {\n        const url = `${this.serverUrl}/v1/batch/registerIntent`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                intent: {\n                    proof: intent.proof,\n                    message: Intent.encodeMessage(intent.message),\n                },\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to register intent: ${errorText}`);\n        }\n\n        const data = await response.json();\n        return data.intentId;\n    }\n\n    async deleteIntent(intent: SignedIntent<Intent.DeleteMessage>): Promise<void> {\n        const url = `${this.serverUrl}/v1/batch/deleteIntent`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                intent: {\n                    proof: intent.proof,\n                    message: Intent.encodeMessage(intent.message),\n                },\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to delete intent: ${errorText}`);\n        }\n    }\n\n    async confirmRegistration(intentId: string): Promise<void> {\n        const url = `${this.serverUrl}/v1/batch/ack`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                intentId,\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to confirm registration: ${errorText}`);\n        }\n    }\n\n    async submitTreeNonces(batchId: string, pubkey: string, nonces: TreeNonces): Promise<void> {\n        const url = `${this.serverUrl}/v1/batch/tree/submitNonces`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                batchId,\n                pubkey,\n                treeNonces: encodeMusig2Nonces(nonces),\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to submit tree nonces: ${errorText}`);\n        }\n    }\n\n    async submitTreeSignatures(\n        batchId: string,\n        pubkey: string,\n        signatures: TreePartialSigs,\n    ): Promise<void> {\n        const url = `${this.serverUrl}/v1/batch/tree/submitSignatures`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                batchId,\n                pubkey,\n                treeSignatures: encodeMusig2Signatures(signatures),\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to submit tree signatures: ${errorText}`);\n        }\n    }\n\n    async submitSignedForfeitTxs(\n        signedForfeitTxs: string[],\n        signedCommitmentTx?: string,\n    ): Promise<void> {\n        const url = `${this.serverUrl}/v1/batch/submitForfeitTxs`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                signedForfeitTxs: signedForfeitTxs,\n                signedCommitmentTx: signedCommitmentTx,\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to submit forfeit transactions: ${response.statusText}`);\n        }\n    }\n\n    getEventStream(signal: AbortSignal, topics: string[]): AsyncIterableIterator<SettlementEvent> {\n        const url = `${this.serverUrl}/v1/batch/events`;\n        const queryParams =\n            topics.length > 0\n                ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join(\"&\")}`\n                : \"\";\n\n        // The EventSource is allocated inside the generator body so that\n        // abandoning the returned iterator before iteration starts does not\n        // leak the underlying SSE connection. `return()` is overridden below\n        // so that closing the generator also closes the connection even when\n        // the body is currently suspended at an await point.\n        let iterator: ReturnType<typeof eventSourceIterator> | null = null;\n        const closeIterator = () => iterator?.close();\n\n        // eslint-disable-next-line @typescript-eslint/no-this-alias\n        const self = this;\n        const gen = (async function* () {\n            const abortHandler = closeIterator;\n            signal?.addEventListener(\"abort\", abortHandler);\n\n            try {\n                while (!signal?.aborted) {\n                    const currentIterator = eventSourceIterator(\n                        resolveEventSource(self.eventSource)(url + queryParams),\n                    );\n                    iterator = currentIterator;\n\n                    try {\n                        for await (const event of currentIterator) {\n                            if (signal?.aborted) break;\n\n                            try {\n                                const data = JSON.parse(event.data);\n                                const settlementEvent = self.parseSettlementEvent(data);\n                                if (settlementEvent) {\n                                    yield settlementEvent;\n                                }\n                            } catch (err) {\n                                console.error(\"Failed to parse event:\", err);\n                                throw err;\n                            }\n                        }\n                    } catch (error) {\n                        if (\n                            signal?.aborted ||\n                            (error instanceof Error && error.name === \"AbortError\")\n                        ) {\n                            break;\n                        }\n\n                        // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n                        if (isFetchTimeoutError(error)) {\n                            console.debug(\"Timeout error ignored\");\n                            continue;\n                        }\n\n                        if (isEventSourceError(error)) {\n                            throw error;\n                        }\n\n                        // A missing EventSource is an environment fact, not a\n                        // stream failure: the caller reports it once (see\n                        // ContractWatcher), where this loop would log it on\n                        // every reconnect attempt.\n                        if (isEventSourceUnavailableError(error)) throw error;\n\n                        console.error(\"Event stream error:\", error);\n                        throw error;\n                    } finally {\n                        currentIterator.close();\n                        iterator = null;\n                    }\n                }\n            } finally {\n                signal?.removeEventListener(\"abort\", abortHandler);\n                closeIterator();\n            }\n        })();\n\n        const origReturn = gen.return.bind(gen);\n        gen.return = (value) => {\n            closeIterator();\n            return origReturn(value);\n        };\n\n        return gen;\n    }\n\n    getTransactionsStream(signal: AbortSignal): AsyncIterableIterator<TxNotificationEvent> {\n        const url = `${this.serverUrl}/v1/txs`;\n        let iterator: ReturnType<typeof eventSourceIterator> | null = null;\n        const closeIterator = () => iterator?.close();\n\n        // eslint-disable-next-line @typescript-eslint/no-this-alias\n        const self = this;\n        const gen = (async function* () {\n            const abortHandler = closeIterator;\n            signal?.addEventListener(\"abort\", abortHandler);\n\n            try {\n                while (!signal?.aborted) {\n                    try {\n                        const currentIterator = eventSourceIterator(\n                            resolveEventSource(self.eventSource)(url),\n                        );\n                        iterator = currentIterator;\n\n                        for await (const event of currentIterator) {\n                            if (signal?.aborted) break;\n\n                            try {\n                                const data = JSON.parse(event.data);\n                                const txNotification = self.parseTransactionNotification(data);\n                                if (txNotification) {\n                                    yield txNotification;\n                                }\n                            } catch (err) {\n                                console.error(\"Failed to parse transaction notification:\", err);\n                                throw err;\n                            }\n                        }\n                    } catch (error) {\n                        if (\n                            signal?.aborted ||\n                            (error instanceof Error && error.name === \"AbortError\")\n                        ) {\n                            break;\n                        }\n\n                        // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n                        if (isFetchTimeoutError(error)) {\n                            console.debug(\"Timeout error ignored\");\n                            continue;\n                        }\n\n                        if (isEventSourceError(error)) {\n                            throw error;\n                        }\n\n                        // A missing EventSource is an environment fact, not a\n                        // stream failure: the caller reports it once (see\n                        // ContractWatcher), where this loop would log it on\n                        // every reconnect attempt.\n                        if (isEventSourceUnavailableError(error)) throw error;\n\n                        console.error(\"Transaction stream error:\", error);\n                        throw error;\n                    } finally {\n                        closeIterator();\n                        iterator = null;\n                    }\n                }\n            } finally {\n                signal?.removeEventListener(\"abort\", abortHandler);\n                closeIterator();\n            }\n        })();\n\n        const origReturn = gen.return.bind(gen);\n        gen.return = (value) => {\n            closeIterator();\n            return origReturn(value);\n        };\n\n        return gen;\n    }\n\n    async getPendingTxs(intent: SignedIntent<Intent.GetPendingTxMessage>): Promise<PendingTx[]> {\n        const url = `${this.serverUrl}/v1/tx/pending`;\n        const response = await this.authedFetch(url, {\n            method: \"POST\",\n            headers: {\n                \"Content-Type\": \"application/json\",\n            },\n            body: JSON.stringify({\n                intent: {\n                    proof: intent.proof,\n                    message: Intent.encodeMessage(intent.message),\n                },\n            }),\n        });\n\n        if (!response.ok) {\n            const errorText = await response.text();\n            handleError(errorText, `Failed to get pending transactions: ${errorText}`);\n        }\n\n        const data = await response.json();\n        return data.pendingTxs;\n    }\n\n    protected parseSettlementEvent(\n        data: ProtoTypes.GetEventStreamResponse,\n    ): SettlementEvent | null {\n        // Check for BatchStarted event\n        if (data.batchStarted) {\n            return {\n                type: SettlementEventType.BatchStarted,\n                id: data.batchStarted.id,\n                intentIdHashes: data.batchStarted.intentIdHashes,\n                batchExpiry: BigInt(data.batchStarted.batchExpiry),\n            };\n        }\n\n        // Check for BatchFinalization event\n        if (data.batchFinalization) {\n            return {\n                type: SettlementEventType.BatchFinalization,\n                id: data.batchFinalization.id,\n                commitmentTx: data.batchFinalization.commitmentTx,\n            };\n        }\n\n        // Check for BatchFinalized event\n        if (data.batchFinalized) {\n            return {\n                type: SettlementEventType.BatchFinalized,\n                id: data.batchFinalized.id,\n                commitmentTxid: data.batchFinalized.commitmentTxid,\n            };\n        }\n\n        // Check for BatchFailed event\n        if (data.batchFailed) {\n            return {\n                type: SettlementEventType.BatchFailed,\n                id: data.batchFailed.id,\n                reason: data.batchFailed.reason,\n            };\n        }\n\n        // Check for TreeSigningStarted event\n        if (data.treeSigningStarted) {\n            return {\n                type: SettlementEventType.TreeSigningStarted,\n                id: data.treeSigningStarted.id,\n                cosignersPublicKeys: data.treeSigningStarted.cosignersPubkeys,\n                unsignedCommitmentTx: data.treeSigningStarted.unsignedCommitmentTx,\n            };\n        }\n\n        // Check for TreeNoncesAggregated event\n        if (data.treeNoncesAggregated) {\n            // skip treeNoncesAggregated event, deprecated\n            return null;\n        }\n\n        if (data.treeNonces) {\n            return {\n                type: SettlementEventType.TreeNonces,\n                id: data.treeNonces.id,\n                topic: data.treeNonces.topic,\n                txid: data.treeNonces.txid,\n                nonces: decodeMusig2Nonces(data.treeNonces.nonces), // pubkey -> public nonce\n            };\n        }\n\n        // Check for TreeTx event\n        if (data.treeTx) {\n            const children = Object.fromEntries(\n                Object.entries(data.treeTx.children).map(([outputIndex, txid]) => {\n                    return [parseInt(outputIndex), txid];\n                }),\n            );\n\n            return {\n                type: SettlementEventType.TreeTx,\n                id: data.treeTx.id,\n                topic: data.treeTx.topic,\n                batchIndex: data.treeTx.batchIndex,\n                chunk: {\n                    txid: data.treeTx.txid,\n                    tx: data.treeTx.tx,\n                    children,\n                },\n            };\n        }\n\n        if (data.treeSignature) {\n            return {\n                type: SettlementEventType.TreeSignature,\n                id: data.treeSignature.id,\n                topic: data.treeSignature.topic,\n                batchIndex: data.treeSignature.batchIndex,\n                txid: data.treeSignature.txid,\n                signature: data.treeSignature.signature,\n            };\n        }\n\n        if (data.streamStarted) {\n            return {\n                type: SettlementEventType.StreamStarted,\n                id: data.streamStarted.id,\n            };\n        }\n\n        // Skip heartbeat events\n        if (data.heartbeat) {\n            return null;\n        }\n\n        console.warn(\"Unknown event type:\", data);\n        return null;\n    }\n\n    protected parseTransactionNotification(\n        data: ProtoTypes.GetTransactionsStreamResponse,\n    ): TxNotificationEvent | null {\n        if (data.commitmentTx) {\n            return { commitmentTx: mapTxNotification(data.commitmentTx) };\n        }\n\n        if (data.arkTx) {\n            return { arkTx: mapTxNotification(data.arkTx) };\n        }\n\n        if (data.sweepTx) {\n            // proto3 omits an empty repeated field, so an absent `swept_vtxos`\n            // means the sweep took nothing — not that the frame is silent.\n            return {\n                sweepTx: {\n                    ...mapTxNotification(data.sweepTx),\n                    sweptVtxos: data.sweepTx.sweptVtxos ?? [],\n                },\n            };\n        }\n\n        // Skip heartbeat events\n        if (data.heartbeat) {\n            return null;\n        }\n\n        console.warn(\"Unknown transaction notification type:\", data);\n        return null;\n    }\n}\n\nfunction encodeMusig2Nonces(nonces: TreeNonces): Record<string, string> {\n    const noncesObject: Record<string, string> = {};\n    for (const [txid, nonce] of nonces) {\n        noncesObject[txid] = hex.encode(nonce.pubNonce);\n    }\n    return noncesObject;\n}\n\nfunction encodeMusig2Signatures(signatures: TreePartialSigs): Record<string, string> {\n    const sigObject: Record<string, string> = {};\n    for (const [txid, sig] of signatures) {\n        sigObject[txid] = hex.encode(sig.encode());\n    }\n    return sigObject;\n}\n\nfunction decodeMusig2Nonces(noncesObject: Record<string, string>): TreeNonces {\n    return new Map(\n        Object.entries(noncesObject).map(([txid, nonce]) => {\n            if (typeof nonce !== \"string\") {\n                throw new Error(\"invalid nonce\");\n            }\n            return [txid, { pubNonce: hex.decode(nonce) }];\n        }),\n    );\n}\n\n// ProtoTypes namespace defines unexported types representing the raw data received from the server\nnamespace ProtoTypes {\n    interface BatchStartedEvent {\n        id: string;\n        intentIdHashes: string[];\n        batchExpiry: number;\n    }\n\n    interface BatchFailed {\n        id: string;\n        reason: string;\n    }\n\n    export interface BatchFinalizationEvent {\n        id: string;\n        commitmentTx: string;\n    }\n\n    interface BatchFinalizedEvent {\n        id: string;\n        commitmentTxid: string;\n    }\n\n    interface TreeSigningStartedEvent {\n        id: string;\n        cosignersPubkeys: string[];\n        unsignedCommitmentTx: string;\n    }\n\n    interface TreeNoncesAggregatedEvent {\n        id: string;\n        treeNonces: Record<string, string>;\n    }\n\n    interface TreeNoncesEvent {\n        id: string;\n        topic: string[];\n        txid: string;\n        nonces: Record<string, string>;\n    }\n\n    interface TreeTxEvent {\n        id: string;\n        topic: string[];\n        batchIndex: number;\n        txid: string;\n        tx: string;\n        children: Record<string, string>;\n    }\n\n    interface TreeSignatureEvent {\n        id: string;\n        topic: string[];\n        batchIndex: number;\n        txid: string;\n        signature: string;\n    }\n\n    interface StreamStartedEvent {\n        id: string;\n    }\n\n    interface Heartbeat {\n        // Empty interface for heartbeat events\n    }\n\n    export interface VtxoData {\n        outpoint: {\n            txid: string;\n            vout: number;\n        };\n        amount: string;\n        script: string;\n        createdAt: string;\n        expiresAt: string | null;\n        commitmentTxids: string[];\n        isPreconfirmed: boolean;\n        isSwept: boolean;\n        isUnrolled: boolean;\n        isSpent: boolean;\n        spentBy: string;\n        settledBy?: string;\n        arkTxid?: string;\n    }\n\n    export interface GetEventStreamResponse {\n        batchStarted?: BatchStartedEvent;\n        batchFailed?: BatchFailed;\n        batchFinalization?: BatchFinalizationEvent;\n        batchFinalized?: BatchFinalizedEvent;\n        treeSigningStarted?: TreeSigningStartedEvent;\n        treeNoncesAggregated?: TreeNoncesAggregatedEvent;\n        treeNonces?: TreeNoncesEvent;\n        treeTx?: TreeTxEvent;\n        treeSignature?: TreeSignatureEvent;\n        streamStarted?: StreamStartedEvent;\n        heartbeat?: Heartbeat;\n    }\n\n    export interface TxNotificationData {\n        txid: string;\n        tx: string;\n        spentVtxos: VtxoData[];\n        spendableVtxos: VtxoData[];\n        checkpointTxs?: Record<string, { txid: string; tx: string }>;\n        sweptVtxos?: { txid: string; vout: number }[];\n    }\n\n    export interface GetTransactionsStreamResponse {\n        commitmentTx?: TxNotificationData;\n        arkTx?: TxNotificationData;\n        sweepTx?: TxNotificationData;\n        heartbeat?: Heartbeat;\n    }\n\n    // Legacy types for backward compatibility\n    export interface EventData {\n        batchStarted?: BatchStartedEvent;\n        batchFailed?: BatchFailed;\n        batchFinalization?: BatchFinalizationEvent;\n        batchFinalized?: BatchFinalizedEvent;\n        treeSigningStarted?: TreeSigningStartedEvent;\n        treeNoncesAggregated?: TreeNoncesAggregatedEvent;\n        treeTx?: TreeTxEvent;\n        treeSignature?: TreeSignatureEvent;\n    }\n\n    export interface TransactionData {\n        commitmentTx?: {\n            txid: string;\n            tx: string;\n            spentVtxos: VtxoData[];\n            spendableVtxos: VtxoData[];\n            checkpointTxs?: Record<string, { txid: string; tx: string }>;\n        };\n        arkTx?: {\n            txid: string;\n            tx: string;\n            spentVtxos: VtxoData[];\n            spendableVtxos: VtxoData[];\n            checkpointTxs?: Record<string, { txid: string; tx: string }>;\n        };\n    }\n}\n\nexport function isFetchTimeoutError(err: any): boolean {\n    const checkError = (error: any) => {\n        if (!(error instanceof Error)) return false;\n\n        // TODO: get something more robust than this\n        const isCloudflare524 = error.name === \"TypeError\" && error.message === \"Failed to fetch\";\n\n        return (\n            isCloudflare524 ||\n            error.name === \"HeadersTimeoutError\" ||\n            error.name === \"BodyTimeoutError\" ||\n            (error as any).code === \"UND_ERR_HEADERS_TIMEOUT\" ||\n            (error as any).code === \"UND_ERR_BODY_TIMEOUT\"\n        );\n    };\n\n    return checkError(err) || checkError((err as any).cause);\n}\n\nfunction mapTxNotification(data: ProtoTypes.TxNotificationData): TxNotification {\n    return {\n        txid: data.txid,\n        tx: data.tx,\n        spentVtxos: data.spentVtxos.map(mapVtxo),\n        spendableVtxos: data.spendableVtxos.map(mapVtxo),\n        checkpointTxs: data.checkpointTxs,\n    };\n}\n\nfunction mapVtxo(vtxo: ProtoTypes.VtxoData): Vtxo {\n    return {\n        outpoint: {\n            txid: vtxo.outpoint.txid,\n            vout: vtxo.outpoint.vout,\n        },\n        amount: vtxo.amount,\n        script: vtxo.script,\n        createdAt: vtxo.createdAt,\n        expiresAt: vtxo.expiresAt,\n        commitmentTxids: vtxo.commitmentTxids,\n        isPreconfirmed: vtxo.isPreconfirmed,\n        isSwept: vtxo.isSwept,\n        isUnrolled: vtxo.isUnrolled,\n        isSpent: vtxo.isSpent,\n        spentBy: vtxo.spentBy,\n        settledBy: vtxo.settledBy,\n        arkTxid: vtxo.arkTxid,\n    };\n}\n\nfunction handleError(errorText: string, defaultMessage: string): never {\n    const error = new Error(errorText);\n    const arkError = maybeArkError(error);\n    throw arkError ?? new Error(defaultMessage);\n}\n","import { FetchError } from \"../utils/fetch\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { ProviderUnavailableError } from \"./errors\";\n\n/**\n * Whether a provider error is a *retryable* availability failure (operator or\n * indexer temporarily unreachable) rather than a terminal one.\n *\n * Retryable:\n *  - {@link ProviderUnavailableError} — already-classified 5xx/429/unavailable\n *    (see e.g. {@link https | RestArkProvider.getInfo}'s non-2xx branch);\n *  - {@link FetchError} — transport-level `fetch` rejection (DNS failure,\n *    connection refused, TLS/CORS), which also carries undici timeouts as its\n *    `cause`;\n *  - {@link isFetchTimeoutError} — header/body timeouts that surface directly.\n *\n * Everything else (4xx, invalid JSON, schema violations, network mismatch,\n * unsupported network) is terminal and returns `false`.\n *\n * NOTE (Step 2, Scope 2): this classifies the errors currently produced by the\n * boot-critical `getInfo` path. Normalizing the indexer's per-branch\n * `!res.ok` throws and the remaining Ark RPC methods into\n * {@link ProviderUnavailableError} is the broader Scope-2 work still pending.\n */\nexport function isRetryableProviderError(error: unknown): boolean {\n    return (\n        error instanceof ProviderUnavailableError ||\n        error instanceof FetchError ||\n        isFetchTimeoutError(error)\n    );\n}\n","/**\n * Default indexer pagination size for batched VTXO queries (`getVtxos`).\n *\n * Shared by {@link ContractManager}'s bulk history sync, the discovery\n * handlers' batched `detectUsedScripts` probe, and `wallet/vtxo.ts`'s chunked\n * reader so they can't drift. It lives in its own leaf module (importing\n * nothing) so every layer can use it without a `handlers → contractManager`\n * import cycle — contractManager imports the handler registry, so the handlers\n * must not import back from contractManager.\n *\n * Large enough that a single wallet index's candidate scripts resolve in one\n * page in the common case.\n */\nexport const DEFAULT_PAGE_SIZE = 500;\n\n/**\n * Maximum scripts per `getVtxos` query string.\n *\n * Scripts cost ~77 bytes each in the URL, so an unbounded wallet-derived list\n * `414`s: a few hundred contracts is ~28 KB. 32 keeps a request at ~2.6 KB —\n * well inside any plausible limit, since `arkd`'s real ceiling is unpublished\n * and 16 is the largest batch observed working in the wild.\n *\n * Shared by `wallet/vtxo.ts`'s `getAllNormalizedVtxos` and the discovery\n * handlers' batched `detectUsedScripts` probe (which also gets a 10-index scan\n * window collapsed into 1-2 requests as a side effect) so the two can't drift\n * onto different budgets for the same URL constraint.\n */\nexport const SCRIPT_QUERY_CHUNK_SIZE = 32;\n\n/**\n * Maximum outpoints per `getVtxos` query string. ~79 encoded bytes each, so 64\n * is ~5 KB — real margin under the common 8 KB request-line ceiling, against\n * the same unpublished `arkd` limit that budgets scripts at 32.\n */\nexport const OUTPOINT_QUERY_CHUNK_SIZE = 64;\n","import {\n    DEFAULT_PAGE_SIZE,\n    OUTPOINT_QUERY_CHUNK_SIZE,\n    SCRIPT_QUERY_CHUNK_SIZE,\n} from \"../contracts/constants\";\nimport { isRetryableProviderError } from \"../providers/availability\";\nimport type { GetVtxosOptions, IndexerProvider, PageResponse, Vtxo } from \"../providers/indexer\";\nimport type { OnchainProvider } from \"../providers/onchain\";\nimport type { ExtendedVirtualCoin, VirtualCoin, VirtualStatus } from \"./index\";\n\n/**\n * Canonical VTXO facts, the conversions between them and the legacy `virtualStatus` projection,\n * and the capability predicates behavior is expected to read.\n *\n * Three directions are owned here:\n *\n * 1. wire `Vtxo` -> canonical ({@link convertVtxo})\n * 2. canonical -> legacy `virtualStatus` ({@link toVirtualStatus})\n * 3. legacy `virtualStatus` -> canonical ({@link normalizeVtxo})\n *\n * Direction 3 is not just for old persisted rows: `IndexerProvider` and `WalletRepository` are\n * public interfaces, so consumer implementations may hand back legacy-shaped coins through the\n * front door. Normalization therefore runs where the SDK *consumes* an interface, never inside an\n * implementation of one.\n */\n\n/**\n * Below this, a millisecond value is too small to be a real batch expiry and is read as a block\n * height instead. The server returns one scalar for both units.\n *\n * A UTC constant rather than `getFullYear()`, which reads local time and would make the\n * classification depend on the runtime's timezone.\n */\nexport const EXPIRY_MIN_PLAUSIBLE_MS = Date.UTC(2025, 0, 1);\n\n/**\n * The current moment, as the expiry predicates need it.\n *\n * `height` is optional: offline-first paths have no chain tip at hand. When it is absent,\n * height-based expiry cannot be evaluated and reads as not expired.\n */\nexport type TimeHeight = { timestamp: Date; height?: number };\n\n/**\n * Resolve the {@link TimeHeight} for one expiry-driven pass.\n *\n * @remarks\n * Fetch the tip once per pass and reuse the result for every VTXO in it, so the pass judges them\n * all against the same height.\n *\n * A tip-fetch failure **degrades to timestamp-only rather than blocking**: height-encoded expiry\n * then reads as not expired, which is what the whole SDK did before heights were evaluated at all.\n * Recovery and deprecated-signer migration must not become unavailable because the onchain provider\n * is down.\n *\n * Pass no provider to opt out of height entirely — the offline-first paths (balance, coin\n * selection) do this deliberately.\n */\nexport async function resolveTimeHeight(\n    provider?: Pick<OnchainProvider, \"getChainTip\">,\n): Promise<TimeHeight> {\n    const timestamp = new Date();\n    if (!provider) return { timestamp };\n    try {\n        const tip = await provider.getChainTip();\n        return { timestamp, height: tip.height };\n    } catch (e) {\n        console.warn(\"Failed to fetch chain tip; height-based expiry will not be evaluated\", e);\n        return { timestamp };\n    }\n}\n\n/**\n * A {@link VirtualCoin} that has passed through {@link normalizeVtxo}: every fact the capability\n * predicates read is present.\n *\n * Internal signatures take this rather than `VirtualCoin` so the compiler rejects un-normalized\n * input — on the public shape these facts are optional, and `undefined` is falsy, so a legacy coin\n * would silently read as \"not swept\", \"not spent\", and drop out of the wrong bucket.\n *\n * It is deliberately a *subtype* of `VirtualCoin`, so normalized coins are returned to consumers\n * directly and no egress projection exists.\n */\nexport type NormalizedVirtualCoin = Omit<\n    VirtualCoin,\n    \"isSwept\" | \"isPreconfirmed\" | \"isSpent\" | \"spentBy\" | \"commitmentTxIds\"\n> & {\n    isSwept: boolean;\n    isPreconfirmed: boolean;\n    isSpent: boolean;\n    spentBy: string;\n    commitmentTxIds: string[];\n};\n\nexport type NormalizedExtendedVirtualCoin = ExtendedVirtualCoin & NormalizedVirtualCoin;\n\n// --- expiry ------------------------------------------------------------------------------------\n\n/** The wire's single `expiresAt` scalar -> canonical, disambiguating seconds from height. */\nexport function parseWireExpiry(raw: string | null | undefined): {\n    expiresAt?: Date;\n    expiresAtHeight?: number;\n} {\n    if (raw === null || raw === undefined || raw === \"\") return {};\n    const n = Number(raw);\n    // `n <= 0` would otherwise yield `expiresAtHeight: 0`, which every chain tip is past — a VTXO\n    // with no expiry would read as permanently expired.\n    if (!Number.isFinite(n) || n <= 0) return {};\n    const ms = n * 1000;\n    if (ms >= EXPIRY_MIN_PLAUSIBLE_MS) return { expiresAt: new Date(ms) };\n    return { expiresAtHeight: n };\n}\n\n/** Canonical -> legacy `batchExpiry`. */\nexport function toBatchExpiry(c: {\n    expiresAt?: Date;\n    expiresAtHeight?: number;\n}): number | undefined {\n    if (c.expiresAt !== undefined) return c.expiresAt.getTime();\n    // Multiplying a block height by 1000 is dimensionally meaningless, but it is what the legacy\n    // converter did and what consumers already receive. Preserved deliberately.\n    if (c.expiresAtHeight !== undefined) return c.expiresAtHeight * 1000;\n    return undefined;\n}\n\n/** Legacy `batchExpiry` -> canonical, inverting {@link toBatchExpiry} on its domain. */\nexport function parseLegacyExpiry(batchExpiry: number | undefined): {\n    expiresAt?: Date;\n    expiresAtHeight?: number;\n} {\n    // Same `<= 0` guard as `parseWireExpiry`.\n    if (batchExpiry === undefined || batchExpiry <= 0) return {};\n    if (batchExpiry >= EXPIRY_MIN_PLAUSIBLE_MS) return { expiresAt: new Date(batchExpiry) };\n    return { expiresAtHeight: batchExpiry / 1000 };\n}\n\n// --- normalization -----------------------------------------------------------------------------\n\n/** Synthesize the legacy projection from canonical facts. */\nexport function toVirtualStatus(c: {\n    isSpent?: boolean;\n    isSwept?: boolean;\n    isPreconfirmed?: boolean;\n    commitmentTxIds?: string[];\n    expiresAt?: Date;\n    expiresAtHeight?: number;\n}): VirtualStatus {\n    return {\n        // Precedence is load-bearing: consumers bucket on this label, so any other order silently\n        // moves VTXOs between buckets.\n        state: c.isSpent\n            ? \"spent\"\n            : c.isSwept\n              ? \"swept\"\n              : c.isPreconfirmed\n                ? \"preconfirmed\"\n                : \"settled\",\n        commitmentTxIds: c.commitmentTxIds,\n        batchExpiry: toBatchExpiry(c),\n    };\n}\n\n/**\n * Fill in every canonical fact, deriving from `virtualStatus` when a coin carries only the legacy\n * shape. Idempotent.\n *\n * Facts are derived with `??` so a coin that already carries its own authoritative value keeps it\n * rather than having it re-derived from the lossy projection.\n */\nexport function normalizeVtxo<T extends VirtualCoin>(v: T): T & NormalizedVirtualCoin {\n    const state = v.virtualStatus?.state;\n    const canonicalExpiry = v.expiresAt !== undefined || v.expiresAtHeight !== undefined;\n    const expiry = canonicalExpiry\n        ? // Coerce: a backend that persists through JSON hands back an ISO string, which typechecks\n          // as `Date` but returns NaN from `.getTime()` — comparing false against everything.\n          {\n              expiresAt: v.expiresAt === undefined ? undefined : new Date(v.expiresAt),\n              expiresAtHeight: v.expiresAtHeight,\n          }\n        : parseLegacyExpiry(v.virtualStatus?.batchExpiry);\n\n    // `state === \"spent\"` cannot tell us whether the coin was *also* swept or preconfirmed — the\n    // collapse destroyed that. Reading them as false matches today's behavior: a spent coin already\n    // fails every spendability check.\n    const isSpent = v.isSpent ?? state === \"spent\";\n    const isSwept = v.isSwept ?? state === \"swept\";\n    const isPreconfirmed = v.isPreconfirmed ?? state === \"preconfirmed\";\n    const commitmentTxIds = v.commitmentTxIds ?? v.virtualStatus?.commitmentTxIds ?? [];\n\n    return {\n        ...v,\n        isSpent,\n        isSwept,\n        isPreconfirmed,\n        spentBy: v.spentBy ?? \"\",\n        commitmentTxIds,\n        ...expiry,\n        virtualStatus:\n            v.virtualStatus ??\n            toVirtualStatus({ isSpent, isSwept, isPreconfirmed, commitmentTxIds, ...expiry }),\n    };\n}\n\n/** Wire `Vtxo` -> canonical `VirtualCoin`. Shared by every indexer provider. */\nexport function convertVtxo(vtxo: Vtxo): NormalizedVirtualCoin {\n    const expiry = parseWireExpiry(vtxo.expiresAt);\n    const facts = {\n        isSpent: vtxo.isSpent,\n        isSwept: vtxo.isSwept,\n        isPreconfirmed: vtxo.isPreconfirmed,\n        commitmentTxIds: vtxo.commitmentTxids,\n        ...expiry,\n    };\n    return {\n        txid: vtxo.outpoint.txid,\n        vout: vtxo.outpoint.vout,\n        value: Number(vtxo.amount),\n        status: {\n            confirmed: !vtxo.isSwept && !vtxo.isPreconfirmed,\n            isLeaf: !vtxo.isPreconfirmed,\n        },\n        ...facts,\n        virtualStatus: toVirtualStatus(facts),\n        spentBy: vtxo.spentBy ?? \"\",\n        settledBy: vtxo.settledBy,\n        arkTxId: vtxo.arkTxid,\n        createdAt: new Date(Number(vtxo.createdAt) * 1000),\n        isUnrolled: vtxo.isUnrolled,\n        script: vtxo.script,\n        assets: vtxo.assets?.map((a) => ({\n            assetId: a.assetId,\n            amount: BigInt(a.amount),\n        })),\n    };\n}\n\n// --- provider boundary -------------------------------------------------------------------------\n\n/**\n * The only sanctioned way for SDK logic to read VTXOs from an `IndexerProvider`: a drop-in for\n * `provider.getVtxos()` that normalizes whatever came back. A cheap pass-through for the built-in\n * providers, which already populate the facts.\n */\nexport async function getNormalizedVtxos(\n    provider: Pick<IndexerProvider, \"getVtxos\">,\n    opts?: GetVtxosOptions,\n): Promise<{ vtxos: NormalizedVirtualCoin[]; page?: PageResponse }> {\n    const { vtxos, page } = await provider.getVtxos(opts);\n    return { vtxos: vtxos.map(normalizeVtxo), page };\n}\n\n/** Everything a script query can filter on, minus the cursor this reader owns. */\nexport type VtxoScriptQuery = Omit<GetVtxosOptions, \"scripts\" | \"outpoints\" | \"pageIndex\">;\n\nconst SCRIPT_CHUNK_CONCURRENCY = 4;\n\n/**\n * Read every virtual output for an arbitrary number of scripts.\n *\n * @remarks\n * Scripts travel in the query string, so a wallet-derived list must be chunked\n * at {@link SCRIPT_QUERY_CHUNK_SIZE} or the request `414`s. Bounded concurrency\n * cuts serial latency without letting a large wallet flood the indexer; each\n * chunk is paged to exhaustion.\n */\nexport async function getAllNormalizedVtxos(\n    provider: Pick<IndexerProvider, \"getVtxos\">,\n    scripts: string[],\n    opts: VtxoScriptQuery = {},\n): Promise<NormalizedVirtualCoin[]> {\n    const { pageSize = DEFAULT_PAGE_SIZE, ...filters } = opts;\n    const all: NormalizedVirtualCoin[] = [];\n\n    const chunks: string[][] = [];\n    for (let i = 0; i < scripts.length; i += SCRIPT_QUERY_CHUNK_SIZE) {\n        chunks.push(scripts.slice(i, i + SCRIPT_QUERY_CHUNK_SIZE));\n    }\n\n    const fetchChunk = async (chunk: string[]): Promise<NormalizedVirtualCoin[]> => {\n        const result: NormalizedVirtualCoin[] = [];\n        let pageIndex = 0;\n        let hasMore = true;\n\n        while (hasMore) {\n            const { vtxos, page } = await getNormalizedVtxos(provider, {\n                ...filters,\n                scripts: chunk,\n                pageIndex,\n                pageSize,\n            });\n            result.push(...vtxos);\n\n            // A short page means the last one: providers that omit `page`\n            // entirely are treated as unpaged.\n            hasMore = page ? vtxos.length === pageSize : false;\n            pageIndex++;\n            if (hasMore) await new Promise((r) => setTimeout(r, 500));\n        }\n        return result;\n    };\n\n    for (let i = 0; i < chunks.length; i += SCRIPT_CHUNK_CONCURRENCY) {\n        const batch = await Promise.all(\n            chunks.slice(i, i + SCRIPT_CHUNK_CONCURRENCY).map(fetchChunk),\n        );\n        for (const result of batch) all.push(...result);\n    }\n\n    return all;\n}\n\n/**\n * Resolve `createdAt` (epoch ms) for txids by querying each txid's output 0 as a virtual\n * outpoint, chunked at {@link OUTPOINT_QUERY_CHUNK_SIZE}. `pageSize` is explicit because the\n * provider omits `page.size` when unset and a server default below the chunk size would\n * silently short-page. Best-effort: a retryable failure drops its chunk and leaves the map\n * partial; terminal errors propagate.\n */\nexport async function fetchVtxoCreatedAtByTxid(\n    provider: Pick<IndexerProvider, \"getVtxos\">,\n    txids: string[],\n): Promise<Map<string, number>> {\n    const unique = [...new Set(txids)].filter((txid) => txid !== \"\");\n    const createdAt = new Map<string, number>();\n\n    for (let i = 0; i < unique.length; i += OUTPOINT_QUERY_CHUNK_SIZE) {\n        const chunk = unique.slice(i, i + OUTPOINT_QUERY_CHUNK_SIZE);\n        try {\n            const { vtxos } = await getNormalizedVtxos(provider, {\n                outpoints: chunk.map((txid) => ({ txid, vout: 0 })),\n                pageSize: DEFAULT_PAGE_SIZE,\n            });\n            for (const v of vtxos) {\n                createdAt.set(v.txid, v.createdAt.getTime());\n            }\n        } catch (err) {\n            if (!isRetryableProviderError(err)) throw err;\n        }\n    }\n\n    return createdAt;\n}\n\n// --- capabilities ------------------------------------------------------------------------------\n\n/**\n * Whether a virtual output has been consumed and can never be spent again.\n *\n * @remarks\n * Unions all three spend facts rather than trusting any one of them. The wire contract permits\n * `isSpent: true` with an empty `spentBy` (settlement inputs needing no forfeit are written that\n * way), so a `spentBy || settledBy` definition would classify a spent VTXO as spendable — inflating\n * balance and selecting it for a send that must fail.\n *\n * `isUnrolled` is deliberately **not** part of this union: it says where the output lives, not that\n * it was consumed. Mirrors NArk's `ArkVtxo.IsSpent()`. The location axis is {@link canSweepOnchain},\n * which the two capability predicates below subtract instead.\n */\nexport function isVtxoSpent(vtxo: VirtualCoin): boolean {\n    const n = normalizeVtxo(vtxo);\n    return !!n.isSpent || !!n.spentBy || !!n.settledBy;\n}\n\n/** @deprecated Use {@link isVtxoSpent}. */\nexport const hasTerminalSpend = isVtxoSpent;\n\n/**\n * Whether a virtual output's batch expiry has passed. Pure expiry — swept is a separate fact, ORed\n * in explicitly by {@link canSpendOffchain} / {@link canRecoverOnchain}.\n *\n * @remarks\n * Not named `isExpired`: the deprecated {@link isExpired} also returns `true` for a swept VTXO, and\n * two same-named predicates with different truth conditions is how a call site gets silently\n * rewired.\n *\n * Height-based expiry is only evaluated when `now.height` is supplied.\n */\nexport function isPastExpiry(vtxo: VirtualCoin, now: TimeHeight): boolean {\n    const n = normalizeVtxo(vtxo);\n    if (n.expiresAt !== undefined && now.timestamp.getTime() >= n.expiresAt.getTime()) return true;\n    return (\n        n.expiresAtHeight !== undefined &&\n        now.height !== undefined &&\n        now.height >= n.expiresAtHeight\n    );\n}\n\n/** Whether a virtual output can be spent in an offchain transaction. The send/coin-selection test. */\nexport function canSpendOffchain(vtxo: VirtualCoin, now: TimeHeight): boolean {\n    const n = normalizeVtxo(vtxo);\n    return !isVtxoSpent(n) && !n.isUnrolled && !(n.isSwept || isPastExpiry(n, now));\n}\n\n/**\n * Whether a virtual output must be recovered into a fresh batch rather than spent offchain. The\n * recovery/renewal test and the `recoverable` balance bucket.\n */\nexport function canRecoverOnchain(vtxo: VirtualCoin, now: TimeHeight): boolean {\n    const n = normalizeVtxo(vtxo);\n    return !isVtxoSpent(n) && !n.isUnrolled && (n.isSwept || isPastExpiry(n, now));\n}\n\n/**\n * Whether a virtual output's exit already happened: the output lives onchain and `completeUnroll`\n * is the only remedy. The third and last capability, on the location axis rather than the spend\n * one — together the three partition the live set, since this claims every unrolled coin and the\n * other two refuse them.\n *\n * @remarks\n * The ts-sdk analogue of NArk's `OnchainSweepService` filter, minus the expiry clause: the relevant\n * maturity here is the exit tx's CSV timelock, which `prepareUnrollTransaction` checks against the\n * chain tip, not the batch expiry.\n */\nexport function canSweepOnchain(vtxo: VirtualCoin): boolean {\n    const n = normalizeVtxo(vtxo);\n    return !isVtxoSpent(n) && !!n.isUnrolled;\n}\n\n/**\n * Whether arkd expects a forfeit for this virtual output in a batch: its `Vtxo.RequiresForfeit()`\n * minus `IsNote()`, since arknotes are not `VirtualCoin`s. Keyed on the operator's `isSwept`, never\n * on expiry, so it is not the complement of {@link canRecoverOnchain}: an output past expiry that\n * arkd has not swept still needs one.\n */\nexport function requiresForfeit(vtxo: VirtualCoin): boolean {\n    const n = normalizeVtxo(vtxo);\n    return !n.isSwept && !n.isUnrolled;\n}\n\n// --- fee estimation ----------------------------------------------------------------------------\n\n/**\n * The `OffchainInput` fields that come from the VTXO itself, shared by every offchain fee estimate.\n *\n * @remarks\n * `expiry` goes through {@link toBatchExpiry} so the estimator keeps seeing exactly what the legacy\n * `batchExpiry` path fed it. Correcting the height case here would move fees, which is out of\n * scope.\n */\nexport function toOffchainInputFeeParams(vtxo: NormalizedVirtualCoin): {\n    amount: bigint;\n    type: \"recoverable\" | \"vtxo\";\n    weight: number;\n    birth: Date;\n    expiry: Date | undefined;\n} {\n    const batchExpiry = toBatchExpiry(vtxo);\n    return {\n        amount: BigInt(vtxo.value),\n        type: vtxo.isSwept ? \"recoverable\" : \"vtxo\",\n        weight: 0,\n        birth: vtxo.createdAt,\n        expiry: batchExpiry ? new Date(batchExpiry) : undefined,\n    };\n}\n\n// --- discrimination ----------------------------------------------------------------------------\n\n/**\n * Narrow a settle input to a virtual output.\n *\n * @remarks\n * Keyed on `script`: it is required on `VirtualCoin` (so legacy and canonical shapes both have it)\n * and absent from `ExtendedCoin`, which the optional canonical facts cannot claim.\n *\n * The `typeof` guard is load-bearing — `settle` accepts arknote strings, and `in` throws a\n * `TypeError` on a primitive rather than returning false.\n */\nexport function isVirtualCoin<T>(input: T): input is T & VirtualCoin {\n    return (\n        typeof input === \"object\" &&\n        input !== null &&\n        typeof (input as { script?: unknown }).script === \"string\"\n    );\n}\n\n// --- deprecated compatibility wrappers ---------------------------------------------------------\n\n/**\n * Return whether a virtual output is still spendable.\n *\n * @param vtxo - virtual output to inspect\n * @returns `true` when the virtual output has not been consumed\n *\n * @deprecated Ambiguous: `true` for swept, expired or unrolled virtual outputs, none of which can\n * in fact be spent offchain. Use {@link canSpendOffchain}.\n */\nexport function isSpendable(vtxo: VirtualCoin): boolean {\n    return !isVtxoSpent(vtxo);\n}\n\n/**\n * Return whether a virtual output is recoverable.\n *\n * @param vtxo - virtual output to inspect\n * @returns `true` when the virtual output is swept but not yet consumed\n *\n * @deprecated Swept-only: ignores virtual outputs that are past expiry but not yet swept, which are\n * equally recoverable, and claims unrolled ones, which are not recoverable at all. Use\n * {@link canRecoverOnchain}.\n */\nexport function isRecoverable(vtxo: VirtualCoin): boolean {\n    const n = normalizeVtxo(vtxo);\n    return n.isSwept && !isVtxoSpent(n);\n}\n\n/**\n * Return whether a virtual output should be treated as expired.\n *\n * @param vtxo - virtual output to inspect\n * @returns `true` when the virtual output is swept or its wall-clock batch expiry has passed\n *\n * @deprecated Conflates swept with expired, and cannot evaluate height-based expiry — being\n * synchronous, it has no source for the current chain tip, so it ignores `expiresAtHeight` exactly\n * as it always has. For the recovery decision use {@link canRecoverOnchain}; to reproduce this\n * truth condition use `v.isSwept || isPastExpiry(v, now)`.\n */\nexport function isExpired(vtxo: VirtualCoin): boolean {\n    const n = normalizeVtxo(vtxo);\n    return n.isSwept || (n.expiresAt !== undefined && n.expiresAt.getTime() <= Date.now());\n}\n"]}