@arkade-os/sdk 0.4.78 → 0.4.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/adapters/expo.cjs +5 -5
- package/dist/adapters/expo.d.cts +3 -3
- package/dist/adapters/expo.d.ts +3 -3
- package/dist/adapters/expo.js +3 -3
- package/dist/{asyncStorageTaskQueue-YW2t31_o.d.ts → asyncStorageTaskQueue-C5yQLJhm.d.ts} +1 -1
- package/dist/{asyncStorageTaskQueue-DiXxP-nQ.d.cts → asyncStorageTaskQueue-Shsih-1l.d.cts} +1 -1
- package/dist/{chunk-ZOCJ7E6M.js → chunk-4MXW2NDN.js} +10 -515
- package/dist/chunk-4MXW2NDN.js.map +1 -0
- package/dist/{chunk-KEEZSFLI.cjs → chunk-54FXLZ3T.cjs} +10 -10
- package/dist/{chunk-KEEZSFLI.cjs.map → chunk-54FXLZ3T.cjs.map} +1 -1
- package/dist/{chunk-PWIESIO6.cjs → chunk-DAYCCIRO.cjs} +372 -198
- package/dist/chunk-DAYCCIRO.cjs.map +1 -0
- package/dist/{chunk-Y7BVR6SQ.cjs → chunk-FUW3OM5X.cjs} +76 -561
- package/dist/chunk-FUW3OM5X.cjs.map +1 -0
- package/dist/{chunk-VJ7M6WKB.cjs → chunk-HAM3SHBV.cjs} +587 -532
- package/dist/chunk-HAM3SHBV.cjs.map +1 -0
- package/dist/{chunk-7KIGEOYT.js → chunk-JCPVP7TJ.js} +373 -201
- package/dist/chunk-JCPVP7TJ.js.map +1 -0
- package/dist/{chunk-DFWLP3MD.cjs → chunk-LASRYLMQ.cjs} +17 -17
- package/dist/{chunk-DFWLP3MD.cjs.map → chunk-LASRYLMQ.cjs.map} +1 -1
- package/dist/{chunk-CTFYT24G.js → chunk-QDXOTONI.js} +3 -3
- package/dist/{chunk-CTFYT24G.js.map → chunk-QDXOTONI.js.map} +1 -1
- package/dist/{chunk-IAM5IEVT.cjs → chunk-SJPPBR2V.cjs} +17 -17
- package/dist/{chunk-IAM5IEVT.cjs.map → chunk-SJPPBR2V.cjs.map} +1 -1
- package/dist/{chunk-P766MOPU.js → chunk-SK4OZRMB.js} +4 -4
- package/dist/{chunk-P766MOPU.js.map → chunk-SK4OZRMB.js.map} +1 -1
- package/dist/{chunk-OUHUC26M.js → chunk-VAFNWP3I.js} +4 -4
- package/dist/{chunk-OUHUC26M.js.map → chunk-VAFNWP3I.js.map} +1 -1
- package/dist/{chunk-LKAASQTL.js → chunk-YPQ37P3H.js} +128 -73
- package/dist/chunk-YPQ37P3H.js.map +1 -0
- package/dist/contracts/handlers/index.cjs +9 -9
- package/dist/contracts/handlers/index.d.cts +4 -4
- package/dist/contracts/handlers/index.d.ts +4 -4
- package/dist/contracts/handlers/index.js +2 -2
- package/dist/{delegate-DaNNUI_B.d.cts → delegate-B4bKASut.d.cts} +1 -1
- package/dist/{delegate-b2Wiymoj.d.ts → delegate-C9lpdrb0.d.ts} +1 -1
- package/dist/{hdWalletCapable-B2XVTOvu.d.ts → hdWalletCapable-CUJDKRKO.d.cts} +2 -3
- package/dist/{hdWalletCapable-D6PqWpuW.d.cts → hdWalletCapable-DJClhYMC.d.ts} +2 -3
- package/dist/{index-CAS4GyN-.d.ts → index-Ctul0N3Y.d.cts} +27 -6
- package/dist/{index-CAS4GyN-.d.cts → index-Ctul0N3Y.d.ts} +27 -6
- package/dist/{index-CYsKAXog.d.ts → index-D0qe2qVY.d.ts} +2 -2
- package/dist/{index-BlB97fYl.d.cts → index-YBFmScVS.d.cts} +2 -2
- package/dist/index.cjs +304 -304
- package/dist/index.d.cts +123 -123
- package/dist/index.d.ts +123 -123
- package/dist/index.js +4 -4
- package/dist/repositories/realm/index.cjs +20 -20
- package/dist/repositories/realm/index.d.cts +3 -3
- package/dist/repositories/realm/index.d.ts +3 -3
- package/dist/repositories/realm/index.js +5 -5
- package/dist/repositories/sqlite/index.cjs +19 -19
- package/dist/repositories/sqlite/index.d.cts +3 -3
- package/dist/repositories/sqlite/index.d.ts +3 -3
- package/dist/repositories/sqlite/index.js +5 -5
- package/dist/{taskRunner-BJj7xe35.d.ts → taskRunner-C08egG5a.d.ts} +1 -1
- package/dist/{taskRunner-HS2d2oda.d.cts → taskRunner-DB17db5n.d.cts} +1 -1
- package/dist/wallet/expo/background.cjs +14 -14
- package/dist/wallet/expo/background.d.cts +4 -4
- package/dist/wallet/expo/background.d.ts +4 -4
- package/dist/wallet/expo/background.js +6 -6
- package/dist/wallet/expo/index.cjs +14 -14
- package/dist/wallet/expo/index.d.cts +5 -5
- package/dist/wallet/expo/index.d.ts +5 -5
- package/dist/wallet/expo/index.js +5 -5
- package/dist/worker/expo/index.cjs +9 -9
- package/dist/worker/expo/index.d.cts +5 -5
- package/dist/worker/expo/index.d.ts +5 -5
- package/dist/worker/expo/index.js +5 -5
- package/package.json +6 -5
- package/dist/chunk-7KIGEOYT.js.map +0 -1
- package/dist/chunk-LKAASQTL.js.map +0 -1
- package/dist/chunk-PWIESIO6.cjs.map +0 -1
- package/dist/chunk-VJ7M6WKB.cjs.map +0 -1
- package/dist/chunk-Y7BVR6SQ.cjs.map +0 -1
- package/dist/chunk-ZOCJ7E6M.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/contracts/handlers/registry.ts","../src/script/default.ts","../src/identity/descriptor.ts","../src/contracts/metadata.ts","../src/contracts/handlers/helpers.ts","../src/contracts/handlers/default.ts","../src/script/delegate.ts","../src/contracts/handlers/delegate.ts","../src/arkade/opcodes.ts","../src/arkade/bignum.ts","../src/arkade/script.ts","../src/utils/keys.ts","../src/arkade/tweak.ts","../src/script/vhtlc.ts","../src/contracts/handlers/vhtlc.ts","../src/contracts/handlers/vhtlcV2.ts","../src/contracts/handlers/boarding.ts","../src/arkade/program.ts","../src/contracts/handlers/arkade.ts","../src/contracts/handlers/index.ts"],"names":["DefaultVtxo","Script","VtxoScript","MultisigTapscript","CSVMultisigTapscript","hex","expand","networks","sequenceToTimelock","SCRIPT_QUERY_CHUNK_SIZE","getNormalizedVtxos","DEFAULT_PAGE_SIZE","timelockToSequence","DelegateVtxo","OP","__export","ScriptNum","P","schnorr","bytesToNumberBE","secp256k1","VHTLC","ConditionMultisigTapscript","CLTVMultisigTapscript","ConditionCSVMultisigTapscript"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,IAAM,0BAAN,MAA8B;AAAA,EAClB,QAAA,uBAAe,GAAA,EAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ7D,SAAS,OAAA,EAAyC;AAC9C,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAA,CAAQ,IAAI,CAAA,uBAAA,CAAyB,CAAA;AAAA,IACvF;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,IAAA,EAAoD;AACpD,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,WAAW,IAAA,EAAwC;AAC/C,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,GAAA,CAAI,IAAI,CAAA;AAC7B,IAAA,IAAI,CAAC,OAAA,EAAS;AACV,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yCAAA,EAA4C,IAAI,CAAA,CAAA,CAAG,CAAA;AAAA,IACvE;AACA,IAAA,OAAO,OAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,IAAA,EAAuB;AACvB,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,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A;AACjD,gBAAA,CAAiB,SAAS,qBAAqB,CAAA","file":"chunk-FUW3OM5X.cjs","sourcesContent":["import { ContractHandler } from \"../types\";\n\n/**\n * Registry for contract handlers.\n *\n * Each contract type (\"default\", \"vhtlc\", etc.) has a handler that knows\n * how to create VtxoScripts, serialize params, and select spending paths.\n *\n * @example\n * ```typescript\n * // Register a custom handler\n * contractHandlers.register(myCustomHandler);\n *\n * // Get handler for a type\n * const handler = contractHandlers.get(\"vhtlc\");\n * const script = handler.createScript(contract.params);\n * ```\n */\nclass ContractHandlerRegistry {\n private handlers = new Map<string, ContractHandler<unknown>>();\n\n /**\n * Register a contract handler.\n *\n * @param handler - The handler to register\n * @throws If a handler for this type is already registered\n */\n register(handler: ContractHandler<unknown>): void {\n if (this.handlers.has(handler.type)) {\n throw new Error(`Contract handler for type '${handler.type}' is already registered`);\n }\n this.handlers.set(handler.type, handler);\n }\n\n /**\n * Get a handler by type.\n *\n * @param type - The contract type\n * @returns The handler, or undefined if not found\n */\n get(type: string): ContractHandler<unknown> | undefined {\n return this.handlers.get(type);\n }\n\n /**\n * Get a handler by type, throwing if not found.\n *\n * @param type - The contract type\n * @returns The handler\n * @throws If no handler is registered for this type\n */\n getOrThrow(type: string): ContractHandler<unknown> {\n const handler = this.get(type);\n if (!handler) {\n throw new Error(`No contract handler registered for type '${type}'`);\n }\n return handler;\n }\n\n /**\n * Check if a handler is registered.\n *\n * @param type - The contract type\n */\n has(type: string): boolean {\n return this.handlers.has(type);\n }\n\n /**\n * Get all registered types.\n */\n getRegisteredTypes(): string[] {\n return Array.from(this.handlers.keys());\n }\n\n /**\n * Unregister a handler (mainly for testing).\n */\n unregister(type: string): boolean {\n return this.handlers.delete(type);\n }\n\n /**\n * Clear all handlers (mainly for testing).\n */\n clear(): void {\n this.handlers.clear();\n }\n}\n\n/**\n * Global registry of contract handlers.\n */\nexport const contractHandlers = new ContractHandlerRegistry();\n","import { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { CSVMultisigTapscript, MultisigTapscript, RelativeTimelock } from \"./tapscript\";\nimport { hex } from \"@scure/base\";\n\n/**\n * DefaultVtxo is the default implementation of a VtxoScript.\n * It contains 1 forfeit path and 1 exit path.\n * - forfeit = (Alice + Server)\n * - exit = (Alice) after csvTimelock\n */\nexport namespace DefaultVtxo {\n /**\n * Options is the options for the DefaultVtxo.Script class.\n * csvTimelock is the exit path timelock, default is 144 blocks (1 day).\n */\n export interface Options {\n pubKey: Bytes;\n serverPubKey: Bytes;\n csvTimelock: RelativeTimelock;\n }\n\n /**\n * DefaultVtxo.Script is the class letting to create the vtxo script.\n * @example\n * ```typescript\n * const vtxoScript = new DefaultVtxo.Script({\n * pubKey: new Uint8Array(32),\n * serverPubKey: new Uint8Array(32),\n * csvTimelock: {\n * value: 605184n,\n * type: \"seconds\"\n * }\n * });\n *\n * console.log(\"script pub key:\", vtxoScript.pkScript)\n * ```\n */\n export class Script extends VtxoScript {\n static readonly DEFAULT_TIMELOCK: RelativeTimelock = {\n value: 144n,\n type: \"blocks\",\n }; // 1 day in blocks\n\n readonly forfeitScript: string;\n readonly exitScript: string;\n\n /** Create the default virtual output script with one forfeit path and one exit path. */\n constructor(readonly options: Options) {\n const { pubKey, serverPubKey, csvTimelock } = options;\n\n const forfeitScript = MultisigTapscript.encode({\n pubkeys: [pubKey, serverPubKey],\n }).script;\n\n const exitScript = CSVMultisigTapscript.encode({\n timelock: csvTimelock,\n pubkeys: [pubKey],\n }).script;\n\n super([forfeitScript, exitScript]);\n\n this.forfeitScript = hex.encode(forfeitScript);\n this.exitScript = hex.encode(exitScript);\n }\n\n /** Return the forfeit tapleaf script. */\n forfeit(): TapLeafScript {\n return this.findLeaf(this.forfeitScript);\n }\n\n /** Return the unilateral exit tapleaf script. */\n exit(): TapLeafScript {\n return this.findLeaf(this.exitScript);\n }\n }\n}\n","import { expand, networks } from \"@bitcoinerlab/descriptors-scure\";\nimport { hex } from \"@scure/base\";\n\n/**\n * True iff `descriptor` is a Bitcoin mainnet descriptor (xpub-prefixed\n * BIP32 key).\n *\n * Note: testnet, signet, regtest, mutinynet, and other non-mainnet\n * networks all share the same `tpub` BIP32 version bytes — they cannot\n * be distinguished from one another at the descriptor level. Callers\n * that need a `Network` constants object for `expand()` pick\n * `networks.bitcoin` vs `networks.testnet` themselves; callers that\n * need the *actual* network the wallet is on must track that\n * out-of-band.\n */\nexport function isMainnetDescriptor(descriptor: string): boolean {\n return !descriptor.includes(\"tpub\");\n}\n\n/**\n * Shared \"does `candidate` belong to the identity backed by\n * `ourDescriptor`?\" predicate.\n *\n * - HD descriptors (expanding to a `bip32` key) match by account xpub\n * on both sides — index-agnostic, so a wildcard template and any\n * concrete index under it all collapse to the same xpub.\n * - Bare `tr(pubkey)` candidates fall back to comparing the candidate\n * pubkey against `ourXOnlyPubkey` (the cached pubkey on the identity\n * side, since pulling it from `ourDescriptor` would require an index\n * substitution the caller already performed).\n */\nexport function descriptorIsOurs(\n candidate: string,\n ourDescriptor: string,\n ourXOnlyPubkey: Uint8Array,\n): boolean {\n if (!isDescriptor(candidate)) return false;\n try {\n const candidateInfo = expand({\n descriptor: candidate,\n network: isMainnetDescriptor(candidate) ? networks.bitcoin : networks.testnet,\n }).expansionMap?.[\"@0\"];\n if (!candidateInfo) return false;\n\n if (candidateInfo.bip32) {\n const ourBip32 = expand({\n descriptor: ourDescriptor,\n network: isMainnetDescriptor(ourDescriptor) ? networks.bitcoin : networks.testnet,\n }).expansionMap?.[\"@0\"]?.bip32;\n if (!ourBip32) return false;\n return ourBip32.toBase58() === candidateInfo.bip32.toBase58();\n }\n if (candidateInfo.pubkey) {\n // For tr() the library hands back a 32-byte x-only key, but\n // strip a leading parity byte defensively so a 33-byte\n // compressed key (mismatched length) doesn't silently\n // false-negative against our 32-byte x-only side.\n const candidatePub =\n candidateInfo.pubkey.length === 33\n ? candidateInfo.pubkey.subarray(1)\n : candidateInfo.pubkey;\n if (candidatePub.length !== ourXOnlyPubkey.length) return false;\n return hex.encode(candidatePub) === hex.encode(ourXOnlyPubkey);\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a string is a descriptor of the shape `tr(...)`.\n *\n * This is a shape check only — it does not validate the inner key material.\n * Use {@link expand} (via {@link extractPubKey} / {@link parseHDDescriptor})\n * for full parsing. The guard rejects empty bodies and missing/trailing\n * parentheses so callers can safely branch on descriptor vs. raw pubkey.\n */\nexport function isDescriptor(value: string): boolean {\n if (typeof value !== \"string\") return false;\n if (!value.startsWith(\"tr(\") || !value.endsWith(\")\")) return false;\n // body length > 0 after stripping \"tr(\" and \")\"\n return value.length > \"tr()\".length;\n}\n\n/**\n * Normalize a value to descriptor format.\n * If already a descriptor, return as-is. If hex pubkey, wrap as tr(pubkey).\n * Throws when the value is empty or not a string so we never produce\n * malformed descriptors like `tr()` that downstream parsers would reject.\n */\nexport function normalizeToDescriptor(value: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"normalizeToDescriptor: expected a non-empty string value\");\n }\n if (isDescriptor(value)) {\n return value;\n }\n return `tr(${value})`;\n}\n\n/**\n * Extract the public key from a simple descriptor.\n * For simple descriptors (tr(pubkey)), extracts the pubkey using the library.\n * For HD descriptors, throws — use DescriptorProvider to derive the key.\n */\nexport function extractPubKey(descriptor: string): string {\n if (!isDescriptor(descriptor)) {\n return descriptor;\n }\n\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n const expansion = expand({ descriptor, network });\n\n if (!expansion.expansionMap) {\n throw new Error(\"Cannot extract pubkey from descriptor: expansion failed.\");\n }\n\n const key = expansion.expansionMap[\"@0\"];\n\n // HD descriptors (have a bip32 key) require DescriptorProvider for derivation\n if (key?.bip32) {\n throw new Error(\n \"Cannot extract pubkey from HD descriptor without derivation. \" +\n \"Use DescriptorProvider to derive the key from the xpub.\",\n );\n }\n\n if (!key?.pubkey) {\n throw new Error(\"Cannot extract pubkey from descriptor: no key found.\");\n }\n\n return hex.encode(key.pubkey);\n}\n\n/**\n * Extract the x-only (32-byte) pubkey from a materialized descriptor.\n * Handles both static `tr(pubkey)` and materialized HD\n * `tr([fp/..]xpub/0/<i>)` shapes via the descriptors-scure expansion map.\n * Throws a plain Error when the descriptor is non-rangeable / unparseable;\n * callers that need a typed error wrap this.\n */\nexport function deriveDescriptorLeafPubKey(descriptor: string): Uint8Array {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n let expansion;\n try {\n expansion = expand({ descriptor, network });\n } catch (e) {\n throw new Error(\n `Cannot derive leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `ensure it is materialized (no wildcard) and parsable.`,\n { cause: e },\n );\n }\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.pubkey) {\n throw new Error(\n `Cannot derive leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `parsed but no '@0' pubkey in the expansion map.`,\n );\n }\n return key.pubkey;\n}\n\n/**\n * Compressed (33-byte) counterpart of {@link deriveDescriptorLeafPubKey}, for\n * protocols that key on the parity byte (Boltz swap keys).\n *\n * Only HD descriptors are supported: a bare `tr(xonly)` has lost its parity and\n * synthesizing `02||xonly` would silently produce the wrong key half the time.\n */\nexport function deriveDescriptorLeafCompressedPubKey(descriptor: string): Uint8Array {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n let expansion;\n try {\n expansion = expand({ descriptor, network });\n } catch (e) {\n throw new Error(\n `Cannot derive compressed leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `ensure it is materialized (no wildcard) and parsable.`,\n { cause: e },\n );\n }\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.bip32) {\n throw new Error(\n `Cannot derive compressed leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `not an HD descriptor, so the key parity is unrecoverable.`,\n );\n }\n // derivePath returns a fresh node; keyPath is relative to the xpub and the\n // library's derivePath prepends \"m/\" itself.\n return key.keyPath\n ? key.bip32.derivePath(key.keyPath.replace(/^\\//, \"\")).publicKey\n : key.bip32.publicKey;\n}\n\n/** Parsed HD descriptor components. */\nexport interface ParsedHDDescriptor {\n fingerprint: string;\n basePath: string;\n xpub: string;\n derivationPath: string;\n}\n\n/**\n * Parse an HD descriptor into its components.\n * HD descriptors have the format: tr([fingerprint/path']xpub/derivation)\n * Returns null if the descriptor is not in HD format.\n */\nexport function parseHDDescriptor(descriptor: string): ParsedHDDescriptor | null {\n if (!isDescriptor(descriptor)) {\n return null;\n }\n\n let expansion;\n try {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n expansion = expand({ descriptor, network });\n } catch {\n return null;\n }\n\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.masterFingerprint || !key.originPath || !key.keyPath || !key.bip32) {\n return null;\n }\n\n return {\n fingerprint: hex.encode(key.masterFingerprint),\n basePath: key.originPath.replace(/^\\//, \"\"),\n xpub: key.bip32.toBase58(),\n derivationPath: key.keyPath.replace(/^\\//, \"\"),\n };\n}\n\n/**\n * The descriptor that names an identity's own key: the whole of a static\n * wallet's key policy, and the descriptor a record bound before an `auto`\n * wallet became HD carries.\n *\n * One spelling, deliberately. Every site that mints this must produce\n * byte-identical output for one identity, or a stored descriptor stops\n * round-tripping through `signerForDescriptor` and `contractSigner`'s\n * pubkey-equality check — a record the wallet can sign for, refused as\n * foreign.\n */\nexport async function identityDescriptor(identity: {\n xOnlyPublicKey(): Promise<Uint8Array>;\n}): Promise<string> {\n return normalizeToDescriptor(hex.encode(await identity.xOnlyPublicKey()));\n}\n","/**\n * Sentinel stored in `contract.metadata.source` to mark a contract the\n * wallet generated for its own rotating receive address. Lives here (the\n * contracts layer) so contract handlers can tag/discover without importing\n * the wallet module. Re-exported from `wallet/walletReceiveRotator` for\n * backward compatibility of existing import paths.\n *\n * Tagging makes the boot lookup unambiguous — the rotator filters on\n * `metadata.source === WALLET_RECEIVE_SOURCE` rather than on \"any active\n * default contract\", so a contract repo that also holds default contracts\n * created for other reasons (legacy timelock variants, external\n * integrations) doesn't confuse the wallet's display state.\n */\nexport const WALLET_RECEIVE_SOURCE = \"wallet-receive\";\n","import { hex } from \"@scure/base\";\nimport { sequenceToTimelock } from \"../../utils/timelock\";\nimport { Contract, DiscoveredContract, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, Discoverable, DiscoveryDeps } from \"../types\";\nimport {\n isDescriptor,\n extractPubKey,\n normalizeToDescriptor,\n deriveDescriptorLeafPubKey,\n} from \"../../identity/descriptor\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport { getNormalizedVtxos } from \"../../wallet/vtxo\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport type { TapLeafScript } from \"../../script/base\";\nimport type { RelativeTimelock } from \"../../script/tapscript\";\nimport { WALLET_RECEIVE_SOURCE } from \"../metadata\";\nimport { DEFAULT_PAGE_SIZE, SCRIPT_QUERY_CHUNK_SIZE } from \"../constants\";\n\n/**\n * Extract raw hex pubkey from a value that may be a descriptor or raw hex.\n * Returns undefined for HD descriptors or unparseable values so role\n * resolution stays best-effort and never throws.\n */\nfunction extractRawPubKey(value: string): string | undefined {\n if (!isDescriptor(value)) {\n return value.toLowerCase();\n }\n try {\n return extractPubKey(value).toLowerCase();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve wallet's role from explicit role or by matching descriptor/pubkey.\n */\nexport function resolveRole(\n contract: Contract,\n context: PathContext,\n): \"sender\" | \"receiver\" | undefined {\n // Explicit role takes precedence\n if (context.role === \"sender\" || context.role === \"receiver\") {\n return context.role;\n }\n\n const senderKey = contract.params.sender ? extractRawPubKey(contract.params.sender) : undefined;\n const receiverKey = contract.params.receiver\n ? extractRawPubKey(contract.params.receiver)\n : undefined;\n\n const matchRole = (rawWalletKey: string | undefined): \"sender\" | \"receiver\" | undefined => {\n if (!rawWalletKey) return undefined;\n if (senderKey && rawWalletKey === senderKey) {\n return \"sender\";\n }\n if (receiverKey && rawWalletKey === receiverKey) {\n return \"receiver\";\n }\n return undefined;\n };\n\n // Try the preferred descriptor first. If it cannot be resolved\n // (for example an HD descriptor without derivation support), fall back\n // to walletPubKey for backward compatibility.\n if (context.walletDescriptor) {\n const walletDescriptorKey = extractRawPubKey(context.walletDescriptor);\n const matchedRole = matchRole(walletDescriptorKey);\n if (matchedRole) {\n return matchedRole;\n }\n\n if (!walletDescriptorKey && context.walletPubKey) {\n return matchRole(extractRawPubKey(context.walletPubKey));\n }\n return undefined;\n }\n\n if (context.walletPubKey) {\n return matchRole(extractRawPubKey(context.walletPubKey));\n }\n\n return undefined;\n}\n\n/**\n * Extract pubkey bytes from a persisted param that may hold either a\n * descriptor or a raw hex key.\n *\n * Shared by every descriptor-capable handler (`default` / `delegate` /\n * `boarding` — see `DESCRIPTOR_CAPABLE_CONTRACT_TYPES`) so a rotated row whose\n * key param was persisted in descriptor form deserializes identically\n * whichever handler owns it.\n */\nexport function extractPubKeyBytes(value: string): Uint8Array {\n return hex.decode(extractPubKey(normalizeToDescriptor(value)));\n}\n\n/**\n * Decode a persisted `csvTimelock` param, restoring the default when absent.\n *\n * The param may be missing or empty on legacy/minimal rows (e.g. hex pubkeys\n * written with no timelock). The script classes no longer apply their own\n * fallback, and an unguarded decode does *not* fail loudly: `Number(\"\")` /\n * `Number(undefined)` is `NaN`, and `bip68.decode(NaN)` returns\n * `{ blocks: 0 }`, so `sequenceToTimelock` silently yields a zero timelock —\n * an exit path that reads as immediately spendable. Restore the documented\n * default instead of decoding a NaN.\n */\nexport function deserializeCsvTimelock(value: string | undefined): RelativeTimelock {\n return value !== undefined && value !== \"\"\n ? sequenceToTimelock(Number(value))\n : DefaultVtxo.Script.DEFAULT_TIMELOCK;\n}\n\n/**\n * BIP65 threshold: locktime values below this are interpreted as block heights,\n * values at or above are interpreted as Unix timestamps (seconds).\n */\nconst CLTV_HEIGHT_THRESHOLD = 500_000_000n;\n\n/**\n * Check if an absolute (CLTV) locktime is currently satisfied.\n *\n * Following the BIP65 convention:\n * - locktime < 500_000_000 → interpreted as a block height; compared against `context.blockHeight`\n * - locktime >= 500_000_000 → interpreted as a Unix timestamp (seconds); compared against `context.currentTime`\n *\n * Returns false if the relevant context field is missing.\n */\nexport function isCltvSatisfied(context: PathContext, locktime: bigint): boolean {\n // Deliberately the same clock `cltvMaturity` reads. Offering a path and\n // refusing one are two answers to one question, and sourcing them from\n // different clocks lets a wallet offer a leaf its own guard would reject.\n return cltvMaturity(context, locktime) === \"satisfied\";\n}\n\n/**\n * How an absolute (CLTV) locktime stands against `context`, keeping \"not yet\"\n * and \"cannot tell\" apart.\n *\n * {@link isCltvSatisfied} folds both into `false`, which is the right answer\n * for OFFERING a path — an unknown maturity is not an invitation to spend. It\n * is the wrong answer for REFUSING one: a height-typed locktime with no\n * `blockHeight` in context is unreadable, not immature, and turning that into a\n * refusal would reject spends that are perfectly valid. Anything that fails a\n * caller rather than merely withholding an option must ask this instead.\n *\n * - `satisfied` — matured; the leaf behind it is spendable now.\n * - `pending` — definitively not matured yet, with a maturity to quote.\n * - `unknown` — height-typed with no chain tip supplied. Say nothing.\n */\nexport type CltvMaturity = \"satisfied\" | \"pending\" | \"unknown\";\n\nexport function cltvMaturity(context: PathContext, locktime: bigint): CltvMaturity {\n if (locktime < CLTV_HEIGHT_THRESHOLD) {\n if (context.blockHeight === undefined) return \"unknown\";\n return BigInt(context.blockHeight) >= locktime ? \"satisfied\" : \"pending\";\n }\n // Chain time where we have it. The wall-clock fallback is a decent estimate\n // and a poor authority: the server matures this against median-time-past,\n // which trails wall clock, so a drifting host reads the boundary wrong in\n // whichever direction it drifted — including \"not yet\" for something the\n // chain already accepts.\n return nowSeconds(context) >= locktime ? \"satisfied\" : \"pending\";\n}\n\n/** Chain time if the context carries it, else the local clock. Seconds. */\nfunction nowSeconds(context: PathContext): bigint {\n return BigInt(Math.floor(context.chainTime ?? context.currentTime / 1000));\n}\n\n/** Whether `locktime` is height-typed (BIP65), for phrasing a maturity. */\nexport function isHeightLocktime(locktime: bigint): boolean {\n return locktime < CLTV_HEIGHT_THRESHOLD;\n}\n\n/**\n * The VHTLC spendability refusal, shared by the v1 and v2 handlers.\n *\n * Both versions gate the sender's only collaborative leaf —\n * `refundWithoutReceiver` — on `refundLocktime`. Before it matures the sender\n * has nothing collaborative to spend: `claim` belongs to the receiver and needs\n * a preimage, and `refund` / `nonInteractiveRefund` need the receiver's\n * signature, which is precisely what a refunding sender cannot get. So an\n * explicit `settle({ inputs })` naming that lockup is refusable with certainty\n * rather than guessed at.\n *\n * Lives here rather than in either handler because v1 and v2 differ only in\n * which preimage fragment their claim leaves are built from; a rule applied to\n * one and not the other is the realistic drift, and the same reasoning already\n * keeps their path selection in step.\n *\n * Silent in every case that is not a certainty:\n * - not collaborative — a unilateral spend answers to its CSV, not this\n * - not the sender — the receiver's claim turns on a preimage this cannot see\n * - maturity `unknown` — height-typed with no chain tip; unreadable, not immature\n */\nexport function assertVhtlcSpendableNow(contract: Contract, context: PathContext): void {\n if (!context.collaborative) return;\n if (resolveRole(contract, context) !== \"sender\") return;\n\n const raw = contract.params?.refundLocktime;\n if (raw === undefined) return;\n let refundLocktime: bigint;\n try {\n refundLocktime = BigInt(raw);\n } catch {\n // Unparseable params are someone else's error to report, not ours to\n // guess at — createScript already refuses them with a better message.\n return;\n }\n\n if (cltvMaturity(context, refundLocktime) !== \"pending\") return;\n\n const [matures, now] = isHeightLocktime(refundLocktime)\n ? [`block ${refundLocktime}`, `${context.blockHeight}`]\n : [\n `${new Date(Number(refundLocktime) * 1000).toISOString()}`,\n new Date(context.currentTime).toISOString(),\n ];\n // Addressed to the sender — the only role that reaches here. Do not offer\n // them the preimage claim: that is the receiver's leaf and the receiver's\n // secret, and suggesting it sends the reader looking for a key they will\n // never hold.\n throw new Error(\n `vhtlc ${contract.script} cannot be spent yet: its refund path opens at ${matures}, ` +\n `now ${now}. Until then the lockup is the receiver's to claim, and the server ` +\n `rejects a spend of it. Retry after ${matures}, or wait for the receiver to ` +\n `claim it with the preimage.`,\n );\n}\n\n/**\n * Check if a CSV timelock is currently satisfied for the given context/virtual output.\n */\nexport function isCsvSpendable(context: PathContext, sequence?: number): boolean {\n if (sequence === undefined) return true;\n if (!context.vtxo) return false;\n const timelock = sequenceToTimelock(sequence);\n\n if (timelock.type === \"blocks\") {\n if (context.blockHeight === undefined || context.vtxo.status.block_height === undefined) {\n return false;\n }\n return context.blockHeight - context.vtxo.status.block_height >= Number(timelock.value);\n }\n\n if (timelock.type === \"seconds\") {\n // The input's own confirmation time is the CSV's origin — a relative\n // timelock is measured from when THIS coin confirmed, not from now.\n // Absent, the age is unknowable and the answer is no.\n const blockTime = context.vtxo.status.block_time;\n if (blockTime === undefined) return false;\n return Number(nowSeconds(context)) - blockTime >= Number(timelock.value);\n }\n\n return false;\n}\n\n/**\n * The tapleaf surface shared by `DefaultVtxo.Script` and\n * `DelegateVtxo.Script`. Structural rather than nominal: the two classes are\n * siblings (delegate wraps a default rather than extending it), so a shared\n * interface is what lets both feed the forfeit/exit path helpers below.\n */\nexport interface ForfeitExitScript {\n forfeit(): TapLeafScript;\n exit(): TapLeafScript;\n}\n\n/**\n * BIP68 sequence for a contract's exit path, or `undefined` when the contract\n * carries no `csvTimelock` param (an exit with no relative timelock).\n */\nexport function exitSequence(contract: Contract): number | undefined {\n return contract.params.csvTimelock ? Number(contract.params.csvTimelock) : undefined;\n}\n\n/**\n * The `forfeit`-or-`exit` selection every forfeit/exit contract shares:\n * collaborative spending takes the forfeit path, otherwise the exit path once\n * its CSV has matured. Returns null when neither is available.\n */\nexport function selectForfeitOrExitPath(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection | null {\n if (context.collaborative) {\n return { leaf: script.forfeit() };\n }\n\n const sequence = exitSequence(contract);\n if (!isCsvSpendable(context, sequence)) {\n return null;\n }\n return { leaf: script.exit(), sequence };\n}\n\n/**\n * Every forfeit/exit path that exists at all: forfeit when the server\n * cooperates, plus exit unconditionally (its CSV is checked at tx build time,\n * not here).\n */\nexport function forfeitExitAllPaths(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection[] {\n const paths: PathSelection[] = [];\n\n if (context.collaborative) {\n paths.push({ leaf: script.forfeit() });\n }\n\n const exitPath: PathSelection = { leaf: script.exit() };\n const sequence = exitSequence(contract);\n if (sequence !== undefined) {\n exitPath.sequence = sequence;\n }\n paths.push(exitPath);\n\n return paths;\n}\n\n/**\n * The subset of {@link forfeitExitAllPaths} spendable *right now* — the exit\n * path is dropped until its CSV has matured.\n */\nexport function forfeitExitSpendablePaths(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection[] {\n const paths: PathSelection[] = [];\n\n if (context.collaborative) {\n paths.push({ leaf: script.forfeit() });\n }\n\n const sequence = exitSequence(contract);\n if (isCsvSpendable(context, sequence)) {\n const exitPath: PathSelection = { leaf: script.exit() };\n if (sequence !== undefined) {\n exitPath.sequence = sequence;\n }\n paths.push(exitPath);\n }\n\n return paths;\n}\n\n/**\n * Batched discovery probe: given candidate pkScripts a discovery pass built\n * (the signer × CSV-timelock cross-product, possibly across several wallet\n * indices), return the subset the indexer has at least one VTXO for — in any\n * state, since restore counts a spent-but-used script as activity.\n *\n * Collapses what used to be one `getVtxos` call per candidate script into a\n * single call per page, the same batching shape as\n * {@link ContractManager.fetchContractVtxosBulk}: the indexer reports each\n * returned VTXO's `script`, which is matched back to the candidate set. It\n * pages only as far as needed to observe every candidate (stopping early once\n * all are seen), and otherwise to the end of history, so the discovered set is\n * identical to the prior per-script path — a heavily-reused candidate cannot\n * starve another candidate off the first page.\n *\n * Scripts beyond {@link SCRIPT_QUERY_CHUNK_SIZE} are split into sequential\n * chunks (a URL-length budget, see the constant). Chunks are issued serially,\n * not concurrently: pacing the indexer is the point of batching here. A chunk\n * rejecting rejects the whole call — callers treat a partial answer as\n * indeterminate, so there is no partial-result channel to leak into.\n */\nexport async function detectUsedScripts(\n indexerProvider: IndexerProvider,\n scriptHexes: string[],\n): Promise<Set<string>> {\n const used = new Set<string>();\n // Distinct indices can derive the same script (e.g. an unrotated signer),\n // and a duplicate would only pad the query string.\n const unique = [...new Set(scriptHexes)];\n\n for (let offset = 0; offset < unique.length; offset += SCRIPT_QUERY_CHUNK_SIZE) {\n const scripts = unique.slice(offset, offset + SCRIPT_QUERY_CHUNK_SIZE);\n // `scripts` stays the full chunk across pages so the indexer's\n // pagination is consistent; `remaining` only drives the early stop.\n const remaining = new Set(scripts);\n let pageIndex = 0;\n let hasMore = true;\n while (hasMore && remaining.size > 0) {\n const { vtxos, page } = await getNormalizedVtxos(indexerProvider, {\n scripts,\n pageIndex,\n pageSize: DEFAULT_PAGE_SIZE,\n });\n for (const vtxo of vtxos) {\n if (remaining.delete(vtxo.script)) used.add(vtxo.script);\n }\n // Same end-of-history heuristic as fetchContractVtxosBulk: a short\n // page (or absent page metadata) means there is nothing left to\n // fetch.\n hasMore = page ? vtxos.length === DEFAULT_PAGE_SIZE : false;\n pageIndex++;\n }\n }\n return used;\n}\n\n/**\n * Shared body of an indexer-backed handler's `discoverAt` / `discoverRange`.\n *\n * Both verbs are this one function — per-index discovery is just a range of\n * one — so the two paths cannot drift into reporting different contracts for\n * the same wallet state. Every I/O the pass needs is the single\n * {@link detectUsedScripts} call over the union of all indices' candidates,\n * which is what turns a 10-index window's ~20 concurrent 2-script requests\n * into 1-2 sequential batched ones.\n *\n * The returned map covers **every** requested index (empty array when nothing\n * hit), satisfying the `discoverRange` coverage contract the scanner enforces.\n */\nexport async function discoverIndexerCandidates<C extends { script: string }>(\n indexerProvider: IndexerProvider,\n entries: readonly { index: number; descriptor: string }[],\n buildCandidates: (index: number, descriptor: string) => C[],\n emit: (candidate: C, index: number, descriptor: string) => DiscoveredContract,\n): Promise<Map<number, DiscoveredContract[]>> {\n const perIndex = entries.map((entry) => ({\n ...entry,\n candidates: buildCandidates(entry.index, entry.descriptor),\n }));\n\n const used = await detectUsedScripts(\n indexerProvider,\n perIndex.flatMap((e) => e.candidates.map((c) => c.script)),\n );\n\n const out = new Map<number, DiscoveredContract[]>();\n for (const { index, descriptor, candidates } of perIndex) {\n out.set(\n index,\n candidates.filter((c) => used.has(c.script)).map((c) => emit(c, index, descriptor)),\n );\n }\n return out;\n}\n\n/**\n * One probe candidate: a built script plus the (signer, timelock) pair that\n * produced it, so the matched signer can be threaded into the emitted\n * contract's params and address.\n */\nexport interface SignerCandidate<S> {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n script: S;\n scriptHex: string;\n}\n\n/**\n * Candidate scripts for one wallet index: the current signer first, then any\n * deprecated signers (so a VTXO minted under a now-rotated server key is still\n * discovered), each crossed with the CSV-timelock matrix.\n *\n * Dedup by scriptHex — a deprecated signer that produced no rotation yields\n * the same scripts as the current key, so it must neither be probed nor\n * emitted twice; the current signer wins the attribution by being first.\n *\n * `makeScript` is the only per-contract-type part, which is what lets\n * `default` and `delegate` share one cross-product.\n */\nexport function buildSignerTimelockCandidates<S extends { pkScript: Uint8Array }>(\n descriptor: string,\n deps: CandidateDeps,\n makeScript: (opts: {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n }) => S,\n): SignerCandidate<S>[] {\n const pubKey = deriveDescriptorLeafPubKey(descriptor);\n const signers = [deps.serverPubKey, ...(deps.deprecatedSignerPubKeys ?? [])];\n const seen = new Set<string>();\n const candidates: SignerCandidate<S>[] = [];\n for (const serverPubKey of signers) {\n for (const csvTimelock of deps.csvTimelocks) {\n const script = makeScript({ pubKey, serverPubKey, csvTimelock });\n const scriptHex = hex.encode(script.pkScript);\n if (seen.has(scriptHex)) continue;\n seen.add(scriptHex);\n candidates.push({ pubKey, serverPubKey, csvTimelock, script, scriptHex });\n }\n }\n return candidates;\n}\n\n/**\n * Metadata tagging a discovered contract as one of the wallet's own rotating\n * receive addresses — spread into a {@link DiscoveredContract} literal.\n *\n * Only *rotated* rows (index > 0) are tagged, so boot resolution can find the\n * newest address and descriptor-aware signing can recover the per-index key.\n * The index-0 baseline stays untagged across every handler.\n */\nexport function rotatedReceiveMetadata(\n index: number,\n descriptor: string,\n): Pick<DiscoveredContract, \"metadata\"> {\n return index > 0\n ? { metadata: { source: WALLET_RECEIVE_SOURCE, signingDescriptor: descriptor } }\n : {};\n}\n\n/**\n * Metadata for a *speculative* candidate the look-ahead band watches: the\n * signing descriptor, so a promoted row stays spendable, and never\n * {@link WALLET_RECEIVE_SOURCE} — the tag would make the next boot advertise a\n * third party's invoice address as the wallet's own. Unconditional on the\n * index, unlike {@link rotatedReceiveMetadata}: an unpersisted entry has no\n * display-address meaning to protect at index 0.\n */\nexport function speculativeReceiveMetadata(\n descriptor: string,\n): Pick<DiscoveredContract, \"metadata\"> {\n return { metadata: { signingDescriptor: descriptor } };\n}\n\n/**\n * Derive a handler's {@link Discoverable.discoverAt} from its\n * {@link Discoverable.discoverRange}: per-index discovery is just a range of\n * one, so the two verbs cannot drift into reporting different contracts for\n * the same wallet state.\n *\n * The `?? []` mirrors `discoverRange`'s coverage contract from the caller's\n * side — a range that omitted the requested index reports a miss here rather\n * than `undefined`.\n */\nexport function discoverAtViaRange(\n discoverRange: NonNullable<Discoverable[\"discoverRange\"]>,\n): Discoverable[\"discoverAt\"] {\n return async (index: number, descriptor: string, deps: DiscoveryDeps) =>\n (await discoverRange([{ index, descriptor }], deps)).get(index) ?? [];\n}\n","import { hex } from \"@scure/base\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport {\n discoverIndexerCandidates,\n discoverAtViaRange,\n extractPubKeyBytes,\n deserializeCsvTimelock,\n rotatedReceiveMetadata,\n buildSignerTimelockCandidates,\n selectForfeitOrExitPath,\n forfeitExitAllPaths,\n forfeitExitSpendablePaths,\n} from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for DefaultVtxo contracts.\n */\nexport interface DefaultContractParams {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n}\n\n/**\n * Handler for default wallet VTXOs.\n *\n * Default contracts use the standard forfeit + exit tapscript:\n * - forfeit: (Alice + Server) multisig for collaborative spending\n * - exit: (Alice) + CSV timelock for unilateral exit\n */\nexport const DefaultContractHandler: ContractHandler<DefaultContractParams, DefaultVtxo.Script> &\n Discoverable = {\n type: \"default\",\n\n createScript(params: Record<string, string>): DefaultVtxo.Script {\n const typed = this.deserializeParams(params);\n return new DefaultVtxo.Script(typed);\n },\n\n serializeParams(params: DefaultContractParams): Record<string, string> {\n return {\n pubKey: hex.encode(params.pubKey),\n serverPubKey: hex.encode(params.serverPubKey),\n csvTimelock: timelockToSequence(params.csvTimelock).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): DefaultContractParams {\n return {\n pubKey: extractPubKeyBytes(params.pubKey),\n serverPubKey: extractPubKeyBytes(params.serverPubKey),\n csvTimelock: deserializeCsvTimelock(params.csvTimelock),\n };\n },\n\n selectPath(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectForfeitOrExitPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitAllPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitSpendablePaths(script, contract, context);\n },\n\n /** The wallet's own money. */\n isGenericallySpendable: () => true,\n\n discoverAt: discoverAtViaRange(discoverDefaultRange),\n\n discoverRange: discoverDefaultRange,\n\n candidatesAt: defaultCandidatesAt,\n};\n\n/**\n * The signer × CSV-timelock cross-product under the index's leaf key. Each\n * candidate's own signer is threaded through its params and address so\n * signing/forfeit later resolves the right key.\n */\nfunction defaultCandidatesAt(\n _index: number,\n descriptor: string,\n deps: CandidateDeps,\n): DiscoveredContract[] {\n return buildSignerTimelockCandidates(\n descriptor,\n deps,\n (opts) => new DefaultVtxo.Script(opts),\n ).map((c) => ({\n type: \"default\",\n params: {\n pubKey: hex.encode(c.pubKey),\n serverPubKey: hex.encode(c.serverPubKey),\n csvTimelock: timelockToSequence(c.csvTimelock).toString(),\n },\n script: c.scriptHex,\n address: c.script.address(deps.network.hrp, c.serverPubKey).encode(),\n }));\n}\n\nfunction discoverDefaultRange(\n entries: readonly { index: number; descriptor: string }[],\n deps: DiscoveryDeps,\n): Promise<Map<number, DiscoveredContract[]>> {\n return discoverIndexerCandidates(\n deps.indexerProvider,\n entries,\n (index, descriptor) => defaultCandidatesAt(index, descriptor, deps),\n (c, index, descriptor) => ({ ...c, ...rotatedReceiveMetadata(index, descriptor) }),\n );\n}\n","import { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { DefaultVtxo } from \"./default\";\nimport { MultisigTapscript } from \"./tapscript\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { hex } from \"@scure/base\";\n\n/**\n * DelegateVtxo extends DefaultVtxo with an extra delegate path\n */\nexport namespace DelegateVtxo {\n /**\n * Options extends DefaultVtxo.Options and adds a delegatePubKey\n */\n export interface Options extends DefaultVtxo.Options {\n delegatePubKey: Bytes;\n }\n\n /**\n * DelegateVtxo.Script extends DefaultVtxo.Script and adds a delegate path.\n * @example\n * ```typescript\n * const vtxoScript = new DelegateVtxo.Script({\n * pubKey: new Uint8Array(32),\n * serverPubKey: new Uint8Array(32),\n * delegatePubKey: new Uint8Array(32),\n * csvTimelock: {\n * value: 605184n,\n * type: \"seconds\"\n * }\n * });\n *\n * console.log(\"script pub key:\", vtxoScript.pkScript)\n * ```\n */\n export class Script extends VtxoScript {\n readonly defaultVtxo: DefaultVtxo.Script;\n readonly delegateScript: string;\n\n /** Create a delegated virtual output script with forfeit, exit, and delegate paths. */\n constructor(readonly options: Options) {\n const defaultVtxo = new DefaultVtxo.Script(options);\n const { delegatePubKey, pubKey, serverPubKey } = options;\n const delegateScript = MultisigTapscript.encode({\n pubkeys: [pubKey, delegatePubKey, serverPubKey],\n }).script;\n\n super([...defaultVtxo.scripts, delegateScript]);\n\n this.defaultVtxo = defaultVtxo;\n this.delegateScript = hex.encode(delegateScript);\n }\n\n /** Return the forfeit tapleaf script. */\n forfeit(): TapLeafScript {\n return this.findLeaf(this.defaultVtxo.forfeitScript);\n }\n\n /** Return the unilateral exit tapleaf script. */\n exit(): TapLeafScript {\n return this.findLeaf(this.defaultVtxo.exitScript);\n }\n\n /** Return the delegate tapleaf script. */\n delegate(): TapLeafScript {\n return this.findLeaf(this.delegateScript);\n }\n }\n}\n","import { hex } from \"@scure/base\";\nimport { DelegateVtxo } from \"../../script/delegate\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport {\n discoverIndexerCandidates,\n discoverAtViaRange,\n extractPubKeyBytes,\n deserializeCsvTimelock,\n rotatedReceiveMetadata,\n buildSignerTimelockCandidates,\n selectForfeitOrExitPath,\n forfeitExitAllPaths,\n forfeitExitSpendablePaths,\n} from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for DelegateVtxo contracts.\n */\nexport interface DelegateContractParams {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n delegatePubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n}\n\n/**\n * Handler for delegate wallet virtual outputs.\n *\n * Delegate contracts extend the default tapscript with an additional delegate path:\n * - forfeit: (Alice + Server) multisig for collaborative spending\n * - exit: (Alice) + CSV timelock for unilateral exit\n * - delegate: (Alice + Delegate + Server) multisig for delegated renewal\n */\nexport const DelegateContractHandler: ContractHandler<DelegateContractParams, DelegateVtxo.Script> &\n Discoverable = {\n type: \"delegate\",\n\n createScript(params: Record<string, string>): DelegateVtxo.Script {\n const typed = this.deserializeParams(params);\n return new DelegateVtxo.Script(typed);\n },\n\n serializeParams(params: DelegateContractParams): Record<string, string> {\n return {\n pubKey: hex.encode(params.pubKey),\n serverPubKey: hex.encode(params.serverPubKey),\n delegatePubKey: hex.encode(params.delegatePubKey),\n csvTimelock: timelockToSequence(params.csvTimelock).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): DelegateContractParams {\n return {\n pubKey: extractPubKeyBytes(params.pubKey),\n serverPubKey: extractPubKeyBytes(params.serverPubKey),\n delegatePubKey: extractPubKeyBytes(params.delegatePubKey),\n csvTimelock: deserializeCsvTimelock(params.csvTimelock),\n };\n },\n\n selectPath(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectForfeitOrExitPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return [\n ...forfeitExitAllPaths(script, contract, context),\n // Delegate path (Alice + Delegate + Server) — collaborative only,\n // and last so the shared forfeit/exit ordering is unchanged.\n ...(context.collaborative ? [{ leaf: script.delegate() }] : []),\n ];\n },\n\n getSpendablePaths(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitSpendablePaths(script, contract, context);\n },\n\n /** The wallet's own money, delegated signing. */\n isGenericallySpendable: () => true,\n\n discoverAt: discoverAtViaRange(discoverDelegateRange),\n\n discoverRange: discoverDelegateRange,\n\n candidatesAt: delegateCandidatesAt,\n};\n\n/**\n * The `default` cross-product (@see DefaultContractHandler.candidatesAt) under\n * the wallet's delegate key. Empty for a non-delegate wallet.\n */\nfunction delegateCandidatesAt(\n _index: number,\n descriptor: string,\n deps: CandidateDeps,\n): DiscoveredContract[] {\n const delegatePubKey = deps.delegatePubKey;\n if (!delegatePubKey) return [];\n\n return buildSignerTimelockCandidates(\n descriptor,\n deps,\n (opts) => new DelegateVtxo.Script({ ...opts, delegatePubKey }),\n ).map((c) => ({\n type: \"delegate\",\n params: {\n pubKey: hex.encode(c.pubKey),\n serverPubKey: hex.encode(c.serverPubKey),\n delegatePubKey: hex.encode(delegatePubKey),\n csvTimelock: timelockToSequence(c.csvTimelock).toString(),\n },\n script: c.scriptHex,\n address: c.script.address(deps.network.hrp, c.serverPubKey).encode(),\n }));\n}\n\nfunction discoverDelegateRange(\n entries: readonly { index: number; descriptor: string }[],\n deps: DiscoveryDeps,\n): Promise<Map<number, DiscoveredContract[]>> {\n // Not a delegate wallet: still answer for every requested index, since an\n // omission would read as indeterminate and truncate the scan.\n if (!deps.delegatePubKey) {\n return Promise.resolve(new Map(entries.map((e) => [e.index, []])));\n }\n\n return discoverIndexerCandidates(\n deps.indexerProvider,\n entries,\n (index, descriptor) => delegateCandidatesAt(index, descriptor, deps),\n (c, index, descriptor) => ({ ...c, ...rotatedReceiveMetadata(index, descriptor) }),\n );\n}\n","/**\n * Arkade Script Opcodes\n *\n * This module defines ONLY Arkade-specific opcodes (0xb3, 0xc3-0xf8).\n * Standard Bitcoin opcodes are imported from @scure/btc-signer.\n *\n * Reference: arkade-os/emulator pkg/arkade/opcode.go.\n * Byte 0xdc is OP_CHECKTIME, matching emulator v0.0.8 and compiler artifacts.\n */\n\nimport { OP } from \"@scure/btc-signer\";\nexport { OP };\n\nexport const ARKADE_OP = {\n // Merkle Branch Verification (0xb3 — repurposed NOP4 slot)\n MERKLEBRANCHVERIFY: 0xb3,\n\n // Digest (0xc3)\n DIGEST: 0xc3,\n\n // SHA256 Streaming (0xc4-0xc6)\n SHA256INITIALIZE: 0xc4,\n SHA256UPDATE: 0xc5,\n SHA256FINALIZE: 0xc6,\n\n // Input Introspection (0xc7-0xcb)\n INSPECTINPUTOUTPOINT: 0xc7,\n INSPECTINPUTARKADESCRIPTHASH: 0xc8,\n INSPECTINPUTVALUE: 0xc9,\n INSPECTINPUTSCRIPTPUBKEY: 0xca,\n INSPECTINPUTSEQUENCE: 0xcb,\n\n // Signatures (0xcc-0xcd)\n CHECKSIGFROMSTACK: 0xcc,\n PUSHCURRENTINPUTINDEX: 0xcd,\n\n // Input Arkade Witness Introspection (0xce)\n INSPECTINPUTARKADEWITNESSHASH: 0xce,\n\n // Output Introspection (0xcf, 0xd1)\n INSPECTOUTPUTVALUE: 0xcf,\n INSPECTOUTPUTSCRIPTPUBKEY: 0xd1,\n\n // Transaction Introspection (0xd2-0xd6)\n INSPECTVERSION: 0xd2,\n INSPECTLOCKTIME: 0xd3,\n INSPECTNUMINPUTS: 0xd4,\n INSPECTNUMOUTPUTS: 0xd5,\n TXWEIGHT: 0xd6,\n\n // Byte/Number Conversion & Arithmetic (0xd7-0xda)\n NUM2BIN: 0xd7,\n BIN2NUM: 0xd8,\n REVERSEBYTES: 0xd9,\n MODEXP: 0xda,\n // VTXO Expiry & Emulator Clock (0xdb-0xdc)\n PUSHEXPIRY: 0xdb,\n CHECKTIME: 0xdc,\n // 0xdd-0xdf are unassigned (OP_UNKNOWN221-223)\n\n // EC Operations (0xe0-0xe2)\n ECADD: 0xe0,\n ECMUL: 0xe1,\n ECPAIRING: 0xe2,\n\n // EC Operations (0xe3-0xe4)\n ECMULSCALARVERIFY: 0xe3,\n TWEAKVERIFY: 0xe4,\n\n // Asset Groups (0xe5-0xf2)\n INSPECTNUMASSETGROUPS: 0xe5,\n INSPECTASSETGROUPASSETID: 0xe6,\n INSPECTASSETGROUPCTRL: 0xe7,\n FINDASSETGROUPBYASSETID: 0xe8,\n INSPECTASSETGROUPMETADATAHASH: 0xe9,\n INSPECTASSETGROUPNUM: 0xea,\n INSPECTASSETGROUP: 0xeb,\n INSPECTASSETGROUPSUM: 0xec,\n INSPECTOUTASSETCOUNT: 0xed,\n INSPECTOUTASSETAT: 0xee,\n INSPECTOUTASSETLOOKUP: 0xef,\n INSPECTINASSETCOUNT: 0xf0,\n INSPECTINASSETAT: 0xf1,\n INSPECTINASSETLOOKUP: 0xf2,\n\n // Transaction ID (0xf3)\n TXID: 0xf3,\n\n // Packet Introspection (0xf4-0xf5) — added in emulator v0.0.1\n INSPECTPACKET: 0xf4,\n INSPECTINPUTPACKET: 0xf5,\n\n // Signature Hash (0xf6)\n SIGHASH: 0xf6,\n\n // Continuation & Intent Introspection (0xf7-0xf8)\n TUNNEL: 0xf7,\n INSPECTINTENTMESSAGE: 0xf8,\n} as const;\n\nexport const ARKADE_OPCODES: number[] = Object.values(ARKADE_OP);\n\nexport const ARKADE_OPCODE_NAMES: Record<number, string> = Object.fromEntries(\n Object.entries(ARKADE_OP).map(([name, value]) => [value, name]),\n);\n\nexport const ARKADE_OPCODE_VALUES: Record<string, number> = Object.fromEntries(\n Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [name, Number(value)]),\n);\n\nfunction buildBitcoinOpcodeNames(): Record<number, string> {\n const names: Record<number, string> = {};\n\n // Standard opcodes from @scure/btc-signer\n for (const [key, value] of Object.entries(OP)) {\n if (typeof value === \"number\") {\n // @scure uses names without OP_ prefix (e.g., \"DUP\", \"HASH160\")\n // We need to add OP_ prefix for consistency\n const name = key.startsWith(\"OP_\") ? key : `OP_${key}`;\n names[value] = name;\n }\n }\n\n // Special case: OP_0 is stored as \"OP_0\" in @scure\n names[0x00] = \"OP_0\";\n\n return names;\n}\n\nfunction buildBitcoinOpcodeValues(): Record<string, number> {\n const values: Record<string, number> = {};\n\n for (const [key, value] of Object.entries(OP)) {\n if (typeof value === \"number\") {\n const name = key.startsWith(\"OP_\") ? key : `OP_${key}`;\n values[name] = value;\n // Also support name without prefix\n values[key] = value;\n }\n }\n\n return values;\n}\n\nconst BITCOIN_OPCODE_NAMES = buildBitcoinOpcodeNames();\nconst BITCOIN_OPCODE_VALUES = buildBitcoinOpcodeValues();\n\n/**\n * Combined map from opcode value to name (with OP_ prefix)\n * Includes both Bitcoin and Arkade opcodes\n */\nexport const OPCODE_NAMES: Record<number, string> = {\n ...BITCOIN_OPCODE_NAMES,\n // Add Arkade opcodes with OP_ prefix\n ...Object.fromEntries(\n Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [Number(value), `OP_${name}`]),\n ),\n};\n\n/**\n * Combined map from opcode name to value\n * Supports both with and without OP_ prefix\n * Includes both Bitcoin and Arkade opcodes\n */\nexport const OPCODE_VALUES: Record<string, number> = {\n ...BITCOIN_OPCODE_VALUES,\n // Add Arkade opcodes with and without OP_ prefix\n ...ARKADE_OPCODE_VALUES,\n ...Object.fromEntries(\n Object.entries(ARKADE_OPCODE_VALUES).map(([name, value]) => [`OP_${name}`, value]),\n ),\n};\n\n/**\n * Get the name of an opcode from its value\n * Returns OP_DATA_N for data push opcodes (0x01-0x4b)\n *\n * @param value Opcode byte value\n * @returns Opcode name with OP_ prefix, or undefined if unknown\n */\nexport function getOpcodeName(value: number): string | undefined {\n // Handle data push opcodes (0x01-0x4b) as OP_DATA_N\n if (value >= 0x01 && value <= 0x4b) {\n return `OP_DATA_${value}`;\n }\n\n // Check combined mappings\n return OPCODE_NAMES[value];\n}\n\n/**\n * Get the value of an opcode from its name\n * Supports OP_DATA_N pattern for data push opcodes\n *\n * @param name Opcode name (with or without OP_ prefix)\n * @returns Opcode byte value, or undefined if unknown\n */\nexport function getOpcodeValue(name: string): number | undefined {\n // Handle OP_DATA_N pattern\n const dataMatch = name.match(/^OP_DATA_(\\d+)$/);\n if (dataMatch) {\n const n = parseInt(dataMatch[1], 10);\n if (n >= 1 && n <= 75) {\n return n;\n }\n return undefined;\n }\n\n // Check combined mappings\n return OPCODE_VALUES[name];\n}\n","/**\n * BigNum — arbitrary-precision sign-magnitude little-endian encoding used by\n * the arkade VM in emulator v0.0.1. Up to 520 bytes (= MaxScriptElementSize).\n *\n * Wire format:\n * - empty bytes = 0\n * - last byte's high bit (0x80) is the sign (set = negative)\n * - remaining bits are magnitude, little-endian\n * - minimal: no trailing zero magnitude byte; `[0x80]` (negative zero) is rejected\n *\n * Wraps `@scure/btc-signer`'s `ScriptNum` with a 520-byte cap. Use the\n * standalone API when you need to round-trip values outside of script encoding;\n * inside `ArkadeScript.encode([...])`, plain `bigint` literals work directly.\n */\n\nimport { ScriptNum } from \"@scure/btc-signer\";\n\n/** Maximum number of bytes for a BigNum (= MaxScriptElementSize). */\nexport const BIGNUM_MAX_BYTES = 520;\n\nconst codec = ScriptNum(BIGNUM_MAX_BYTES, /* forceMinimal */ true);\n\n/**\n * Encode `value` as a minimal sign-magnitude little-endian byte string.\n * Throws if the encoding would exceed 520 bytes.\n */\nexport function encode(value: bigint): Uint8Array {\n const result = codec.encode(value);\n if (result.length > BIGNUM_MAX_BYTES) {\n throw new Error(`BigNum value exceeds 520 bytes (encoded to ${result.length} bytes)`);\n }\n return result;\n}\n\n/**\n * Decode a minimal sign-magnitude little-endian byte string into a bigint.\n * Throws on non-minimal encodings or values longer than 520 bytes.\n */\nexport function decode(value: Uint8Array): bigint {\n return codec.decode(value);\n}\n","/**\n * Arkade Script Encoding and Decoding\n *\n * This module provides script encoding/decoding and ASM conversion helpers\n * that work with both standard Bitcoin opcodes and Arkade extension opcodes.\n *\n * Note: We use our own decoder for scripts because @scure/btc-signer doesn't\n * recognize Arkade opcodes (0xb3, 0xc4-0xf3) and would treat them as data pushes.\n */\n\nimport * as P from \"micro-packed\";\nimport { Script, type ScriptType, OP } from \"@scure/btc-signer\";\nimport { hex } from \"@scure/base\";\nimport { ARKADE_OP } from \"./opcodes\";\nimport * as BigNum from \"./bignum\";\n\n// Re-export Script and ScriptType from @scure\nexport { Script, type ScriptType };\n\n/**\n * Combined OP map: standard Bitcoin opcodes + Arkade extension opcodes.\n * Keys follow @scure convention (without OP_ prefix for most).\n */\nexport const ARKADE_OPS = { ...OP, ...ARKADE_OP } as const;\n\n/** Reverse lookup: byte value → opcode name */\nconst ArkadeOPNames: Record<number, string> = {};\nfor (const [k, v] of Object.entries(ARKADE_OPS)) {\n if (typeof v === \"number\") ArkadeOPNames[v] = k;\n}\n\n/** A single script operation: opcode string key, raw bytes, number, or bigint */\nexport type ArkadeScriptOP = keyof typeof ARKADE_OPS | Uint8Array | number | bigint;\n\n/** Array of script operations — the type that ArkadeScript encodes/decodes */\nexport type ArkadeScriptType = ArkadeScriptOP[];\n\n/**\n * Script CoderType with Arkade extension opcodes.\n *\n * Same API as `Script` from @scure/btc-signer, but with Arkade extension opcodes.\n *\n * @example\n * ```typescript\n * const script: ArkadeScriptType = ['DUP', 'HASH160', pubkeyHash, 'EQUALVERIFY', 'NUM2BIN'];\n * const bytes = ArkadeScript.encode(script);\n * const decoded = ArkadeScript.decode(bytes);\n * ```\n */\nexport const ArkadeScript: P.CoderType<ArkadeScriptType> = P.wrap({\n encodeStream: (w: P.Writer, value: ArkadeScriptType) => {\n for (let o of value) {\n if (typeof o === \"string\") {\n const v = ARKADE_OPS[o as keyof typeof ARKADE_OPS];\n if (v === undefined) throw new Error(`Unknown opcode=${o}`);\n w.byte(v);\n continue;\n } else if (typeof o === \"number\" || typeof o === \"bigint\") {\n // Encode numbers via BigNum (520-byte cap).\n const big = typeof o === \"number\" ? BigInt(o) : o;\n o = BigNum.encode(big);\n }\n if (!(o instanceof Uint8Array)) throw new Error(`Wrong Script OP=${o} (${typeof o})`);\n // Bytes (data push)\n const len = o.length;\n // Arkade VM enforces MINIMALDATA for small script numbers.\n if (len === 1 && o[0] >= 1 && o[0] <= 16) {\n w.byte(OP.OP_1 - 1 + o[0]);\n continue;\n } else if (len === 1 && o[0] === 0x81) {\n w.byte(OP[\"1NEGATE\"]);\n continue;\n } else if (len < OP.PUSHDATA1) w.byte(len);\n else if (len <= 0xff) {\n w.byte(OP.PUSHDATA1);\n w.byte(len);\n } else if (len <= 0xffff) {\n w.byte(OP.PUSHDATA2);\n w.bytes(P.U16LE.encode(len));\n } else {\n w.byte(OP.PUSHDATA4);\n w.bytes(P.U32LE.encode(len));\n }\n w.bytes(o);\n }\n },\n decodeStream: (r: P.Reader): ArkadeScriptType => {\n const out: ArkadeScriptType = [];\n while (!r.isEnd()) {\n const cur = r.byte();\n // Data push: 0 < cur <= PUSHDATA4\n if (OP.OP_0 < cur && cur <= OP.PUSHDATA4) {\n let len;\n if (cur < OP.PUSHDATA1) len = cur;\n else if (cur === OP.PUSHDATA1) len = P.U8.decodeStream(r);\n else if (cur === OP.PUSHDATA2) len = P.U16LE.decodeStream(r);\n else if (cur === OP.PUSHDATA4) len = P.U32LE.decodeStream(r);\n else throw new Error(\"Should be not possible\");\n out.push(r.bytes(len));\n } else if (cur === 0x00) {\n out.push(0);\n } else if (OP.OP_1 <= cur && cur <= OP.OP_16) {\n out.push(cur - (OP.OP_1 - 1));\n } else if (cur === OP[\"1NEGATE\"]) {\n out.push(-1);\n } else {\n const op = ArkadeOPNames[cur] as keyof typeof ARKADE_OPS;\n if (op === undefined) throw new Error(`Unknown opcode=${cur.toString(16)}`);\n out.push(op);\n }\n }\n return out;\n },\n});\n\n/**\n * Convert script operations to ASM (assembly) format.\n * Supports both Bitcoin and Arkade opcodes.\n *\n * @example\n * ```typescript\n * toASM(['DUP', 'HASH160', 'INSPECTOUTPUTVALUE']) // \"OP_DUP OP_HASH160 OP_INSPECTOUTPUTVALUE\"\n * toASM(ArkadeScript.decode(bytes))\n * ```\n */\nexport function toASM(script: ArkadeScriptType): string {\n const parts: string[] = [];\n\n for (const op of script) {\n if (typeof op === \"string\") {\n // Opcode name from ArkadeOPNames — add OP_ prefix for ASM format\n const name = op.startsWith(\"OP_\") ? op : `OP_${op}`;\n parts.push(name);\n } else if (typeof op === \"number\" || typeof op === \"bigint\") {\n if (op === 0 || op === 0n) {\n parts.push(\"OP_0\");\n } else if (op >= 1 && op <= 16) {\n parts.push(`OP_${op}`);\n } else if (op === -1 || op === -1n) {\n parts.push(\"OP_1NEGATE\");\n } else {\n // A bare decimal token would not survive fromASM (it parses\n // hex or opcodes only) — render the minimal script-num bytes,\n // which re-encode byte-identically to the number itself.\n parts.push(hex.encode(BigNum.encode(BigInt(op))));\n }\n } else {\n // Uint8Array data\n parts.push(hex.encode(op));\n }\n }\n\n return parts.join(\" \");\n}\n\n/**\n * Parse ASM (assembly) format to script operations.\n * Supports both Bitcoin and Arkade opcodes.\n *\n * @example\n * ```typescript\n * fromASM(\"OP_DUP OP_HASH160 deadbeef OP_NUM2BIN\")\n * // => ['DUP', 'HASH160', Uint8Array, 'NUM2BIN']\n * ```\n */\nexport function fromASM(asm: string): ArkadeScriptType {\n const tokens = asm.trim().split(/\\s+/).filter(Boolean);\n const out: ArkadeScriptType = [];\n\n for (const token of tokens) {\n // OP_0 → number 0\n if (token === \"OP_0\" || token === \"OP_FALSE\") {\n out.push(0);\n continue;\n }\n\n // OP_TRUE → number 1\n if (token === \"OP_TRUE\") {\n out.push(1);\n continue;\n }\n\n // OP_1 through OP_16 → number\n const numMatch = token.match(/^OP_(\\d+)$/);\n if (numMatch) {\n const n = parseInt(numMatch[1], 10);\n if (n >= 1 && n <= 16) {\n out.push(n);\n continue;\n }\n }\n\n // Try opcode lookup: strip OP_ prefix to get the key in ARKADE_OPS\n let key: string | undefined;\n if (token.startsWith(\"OP_\")) {\n key = token.slice(3);\n } else {\n key = token;\n }\n\n if (key in ARKADE_OPS) {\n out.push(key as keyof typeof ARKADE_OPS);\n continue;\n }\n\n // Try to parse as hex data\n if (/^[0-9a-fA-F]+$/.test(token) && token.length % 2 === 0) {\n try {\n out.push(hex.decode(token));\n continue;\n } catch {\n // Not valid hex, fall through\n }\n }\n\n throw new Error(`Invalid ASM token: ${token}`);\n }\n\n return out;\n}\n\n/**\n * Convert ASM string directly to script bytes\n */\nexport function asmToBytes(asm: string): Uint8Array {\n return ArkadeScript.encode(fromASM(asm));\n}\n\n/**\n * Convert script bytes directly to ASM string\n */\nexport function bytesToASM(script: Uint8Array): string {\n return toASM(ArkadeScript.decode(script));\n}\n","/**\n * Normalize a secp256k1 public key to the 32-byte x-only form every tapscript,\n * covenant param and `params.serverPubKey` in this SDK is denominated in.\n *\n * A compressed key drops its parity prefix; an x-only key passes through. Both\n * arrive over the same wires — arkd advertises `signerPubkey` either way,\n * `Identity.xOnlyPublicKey` implementations vary, and solver-supplied fields\n * are whatever the peer sent — so the caller usually cannot know which it\n * holds. Anything else is refused rather than silently truncated: a 65-byte\n * uncompressed key, stripped of one byte, yields a plausible 32-byte value\n * that is not the key, which surfaces as an address nobody funded.\n *\n * The result may alias `key` rather than copy it; callers that mutate either\n * value after normalization should copy first.\n *\n * @param key - 32-byte x-only or 33-byte compressed public key\n * @param label - Name used in the error, e.g. `\"ark signer key\"`\n * @see toXOnlySignerHex for the hex-in, hex-out signer-rotation equivalent\n */\nexport function toXOnly(key: Uint8Array, label = \"public key\"): Uint8Array {\n if (key.length === 32) return key;\n if (key.length === 33 && (key[0] === 0x02 || key[0] === 0x03)) return key.subarray(1);\n throw new Error(`${label} is not a compressed or x-only public key`);\n}\n","/**\n * Arkade Script Tweak\n *\n * Computes the tweaked public key for Arkade scripts.\n * The tweak is: tweakedPubKey = P + taggedHash(\"ArkScriptHash\", script) * G\n *\n * This is NOT taproot tweaking — it's a simple EC point addition used by\n * the emulator service to bind a script to a signing key.\n */\n\nimport { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesToNumberBE } from \"@noble/curves/utils.js\";\n\nimport { toXOnly } from \"../utils/keys\";\n\nconst TAG_SCRIPT = \"ArkScriptHash\";\nconst TAG_WITNESS = \"ArkWitnessHash\";\n\n/**\n * Compute the tagged hash of an Arkade script.\n * Uses BIP-340 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || script)\n *\n * @param script - The raw Arkade script bytes\n * @returns 32-byte hash\n */\nexport function arkadeScriptHash(script: Uint8Array): Uint8Array {\n return schnorr.utils.taggedHash(TAG_SCRIPT, script);\n}\n\n/**\n * Compute the tagged hash of an Arkade witness.\n * Uses BIP-340 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || witness)\n *\n * @param witness - The raw Arkade witness bytes\n * @returns 32-byte hash, or 32 zero bytes if witness is empty\n */\nexport function arkadeWitnessHash(witness: Uint8Array): Uint8Array {\n if (witness.length === 0) {\n return new Uint8Array(32);\n }\n return schnorr.utils.taggedHash(TAG_WITNESS, witness);\n}\n\n/**\n * Compute the Arkade script tweaked public key.\n * result = pubKey + taggedHash(\"ArkScriptHash\", script) * G\n *\n * The input pubKey should be a compressed (33-byte) or x-only (32-byte) public key.\n * Returns a 32-byte x-only public key.\n *\n * @param pubKey - The emulator's base public key (32 or 33 bytes)\n * @param script - The raw Arkade script bytes\n * @returns 32-byte x-only tweaked public key\n */\nexport function computeArkadeScriptPublicKey(pubKey: Uint8Array, script: Uint8Array): Uint8Array {\n const hash = arkadeScriptHash(script);\n\n const point = schnorr.utils.lift_x(bytesToNumberBE(toXOnly(pubKey, \"emulator key\")));\n\n // tweak = (scriptHash mod n) * G\n const scalar = bytesToNumberBE(hash) % secp256k1.Point.CURVE().n;\n const tweak = secp256k1.Point.BASE.multiply(scalar);\n\n return schnorr.utils.pointToBytes(point.add(tweak));\n}\n","import { Script } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport {\n CLTVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n ConditionMultisigTapscript,\n CSVMultisigTapscript,\n MultisigTapscript,\n RelativeTimelock,\n} from \"./tapscript\";\nimport { hex } from \"@scure/base\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { ArkadeScript, type ArkadeScriptType } from \"../arkade/script\";\nimport { computeArkadeScriptPublicKey } from \"../arkade/tweak\";\n\n/** Virtual Hash Time Lock Contract (VHTLC) namespace. */\nexport namespace VHTLC {\n export interface Options {\n sender: Bytes;\n receiver: Bytes;\n server: Bytes;\n preimageHash: Bytes;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n /**\n * The emulator covenant leaves, ALL OR NOTHING. Present, this adds the\n * three non-interactive leaves the emulator co-signs under a covenant\n * pinning the payout to a pre-committed destination:\n *\n * - `nonInteractiveClaim`: `server` + a covenant-tweaked emulator\n * co-signer, paying `receiverPkScript` — the receiver's claim can\n * be pushed without the receiver being online.\n * - `nonInteractiveRefund`: `server` + `receiver` + a covenant-tweaked\n * emulator co-signer, paying `senderPkScript`, no timelock — lets\n * server and receiver release the refund the moment they agree the\n * swap has failed, and recoverable even if the sender's own key is\n * lost, since no OTHER refund-side leaf survives that.\n * - `nonInteractiveRefundWithoutReceiver`: `server` + the SAME\n * covenant-tweaked co-signer as `nonInteractiveRefund`, paying\n * `senderPkScript` after `refundLocktime` — the only refund tier\n * needing no participant signature at all, so a sender who funded\n * a lockup and vanished is refundable through it alone.\n *\n * WHY ONE FLAG AND NOT A SWITCH PER LEAF. The three are one mechanism\n * — the same emulator key, the same `enforcePayTo` covenant pointed\n * at a per-role destination — and they protect opposite directions of\n * the same swap, so no real configuration wants a subset. A subset\n * would cost, not buy: every optional leaf multiplies the tree shapes\n * a counterparty must derive to verify an address (nothing on the\n * wire says which leaves a quote carries), so per-leaf toggling turns\n * one address comparison into a combinatorial guess. All-or-nothing\n * keeps the shape count at two: suite, or no suite.\n *\n * Leaf order fixes the taproot merkle root, so the suite is appended\n * after the six signature leaves in a fixed order (claim, refund,\n * timelocked refund) and a script built with this option NEVER\n * collides with one built without it — which is what makes \"did this\n * quote opt in\" a question an address comparison answers.\n *\n * STABLE PER RELEASE: what this option builds does not change within\n * a published SDK version. A future covenant leaf joins the suite\n * only behind a NEW option, so re-deriving a lockup with the SDK\n * that quoted it reproduces its address byte-for-byte.\n */\n nonInteractiveParameters?: {\n /**\n * The emulator service's public key, 32-byte x-only or 33-byte\n * compressed. ONE key, tweaked per covenant destination, becomes\n * the co-signer of every leaf in the suite — the leaves share it\n * structurally, and BIP-341 tapscript sighashes committing to the\n * tapleaf hash are what keep a signature for one leaf from\n * replaying against another.\n */\n emulatorPubkey: Bytes;\n /**\n * Where the claim covenant pays: the receiver's own P2TR\n * pkScript, 34 bytes.\n */\n receiverPkScript: Bytes;\n /**\n * Where BOTH refund covenants pay: the sender's own P2TR\n * pkScript, 34 bytes. One destination shared by both refund\n * leaves, so they cannot diverge on where a refund goes.\n */\n senderPkScript: Bytes;\n /**\n * LEGACY REBUILD ONLY — never for a new lockup.\n *\n * `\"preTimelockedRefund\"` builds the suite WITHOUT its timelocked\n * refund leaf: the shape every emulator-covenant lockup funded\n * before that leaf shipped carries. Lockups already funded in that\n * shape keep it permanently — a leaf cannot be retrofitted onto an\n * address already committed — so re-deriving such a lockup (to\n * spend it, or to verify an old quote's address) needs this. A new\n * lockup that omits the leaf gives up the one refund tier needing\n * nobody, for nothing.\n */\n legacy?: \"preTimelockedRefund\";\n };\n /**\n * Optional: denominate this contract in an Arkade ASSET rather than in\n * sats alone.\n *\n * Only the two NON-INTERACTIVE leaves change. Every other leaf is a\n * signature path that asserts nothing about value, so an asset makes no\n * difference to them — which is why this option reaches exactly the\n * leaves whose covenant the emulator enforces.\n *\n * When set, those covenants additionally require the output to carry at\n * least the input's amount of THIS asset, and to carry exactly one\n * asset. The sat clause is RETAINED, not replaced: an asset-carrying\n * VTXO carries sats too, so dropping it would let a spend satisfy the\n * asset covenant while stripping the sats — exactly as the sat-only\n * covenant lets a spend strip the asset.\n *\n * ONE ASSET IS BOUND, AND ONLY THAT ONE IS PROTECTED. If a VTXO funded to\n * this contract carries ADDITIONAL assets alongside the bound one, those\n * are not covered: whoever assembles a covenant spend chooses where they\n * go, and can send them anywhere.\n *\n * `INSPECTOUTASSETCOUNT == 1` does not close that. It constrains the\n * covenant's OUTPUT to exactly one asset — so the extras cannot ride\n * along with the bound asset — but arkd's conservation rule is satisfied\n * by routing them to a different output, which the covenant says nothing\n * about. The bound asset arrives; the rest is the spender's to direct.\n *\n * So fund an asset contract with the asset it names and nothing else. A\n * multi-asset VTXO behind this covenant is a loss waiting for whoever\n * pushes the spend.\n *\n * The id is the pair the introspection opcodes take. A canonical Asset\n * ID is `(genesis txid, group index)`, never a single blob.\n */\n asset?: {\n /**\n * The asset's genesis transaction id, 32 bytes, in CANONICAL order\n * — exactly the leading 32 bytes of a serialized Asset ID, no flip.\n *\n * The covenant reverses it internally because the introspection\n * opcodes match wire order; callers never do that themselves, and a\n * caller who pre-reverses gets a contract that is unspendable on its\n * covenant leaves with nothing in the error naming why.\n */\n txid: Bytes;\n /** The asset group index within that genesis transaction. */\n groupIndex: number;\n };\n }\n\n /**\n * Shared construction and accessors for every VHTLC script version. The\n * only thing that varies between versions is which preimage-condition\n * fragment `claim`/`unilateralClaim`/`nonInteractiveClaim` are built\n * from — everything else (the multisig/timelock leaves, the\n * non-interactive covenant leaves, the accessor methods) is identical,\n * so versions are expressed as thin subclasses over one builder rather\n * than as separate, independently-maintained copies of this class.\n */\n abstract class BaseScript extends VtxoScript {\n readonly options: Options;\n readonly claimScript: string;\n readonly refundScript: string;\n readonly refundWithoutReceiverScript: string;\n readonly unilateralClaimScript: string;\n readonly unilateralRefundScript: string;\n readonly unilateralRefundWithoutReceiverScript: string;\n readonly nonInteractiveClaimScript?: string;\n readonly nonInteractiveClaimArkadeScript?: Bytes;\n readonly nonInteractiveRefundScript?: string;\n readonly nonInteractiveRefundArkadeScript?: Bytes;\n readonly nonInteractiveRefundWithoutReceiverScript?: string;\n readonly nonInteractiveRefundWithoutReceiverArkadeScript?: Bytes;\n\n protected constructor(options: Options, preimageCondition: (hash: Bytes) => Bytes) {\n validateOptions(options);\n\n const {\n sender,\n receiver,\n server,\n preimageHash,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n } = options;\n\n // The one leaf-condition fragment `claim`, `unilateralClaim`, and\n // (when present) `nonInteractiveClaim` all reuse below — computed\n // once so all three can never drift from one another within the\n // same script version.\n const conditionScript = preimageCondition(preimageHash);\n\n const claimScript = ConditionMultisigTapscript.encode({\n conditionScript,\n pubkeys: [receiver, server],\n }).script;\n\n const refundScript = MultisigTapscript.encode({\n pubkeys: [sender, receiver, server],\n }).script;\n\n const refundWithoutReceiverScript = CLTVMultisigTapscript.encode({\n absoluteTimelock: refundLocktime,\n pubkeys: [sender, server],\n }).script;\n\n const unilateralClaimScript = ConditionCSVMultisigTapscript.encode({\n conditionScript,\n timelock: unilateralClaimDelay,\n pubkeys: [receiver],\n }).script;\n\n const unilateralRefundScript = CSVMultisigTapscript.encode({\n timelock: unilateralRefundDelay,\n pubkeys: [sender, receiver],\n }).script;\n\n const unilateralRefundWithoutReceiverScript = CSVMultisigTapscript.encode({\n timelock: unilateralRefundWithoutReceiverDelay,\n pubkeys: [sender],\n }).script;\n\n const scripts = [\n claimScript,\n refundScript,\n refundWithoutReceiverScript,\n unilateralClaimScript,\n unilateralRefundScript,\n unilateralRefundWithoutReceiverScript,\n ];\n\n let arkadeScriptNic: Bytes | undefined;\n let nonInteractiveClaimScript: Bytes | undefined;\n let arkadeScriptNir: Bytes | undefined;\n let nonInteractiveRefundScript: Bytes | undefined;\n let nonInteractiveRefundWithoutReceiverScript: Bytes | undefined;\n const covenants = options.nonInteractiveParameters;\n if (covenants) {\n arkadeScriptNic = enforcePayToMaybeAsset(covenants.receiverPkScript, options.asset);\n nonInteractiveClaimScript = ConditionMultisigTapscript.encode({\n conditionScript,\n pubkeys: [\n server,\n computeArkadeScriptPublicKey(covenants.emulatorPubkey, arkadeScriptNic),\n ],\n }).script;\n scripts.push(nonInteractiveClaimScript);\n\n arkadeScriptNir = enforcePayToMaybeAsset(covenants.senderPkScript, options.asset);\n // Derived ONCE and shared by both refund covenant leaves. They\n // pin the same destination, so they must commit to the same\n // key; computing it twice would make that a coincidence rather\n // than a guarantee.\n const nirCosigner = computeArkadeScriptPublicKey(\n covenants.emulatorPubkey,\n arkadeScriptNir,\n );\n // No timelock: server + receiver together can release this\n // immediately, same as `refund` above, just without needing\n // the sender's own signature — the covenant is what still\n // guarantees the payout can only reach the sender.\n nonInteractiveRefundScript = MultisigTapscript.encode({\n pubkeys: [server, receiver, nirCosigner],\n }).script;\n scripts.push(nonInteractiveRefundScript);\n\n if (covenants.legacy !== \"preTimelockedRefund\") {\n // The same tier `refundWithoutReceiver` reaches, reached\n // without the sender: their signature is replaced by the\n // covenant, exactly as `nonInteractiveRefund` replaces it\n // in `refund`. Last in `scripts`, because leaf order fixes\n // the merkle root and every earlier leaf must keep its\n // position.\n nonInteractiveRefundWithoutReceiverScript = CLTVMultisigTapscript.encode({\n absoluteTimelock: refundLocktime,\n pubkeys: [server, nirCosigner],\n }).script;\n scripts.push(nonInteractiveRefundWithoutReceiverScript);\n }\n }\n\n super(scripts);\n\n this.options = options;\n this.claimScript = hex.encode(claimScript);\n this.refundScript = hex.encode(refundScript);\n this.refundWithoutReceiverScript = hex.encode(refundWithoutReceiverScript);\n this.unilateralClaimScript = hex.encode(unilateralClaimScript);\n this.unilateralRefundScript = hex.encode(unilateralRefundScript);\n this.unilateralRefundWithoutReceiverScript = hex.encode(\n unilateralRefundWithoutReceiverScript,\n );\n if (nonInteractiveClaimScript) {\n this.nonInteractiveClaimScript = hex.encode(nonInteractiveClaimScript);\n this.nonInteractiveClaimArkadeScript = arkadeScriptNic;\n }\n if (nonInteractiveRefundScript) {\n this.nonInteractiveRefundScript = hex.encode(nonInteractiveRefundScript);\n this.nonInteractiveRefundArkadeScript = arkadeScriptNir;\n }\n if (nonInteractiveRefundWithoutReceiverScript) {\n this.nonInteractiveRefundWithoutReceiverScript = hex.encode(\n nonInteractiveRefundWithoutReceiverScript,\n );\n this.nonInteractiveRefundWithoutReceiverArkadeScript = arkadeScriptNir;\n }\n }\n\n /** Return the collaborative claim tapleaf script. */\n claim(): TapLeafScript {\n return this.findLeaf(this.claimScript);\n }\n\n /** Return the collaborative refund tapleaf script. */\n refund(): TapLeafScript {\n return this.findLeaf(this.refundScript);\n }\n\n /** Return the refund-without-receiver tapleaf script. */\n refundWithoutReceiver(): TapLeafScript {\n return this.findLeaf(this.refundWithoutReceiverScript);\n }\n\n /** Return the unilateral claim tapleaf script. */\n unilateralClaim(): TapLeafScript {\n return this.findLeaf(this.unilateralClaimScript);\n }\n\n /** Return the unilateral refund tapleaf script. */\n unilateralRefund(): TapLeafScript {\n return this.findLeaf(this.unilateralRefundScript);\n }\n\n /** Return the unilateral refund-without-receiver tapleaf script. */\n unilateralRefundWithoutReceiver(): TapLeafScript {\n return this.findLeaf(this.unilateralRefundWithoutReceiverScript);\n }\n\n /** Return the non-interactive claim tapleaf script as well as the ArkadeScript. */\n nonInteractiveClaim(): [TapLeafScript, Bytes] {\n if (!this.nonInteractiveClaimScript || !this.nonInteractiveClaimArkadeScript) {\n throw new Error(\"VHTLC has no non-interactive claim leaf\");\n }\n return [\n this.findLeaf(this.nonInteractiveClaimScript),\n this.nonInteractiveClaimArkadeScript,\n ];\n }\n\n /** Return the non-interactive refund tapleaf script as well as the ArkadeScript. */\n nonInteractiveRefund(): [TapLeafScript, Bytes] {\n if (!this.nonInteractiveRefundScript || !this.nonInteractiveRefundArkadeScript) {\n throw new Error(\"VHTLC has no non-interactive refund leaf\");\n }\n return [\n this.findLeaf(this.nonInteractiveRefundScript),\n this.nonInteractiveRefundArkadeScript,\n ];\n }\n\n /**\n * Return the timelocked non-interactive refund tapleaf and its ArkadeScript.\n *\n * SPENDING THIS LEAF, CONCRETELY — confirmed from this SDK's own\n * emulator client and covenant-spend builder ({@link\n * EmulatorProvider} in `src/providers/emulator.ts`, and {@link\n * ArkadeTransactionBuilder} in `src/arkade/contract.ts`), which is\n * the general machinery every covenant leaf in this file goes\n * through:\n *\n * 1. Build the ark tx spending this leaf (this method's {@link\n * TapLeafScript} as `tapLeafScript`, this script's {@link\n * VtxoScript.encode} as `tapTree`), plus its checkpoint tx.\n * 2. Attach the ArkadeScript this method returns to the spent\n * input via an `EmulatorPacket` (type 1) — `{ vin, script:\n * <this ArkadeScript>, witness: <empty> }`, empty because the\n * script pushes its own input/output index with\n * `PUSHCURRENTINPUTINDEX` rather than reading one from the\n * witness — wrapped in an `Extension` OP_RETURN output on the\n * ark tx.\n * 3. Attach the spent input's OWN creating ark tx as `PrevArkTx` on\n * input 0 — required so the emulator can resolve that input's\n * prevout pkScript/value; it does not otherwise have them.\n * 4. POST the (base64-PSBT) ark tx and checkpoint(s) as `{ arkTx,\n * checkpointTxs }` to the emulator's `POST /v1/tx`.\n *\n * THE COVENANT CHECK the emulator runs against that ArkadeScript —\n * `enforcePayTo(senderPkScript)`, see that function above — is: the\n * output at this SAME input's index is a v1 P2TR output paying\n * `senderPkScript`, with a value at least the input's. Only on that\n * check passing does the emulator sign for `nirCosigner` (the\n * `emulatorPubkey` tweaked by this ArkadeScript's hash); the\n * response carries the fully co-signed `signedArkTx` and\n * `signedCheckpointTxs` — `ArkadeTransactionBuilder.send()`'s own\n * comment on this path: \"the emulator executes the arkade script\n * and finalizes with arkd\" — no separate call to arkd is made by\n * this SDK for a covenant spend.\n * Neither `server` nor `receiver` play any part in that check: this\n * leaf's tapscript still requires `server`'s own signature\n * alongside `nirCosigner`'s (see the class doc above), but that is\n * consensus-level multisig, not something the covenant enforces.\n *\n * NOT SPENDABLE UNTIL `refundLocktime` MATURES — the tapscript's\n * `OP_CHECKLOCKTIMEVERIFY` is arkd's concern, not the emulator's;\n * the emulator will happily co-sign an immature spend and arkd will\n * then refuse it. A block-height-typed `refundLocktime` (below the\n * standard height/timestamp boundary this SDK names\n * `CLTV_HEIGHT_THRESHOLD`, 500,000,000, in\n * `src/contracts/handlers/helpers.ts`) is refused by arkd for a\n * forfeit-eligible leaf independent of maturity — use a\n * seconds-typed (absolute Unix timestamp) value.\n */\n nonInteractiveRefundWithoutReceiver(): [TapLeafScript, Bytes] {\n if (\n !this.nonInteractiveRefundWithoutReceiverScript ||\n !this.nonInteractiveRefundWithoutReceiverArkadeScript\n ) {\n throw new Error(\"VHTLC has no non-interactive refund-without-receiver leaf\");\n }\n return [\n this.findLeaf(this.nonInteractiveRefundWithoutReceiverScript),\n this.nonInteractiveRefundWithoutReceiverArkadeScript,\n ];\n }\n }\n\n /**\n * Virtual Hash Time Lock Contract (VHTLC) script implementation.\n *\n * VHTLC enables atomic swaps and conditional payments in the Arkade protocol.\n * It provides multiple spending paths:\n *\n * - **claim**: Receiver can claim funds by revealing the preimage\n * - **refund**: Sender and receiver can collaboratively refund\n * - **refundWithoutReceiver**: Sender can refund after locktime expires\n * - **unilateralClaim**: Receiver can claim unilaterally after delay\n * - **unilateralRefund**: Sender and receiver can refund unilaterally after delay\n * - **unilateralRefundWithoutReceiver**: Sender can refund unilaterally after delay\n * - **nonInteractiveClaim** (with `nonInteractiveParameters`): server + emulator\n * can push the receiver's claim, pinned to a pre-committed destination\n * - **nonInteractiveRefund** (with `nonInteractiveParameters`): server + receiver\n * + emulator can push the sender's refund immediately, no timelock,\n * pinned to a pre-committed destination — recoverable even if the\n * sender's own key is lost\n * - **nonInteractiveRefundWithoutReceiver** (with `nonInteractiveParameters`):\n * server + emulator can push the sender's refund after `refundLocktime`,\n * pinned to a pre-committed destination — the only refund tier needing\n * no participant signature at all\n *\n * See {@link ScriptV2} for the current recommended construction — same\n * leaf ladder, same options shape, an added length check on the claim\n * preimage. This class is unchanged and stays available as-is.\n *\n * **Pre-existing limitation: the `vhtlc` contract handler registers none\n * of the covenant leaves.** `nonInteractiveParameters` builds on this class\n * exactly as it does on {@link ScriptV2} — both extend the same\n * `BaseScript` where those leaves are constructed. But the `vhtlc`\n * contract handler (`src/contracts/handlers/vhtlc.ts`) round-trips none\n * of them: its params type carries no covenant fields, and\n * `createScript` only ever builds the six signature-only leaves. A V1\n * script built with the covenant suite therefore compiles and can\n * be funded, but cannot be registered as a `vhtlc` contract — the\n * handler would derive a different (six-leaf) script for the same\n * params and `ContractManager` refuses the mismatch. Register through\n * the `vhtlc-v2` handler instead, which round-trips the suite.\n *\n * @example\n * ```typescript\n * const vhtlc = new VHTLC.Script({\n * sender: alicePubKey,\n * receiver: bobPubKey,\n * server: serverPubKey,\n * preimageHash: hash160(secret),\n * refundLocktime: BigInt(chainTip + 10),\n * unilateralClaimDelay: { type: 'blocks', value: 100n },\n * unilateralRefundDelay: { type: 'blocks', value: 102n },\n * unilateralRefundWithoutReceiverDelay: { type: 'blocks', value: 103n }\n * });\n * ```\n */\n export class Script extends BaseScript {\n constructor(options: Options) {\n super(options, preimageConditionScript);\n }\n }\n\n /**\n * Same leaf ladder as {@link Script}, built with {@link\n * preimageConditionScriptV2} instead of {@link preimageConditionScript}\n * for every leaf that gates on the preimage (`claim`, `unilateralClaim`,\n * and, when present, `nonInteractiveClaim`) — see that function's doc\n * comment for what differs and why. A distinct class rather than a flag\n * on {@link Script}: the two produce different script bytes (and so\n * different addresses) for the same participant keys, and keeping them\n * as separate types makes that a compile-time-visible choice at every\n * call site instead of a runtime option that's easy to get wrong.\n */\n export class ScriptV2 extends BaseScript {\n constructor(options: Options) {\n super(options, preimageConditionScriptV2);\n }\n }\n\n function validateOptions(options: Options): void {\n const {\n sender,\n receiver,\n server,\n preimageHash,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n } = options;\n\n if (!preimageHash || preimageHash.length !== 20) {\n throw new Error(\"preimage hash must be 20 bytes\");\n }\n // The non-interactive leaves are the ONLY ones carrying a covenant\n // — the signature leaves assert nothing about value — so they are the\n // only place an asset can be bound. Accepting `asset` without the\n // covenant suite would emit a sat-only contract and say nothing about\n // it: the caller funds it believing the asset is protected, and any\n // spend that satisfies the sat covenant walks off with the asset. The\n // one outward difference is a pkScript matching a non-asset address,\n // which is not something a caller thinks to check. Refuse instead of\n // dropping it.\n if (options.asset !== undefined && !options.nonInteractiveParameters) {\n throw new Error(\"asset has no effect without nonInteractiveParameters\");\n }\n\n if (options.nonInteractiveParameters) {\n const { emulatorPubkey, receiverPkScript, senderPkScript, legacy } =\n options.nonInteractiveParameters;\n if (!emulatorPubkey || (emulatorPubkey.length !== 32 && emulatorPubkey.length !== 33)) {\n throw new Error(\"Invalid public key length (emulator)\");\n }\n if (!receiverPkScript || !isP2trPkScript(receiverPkScript)) {\n throw new Error(\"Invalid P2TR script\");\n }\n if (!senderPkScript || !isP2trPkScript(senderPkScript)) {\n throw new Error(\"Invalid P2TR script\");\n }\n // One literal is the whole point of the field (see its doc\n // comment); anything else is a caller inventing a shape that does\n // not exist, and TS types are no check at all from JS.\n if (legacy !== undefined && legacy !== \"preTimelockedRefund\") {\n throw new Error(\n `nonInteractiveParameters.legacy must be \"preTimelockedRefund\" when set, got ${JSON.stringify(legacy)}`,\n );\n }\n }\n if (!receiver || receiver.length !== 32) {\n throw new Error(\"Invalid public key length (receiver)\");\n }\n if (!sender || sender.length !== 32) {\n throw new Error(\"Invalid public key length (sender)\");\n }\n if (!server || server.length !== 32) {\n throw new Error(\"Invalid public key length (server)\");\n }\n if (typeof refundLocktime !== \"bigint\" || refundLocktime <= 0n) {\n throw new Error(\"refund locktime must be greater than 0\");\n }\n if (\n !unilateralClaimDelay ||\n typeof unilateralClaimDelay.value !== \"bigint\" ||\n unilateralClaimDelay.value <= 0n\n ) {\n throw new Error(\"unilateral claim delay must greater than 0\");\n }\n if (unilateralClaimDelay.type === \"seconds\" && unilateralClaimDelay.value % 512n !== 0n) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (unilateralClaimDelay.type === \"seconds\" && unilateralClaimDelay.value < 512n) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n if (\n !unilateralRefundDelay ||\n typeof unilateralRefundDelay.value !== \"bigint\" ||\n unilateralRefundDelay.value <= 0n\n ) {\n throw new Error(\"unilateral refund delay must greater than 0\");\n }\n if (unilateralRefundDelay.type === \"seconds\" && unilateralRefundDelay.value % 512n !== 0n) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (unilateralRefundDelay.type === \"seconds\" && unilateralRefundDelay.value < 512n) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n if (\n !unilateralRefundWithoutReceiverDelay ||\n typeof unilateralRefundWithoutReceiverDelay.value !== \"bigint\" ||\n unilateralRefundWithoutReceiverDelay.value <= 0n\n ) {\n throw new Error(\"unilateral refund without receiver delay must greater than 0\");\n }\n if (\n unilateralRefundWithoutReceiverDelay.type === \"seconds\" &&\n unilateralRefundWithoutReceiverDelay.value % 512n !== 0n\n ) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (\n unilateralRefundWithoutReceiverDelay.type === \"seconds\" &&\n unilateralRefundWithoutReceiverDelay.value < 512n\n ) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n }\n}\n\nfunction preimageConditionScript(preimageHash: Bytes): Bytes {\n return Script.encode([\"HASH160\", preimageHash, \"EQUAL\"]);\n}\n\n/**\n * Same as {@link preimageConditionScript}, plus an explicit length check on\n * the witness item before it's hashed: `OP_SIZE 32 OP_EQUALVERIFY` ahead of\n * the `OP_HASH160` check, the same prefix real-world HTLC scripts (e.g.\n * BOLT3's) carry for the same reason — the claim leaf otherwise accepts any\n * witness value whose HASH160 matches, regardless of length, and this\n * contract's preimage is always exactly 32 bytes by construction. Used by\n * {@link VHTLC.ScriptV2} for every leaf gated on the preimage.\n */\nfunction preimageConditionScriptV2(preimageHash: Bytes): Bytes {\n return Script.encode([\"SIZE\", 32, \"EQUALVERIFY\", \"HASH160\", preimageHash, \"EQUAL\"]);\n}\n\n/**\n * A v1 P2TR pkScript is exactly `OP_1 <32-byte-program>` (0x51 0x20 ...) — 34\n * bytes total. Length alone isn't enough: any other 34-byte value (e.g.\n * {@link ArkAddress.subdustPkScript}'s `OP_RETURN <32 bytes>`, or a P2WSH\n * script) has the same length but a different witness version, and\n * `enforcePayTo` below trusts byte 2 onward as the taproot program\n * unconditionally.\n */\nfunction isP2trPkScript(pkScript: Bytes): boolean {\n return pkScript.length === 34 && pkScript[0] === 0x51 && pkScript[1] === 0x20;\n}\n\n/**\n * The covenant: \"this input's output pays the given P2TR script, value >=\n * input\". Shared by every leaf {@link VHTLC.Options.nonInteractiveParameters}\n * builds — only the destination and the tier it gates differ.\n *\n * `PUSHCURRENTINPUTINDEX` as the output index is not an assumption about how\n * the Ark round pairs inputs with outputs — the covenant imposes the pairing\n * on the spender. Whatever index a spending tx places this input at, the\n * output at that same index must pay the destination at least the input's\n * value, or the ArkadeScript fails and the server never co-signs. A tx with no\n * output at that index fails the same way: the leaf is unsatisfiable, not\n * fooled. Index alignment is therefore a *liveness* obligation on whoever\n * assembles the spend (the solver, for both leaves — this SDK never builds\n * them; its own aggregate refund uses the interactive leaf precisely because\n * it lacks this per-index constraint, see `refund.ts`), never a safety\n * assumption.\n *\n * WHY `>= input` AND NOT `>= the quoted amount`. This bound is CONSERVATION,\n * not agreement: it says the spend may not skim, and says nothing about what\n * any quote promised. That is deliberate, on both leaves, and it is a question\n * worth answering here because the covenant reads like the natural place to\n * pin a quote and is not.\n *\n * - A QUOTE IS NOT THE COVENANT'S TO KNOW. Pinning one compiles it into the\n * leaf, hence into the emulator key, hence into the ADDRESS. Re-quoting\n * would move the address of a contract that may already be funded.\n * - MISFUNDING IS THE SENDER'S EXPOSURE. They chose the amount. A lockup that\n * over- or underpays the quote is theirs to have created, and the\n * counterparty's protection is to decline it — refuse the swap and let it\n * refund — which is an application-layer decision, taken where a quote\n * actually lives, and revisable without moving anyone's address.\n * - NOTHING IS CLAIMED WITHOUT THE PREIMAGE. Both covenant leaves sit behind\n * the hash condition, so an underfunded lockup cannot be claimed out from\n * under the counterparty on the covenant's say-so. The covenant's job is to\n * stop a spend that satisfies the condition from redirecting the value; it\n * is not to adjudicate whether the trade was fair.\n *\n * So a funding gate that compares a lockup against its quote belongs in the\n * consumer, not here. `lightning-swap-service`'s `lockupIsFunded` is that gate.\n */\n/**\n * The sat half of both covenants: the output at this input's index is P2TR,\n * pays `destinationPkScript`, and carries at least the input's value.\n *\n * ONE COPY, shared by {@link enforcePayTo} and {@link enforcePayToAsset}. The\n * asset covenant used to restate these tokens inline under a comment promising\n * they matched \"byte-for-byte\" — a promise nothing enforced, and one that an\n * option added to one and forgotten on the other would have broken silently.\n */\nfunction satClause(destinationPkScript: Bytes): ArkadeScriptType {\n return [\n \"PUSHCURRENTINPUTINDEX\",\n \"DUP\",\n \"INSPECTOUTPUTSCRIPTPUBKEY\",\n 1,\n \"EQUALVERIFY\",\n destinationPkScript.subarray(2),\n \"EQUALVERIFY\",\n \"INSPECTOUTPUTVALUE\",\n \"PUSHCURRENTINPUTINDEX\",\n \"INSPECTINPUTVALUE\",\n \"GREATERTHANOREQUAL\",\n ];\n}\n\nfunction enforcePayTo(destinationPkScript: Bytes): Bytes {\n // validateOptions already checked this for both current call sites — kept\n // here too, since this covenant is the one place a wrong destination\n // becomes irreversible (a mis-typed leaf, unlike a rejected constructor\n // call, only surfaces once someone tries to spend it).\n if (!isP2trPkScript(destinationPkScript)) {\n throw new Error(\"invalid P2TR script\");\n }\n return ArkadeScript.encode(satClause(destinationPkScript));\n}\n\n/**\n * {@link enforcePayTo} for a contract denominated in an Arkade ASSET: the same\n * covenant, plus \"carries at least the input's amount of exactly this one\n * asset\".\n *\n * The sat covenant is this one's TAIL, restated inline below, so an asset\n * contract enforces everything a sat contract does and never less. That\n * matters because an asset-carrying VTXO carries sats too: a covenant\n * constraining only the asset would let a spend strip the sats, and the\n * sat-only covenant lets a spend strip the ASSET -- the loss this exists to\n * prevent.\n *\n * Two opcode details decide whether it is safe, and the intuitive reading gets\n * both wrong:\n *\n * - A canonical Asset ID is TWO stack items, `asset_txid` then `asset_gidx`.\n * Pushing it as one 32-byte blob encodes cleanly and fails only at spend\n * time, once the contract is already funded.\n * - `INSPECTOUTASSETLOOKUP` pushes `amount 1`, or `0 0` when the asset is\n * ABSENT. The `VERIFY` after each lookup pops that success flag and is\n * load-bearing, not defensive: without it an output carrying NONE of the\n * asset reports amount 0, `0 >= 0` passes, and the stripping spend succeeds\n * anyway. Applied to the input lookup too, so an input whose asset is\n * undeclared cannot compare `0 >= 0` either.\n *\n * `INSPECTOUTASSETCOUNT == 1` bounds the output to the single asset bound, so\n * nothing can be injected alongside it. Deliberately strict: a covenant that\n * is too permissive cannot be tightened once funds are locked to it, while a\n * strict one can be relaxed in a later contract version.\n */\nfunction enforcePayToAsset(\n destinationPkScript: Bytes,\n asset: { txid: Bytes; groupIndex: number },\n): Bytes {\n if (!isP2trPkScript(destinationPkScript)) {\n throw new Error(\"invalid P2TR script\");\n }\n if (asset.txid.length !== 32) {\n throw new Error(`asset txid must be 32 bytes, got ${asset.txid.length}`);\n }\n if (!Number.isInteger(asset.groupIndex) || asset.groupIndex < 0 || asset.groupIndex > 0xffff) {\n throw new Error(\n `asset group index must be an integer in [0, 65535], got ${asset.groupIndex}`,\n );\n }\n // REVERSED, once, here. `asset.txid` is the id in CANONICAL order -- the\n // leading 32 bytes of the serialized Asset ID, which arkd's `serializeTxHash`\n // already reversed \"to match the canonical txid format\". The introspection\n // opcodes match against WIRE order, which is those bytes reversed back. Push\n // the canonical bytes unflipped and the lookup reports the asset ABSENT\n // (`0 0`), so the covenant fails and the contract it guards is unspendable. Nothing in the failure says so: the emulator returns only\n // `OP_VERIFY failed`, and returns it whatever the amount comparison says.\n // Established on regtest against a real minted asset, by elimination against\n // a passing BTC-only control.\n //\n // A copy rather than an in-place reverse: the caller's id is theirs.\n const inspectionTxid = Uint8Array.from(asset.txid).reverse();\n return ArkadeScript.encode([\n // The output carries at least as much of the asset as the input did.\n // Output index is the input's -- the same index alignment the sat\n // covenant relies on, and the same liveness obligation on whoever\n // assembles the spend.\n \"PUSHCURRENTINPUTINDEX\",\n inspectionTxid,\n asset.groupIndex,\n \"INSPECTOUTASSETLOOKUP\",\n \"VERIFY\", // PRESENT on the output, not merely \"zero of it\"\n \"PUSHCURRENTINPUTINDEX\",\n inspectionTxid,\n asset.groupIndex,\n \"INSPECTINASSETLOOKUP\",\n \"VERIFY\", // ...and on the input, so the comparison means something\n \"GREATERTHANOREQUAL\",\n \"VERIFY\",\n // Exactly one asset out: nothing injected alongside the one bound.\n \"PUSHCURRENTINPUTINDEX\",\n \"INSPECTOUTASSETCOUNT\",\n 1,\n \"EQUALVERIFY\",\n // ...then the sat covenant, the same tokens `enforcePayTo` emits.\n ...satClause(destinationPkScript),\n ]);\n}\n\n/** Pick the covenant this contract's denomination calls for. */\nfunction enforcePayToMaybeAsset(\n destinationPkScript: Bytes,\n asset: { txid: Bytes; groupIndex: number } | undefined,\n): Bytes {\n return asset === undefined\n ? enforcePayTo(destinationPkScript)\n : enforcePayToAsset(destinationPkScript, asset);\n}\n","import { hex } from \"@scure/base\";\nimport { VHTLC } from \"../../script/vhtlc\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { assertVhtlcSpendableNow, isCltvSatisfied, isCsvSpendable, resolveRole } from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for VHTLC contracts.\n */\nexport interface VHTLCContractParams {\n sender: Uint8Array;\n receiver: Uint8Array;\n server: Uint8Array;\n preimageHash: Uint8Array;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n}\n\n/**\n * Handler for Virtual Hash Time Lock Contract (VHTLC).\n *\n * VHTLC supports multiple spending paths:\n *\n * Collaborative paths (with server):\n * - claim: Receiver + Server with preimage\n * - refund: Sender + Receiver + Server\n * - refundWithoutReceiver: Sender + Server after CLTV locktime\n *\n * Unilateral paths (without server):\n * - unilateralClaim: Receiver with preimage after CSV delay\n * - unilateralRefund: Sender + Receiver after CSV delay\n * - unilateralRefundWithoutReceiver: Sender after CSV delay\n */\nexport const VHTLCContractHandler: ContractHandler<VHTLCContractParams, VHTLC.Script> &\n TapscriptDeriving<VHTLC.Script> = {\n type: \"vhtlc\",\n\n createScript(params: Record<string, string>): VHTLC.Script {\n const typed = this.deserializeParams(params);\n return new VHTLC.Script(typed);\n },\n\n serializeParams(params: VHTLCContractParams): Record<string, string> {\n return {\n sender: hex.encode(params.sender),\n receiver: hex.encode(params.receiver),\n server: hex.encode(params.server),\n hash: hex.encode(params.preimageHash),\n refundLocktime: params.refundLocktime.toString(),\n claimDelay: timelockToSequence(params.unilateralClaimDelay).toString(),\n refundDelay: timelockToSequence(params.unilateralRefundDelay).toString(),\n refundNoReceiverDelay: timelockToSequence(\n params.unilateralRefundWithoutReceiverDelay,\n ).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): VHTLCContractParams {\n return {\n sender: hex.decode(params.sender),\n receiver: hex.decode(params.receiver),\n server: hex.decode(params.server),\n preimageHash: hex.decode(params.hash),\n refundLocktime: BigInt(params.refundLocktime),\n unilateralClaimDelay: sequenceToTimelock(Number(params.claimDelay)),\n unilateralRefundDelay: sequenceToTimelock(Number(params.refundDelay)),\n unilateralRefundWithoutReceiverDelay: sequenceToTimelock(\n Number(params.refundNoReceiverDelay),\n ),\n };\n },\n\n /**\n * Select spending path based on context.\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n selectPath(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const role = resolveRole(contract, context);\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (!role) {\n return null;\n }\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n return {\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n };\n }\n\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n return {\n leaf: script.refundWithoutReceiver(),\n };\n }\n\n return null;\n }\n\n // Unilateral paths\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n };\n }\n\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n };\n }\n\n return null;\n },\n\n /**\n * Get all possible spending paths (no timelock checks).\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n getAllSpendingPaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n\n if (context.collaborative) {\n // Collaborative paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\") {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n } else {\n // Unilateral paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n getSpendablePaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n return paths;\n }\n\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n /**\n * Refuse an explicit spend of a lockup whose refund path has not opened.\n * Shared with the v2 handler so the two cannot drift.\n * @see assertVhtlcSpendableNow for why this is the one certain case.\n */\n assertSpendableNow(_script: VHTLC.Script, contract: Contract, context: PathContext): void {\n assertVhtlcSpendableNow(contract, context);\n },\n\n /**\n * Never. A live VHTLC is escrow: the counterparty's claim leaf is armed,\n * and generic selection — send, settle, renewal, offboard — would move the\n * lockup out from under a swap the counterparty is still entitled to\n * complete, or race a claim already in flight.\n *\n * Two narrow reasons, and neither is \"spending this would destroy the\n * VTXO\". It would not: the leaf {@link deriveTapscripts} stamps is\n * `refundWithoutReceiver` — `CLTV[sender, server]`, the sender's OWN\n * refund, which the server rejects until `refundLocktime` matures. The\n * reasons are that an escrowed lockup must not count toward the\n * `available` balance bucket, and that generic RENEWAL must not silently\n * execute a refund the caller never asked for — `runPeriodicSettle` selects\n * through `getSpendableVtxos`, which this gate filters, and it runs\n * unprompted whenever a wallet is built without an explicit\n * `settlementConfig`.\n *\n * **Inseparable from {@link deriveTapscripts}.** Deriving the leaf without\n * closing the gate hands generic renewal an escrow it had never been\n * offered before; before that method existed the answer here was\n * unobservable, so the two only ever made sense together.\n *\n * Recovery is filtered on {@link assertSpendableNow}, not on this: the gate\n * is permanent, and applying it there would strand a matured lockup.\n */\n isGenericallySpendable: () => false,\n\n /**\n * The annotation leaf stamped onto every VTXO locked to this contract.\n *\n * **Without this the contract is unusable, not merely unoptimized.**\n * `deriveContractTapscripts` falls back to `script.forfeit()` for any\n * handler that does not implement {@link TapscriptDeriving}, and no VHTLC\n * script version has a `forfeit()` — `VtxoScript` does not define one and\n * `VHTLC.BaseScript` does not add one. The fallback therefore threw\n * `legacy.forfeit is not a function`, `annotatableIn` caught it, and\n * `fetchContractVtxosBulk` dropped this contract's VTXOs before they were\n * persisted. The row existed and was watched while its balance stayed\n * permanently invisible, and `getSyncState()` reported `degraded` forever.\n *\n * `refundWithoutReceiver` is the leaf, for both roles the annotation\n * serves, because it is the only collaborative path this wallet can\n * actually satisfy as the sender — the same conclusion `selectPath`\n * reaches, kept in step with it deliberately. The claim leaves belong to\n * the receiver and need a preimage the sender does not have; `refund` and\n * `unilateralRefund` both need the counterparty's signature, which this\n * protocol has no message to ask for. V1 has no covenant leaves at all.\n *\n * **It carries a CLTV, and callers must respect it.** A settlement built\n * on this leaf is only valid once `refundLocktime` has matured, so a\n * recovery round that sweeps this VTXO early is rejected by the server.\n * Nothing in this handler can enforce that, because the annotation is\n * derived per contract and knows no clock; `recoverVtxos` filters on\n * {@link assertSpendableNow} for it.\n *\n * **Role-blind.** A receiver's row gets the same leaf, which names keys that\n * wallet does not hold, so it is satisfiable only by the wallet holding the\n * lockup's `sender` key and fails at intent registration for anyone else.\n */\n deriveTapscripts(script: VHTLC.Script): DerivedContractTapscripts {\n const leaf = script.refundWithoutReceiver();\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","import { hex } from \"@scure/base\";\nimport { VHTLC } from \"../../script/vhtlc\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { assertVhtlcSpendableNow, isCltvSatisfied, isCsvSpendable, resolveRole } from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * The stored `assetGroupIndex`, as a number, or a throw naming the row.\n *\n * `Number()` alone is not enough here, and it fails in exactly one direction\n * that matters. `VHTLC.ScriptV2` already refuses a non-integer, a negative or\n * anything past `0xffff`, so `\"abc\"`, `\"1.5\"` and `\"-1\"` die one frame down with\n * a clear message. What survives is `Number(\"\")`, `Number(\" \")` and\n * `Number(\"\\t\")` — all of which are **0**, a perfectly valid group index.\n *\n * A blank field therefore does not fail: it silently names group 0 of the same\n * genesis transaction, which is a DIFFERENT asset. The contract then derives a\n * different script from the one the row was written against, and registration\n * dies at `upsertContractRow` with an opaque `Script mismatch` — the same\n * silent-drop class the both-halves-or-neither check above exists to close, one\n * value further in.\n *\n * Anchored and canonical: no sign, no point, no exponent, no leading zero, so a\n * row that round-tripped through this handler's own `serializeParams` is the\n * only shape accepted back.\n */\nconst parseGroupIndex = (raw: string): number => {\n if (!/^(0|[1-9][0-9]*)$/.test(raw)) {\n throw new Error(\n `assetGroupIndex must be a canonical decimal integer, got ${JSON.stringify(raw)}`,\n );\n }\n return Number(raw);\n};\n\n/**\n * Typed parameters for {@link VHTLC.ScriptV2} contracts.\n *\n * The eight mandatory fields are `VHTLCContractParams` verbatim — the two\n * script versions take the same {@link VHTLC.Options}, so a divergent shape\n * here would be a difference with no cause. What V1's handler has no field for\n * is the emulator covenant suite, and that is exactly what the swap corridor's\n * lockup carries, so leaving it out would make this handler unable to\n * round-trip the contract it exists to serve.\n */\nexport interface VHTLCV2ContractParams {\n sender: Uint8Array;\n receiver: Uint8Array;\n server: Uint8Array;\n preimageHash: Uint8Array;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n /**\n * The Arkade asset the covenant leaves bind, if any.\n *\n * @see VHTLC.Options.asset\n */\n asset?: {\n /** The asset's genesis txid, 32 bytes, canonical order — as the serialized Asset ID carries it. */\n txid: Uint8Array;\n /** The asset group index within that genesis transaction. */\n groupIndex: number;\n };\n /**\n * The emulator covenant suite, all or nothing — mirrors {@link\n * VHTLC.Options.nonInteractiveParameters} exactly, including the legacy selector:\n * a row funded before the timelocked refund leaf shipped round-trips with\n * `legacy: \"preTimelockedRefund\"` and re-derives its eight-leaf shape.\n */\n nonInteractiveParameters?: {\n receiverPkScript: Uint8Array;\n emulatorPubkey: Uint8Array;\n senderPkScript: Uint8Array;\n /** @see VHTLC.Options.nonInteractiveParameters.legacy */\n legacy?: \"preTimelockedRefund\";\n };\n}\n\n/**\n * Both halves of an optional covenant leaf, or neither.\n *\n * A row carrying one half of the pair would derive a script with that leaf\n * DROPPED — a different taproot tree, a different pkScript, and so a\n * `Script mismatch` from `upsertContractRow` naming two hex strings and no\n * cause. Rejecting the half-specified pair here names it instead. It is a\n * diagnostic, not a safety boundary: the mismatch check is what actually stops\n * a wrong script from being persisted, and it stops this case too.\n */\nfunction decodeCovenantLeaf<K extends string>(\n params: Record<string, string>,\n destinationKey: K,\n emulatorKey: string,\n label: string,\n): { destination: Uint8Array; emulatorPubkey: Uint8Array } | undefined {\n const destination = params[destinationKey];\n const emulator = params[emulatorKey];\n if (!destination && !emulator) return undefined;\n if (!destination || !emulator) {\n throw new Error(`${label} needs both '${destinationKey}' and '${emulatorKey}', or neither`);\n }\n return { destination: hex.decode(destination), emulatorPubkey: hex.decode(emulator) };\n}\n\n/**\n * Handler for {@link VHTLC.ScriptV2} — the VHTLC whose preimage leaves carry an\n * explicit `OP_SIZE 32 OP_EQUALVERIFY` before the hash check, and which the RFQ\n * swap corridor builds (`@arkade-os/swap`'s `lightningSendVtxoScript`).\n *\n * **Why a separate type string rather than a flag on `vhtlc`.** A handler's\n * `type` names the script class it derives, the way every other registered type\n * does (`default` → `DefaultVtxo.Script`, `vhtlc` → `VHTLC.Script`, `boarding`,\n * `arkade`). V1 and V2 produce different script bytes — and so different\n * pkScripts — for identical participant keys, and `upsertContractRow` derives\n * the script from `params` and refuses any row whose supplied `script` does not\n * match. One type cannot serve both. `vhtlc-v2` also cannot COLLIDE with\n * `vhtlc`: a colliding row needs one pkScript claimed by two types, and the two\n * versions' preimage conditions differ in every tree, so no parameters make\n * them equal. A use-named type (`swap-lockup`) was the alternative and is\n * worse: contracts are keyed by script, so the moment a second use registered\n * the same ScriptV2 the two uses would fight over one row.\n *\n * **Which leaves this offers, and why the set is smaller than the ladder.**\n * ScriptV2 has nine leaves; a wallet holding ONE of the two participant keys\n * can satisfy four of them, and offering a leaf whose signature the caller\n * cannot produce is worse than offering fewer — it turns a refusal into a\n * transaction that gets built and then rejected.\n *\n * | leaf | needs | offered |\n * |---------------------------------------|--------------------------------|---------|\n * | `claim` | receiver + server, preimage | yes, to the receiver |\n * | `refund` | sender + receiver + server | no — needs the counterparty live |\n * | `refundWithoutReceiver` | sender + server, CLTV | yes, to the sender |\n * | `unilateralClaim` | receiver, CSV | yes, to the receiver |\n * | `unilateralRefund` | sender + receiver, CSV | no — needs the counterparty live |\n * | `unilateralRefundWithoutReceiver` | sender, CSV | yes, to the sender |\n * | `nonInteractiveClaim` | server + emulator | no — the wallet holds neither key |\n * | `nonInteractiveRefund` | server + receiver + emulator | no — the wallet holds neither key |\n * | `nonInteractiveRefundWithoutReceiver` | server + emulator, CLTV | no — the wallet holds neither key |\n *\n * The two omitted interactive leaves are the same two the `vhtlc` handler\n * omits, for the same reason: `refund` and `unilateralRefund` both need the\n * OTHER party's signature, and this protocol has no message that asks for one\n * (see `@arkade-os/swap`'s `refund.ts` module doc). The two covenant leaves are\n * pushed by the emulator on the counterparty's behalf and are not this wallet's\n * to build at all.\n *\n * So `refundWithoutReceiver` is the sender's only collaborative way out, gated\n * on the CLTV the quote committed to — which is exactly the leaf\n * `pushRefundWithoutReceiver` builds. The CSV leaves are offered only in the\n * non-collaborative context, where the caller has already accepted that\n * spending them means a real unilateral exit first.\n *\n * The selection discipline is deliberately identical to the `vhtlc` handler's,\n * and `test/contracts/vhtlcV2-handler.test.ts` pins the two against each other\n * rung-for-rung across every role and timelock context so they cannot drift.\n */\nexport const VHTLCV2ContractHandler: ContractHandler<VHTLCV2ContractParams, VHTLC.ScriptV2> &\n TapscriptDeriving<VHTLC.ScriptV2> = {\n type: \"vhtlc-v2\",\n\n createScript(params: Record<string, string>): VHTLC.ScriptV2 {\n const typed = this.deserializeParams(params);\n return new VHTLC.ScriptV2(typed);\n },\n\n serializeParams(params: VHTLCV2ContractParams): Record<string, string> {\n const covenants = params.nonInteractiveParameters;\n return {\n sender: hex.encode(params.sender),\n receiver: hex.encode(params.receiver),\n server: hex.encode(params.server),\n hash: hex.encode(params.preimageHash),\n refundLocktime: params.refundLocktime.toString(),\n claimDelay: timelockToSequence(params.unilateralClaimDelay).toString(),\n refundDelay: timelockToSequence(params.unilateralRefundDelay).toString(),\n refundNoReceiverDelay: timelockToSequence(\n params.unilateralRefundWithoutReceiverDelay,\n ).toString(),\n // The on-disk keys keep their per-leaf names even though the typed\n // param is ONE group: rows written by older SDKs carry exactly\n // these keys, and changing the storage encoding would orphan them.\n // The group maps onto them without loss — one emulator key serves\n // both covenant destinations by construction (see the option's doc\n // on VHTLC.Options), so the two emulator-key columns always hold\n // the same value on a row written from here.\n //\n // Spread rather than written as `undefined`: a `Record<string,\n // string>` round-tripped through a repository must not gain keys\n // whose value is the string \"undefined\".\n ...(covenants && {\n nonInteractiveClaimReceiverPkScript: hex.encode(covenants.receiverPkScript),\n nonInteractiveClaimEmulatorPubkey: hex.encode(covenants.emulatorPubkey),\n nonInteractiveRefundSenderPkScript: hex.encode(covenants.senderPkScript),\n nonInteractiveRefundEmulatorPubkey: hex.encode(covenants.emulatorPubkey),\n // The legacy marker is precisely the ABSENCE of this key: a\n // row carrying it re-derives the full suite (nine leaves), a\n // row lacking it the pre-timelocked-refund eight — the same\n // encoding older SDKs wrote for eight-leaf rows, so those rows\n // read back unchanged. Spread rather than a \"false\"/\"undefined\"\n // string: a dropped flag re-derives the EIGHT-leaf script, a\n // different pkScript, and registration dies at\n // `upsertContractRow` with an opaque `Script mismatch`.\n ...(covenants.legacy === undefined && {\n nonInteractiveRefundWithoutReceiver: \"1\",\n }),\n }),\n // The asset must round-trip, and its absence here used to be silent\n // in the worst way. `ContractManager` re-derives a contract from\n // these params; dropping the asset derives the SAT-ONLY script, so\n // registration died at `upsertContractRow` with a `Script mismatch`\n // naming two hex strings and no cause. Same silent-drop class\n // `validateOptions` refuses one layer up.\n //\n // Two keys rather than one blob, mirroring the script's own view of\n // an Asset ID as a (txid, groupIndex) pair.\n ...(params.asset && {\n assetTxid: hex.encode(params.asset.txid),\n assetGroupIndex: params.asset.groupIndex.toString(),\n }),\n };\n },\n\n deserializeParams(params: Record<string, string>): VHTLCV2ContractParams {\n const claim = decodeCovenantLeaf(\n params,\n \"nonInteractiveClaimReceiverPkScript\",\n \"nonInteractiveClaimEmulatorPubkey\",\n \"nonInteractiveClaim\",\n );\n const refund = decodeCovenantLeaf(\n params,\n \"nonInteractiveRefundSenderPkScript\",\n \"nonInteractiveRefundEmulatorPubkey\",\n \"nonInteractiveRefund\",\n );\n // The covenant suite is all-or-nothing in the typed params, but the\n // on-disk keys predate that: a row written by an older SDK could name\n // one leaf's pair without the other's. Such a row has no group\n // representation — building one would mean inventing the missing\n // half — so refuse it by name rather than drop a leaf silently.\n if ((claim === undefined) !== (refund === undefined)) {\n throw new Error(\n \"emulator covenant params are all-or-nothing: the claim keys \" +\n \"(nonInteractiveClaim*) and the refund keys (nonInteractiveRefund*) must \" +\n \"both be present or both absent — a row carrying one side was written \" +\n \"for a leaf subset this handler no longer derives\",\n );\n }\n // Both pairs decoded. One emulator key serves both destinations in the\n // group; a row naming two DIFFERENT keys was legal for an older SDK\n // and is unrepresentable now. Rebuilding with either one would move\n // the pkScript, so name it instead.\n if (\n claim &&\n refund &&\n hex.encode(claim.emulatorPubkey) !== hex.encode(refund.emulatorPubkey)\n ) {\n throw new Error(\n \"emulator covenant params name two different emulator pubkeys: the suite \" +\n \"derives both covenant cosigners from ONE key, so this row cannot be \" +\n \"rebuilt as a group\",\n );\n }\n // Both halves or neither: a txid without its group index names no asset,\n // and an index without a txid names nothing at all. Either alone is a\n // corrupt row rather than a contract that happens to lack an asset, and\n // reading it as the latter re-derives the sat-only script — the exact\n // silent drop this round-trip exists to close.\n if ((params.assetTxid === undefined) !== (params.assetGroupIndex === undefined)) {\n throw new Error(\n \"asset params are incomplete: assetTxid and assetGroupIndex must both be present or both absent\",\n );\n }\n // A row written by a strict-capable release (0.4.67 and earlier) carries\n // a quoted bound compiled into its claim leaf. The option is gone, so\n // that bound cannot be re-derived here — and reading the row as \"not\n // strict\" would rebuild the DEFAULT covenant, a different pkScript, and\n // die at `upsertContractRow` with an opaque `Script mismatch`. Name it.\n if (params.strictClaimAmount !== undefined || params.strictClaimAssetAmount !== undefined) {\n throw new Error(\n \"strict claim params on a stored row: the strict claim bound was removed \" +\n \"and this row's lockup cannot be re-derived without it — restore it with \" +\n \"the SDK version that wrote it\",\n );\n }\n // Same silent-drop shape as the two checks above, one flag further in:\n // a row naming this flag without the suite it extends, or read as \"not\n // set\", would re-derive a script missing the timelocked refund leaf.\n if (params.nonInteractiveRefundWithoutReceiver !== undefined && !refund) {\n throw new Error(\n \"nonInteractiveRefundWithoutReceiver without the emulator covenant keys it \" +\n \"extends: reading this as 'not set' would re-derive a script without the leaf\",\n );\n }\n if (\n params.nonInteractiveRefundWithoutReceiver !== undefined &&\n params.nonInteractiveRefundWithoutReceiver !== \"1\"\n ) {\n throw new Error(\n `nonInteractiveRefundWithoutReceiver must be \"1\" when present, got ` +\n JSON.stringify(params.nonInteractiveRefundWithoutReceiver),\n );\n }\n const asset =\n params.assetTxid !== undefined && params.assetGroupIndex !== undefined\n ? {\n txid: hex.decode(params.assetTxid),\n groupIndex: parseGroupIndex(params.assetGroupIndex),\n }\n : undefined;\n return {\n sender: hex.decode(params.sender),\n receiver: hex.decode(params.receiver),\n server: hex.decode(params.server),\n preimageHash: hex.decode(params.hash),\n refundLocktime: BigInt(params.refundLocktime),\n ...(asset && { asset }),\n unilateralClaimDelay: sequenceToTimelock(Number(params.claimDelay)),\n unilateralRefundDelay: sequenceToTimelock(Number(params.refundDelay)),\n unilateralRefundWithoutReceiverDelay: sequenceToTimelock(\n Number(params.refundNoReceiverDelay),\n ),\n ...(claim &&\n refund && {\n nonInteractiveParameters: {\n receiverPkScript: claim.destination,\n senderPkScript: refund.destination,\n emulatorPubkey: claim.emulatorPubkey,\n // Absence of the flag IS the legacy marker — the same\n // encoding older SDKs wrote for eight-leaf rows.\n ...(params.nonInteractiveRefundWithoutReceiver !== \"1\" && {\n legacy: \"preTimelockedRefund\" as const,\n }),\n },\n }),\n };\n },\n\n /**\n * Select spending path based on context.\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n selectPath(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const role = resolveRole(contract, context);\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (!role) {\n return null;\n }\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n return {\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n };\n }\n\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n return {\n leaf: script.refundWithoutReceiver(),\n };\n }\n\n return null;\n }\n\n // Unilateral paths\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n };\n }\n\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n };\n }\n\n return null;\n },\n\n /**\n * Get all possible spending paths (no timelock checks).\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n getAllSpendingPaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n\n if (context.collaborative) {\n // Collaborative paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\") {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n } else {\n // Unilateral paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n getSpendablePaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n return paths;\n }\n\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n /**\n * Refuse an explicit spend of a lockup whose refund path has not opened.\n * @see assertVhtlcSpendableNow for why this is the one certain case.\n */\n assertSpendableNow(_script: VHTLC.ScriptV2, contract: Contract, context: PathContext): void {\n assertVhtlcSpendableNow(contract, context);\n },\n\n /**\n * Never. A live VHTLC is escrow: the counterparty's claim leaf is armed,\n * and generic selection — send, settle, RENEWAL, offboard — would move the\n * lockup out from under a swap the counterparty is still entitled to\n * complete, or race a claim already in flight. The `vhtlc` handler now\n * answers the same, for the same reason.\n *\n * The gate covers `available` and renewal. Recovery is generic and names\n * nothing, so it is not covered here: `recoverVtxos` filters on\n * {@link assertSpendableNow} instead, which drops a lockup only while its\n * refund path is shut rather than forever. The explicit routes out —\n * `settle({ inputs })`, or `@arkade-os/swap`'s `pushRefundWithoutReceiver`\n * over `findLockupVtxos`' outpoints — are unaffected either way.\n */\n isGenericallySpendable: () => false,\n\n /**\n * The annotation leaf stamped onto every VTXO locked to this contract.\n *\n * **Without this the contract is unusable, not merely unoptimized.**\n * `deriveContractTapscripts` falls back to `script.forfeit()` for any\n * handler that does not implement {@link TapscriptDeriving}, and no VHTLC\n * script version has a `forfeit()` — `VtxoScript` does not define one and\n * `VHTLC.BaseScript` does not add one. The fallback therefore throws\n * `legacy.forfeit is not a function`, `annotatableIn` catches it, and\n * `fetchContractVtxosBulk` drops this contract's VTXOs before they are\n * persisted. The row would exist and be watched while its balance stayed\n * permanently invisible, and `getSyncState()` would report `degraded`\n * forever. (The `vhtlc` handler had the same gap and now closes it the same\n * way; nothing registers V1 rows through `ContractManager` in this repo, so\n * it was never hit here.)\n *\n * `refundWithoutReceiver` is the leaf, for both roles the annotation\n * serves, because it is the only collaborative path this wallet can\n * actually satisfy as the sender — the same conclusion `selectPath`\n * reaches, kept in step with it deliberately. The claim leaves belong to\n * the receiver and need a preimage the sender does not have; `refund` and\n * `unilateralRefund` need the counterparty; the covenant leaves are the\n * emulator's.\n *\n * **It carries a CLTV, and callers must respect it.** A settlement built on\n * this leaf is only valid once `refundLocktime` has matured, so a recovery\n * round that sweeps this VTXO early is rejected by the server. That is the\n * same constraint `packages/boltz-swap` encodes as \"pre-CLTV recoverable →\n * skipped\"; nothing in this handler can enforce it, because the annotation\n * is derived per contract and knows no clock. `recoverVtxos` filters on\n * {@link assertSpendableNow} for it.\n *\n * **Role-blind.** A receiver's row gets the same leaf, which names keys that\n * wallet does not hold, so it is satisfiable only by the wallet holding the\n * lockup's `sender` key and fails at intent registration for anyone else.\n */\n deriveTapscripts(script: VHTLC.ScriptV2): DerivedContractTapscripts {\n const leaf = script.refundWithoutReceiver();\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","import { hex } from \"@scure/base\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport { DefaultContractHandler, DefaultContractParams } from \"./default\";\nimport { deriveDescriptorLeafPubKey } from \"../../identity/descriptor\";\nimport { timelockToSequence } from \"../../utils/timelock\";\nimport { rotatedReceiveMetadata } from \"./helpers\";\n\n/**\n * Typed parameters for boarding contracts.\n *\n * Boarding reuses the exact `default` contract parameter shape\n * (`pubKey` / `serverPubKey` / `csvTimelock`) rather than inventing\n * boarding-specific names — the boarding semantics come from the\n * contract type and from populating `csvTimelock` with the server's\n * boarding-exit delay (`ArkInfo.boardingExitDelay`) instead of the\n * offchain unilateral-exit delay.\n */\nexport type BoardingContractParams = DefaultContractParams;\n\n/**\n * Handler for the boarding contract (registered type `boarding`).\n *\n * The boarding contract derives the on-chain Bitcoin address used to\n * board funds onto Arkade. It shares the exact `DefaultVtxo.Script`\n * shape with the `default` contract — a Taproot output co-owned by the\n * wallet and the Ark server, with a CSV exit path back to the wallet —\n * and therefore reuses the `default` handler's path logic (forfeit via\n * server cooperation, exit after the boarding CSV).\n *\n * Boarding semantics come entirely from the contract type and from\n * sourcing the CSV timelock from the server's boarding-exit delay\n * (`ArkInfo.boardingExitDelay`), not from renamed parameters. The\n * offchain `default` contract is built from `ArkInfo.unilateralExitDelay`\n * instead, so the two share a script shape but differ in their CSV\n * timelock value. Parameters round-trip through the same\n * `timelockToSequence` / `sequenceToTimelock` helpers and BIP68 sequence\n * encoding as `default` / `delegate`.\n *\n * Like `default` / `delegate`, the boarding handler implements\n * {@link Discoverable.discoverAt} so `wallet.restore()` can rediscover\n * used boarding indices from authoritative on-chain data. It differs from\n * the L2 handlers in its source of truth: boarding probes the **on-chain**\n * UTXO set at its P2TR address (`OnchainProvider.getCoins`) rather than the\n * Ark indexer, and builds its candidate from the boarding-exit CSV\n * (`deps.boardingTimelock`). When boarding discovery is not plumbed (no\n * `deps.boardingTimelock` / `deps.onchainNetwork`) `discoverAt` no-ops.\n *\n * Identity & the default/boarding collision: a contract's `script` (pkScript)\n * is its unique identity — a script owns exactly one repository row. `boarding`\n * is a first-class type with its own row **when its script is distinct** from\n * the wallet's `default` baseline — the real-world case, since a sound Ark\n * server keeps boardingExitDelay strictly longer than unilateralExitDelay (equal\n * delays would expose the provider to a double-spend). Should those delays ever\n * coincide (a misconfigured/malicious server), the boarding script is\n * byte-identical to the default script. `discoverAt` does NOT pre-coalesce that\n * collision: it always emits `type: \"boarding\"`, and the single shared row is\n * resolved FIRST-WINS at the persistence layer\n * ({@link ContractManager.upsertContract}) — whichever purpose is persisted\n * first keeps the row, and the scan deliberately probes boarding first\n * (see docs/hd-wallets_onchain_rotation_collision_fix.md §5.1–5.2). Either way\n * the funds are equally spendable through the shared `DefaultVtxo.Script` paths.\n * Consumers must NOT rely on `contract.type === \"boarding\"` to identify the\n * boarding purpose — resolve the boarding script via\n * `wallet.getBoardingAddress()` / `wallet.boardingTapscript` (which never depend\n * on the persisted contract's type) and match by script when needed.\n */\nexport const BoardingContractHandler: ContractHandler<BoardingContractParams, DefaultVtxo.Script> &\n Discoverable = {\n type: \"boarding\",\n\n createScript(params: Record<string, string>): DefaultVtxo.Script {\n return DefaultContractHandler.createScript(params);\n },\n\n serializeParams(params: BoardingContractParams): Record<string, string> {\n return DefaultContractHandler.serializeParams(params);\n },\n\n deserializeParams(params: Record<string, string>): BoardingContractParams {\n return DefaultContractHandler.deserializeParams(params);\n },\n\n selectPath(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return DefaultContractHandler.selectPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return DefaultContractHandler.getAllSpendingPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return DefaultContractHandler.getSpendablePaths(script, contract, context);\n },\n\n /** Preserves today's settle/board behaviour. */\n isGenericallySpendable: () => true,\n\n /**\n * Probe the on-chain UTXO set for a boarding output at this HD index.\n *\n * Boarding's source of truth is the **current** on-chain coin set\n * (`OnchainProvider.getCoins`), not the Ark indexer: a boarded (spent)\n * boarding output becomes an L2 VTXO at the receive index, so the\n * indexer probe already keeps the gap window open for it; only an\n * *unspent* boarding output needs the on-chain probe (see plan §2).\n *\n * No-ops (returns `[]`) when boarding discovery is not plumbed — i.e.\n * `deps.boardingTimelock` or `deps.onchainNetwork` is absent — so the\n * scanner unit harness (which sets neither) is unaffected.\n *\n * Always emits `type: \"boarding\"`, even in the degenerate equal-delay case\n * where the boarding script is byte-identical to a `default` script at this\n * index (`boardingExitDelay === unilateralExitDelay`). The collision is no\n * longer pre-judged in discovery; it is tolerated FIRST-WINS at the\n * persistence layer ({@link ContractManager.upsertContract}). `deps.csvTimelocks`\n * is intentionally not read here.\n */\n async discoverAt(\n index: number,\n descriptor: string,\n deps: DiscoveryDeps,\n ): Promise<DiscoveredContract[]> {\n if (!deps.boardingTimelock || !deps.onchainNetwork) return [];\n\n const pubKey = deriveDescriptorLeafPubKey(descriptor);\n const script = new DefaultVtxo.Script({\n pubKey,\n serverPubKey: deps.serverPubKey,\n csvTimelock: deps.boardingTimelock,\n });\n const onchainAddress = script.onchainAddress(deps.onchainNetwork);\n\n const coins = await deps.onchainProvider.getCoins(onchainAddress);\n if (coins.length === 0) return [];\n\n const scriptHex = hex.encode(script.pkScript);\n const boardingSeq = timelockToSequence(deps.boardingTimelock);\n\n // Always `type: \"boarding\"` (see method doc). The equal-delay\n // same-script collision is resolved first-wins at persistence, and the\n // scan probes boarding before default so a both-purpose rotated index\n // resolves to a `boarding` row — keeping both the on-chain UTXO and any\n // L2 VTXO recoverable (docs/hd-wallets_onchain_rotation_collision_fix.md\n // §5.2, §5.4).\n return [\n {\n type: \"boarding\",\n params: {\n pubKey: hex.encode(pubKey),\n serverPubKey: hex.encode(deps.serverPubKey),\n csvTimelock: boardingSeq.toString(),\n },\n script: scriptHex,\n // The persisted row's `address` is the *Ark* address (not the\n // on-chain P2TR), matching the row registered at init so the\n // ContractWatcher keeps monitoring the same L2 script and the\n // VTXO repository bucket lines up (plan §6-I.4). The P2TR is\n // recomputed from params only for the `getCoins` probe.\n address: script.address(deps.network.hrp, deps.serverPubKey).encode(),\n // Tag rotated rows (index > 0) so boot resolution can find the\n // newest boarding address and descriptor-aware signing can\n // recover the per-index key (plan §6-II/§6-III.3). The index-0\n // baseline stays untagged, matching `default`/`delegate`.\n ...rotatedReceiveMetadata(index, descriptor),\n },\n ];\n },\n};\n","/**\n * Arkade Program model & compiler.\n *\n * A {@link Program} is the artifact shape shared with the ArkadeScript\n * compiler: named functions, each split into a `tapscript` segment enforced\n * on-chain and an optional `arkadeScript` segment emulated by the co-signing\n * service. This module owns everything that is *pure data → script*:\n *\n * - the Program/segment/token types,\n * - `$param` resolution ({@link resolveAsm}), witness and timelock resolution,\n * - program validation ({@link validateProgram}) — typed constructor params\n * are authoritative when present,\n * - {@link ArkadeProgramScript} — a {@link VtxoScript} compiled from a\n * program, its constructor args and the signer keys,\n * - artifact JSON (de)serialization ({@link parseArtifact} /\n * {@link stringifyArtifact}) and the string-keyed contract params used to\n * persist a program contract through the `src/contracts` pipeline.\n *\n * Keeping this free of provider/transaction imports lets the generic\n * `arkade` contract handler (src/contracts/handlers/arkade.ts) and the\n * high-level `ArkadeContract` client share one compilation path.\n *\n * @module arkade/program\n */\n\nimport { hex } from \"@scure/base\";\nimport { ScriptNum } from \"@scure/btc-signer\";\n\nimport {\n MultisigTapscript,\n CSVMultisigTapscript,\n CLTVMultisigTapscript,\n ConditionMultisigTapscript,\n ConditionCSVMultisigTapscript,\n type ArkTapscript,\n type TapscriptType,\n} from \"../script/tapscript\";\nimport { VtxoScript, type TapLeafScript } from \"../script/base\";\nimport { ArkadeScript } from \"./script\";\nimport { ARKADE_OP } from \"./opcodes\";\nimport { computeArkadeScriptPublicKey } from \"./tweak\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n// --- Program model (mirrors the compiler artifact) -------------------------\n\n/** A token in an `asm` array: an opcode name, a number/bigint push, raw bytes, or a `$param` placeholder. */\nexport type AsmToken = string | number | bigint | Uint8Array;\n\n/** A constructor argument or resolved value. */\nexport type ArkadeParamValue = Uint8Array | bigint | number;\n\n/** A function call argument (function input). */\nexport type ArkadeArgValue = Uint8Array | bigint | number;\n\n/**\n * The declared type of a function input, used to derive the static TS type of\n * the corresponding `functions.<name>(...)` argument. Byte-like types map to\n * `Uint8Array`; `int` maps to `bigint | number`.\n */\nexport type ArkadeArgType = \"bytes\" | \"pubkey\" | \"sig\" | \"hash\" | \"int\";\n\n/**\n * Maps an {@link ArkadeArgType} to its TypeScript argument type.\n * @internal\n */\nexport interface ArkadeValueType {\n bytes: Uint8Array;\n pubkey: Uint8Array;\n sig: Uint8Array;\n hash: Uint8Array;\n int: bigint | number;\n}\n\n/** A typed function input or constructor param: a name plus its {@link ArkadeArgType}. */\nexport interface InputDef {\n name: string;\n type: ArkadeArgType;\n}\n\n/**\n * A function input or constructor param declaration: either a typed descriptor\n * `{ name, type }` (the argument is statically typed and its bound value is\n * validated) or a bare name string (the argument falls back to the loose\n * {@link ArkadeArgValue}).\n */\nexport type InputRef = string | InputDef;\n\n/** Constructor pubkey `$param` tweaked by `fn`'s covenant. */\nexport interface TweakedSigner {\n tweak: string;\n fn: string;\n}\n\n/** A `\"$param\"` reference, literal x-only bytes, or a {@link TweakedSigner}. */\nexport type SignerRef = string | Uint8Array | TweakedSigner;\n\n/** A witness-stack item: a function-input name, a `\"$param\"`, a literal number/bigint (minimal script-num), or raw bytes. */\nexport type WitnessRef = string | number | bigint | Uint8Array;\n\n/** Bitcoin Script segment of a spending path — enforced on-chain. */\nexport interface TapscriptSegment {\n /**\n * Required signers. A path with `arkadeScript` also appends the emulator\n * co-signer, unless `emulator` is `null`.\n */\n signers: SignerRef[];\n /**\n * Covenant named by `<EMULATOR_KEY:fn>`. `null` when this leaf belongs to a\n * covenant but signs with a constructor-key tweak instead. Omitted on\n * hand-written programs, which still append the co-signer.\n */\n emulator?: string | null;\n /**\n * Optional standard-opcode condition (e.g. a hashlock), encoded into a\n * ConditionMultisig leaf — or ConditionCSVMultisig when combined with `csv`.\n */\n asm?: AsmToken[];\n /**\n * Relative timelock (CSV). The value is a literal or a `\"$param\"` reference\n * resolved against the constructor args (same convention as {@link SignerRef}).\n * Combinable with `asm` (condition + CSV); mutually exclusive with `cltv`.\n */\n csv?: { type: \"blocks\" | \"seconds\"; value: bigint | string };\n /**\n * Absolute timelock (CLTV): a literal or a `\"$param\"` reference.\n * Mutually exclusive with `csv`/`asm`.\n */\n cltv?: bigint | string;\n /** Items satisfying the condition (e.g. an HTLC preimage); set via the ConditionWitness PSBT field. */\n witness?: WitnessRef[];\n}\n\n/** Arkade Script segment of a spending path — emulated, bound via the key tweak. */\nexport interface ArkadeSegment {\n /** Raw Arkade opcodes with `$param` placeholders. */\n asm: AsmToken[];\n /** The arkade-script witness stack (e.g. an output index). */\n witness?: WitnessRef[];\n}\n\n/** One named spending path. */\nexport interface ArkadeFunction {\n /**\n * The function ABI: an ordered list of call arguments. Each entry is a typed\n * descriptor `{ name, type }` (which gives the matching `functions.<name>`\n * argument a precise static type) or a bare name string (loose\n * {@link ArkadeArgValue}). Absent for nullary paths (e.g. exit/cancel).\n */\n inputs?: readonly InputRef[];\n tapscript: TapscriptSegment;\n /** Present for covenant paths; absent for pure-tapscript paths (cancel/exit). */\n arkadeScript?: ArkadeSegment;\n}\n\nexport const SUPPORTED_PROGRAM_VERSION = 0;\n\n/** An Arkade contract program (hand-written or compiler-emitted). */\nexport interface Program {\n version: number;\n /**\n * Optional program name — metadata only: round-tripped through the\n * artifact JSON, never used in compilation or the taproot tree.\n */\n name?: string;\n /**\n * Ordered constructor parameters. Bare name strings are documentation only\n * (the legacy hand-written form); typed descriptors `{ name, type }` make\n * the list authoritative — see {@link validateProgram}.\n */\n params?: readonly InputRef[];\n functions: Record<string, ArkadeFunction>;\n}\n\n// --- helpers ---------------------------------------------------------------\n\n/** The declared name of a function input or constructor param, whether typed descriptor or bare string. */\nexport function inputName(ref: InputRef): string {\n return typeof ref === \"string\" ? ref : ref.name;\n}\n\n/** Look up a `$param` / function-input value in a bind map; throws when unbound. */\nexport function bindValue(bind: Record<string, ArkadeParamValue>, name: string): ArkadeParamValue {\n const v = bind[name];\n if (v === undefined) throw new Error(`unbound parameter '${name}'`);\n return v;\n}\n\n/**\n * Resolve a timelock value to a bigint: bigints pass through; a `\"$param\"`\n * string resolves against the program's constructor args and must be bound to\n * a bigint/number. Any other string is an error.\n */\nexport function resolveTimelockValue(\n value: bigint | string,\n args: Record<string, ArkadeParamValue>,\n): bigint {\n if (typeof value === \"bigint\") return value;\n if (value.startsWith(\"$\")) {\n const v = bindValue(args, value.slice(1));\n if (typeof v === \"bigint\" || typeof v === \"number\") return BigInt(v);\n throw new Error(`timelock value '${value}' must resolve to a number`);\n }\n throw new Error(\n `invalid timelock value '${value}' — expected a bigint or a '$param' reference`,\n );\n}\n\n/**\n * Resolve an `asm` array to bytes: substitute `$param` placeholders from `bind`,\n * pass everything else (opcode names, numbers, raw byte pushes) through to the\n * Arkade script encoder. The SDK does not interpret opcodes — this is pure\n * substitution + encoding. To embed a signer key (server, user, or any\n * other), pass it as a `$param` in the constructor args; there is no\n * `<SERVER_KEY>`/`<COSIGNER_KEY>` token.\n */\nexport function resolveAsm(asm: AsmToken[], bind: Record<string, ArkadeParamValue>): Uint8Array {\n const tokens = asm.map((t) => {\n if (typeof t === \"string\" && t.startsWith(\"$\")) {\n return bindValue(bind, t.slice(1));\n }\n if (t === \"<SELF>\") {\n // Continuation covenants don't hard-code their own address (that would\n // be a non-converging fixpoint); express them with input introspection\n // (PUSHCURRENTINPUTINDEX + INSPECTINPUTSCRIPTPUBKEY) instead.\n throw new Error(\n \"<SELF> is not a placeholder; use INSPECTINPUTSCRIPTPUBKEY for continuation covenants\",\n );\n }\n return t;\n });\n return ArkadeScript.encode(tokens as never);\n}\n\n/**\n * Resolve one witness-stack item to bytes.\n *\n * - raw bytes pass through;\n * - numbers/bigints encode as minimal script-nums;\n * - `\"$param\"` strings resolve against the program's constructor args;\n * - any other string is a function-input name and resolves against `callArgs`\n * (throws when the input is unbound — e.g. outside a function call).\n */\nexport function witnessRefToBytes(\n ref: WitnessRef,\n callArgs: Record<string, ArkadeArgValue>,\n programArgs: Record<string, ArkadeParamValue>,\n): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (typeof ref === \"number\" || typeof ref === \"bigint\") {\n return MinimalScriptNum.encode(BigInt(ref));\n }\n const v = ref.startsWith(\"$\") ? bindValue(programArgs, ref.slice(1)) : bindValue(callArgs, ref);\n if (v instanceof Uint8Array) return v;\n return MinimalScriptNum.encode(BigInt(v));\n}\n\n/**\n * Validate a tapscript segment: it must have signers; `asm` may combine with\n * `csv` (the condition + CSV closure) but `cltv` conflicts with both (arkd\n * recognizes no condition+CLTV or dual-timelock closure); the `asm` may not\n * contain Arkade opcodes (those are `OP_SUCCESS` on-chain and belong in the\n * `arkadeScript` segment).\n */\nexport function validateTapscript(seg: TapscriptSegment): void {\n if (!seg.signers || seg.signers.length === 0) {\n throw new Error(\"tapscript: at least one signer is required\");\n }\n if (seg.asm !== undefined && seg.cltv !== undefined) {\n throw new Error(\n \"tapscript: `asm` and `cltv` conflict — arkd has no condition+CLTV closure\",\n );\n }\n if (seg.csv !== undefined && seg.cltv !== undefined) {\n throw new Error(\"tapscript: `csv` and `cltv` conflict — use at most one timelock\");\n }\n for (const t of seg.asm ?? []) {\n if (typeof t === \"string\" && t in ARKADE_OP) {\n throw new Error(\n `tapscript: arkade opcode '${t}' is not enforceable on-chain — move it to arkadeScript`,\n );\n }\n }\n}\n\n/** Collect every `\"$name\"` reference in a program's signers, asm, witness and timelock values. */\nfunction collectParamRefs(program: Program): Set<string> {\n const refs = new Set<string>();\n const collect = (items: readonly (AsmToken | WitnessRef | SignerRef)[] | undefined) => {\n for (const t of items ?? []) {\n if (typeof t === \"string\" && t.startsWith(\"$\")) refs.add(t.slice(1));\n else if (isTweakedSigner(t) && t.tweak.startsWith(\"$\")) refs.add(t.tweak.slice(1));\n }\n };\n for (const fn of Object.values(program.functions)) {\n const tap = fn.tapscript;\n collect(tap.signers);\n collect(tap.asm);\n collect(tap.witness);\n collect(tap.csv ? [tap.csv.value] : undefined);\n collect(tap.cltv !== undefined ? [tap.cltv] : undefined);\n collect(fn.arkadeScript?.asm);\n collect(fn.arkadeScript?.witness);\n }\n return refs;\n}\n\n/** Byte lengths enforced for typed values (x-only pubkey, BIP340 signature). */\nconst TYPED_BYTE_LENGTHS: Partial<Record<ArkadeArgType, number>> = { pubkey: 32, sig: 64 };\n\n/** Validate a bound value against its typed declaration; errors name the parameter. */\nfunction validateParamValue(def: InputDef, value: ArkadeParamValue): void {\n if (def.type === \"int\") {\n if (typeof value !== \"bigint\" && typeof value !== \"number\") {\n throw new Error(`program parameter '${def.name}' expects an int, got bytes`);\n }\n return;\n }\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `program parameter '${def.name}' expects ${def.type} bytes, got ${typeof value}`,\n );\n }\n const length = TYPED_BYTE_LENGTHS[def.type];\n if (length !== undefined && value.length !== length) {\n throw new Error(\n `program parameter '${def.name}' expects a ${length}-byte ${def.type}, got ${value.length} bytes`,\n );\n }\n}\n\n/**\n * Validate a program's constructor-parameter declarations against the bound\n * args. A `params` list of bare name strings is documentation only (the\n * legacy hand-written form — no checks). When at least one entry is a typed\n * descriptor (the compiler-emitted form), the list is authoritative: every\n * declared param must be bound in `args`, every `\"$name\"` reference in the\n * program must be declared, and typed entries validate their bound value\n * (bytes-like types require a Uint8Array — 32 bytes for `pubkey`, 64 for\n * `sig`; `int` requires a bigint/number).\n */\nexport function validateProgram(program: Program, args: Record<string, ArkadeParamValue>): void {\n const params = program.params;\n if (!params || !params.some((p) => typeof p !== \"string\")) return;\n\n const declared = new Set(params.map(inputName));\n for (const name of declared) {\n if (args[name] === undefined) {\n throw new Error(`program parameter '${name}' is declared but not bound in args`);\n }\n }\n for (const ref of collectParamRefs(program)) {\n if (!declared.has(ref)) {\n throw new Error(`'$${ref}' is referenced but not declared in program params`);\n }\n }\n for (const p of params) {\n if (typeof p !== \"string\") validateParamValue(p, args[p.name]);\n }\n}\n\n// --- Compilation -----------------------------------------------------------\n\n/** The signer keys a program is compiled against. */\nexport interface ProgramKeys {\n /** The Arkade Service signer key (x-only) — used for address derivation and collaborative-path detection, not for `$param` resolution. */\n serverKey: Uint8Array;\n /** The wallet's x-only key — identifies which inputs the wallet signs. */\n userKey?: Uint8Array;\n /** The co-signer (emulator) key — required only for covenant (`arkadeScript`) functions. */\n emulatorKey?: Uint8Array;\n}\n\n/**\n * A single spending path, fully resolved at compilation: its definition, the\n * committed leaf body, the per-path arkade-script bytes (covenant paths only),\n * and the {@link TapLeafScript} (control block) for spending it.\n */\nexport interface CompiledProgramFunction {\n name: string;\n def: ArkadeFunction;\n /** The committed leaf script (body). */\n leafScript: Uint8Array;\n /** Resolved arkade-script bytes; undefined for pure-tapscript paths. */\n arkadeScript?: Uint8Array;\n /** Resolved signer keys (x-only), in the declared `signers` order. */\n signerKeys: Uint8Array[];\n /** Resolved once — the taproot leaf + control block for this path. */\n tapLeafScript: TapLeafScript;\n}\n\nfunction isTweakedSigner(ref: unknown): ref is TweakedSigner {\n if (typeof ref !== \"object\" || ref === null || ref instanceof Uint8Array) return false;\n const { tweak, fn } = ref as TweakedSigner;\n return typeof tweak === \"string\" && typeof fn === \"string\";\n}\n\n/** Resolve a pubkey signer to x-only key bytes against the program's constructor args. */\nfunction resolveSigner(\n ref: string | Uint8Array,\n args: Record<string, ArkadeParamValue>,\n): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (typeof ref !== \"string\" || !ref.startsWith(\"$\")) {\n throw new Error(`unknown signer reference '${ref}' — use a '$param' or key bytes`);\n }\n const v = bindValue(args, ref.slice(1));\n if (!(v instanceof Uint8Array)) {\n throw new Error(`signer ${ref} must be a pubkey (bytes)`);\n }\n return v;\n}\n\nfunction encodeTapscriptSegment(\n seg: TapscriptSegment,\n pubkeys: Uint8Array[],\n args: Record<string, ArkadeParamValue>,\n): ArkTapscript<TapscriptType, any> {\n if (seg.csv) {\n const timelock = { type: seg.csv.type, value: resolveTimelockValue(seg.csv.value, args) };\n if (seg.asm) {\n // The fifth arkd closure: condition + CSV.\n return ConditionCSVMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n timelock,\n pubkeys,\n });\n }\n return CSVMultisigTapscript.encode({ timelock, pubkeys });\n }\n if (seg.cltv !== undefined) {\n return CLTVMultisigTapscript.encode({\n absoluteTimelock: resolveTimelockValue(seg.cltv, args),\n pubkeys,\n });\n }\n if (seg.asm) {\n return ConditionMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n pubkeys,\n });\n }\n return MultisigTapscript.encode({ pubkeys });\n}\n\nfunction compileFunctions(\n program: Program,\n args: Record<string, ArkadeParamValue>,\n keys: ProgramKeys,\n): Omit<CompiledProgramFunction, \"tapLeafScript\">[] {\n if (program.version !== SUPPORTED_PROGRAM_VERSION) {\n throw new Error(\n `ArkadeContract: unsupported program version ${program.version} — this SDK supports version ${SUPPORTED_PROGRAM_VERSION}`,\n );\n }\n const functions: Record<string, ArkadeFunction> = program.functions;\n const names = Object.keys(functions);\n if (names.length === 0) {\n throw new Error(\"ArkadeContract: program has no functions\");\n }\n validateProgram(program, args);\n const defs = names.map((n) => functions[n]);\n\n // Covenant functions need the emulator's co-signer key for the tweak.\n const covenant = names.find((_, i) => defs[i].arkadeScript);\n if (covenant && !keys.emulatorKey) {\n throw new Error(\n `ArkadeContract: function '${covenant}' has an arkadeScript but no emulator is configured — pass an \\`emulator\\` to Arkade.connect`,\n );\n }\n\n return defs.map((def, i) => {\n validateTapscript(def.tapscript);\n const pubkeys = def.tapscript.signers.map((signer) => {\n if (!isTweakedSigner(signer)) return resolveSigner(signer, args);\n const asm = functions[signer.fn]?.arkadeScript?.asm;\n if (!asm) {\n throw new Error(\n `ArkadeContract: function '${names[i]}' tweaks '${signer.fn}', which has no arkade script`,\n );\n }\n return computeArkadeScriptPublicKey(\n resolveSigner(signer.tweak, args),\n resolveAsm(asm, args),\n );\n });\n\n // A covenant leaf appends the emulator co-signer. A constructor-key\n // tweak of that covenant sets `emulator` to null and does not.\n const arkadeScript = def.arkadeScript ? resolveAsm(def.arkadeScript.asm, args) : undefined;\n const leafPubkeys =\n arkadeScript && def.tapscript.emulator !== null\n ? [...pubkeys, computeArkadeScriptPublicKey(keys.emulatorKey!, arkadeScript)]\n : pubkeys;\n const leafScript = encodeTapscriptSegment(def.tapscript, leafPubkeys, args).script;\n return { name: names[i], def, leafScript, arkadeScript, signerKeys: pubkeys };\n });\n}\n\n/**\n * A {@link VtxoScript} compiled from an Arkade {@link Program}, its\n * constructor args and the signer keys.\n *\n * This is the single compilation path shared by the high-level\n * `ArkadeContract` client and the `\"arkade\"` contract handler: both produce\n * byte-identical taproot trees for the same (program, args, keys), so a\n * contract registered through the `src/contracts` pipeline re-derives the\n * exact script it was created with.\n */\nexport class ArkadeProgramScript extends VtxoScript {\n /** Spending paths in declaration order. */\n readonly compiled: CompiledProgramFunction[];\n\n constructor(\n readonly program: Program,\n readonly args: Record<string, ArkadeParamValue>,\n readonly keys: ProgramKeys,\n ) {\n const partial = compileFunctions(program, args, keys);\n super(partial.map((p) => p.leafScript));\n this.compiled = partial.map((p) => ({\n ...p,\n tapLeafScript: this.findLeaf(hex.encode(p.leafScript)),\n }));\n }\n\n /** The compiled spending path with the given function name, if any. */\n functionByName(name: string): CompiledProgramFunction | undefined {\n return this.compiled.find((f) => f.name === name);\n }\n}\n\n// --- Artifact JSON ----------------------------------------------------------\n\n/**\n * Convert a Program JSON artifact into a {@link Program}. Byte values are\n * encoded as `0x`-prefixed hex strings in `asm`/`witness`/`signers`; opcode names,\n * `$param` placeholders and numbers pass through unchanged.\n *\n * This is *not* the JSON `arkadec` writes. That artifact lists spend groups in\n * an array and uses `<param>` placeholders and raw leaf assembly; pass it to\n * {@link programFromArtifact} instead.\n */\nexport function parseArtifact(artifact: {\n version?: number;\n name?: string;\n params?: readonly InputRef[];\n functions: unknown;\n}): Program {\n // An arkadec ContractJson would otherwise become functions named \"0\", \"1\", \"2\".\n if (Array.isArray(artifact.functions)) {\n throw new Error(\n \"parseArtifact: `functions` is an array, which is the arkadec artifact shape, not an SDK program — read it with programFromArtifact instead\",\n );\n }\n if (typeof artifact.functions !== \"object\" || artifact.functions === null) {\n throw new Error(\"parseArtifact: `functions` must be an object keyed by function name\");\n }\n const hexToken = (t: unknown): any =>\n typeof t === \"string\" && t.startsWith(\"0x\") ? hex.decode(t.slice(2)) : t;\n const signerRef = (s: unknown): SignerRef => {\n if (s instanceof Uint8Array || typeof s === \"string\") return hexToken(s);\n if (isTweakedSigner(s)) return { tweak: s.tweak, fn: s.fn };\n throw new Error(\"parseArtifact: a tweaked signer needs string `tweak` and `fn`\");\n };\n // A \"$param\" timelock stays a reference (resolved at compile time); anything\n // else is a literal.\n const timelockValue = (v: unknown): bigint | string =>\n typeof v === \"string\" && v.startsWith(\"$\") ? v : BigInt(v as string | number);\n\n const functions: Record<string, ArkadeFunction> = {};\n for (const [name, fn] of Object.entries(artifact.functions as Record<string, any>)) {\n const tap = fn.tapscript ?? {};\n const tapscript: TapscriptSegment = {\n signers: (tap.signers ?? []).map(signerRef),\n ...(tap.asm ? { asm: tap.asm.map(hexToken) } : {}),\n ...(tap.witness ? { witness: tap.witness.map(hexToken) } : {}),\n ...(tap.csv\n ? { csv: { type: tap.csv.type, value: timelockValue(tap.csv.value) } }\n : {}),\n ...(tap.cltv !== undefined ? { cltv: timelockValue(tap.cltv) } : {}),\n ...(\"emulator\" in tap ? { emulator: tap.emulator as string | null } : {}),\n };\n const arkadeScript = fn.arkadeScript\n ? {\n asm: fn.arkadeScript.asm.map(hexToken),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(hexToken) }\n : {}),\n }\n : undefined;\n functions[name] = {\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript,\n ...(arkadeScript ? { arkadeScript } : {}),\n };\n }\n return {\n version: artifact.version ?? SUPPORTED_PROGRAM_VERSION,\n ...(artifact.name !== undefined ? { name: artifact.name } : {}),\n ...(artifact.params ? { params: artifact.params } : {}),\n functions,\n };\n}\n\n/**\n * Serialize a {@link Program} to compiler-artifact JSON — the inverse of\n * {@link parseArtifact}: bytes become `0x`-hex strings; bigint tokens become\n * plain numbers (or, above `Number.MAX_SAFE_INTEGER`, `0x`-hex of their\n * minimal script-num bytes, which the script encoder pushes identically);\n * literal timelock values serialize as decimal strings while `\"$param\"`\n * timelock references are emitted as-is.\n */\nexport function stringifyArtifact(program: Program): string {\n const token = (t: AsmToken | WitnessRef | SignerRef): unknown => {\n if (t instanceof Uint8Array) return \"0x\" + hex.encode(t);\n if (typeof t === \"bigint\") {\n if (t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(t);\n }\n // Out of JSON-safe integer range: a plain decimal string would be\n // misread as an opcode name, so emit the equivalent byte push.\n return \"0x\" + hex.encode(MinimalScriptNum.encode(t));\n }\n return t;\n };\n\n const functions: Record<string, unknown> = {};\n for (const [name, fn] of Object.entries(program.functions)) {\n const tap = fn.tapscript;\n functions[name] = {\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript: {\n signers: tap.signers.map(token),\n ...(tap.asm ? { asm: tap.asm.map(token) } : {}),\n ...(tap.witness ? { witness: tap.witness.map(token) } : {}),\n ...(tap.csv\n ? { csv: { type: tap.csv.type, value: tap.csv.value.toString() } }\n : {}),\n ...(tap.cltv !== undefined ? { cltv: tap.cltv.toString() } : {}),\n ...(tap.emulator !== undefined ? { emulator: tap.emulator } : {}),\n },\n ...(fn.arkadeScript\n ? {\n arkadeScript: {\n asm: fn.arkadeScript.asm.map(token),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(token) }\n : {}),\n },\n }\n : {}),\n };\n }\n\n return JSON.stringify({\n version: program.version,\n ...(program.name !== undefined ? { name: program.name } : {}),\n ...(program.params ? { params: program.params } : {}),\n functions,\n });\n}\n\n// --- Persisted contract params ----------------------------------------------\n\n/**\n * Typed parameters of an `\"arkade\"` contract as persisted through the\n * `src/contracts` pipeline. The program serializes as artifact JSON, args as\n * a JSON map (`0x`-hex bytes, decimal-string bigints), keys as hex — so a\n * stored contract row re-derives its script fully offline.\n */\nexport interface ArkadeContractParams {\n program: Program;\n args: Record<string, ArkadeParamValue>;\n serverKey: Uint8Array;\n userKey?: Uint8Array;\n emulatorKey?: Uint8Array;\n}\n\nfunction serializeArgValue(v: ArkadeParamValue): string | number {\n if (v instanceof Uint8Array) return \"0x\" + hex.encode(v);\n if (typeof v === \"bigint\") return v.toString();\n return v;\n}\n\nfunction parseArgValue(v: unknown): ArkadeParamValue {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") {\n if (v.startsWith(\"0x\")) return hex.decode(v.slice(2));\n return BigInt(v);\n }\n throw new Error(`invalid arkade arg value: ${JSON.stringify(v)}`);\n}\n\n/**\n * Decode a persisted arg by its declared type — no `0x`/BigInt guessing. A\n * bytes-like param whose serialized value lacks the `0x` prefix is an error\n * (the untyped heuristic would silently decode such a value as a bigint).\n */\nfunction parseTypedArgValue(name: string, type: ArkadeArgType, v: unknown): ArkadeParamValue {\n if (type === \"int\") {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") return BigInt(v);\n throw new Error(\n `arkade contract params: '${name}' expects an int, got ${JSON.stringify(v)}`,\n );\n }\n if (typeof v === \"string\" && v.startsWith(\"0x\")) return hex.decode(v.slice(2));\n throw new Error(\n `arkade contract params: '${name}' expects ${type} as 0x-prefixed hex, got ${JSON.stringify(v)}`,\n );\n}\n\n/** Serialize {@link ArkadeContractParams} to the string map `Contract.params` requires. */\nexport function serializeArkadeContractParams(typed: ArkadeContractParams): Record<string, string> {\n const args: Record<string, string | number> = {};\n for (const [k, v] of Object.entries(typed.args)) {\n args[k] = serializeArgValue(v);\n }\n return {\n program: stringifyArtifact(typed.program),\n args: JSON.stringify(args),\n serverKey: hex.encode(typed.serverKey),\n ...(typed.userKey ? { userKey: hex.encode(typed.userKey) } : {}),\n ...(typed.emulatorKey ? { emulatorKey: hex.encode(typed.emulatorKey) } : {}),\n };\n}\n\n/** Parse the string map persisted in `Contract.params` back into typed params. */\nexport function deserializeArkadeContractParams(\n params: Record<string, string>,\n): ArkadeContractParams {\n if (!params.program) {\n throw new Error(\"arkade contract params: missing 'program'\");\n }\n if (!params.serverKey) {\n throw new Error(\"arkade contract params: missing 'serverKey'\");\n }\n const program = parseArtifact(JSON.parse(params.program));\n // Typed param declarations direct how their persisted args decode;\n // untyped params keep the legacy 0x/BigInt heuristic.\n const paramTypes = new Map<string, ArkadeArgType>();\n for (const p of program.params ?? []) {\n if (typeof p !== \"string\") paramTypes.set(p.name, p.type);\n }\n const args: Record<string, ArkadeParamValue> = {};\n if (params.args) {\n for (const [k, v] of Object.entries(JSON.parse(params.args))) {\n const type = paramTypes.get(k);\n args[k] = type ? parseTypedArgValue(k, type, v) : parseArgValue(v);\n }\n }\n return {\n program,\n args,\n serverKey: hex.decode(params.serverKey),\n ...(params.userKey ? { userKey: hex.decode(params.userKey) } : {}),\n ...(params.emulatorKey ? { emulatorKey: hex.decode(params.emulatorKey) } : {}),\n };\n}\n","import { hex } from \"@scure/base\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { isCltvSatisfied, isCsvSpendable } from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\nimport { extractPubKey, isDescriptor } from \"../../identity/descriptor\";\nimport {\n ArkadeProgramScript,\n deserializeArkadeContractParams,\n resolveTimelockValue,\n serializeArkadeContractParams,\n witnessRefToBytes,\n type ArkadeContractParams,\n type CompiledProgramFunction,\n} from \"../../arkade/program\";\n\n/**\n * Extract the raw x-only pubkey hex the wallet signs with from the path\n * context, best-effort (mirrors the VHTLC handler's role resolution).\n */\nfunction walletKeyFrom(context: PathContext): string | undefined {\n const extract = (value: string): string | undefined => {\n if (!isDescriptor(value)) return value.toLowerCase();\n try {\n return extractPubKey(value).toLowerCase();\n } catch {\n return undefined;\n }\n };\n if (context.walletDescriptor) {\n const key = extract(context.walletDescriptor);\n if (key) return key;\n }\n if (context.walletPubKey) {\n return extract(context.walletPubKey);\n }\n return undefined;\n}\n\n/**\n * Resolve a pure-tapscript function's condition witness without call\n * arguments: literals and `$param` references resolve, function-input\n * references cannot (they only exist at call time) — those paths are not\n * generically spendable.\n */\nfunction staticWitness(\n fn: CompiledProgramFunction,\n script: ArkadeProgramScript,\n): Uint8Array[] | null {\n const refs = fn.def.tapscript.witness ?? [];\n try {\n return refs.map((w) => witnessRefToBytes(w, {}, script.args));\n } catch {\n return null;\n }\n}\n\n/**\n * Enumerate the spending paths of a compiled program for the given context.\n *\n * Covenant (`arkadeScript`) functions are excluded: they require the\n * co-signing service round-trip and call arguments, so they are spent through\n * `ArkadeContract.functions.<name>(...)`, never through generic wallet path\n * selection. Pure-tapscript functions follow the same conventions as the\n * built-in handlers:\n *\n * - collaborative context → non-timelocked paths (CLTV paths once satisfied);\n * - unilateral context → only paths that do not require the Arkade Service\n * signer, with CSV/CLTV gates applied (`checkTimelocks: false` skips the\n * gates, for `getAllSpendingPaths`).\n * - when the context identifies the wallet key and a path has non-server\n * signers, the wallet must be one of them.\n */\nfunction pathsFor(\n script: ArkadeProgramScript,\n context: PathContext,\n opts: { checkTimelocks: boolean },\n): PathSelection[] {\n const walletKey = walletKeyFrom(context);\n const serverHex = hex.encode(script.keys.serverKey);\n const paths: PathSelection[] = [];\n\n for (const fn of script.compiled) {\n if (fn.arkadeScript) continue;\n\n const witness = staticWitness(fn, script);\n if (witness === null) continue;\n\n const signerHexes = fn.signerKeys.map((s) => hex.encode(s));\n const requiresServer = signerHexes.includes(serverHex);\n const nonServer = signerHexes.filter((s) => s !== serverHex);\n\n // If we know who the wallet is and the path needs non-server\n // signatures, the wallet must be one of those signers.\n if (walletKey && nonServer.length > 0 && !nonServer.includes(walletKey)) {\n continue;\n }\n\n // `$param` timelock values resolved against the constructor args.\n const csvDef = fn.def.tapscript.csv;\n const csv = csvDef\n ? { type: csvDef.type, value: resolveTimelockValue(csvDef.value, script.args) }\n : undefined;\n const cltv =\n fn.def.tapscript.cltv !== undefined\n ? resolveTimelockValue(fn.def.tapscript.cltv, script.args)\n : undefined;\n\n if (context.collaborative) {\n // CSV leaves are unilateral-exit paths by convention.\n if (csv) continue;\n if (opts.checkTimelocks && cltv !== undefined && !isCltvSatisfied(context, cltv)) {\n continue;\n }\n paths.push({\n leaf: fn.tapLeafScript,\n ...(witness.length > 0 ? { extraWitness: witness } : {}),\n });\n continue;\n }\n\n // Unilateral: the Arkade Service will not co-sign.\n if (requiresServer) continue;\n const sequence = csv ? Number(timelockToSequence(csv)) : undefined;\n if (opts.checkTimelocks && csv && !isCsvSpendable(context, sequence)) continue;\n if (opts.checkTimelocks && cltv !== undefined && !isCltvSatisfied(context, cltv)) {\n continue;\n }\n paths.push({\n leaf: fn.tapLeafScript,\n ...(sequence !== undefined ? { sequence } : {}),\n ...(witness.length > 0 ? { extraWitness: witness } : {}),\n });\n }\n\n return paths;\n}\n\n/**\n * Generic handler for artifact/program-based Arkade contracts.\n *\n * Persists the full {@link ArkadeContractParams} (program artifact JSON, args,\n * signer keys) as string params, so any contract created via\n * `arkade.contract(program, args)` participates in the standard contract\n * pipeline: ContractManager persistence and validation, watcher events,\n * repository-backed balances, and offline script re-derivation. Rebuild a\n * callable contract from a stored row with `ArkadeContract.fromContract`.\n */\nexport const ArkadeContractHandler: ContractHandler<ArkadeContractParams, ArkadeProgramScript> &\n TapscriptDeriving<ArkadeProgramScript> = {\n type: \"arkade\",\n\n createScript(params: Record<string, string>): ArkadeProgramScript {\n const typed = this.deserializeParams(params);\n return new ArkadeProgramScript(typed.program, typed.args, {\n serverKey: typed.serverKey,\n userKey: typed.userKey,\n emulatorKey: typed.emulatorKey,\n });\n },\n\n serializeParams(params: ArkadeContractParams): Record<string, string> {\n return serializeArkadeContractParams(params);\n },\n\n deserializeParams(params: Record<string, string>): ArkadeContractParams {\n return deserializeArkadeContractParams(params);\n },\n\n selectPath(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const paths = pathsFor(script, context, { checkTimelocks: true });\n return paths.length > 0 ? paths[0] : null;\n },\n\n getAllSpendingPaths(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return pathsFor(script, context, { checkTimelocks: false });\n },\n\n getSpendablePaths(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return pathsFor(script, context, { checkTimelocks: true });\n },\n\n /**\n * Opt-in, never opt-out. A program artifact cannot say whether its funds are\n * escrowed — an escrow's collaborative cancel leaf is indistinguishable from\n * an ordinary spend — so the answer is read from the row the registering code\n * wrote. Anything but an explicit `true` (absent, malformed, or a row written\n * before this gate existed) is not generically spendable: `createContract` is\n * first-writer-wins, so a fail-open marker would let one unmarked\n * registration permanently open the gate for every contract sharing the script.\n */\n isGenericallySpendable(contract: Contract): boolean {\n return contract.metadata?.genericallySpendable === true;\n },\n\n /**\n * Annotation tapscripts for VTXOs locked to this contract: prefer the\n * collaborative tapscript path (the multisig the Arkade Service co-signs,\n * mirroring `forfeit()` on the built-in script shapes); covenant-only\n * programs fall back to their first covenant leaf (its forfeit is\n * co-signed by the emulator during batch settlement); otherwise the first\n * declared leaf.\n */\n deriveTapscripts(script: ArkadeProgramScript, _contract: Contract): DerivedContractTapscripts {\n const collaborative = pathsFor(\n script,\n { collaborative: true, currentTime: 0 },\n { checkTimelocks: false },\n );\n const leaf =\n collaborative[0]?.leaf ??\n script.compiled.find((f) => f.arkadeScript)?.tapLeafScript ??\n script.compiled[0].tapLeafScript;\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","export { contractHandlers } from \"./registry\";\nexport { DefaultContractHandler } from \"./default\";\nexport type { DefaultContractParams } from \"./default\";\nexport { DelegateContractHandler } from \"./delegate\";\nexport type { DelegateContractParams } from \"./delegate\";\nexport { VHTLCContractHandler } from \"./vhtlc\";\nexport type { VHTLCContractParams } from \"./vhtlc\";\nexport { VHTLCV2ContractHandler } from \"./vhtlcV2\";\nexport type { VHTLCV2ContractParams } from \"./vhtlcV2\";\nexport { BoardingContractHandler } from \"./boarding\";\nexport type { BoardingContractParams } from \"./boarding\";\nexport { ArkadeContractHandler } from \"./arkade\";\n\n// Register built-in handlers\nimport { contractHandlers } from \"./registry\";\nimport { DefaultContractHandler } from \"./default\";\nimport { DelegateContractHandler } from \"./delegate\";\nimport { VHTLCContractHandler } from \"./vhtlc\";\nimport { VHTLCV2ContractHandler } from \"./vhtlcV2\";\nimport { BoardingContractHandler } from \"./boarding\";\nimport { ArkadeContractHandler } from \"./arkade\";\n\ncontractHandlers.register(DefaultContractHandler);\ncontractHandlers.register(DelegateContractHandler);\ncontractHandlers.register(VHTLCContractHandler);\ncontractHandlers.register(VHTLCV2ContractHandler);\ncontractHandlers.register(BoardingContractHandler);\ncontractHandlers.register(ArkadeContractHandler);\n"]}
|