@arkade-os/sdk 0.5.11 → 0.5.13

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.
Files changed (101) hide show
  1. package/dist/adapters/expo.cjs +7 -7
  2. package/dist/adapters/expo.d.cts +2 -2
  3. package/dist/adapters/expo.d.ts +2 -2
  4. package/dist/adapters/expo.js +4 -4
  5. package/dist/{asyncStorageTaskQueue-C0irgPwJ.d.ts → asyncStorageTaskQueue-Dhbe00Ya.d.ts} +1 -1
  6. package/dist/{asyncStorageTaskQueue-B6rFkXzW.d.cts → asyncStorageTaskQueue-Y4BlVm41.d.cts} +1 -1
  7. package/dist/{chunk-WIZCF5IX.cjs → chunk-6TBTL42M.cjs} +92 -5
  8. package/dist/chunk-6TBTL42M.cjs.map +1 -0
  9. package/dist/{chunk-DMYHAUTA.cjs → chunk-6WPP4UGN.cjs} +9962 -8635
  10. package/dist/chunk-6WPP4UGN.cjs.map +1 -0
  11. package/dist/{chunk-WZ2UHHQ7.cjs → chunk-6XVTGWQK.cjs} +20 -20
  12. package/dist/{chunk-WZ2UHHQ7.cjs.map → chunk-6XVTGWQK.cjs.map} +1 -1
  13. package/dist/{chunk-UPIQZRNJ.cjs → chunk-ACIQZLWL.cjs} +379 -20
  14. package/dist/chunk-ACIQZLWL.cjs.map +1 -0
  15. package/dist/{chunk-KRKREYKT.js → chunk-BA36SQY2.js} +4 -4
  16. package/dist/{chunk-KRKREYKT.js.map → chunk-BA36SQY2.js.map} +1 -1
  17. package/dist/{chunk-VJQMUKPZ.js → chunk-BP4NA7HK.js} +5 -5
  18. package/dist/{chunk-VJQMUKPZ.js.map → chunk-BP4NA7HK.js.map} +1 -1
  19. package/dist/{chunk-LKVVWCIW.js → chunk-D4QH6L54.js} +4 -4
  20. package/dist/{chunk-LKVVWCIW.js.map → chunk-D4QH6L54.js.map} +1 -1
  21. package/dist/{chunk-DPFD5KBK.js → chunk-GB67AGXG.js} +86 -6
  22. package/dist/chunk-GB67AGXG.js.map +1 -0
  23. package/dist/{chunk-5HCDXBBG.cjs → chunk-HS7TKVOZ.cjs} +30 -21
  24. package/dist/chunk-HS7TKVOZ.cjs.map +1 -0
  25. package/dist/{chunk-SS5BPVQL.js → chunk-LHLRG2BE.js} +23 -15
  26. package/dist/chunk-LHLRG2BE.js.map +1 -0
  27. package/dist/{chunk-HRFWODLP.js → chunk-QSERJPTT.js} +628 -23
  28. package/dist/chunk-QSERJPTT.js.map +1 -0
  29. package/dist/{chunk-VLO3JAP3.cjs → chunk-TD4PKK2I.cjs} +680 -68
  30. package/dist/chunk-TD4PKK2I.cjs.map +1 -0
  31. package/dist/{chunk-NC6TEEHZ.cjs → chunk-TYSUFG2K.cjs} +11 -11
  32. package/dist/{chunk-NC6TEEHZ.cjs.map → chunk-TYSUFG2K.cjs.map} +1 -1
  33. package/dist/{chunk-GEK6QBSY.cjs → chunk-WFJPLXOE.cjs} +21 -21
  34. package/dist/{chunk-GEK6QBSY.cjs.map → chunk-WFJPLXOE.cjs.map} +1 -1
  35. package/dist/{chunk-4DUTRRXF.js → chunk-X57WKONW.js} +369 -10
  36. package/dist/chunk-X57WKONW.js.map +1 -0
  37. package/dist/{chunk-W2C3KDQA.js → chunk-Y3AWLHQP.js} +9520 -8196
  38. package/dist/chunk-Y3AWLHQP.js.map +1 -0
  39. package/dist/compiler.cjs +3 -4
  40. package/dist/compiler.cjs.map +1 -1
  41. package/dist/compiler.js +2 -3
  42. package/dist/compiler.js.map +1 -1
  43. package/dist/contracts/handlers/index.cjs +15 -11
  44. package/dist/contracts/handlers/index.d.cts +5 -5
  45. package/dist/contracts/handlers/index.d.ts +5 -5
  46. package/dist/contracts/handlers/index.js +4 -4
  47. package/dist/{index-Bq349_ly.d.cts → index-BQwrHcOh.d.cts} +524 -23
  48. package/dist/{index-D4ahI0W6.d.cts → index-BaTItxPx.d.cts} +1 -1
  49. package/dist/{index-Yh5y9G4E.d.ts → index-BapVvuoI.d.ts} +1 -1
  50. package/dist/{index-Mn2POBPj.d.ts → index-DuXylQrN.d.ts} +524 -23
  51. package/dist/index.cjs +403 -368
  52. package/dist/index.d.cts +82 -71
  53. package/dist/index.d.ts +82 -71
  54. package/dist/index.js +6 -7
  55. package/dist/repositories/realm/index.cjs +39 -40
  56. package/dist/repositories/realm/index.cjs.map +1 -1
  57. package/dist/repositories/realm/index.d.cts +2 -2
  58. package/dist/repositories/realm/index.d.ts +2 -2
  59. package/dist/repositories/realm/index.js +7 -8
  60. package/dist/repositories/realm/index.js.map +1 -1
  61. package/dist/repositories/sqlite/index.cjs +37 -38
  62. package/dist/repositories/sqlite/index.cjs.map +1 -1
  63. package/dist/repositories/sqlite/index.d.cts +2 -2
  64. package/dist/repositories/sqlite/index.d.ts +2 -2
  65. package/dist/repositories/sqlite/index.js +7 -8
  66. package/dist/repositories/sqlite/index.js.map +1 -1
  67. package/dist/{taskRunner-BYxEgwM5.d.ts → taskRunner-BxOmg-O6.d.ts} +1 -1
  68. package/dist/{taskRunner-Z3LnHfgs.d.cts → taskRunner-D2itCXf6.d.cts} +1 -1
  69. package/dist/wallet/expo/background.cjs +16 -17
  70. package/dist/wallet/expo/background.cjs.map +1 -1
  71. package/dist/wallet/expo/background.d.cts +3 -3
  72. package/dist/wallet/expo/background.d.ts +3 -3
  73. package/dist/wallet/expo/background.js +8 -9
  74. package/dist/wallet/expo/background.js.map +1 -1
  75. package/dist/wallet/expo/index.cjs +17 -18
  76. package/dist/wallet/expo/index.cjs.map +1 -1
  77. package/dist/wallet/expo/index.d.cts +2 -2
  78. package/dist/wallet/expo/index.d.ts +2 -2
  79. package/dist/wallet/expo/index.js +7 -8
  80. package/dist/wallet/expo/index.js.map +1 -1
  81. package/dist/worker/expo/index.cjs +11 -12
  82. package/dist/worker/expo/index.cjs.map +1 -1
  83. package/dist/worker/expo/index.d.cts +4 -4
  84. package/dist/worker/expo/index.d.ts +4 -4
  85. package/dist/worker/expo/index.js +7 -8
  86. package/dist/worker/expo/index.js.map +1 -1
  87. package/package.json +1 -1
  88. package/dist/chunk-4DUTRRXF.js.map +0 -1
  89. package/dist/chunk-5HCDXBBG.cjs.map +0 -1
  90. package/dist/chunk-DMYHAUTA.cjs.map +0 -1
  91. package/dist/chunk-DPFD5KBK.js.map +0 -1
  92. package/dist/chunk-HRFWODLP.js.map +0 -1
  93. package/dist/chunk-OMZZQTDM.cjs +0 -376
  94. package/dist/chunk-OMZZQTDM.cjs.map +0 -1
  95. package/dist/chunk-PXEFYEKL.js +0 -373
  96. package/dist/chunk-PXEFYEKL.js.map +0 -1
  97. package/dist/chunk-SS5BPVQL.js.map +0 -1
  98. package/dist/chunk-UPIQZRNJ.cjs.map +0 -1
  99. package/dist/chunk-VLO3JAP3.cjs.map +0 -1
  100. package/dist/chunk-W2C3KDQA.js.map +0 -1
  101. package/dist/chunk-WIZCF5IX.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/timelock.ts","../src/script/tapscript.ts","../src/networks.ts","../src/script/address.ts","../src/script/taprootTree.ts","../src/script/base.ts"],"names":["MultisigTapscript","MultisigType","encode","decode","CSVMultisigTapscript","ConditionCSVMultisigTapscript","ConditionMultisigTapscript","CLTVMultisigTapscript","Script","TAP_LEAF_VERSION","leaf","hex"],"mappings":";;;;;;;;;;;;;AAMO,SAAS,mBAAmB,QAAA,EAAoC;AACnE,EAAA,OAAa,KAAA,CAAA,MAAA;AAAA,IACT,QAAA,CAAS,IAAA,KAAS,QAAA,GACZ,EAAE,QAAQ,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,KAC/B,EAAE,OAAA,EAAS,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA;AAAE,GAC5C;AACJ;AAKO,SAAS,mBAAmB,QAAA,EAAoC;AACnE,EAAA,MAAM,OAAA,GAAgB,aAAO,QAAQ,CAAA;AACrC,EAAA,IAAI,QAAA,IAAY,OAAA,IAAW,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW;AACrD,IAAA,OAAO,EAAE,IAAA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,aAAa,MAAA,CAAO,OAAO,EAAE,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,MAAM,CAAA;AACtE,EAAA,MAAM,UAAA,GAAa,IAAI,UAAA,CAAW,OAAO,CAAA;AACzC,EAAA,OAAO,UAAA,CAAW,MAAA,CAAO,GAAA,CAAI,CAAC,IAAA,MAAU;AAAA,IACpC,KAAA,EAAO,IAAA,CAAK,CAAC,CAAA,CAAE,UAAA,CAAW,MAAA;AAAA,IAC1B,OAAA,EAASD,gBAAAA;AAAA,IACT,MAAA,EAAQ,wBAAwB,IAAI;AAAA,GACxC,CAAE,CAAA;AACN;AAsBO,SAAS,YAAY,aAAA,EAAkD;AAC1E,EAAA,IAAI,QAAA,GAA+B,MAAA;AAEnC,EAAA,IAAI;AACA,IAAA,MAAM,qBAAA,GAAwB,cAAc,CAAC,CAAA;AAC7C,IAAA,MAAM,SAAS,qBAAA,CAAsB,QAAA,CAAS,CAAA,EAAG,qBAAA,CAAsB,SAAS,CAAC,CAAA;AACjF,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,oBAAA,CAAqB,MAAA,CAAO,MAAM,CAAA,CAAE,MAAA;AACnD,MAAA,QAAA,GAAW,kBAAA,CAAmB,OAAO,QAAQ,CAAA;AAAA,IACjD,CAAA,CAAA,MAAQ;AACJ,MAAA,MAAM,MAAA,GAAS,qBAAA,CAAsB,MAAA,CAAO,MAAM,CAAA,CAAE,MAAA;AACpD,MAAA,QAAA,GAAW,MAAA,CAAO,OAAO,gBAAgB,CAAA;AAAA,IAC7C;AAAA,EACJ,CAAA,CAAA,MAAQ;AAAA,EAAC;AAET,EAAA,OAAO,QAAA;AACX","file":"chunk-DPFD5KBK.js","sourcesContent":["import * as bip68 from \"bip68\";\nimport type { RelativeTimelock } from \"../script/tapscript\";\n\n/**\n * Convert RelativeTimelock to BIP68 sequence number.\n */\nexport function timelockToSequence(timelock: RelativeTimelock): number {\n return bip68.encode(\n timelock.type === \"blocks\"\n ? { blocks: Number(timelock.value) }\n : { seconds: Number(timelock.value) },\n );\n}\n\n/**\n * Convert BIP68 sequence number back to RelativeTimelock.\n */\nexport function sequenceToTimelock(sequence: number): RelativeTimelock {\n const decoded = bip68.decode(sequence);\n if (\"blocks\" in decoded && decoded.blocks !== undefined) {\n return { type: \"blocks\", value: BigInt(decoded.blocks) };\n }\n if (\"seconds\" in decoded && decoded.seconds !== undefined) {\n return { type: \"seconds\", value: BigInt(decoded.seconds) };\n }\n throw new Error(`Invalid BIP68 sequence: ${sequence}`);\n}\n\n/**\n * Decode a BIP68 sequence, rejecting one that is not the canonical encoding of\n * the timelock it decodes to: the disable flag, or bits outside the value and\n * type fields, which would re-encode to different script bytes.\n */\nexport function sequenceToCanonicalTimelock(sequence: bigint): RelativeTimelock | undefined {\n if (sequence < 0n || sequence >= 0x80000000n) return undefined;\n const timelock = sequenceToTimelock(Number(sequence));\n return BigInt(timelockToSequence(timelock)) === sequence ? timelock : undefined;\n}\n","import { Script, ScriptNum, ScriptType, p2tr_ms } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\nimport { sequenceToTimelock, timelockToSequence } from \"../utils/timelock\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n/**\n * RelativeTimelock lets to create timelocked with CHECKSEQUENCEVERIFY script.\n *\n * @example\n * ```typescript\n * const timelock = { value: 144n, type: \"blocks\" }; // 1 day in blocks\n * const timelock = { value: 512n, type: \"seconds\" }; // 8 minutes in seconds\n * ```\n */\nexport type RelativeTimelock = {\n value: bigint;\n type: \"seconds\" | \"blocks\";\n};\n\nexport enum TapscriptType {\n Multisig = \"multisig\",\n CSVMultisig = \"csv-multisig\",\n ConditionCSVMultisig = \"condition-csv-multisig\",\n ConditionMultisig = \"condition-multisig\",\n CLTVMultisig = \"cltv-multisig\",\n}\n\n/**\n * ArkTapscript is the base element of vtxo scripts.\n * It is used to encode and decode the different types of vtxo scripts.\n */\nexport interface ArkTapscript<T extends TapscriptType, Params> {\n type: T;\n params: Params;\n script: Uint8Array;\n}\n\n/**\n * decodeTapscript is a function that decodes an Arkade tapscript from a raw script.\n *\n * @throws {Error} if the script is not a valid Arkade tapscript\n * @example\n * ```typescript\n * const arkTapscript = decodeTapscript(new Uint8Array(32));\n * console.log(\"type:\", arkTapscript.type);\n * ```\n */\nexport function decodeTapscript(script: Uint8Array): ArkTapscript<TapscriptType, any> {\n const types = [\n MultisigTapscript,\n CSVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n ConditionMultisigTapscript,\n CLTVMultisigTapscript,\n ];\n\n for (const type of types) {\n try {\n return type.decode(script);\n } catch (error) {\n continue;\n }\n }\n\n throw new Error(`Failed to decode: script ${hex.encode(script)} is not a valid tapscript`);\n}\n\n/**\n * Implements a multi-signature tapscript.\n *\n * <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const multisigTapscript = MultisigTapscript.encode({ pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace MultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.Multisig, Params>;\n\n export enum MultisigType {\n CHECKSIG,\n CHECKSIGADD,\n }\n\n export type Params = {\n pubkeys: Bytes[];\n type?: MultisigType;\n };\n\n /** Encode a plain multisig tapscript. */\n export function encode(params: Params): Type {\n if (params.pubkeys.length === 0) {\n throw new Error(\"At least 1 pubkey is required\");\n }\n\n for (const pubkey of params.pubkeys) {\n if (pubkey.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n }\n }\n\n if (!params.type) {\n params.type = MultisigType.CHECKSIG;\n }\n\n if (params.type === MultisigType.CHECKSIGADD) {\n return {\n type: TapscriptType.Multisig,\n params,\n script: p2tr_ms(params.pubkeys.length, params.pubkeys).script,\n };\n }\n\n const asm: ScriptType = [];\n for (let i = 0; i < params.pubkeys.length; i++) {\n asm.push(params.pubkeys[i]);\n\n // CHECKSIGVERIFY except the last pubkey\n if (i < params.pubkeys.length - 1) {\n asm.push(\"CHECKSIGVERIFY\");\n } else {\n asm.push(\"CHECKSIG\");\n }\n }\n\n return {\n type: TapscriptType.Multisig,\n params,\n script: Script.encode(asm),\n };\n }\n\n /** Decode a plain multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n try {\n // Try decoding as checksigAdd first\n return decodeChecksigAdd(script);\n } catch (error) {\n // If checksigAdd fails, try regular checksig\n try {\n return decodeChecksig(script);\n } catch (error2) {\n throw new Error(\n `Failed to decode script: ${error2 instanceof Error ? error2.message : String(error2)}`,\n );\n }\n }\n }\n\n // <pubkey> CHECKSIG <pubkey> CHECKSIGADD <len_keys> NUMEQUAL\n function decodeChecksigAdd(script: Uint8Array): Type {\n const asm = Script.decode(script);\n const pubkeys: Bytes[] = [];\n let foundNumEqual = false;\n\n // Parse through ASM operations\n for (let i = 0; i < asm.length; i++) {\n const op = asm[i];\n\n // If it's a data push, it should be a 32-byte pubkey\n if (typeof op !== \"string\" && typeof op !== \"number\") {\n if (op.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n }\n pubkeys.push(op);\n\n // Check next operation is CHECKSIGADD or CHECKSIG\n if (\n i + 1 >= asm.length ||\n (asm[i + 1] !== \"CHECKSIGADD\" && asm[i + 1] !== \"CHECKSIG\")\n ) {\n throw new Error(\"Expected CHECKSIGADD or CHECKSIG after pubkey\");\n }\n i++; // Skip the CHECKSIGADD op\n continue;\n }\n\n // Last operation should be NUMEQUAL\n if (i === asm.length - 1) {\n if (op !== \"NUMEQUAL\") {\n throw new Error(\"Expected NUMEQUAL at end of script\");\n }\n foundNumEqual = true;\n }\n }\n\n if (!foundNumEqual) {\n throw new Error(\"Missing NUMEQUAL operation\");\n }\n\n if (pubkeys.length === 0) {\n throw new Error(\"Invalid script: must have at least 1 pubkey\");\n }\n\n // Verify the script by re-encoding and comparing\n const reconstructed = encode({\n pubkeys,\n type: MultisigType.CHECKSIGADD,\n });\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.Multisig,\n params: { pubkeys, type: MultisigType.CHECKSIGADD },\n script,\n };\n }\n\n // <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n function decodeChecksig(script: Uint8Array): Type {\n const asm = Script.decode(script);\n const pubkeys: Bytes[] = [];\n\n // Parse through ASM operations\n for (let i = 0; i < asm.length; i++) {\n const op = asm[i];\n\n // If it's a data push, it should be a 32-byte pubkey\n if (typeof op !== \"string\" && typeof op !== \"number\") {\n if (op.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n }\n pubkeys.push(op);\n\n // Check next operation\n if (i + 1 >= asm.length) {\n throw new Error(\"Unexpected end of script\");\n }\n\n const nextOp = asm[i + 1];\n if (nextOp !== \"CHECKSIGVERIFY\" && nextOp !== \"CHECKSIG\") {\n throw new Error(\"Expected CHECKSIGVERIFY or CHECKSIG after pubkey\");\n }\n\n // Last operation must be CHECKSIG, not CHECKSIGVERIFY\n if (i === asm.length - 2 && nextOp !== \"CHECKSIG\") {\n throw new Error(\"Last operation must be CHECKSIG\");\n }\n\n i++; // Skip the CHECKSIG/CHECKSIGVERIFY op\n continue;\n }\n }\n\n if (pubkeys.length === 0) {\n throw new Error(\"Invalid script: must have at least 1 pubkey\");\n }\n\n // Verify the script by re-encoding and comparing\n const reconstructed = encode({ pubkeys, type: MultisigType.CHECKSIG });\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.Multisig,\n params: { pubkeys, type: MultisigType.CHECKSIG },\n script,\n };\n }\n\n /** Return true when the tapscript is a plain multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.Multisig;\n }\n}\n\n/**\n * Implements a relative timelock script that requires all specified pubkeys to sign\n * after the relative timelock has expired. The timelock can be specified in blocks or seconds.\n *\n * This is the standard exit closure and it is also used for the sweep closure in vtxo trees.\n *\n * <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const csvMultisigTapscript = CSVMultisigTapscript.encode({ timelock: { type: \"blocks\", value: 144 }, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CSVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.CSVMultisig, Params>;\n\n export type Params = {\n timelock: RelativeTimelock;\n } & MultisigTapscript.Params;\n\n /** Encode a CSV multisig tapscript. */\n export function encode(params: Params): Type {\n for (const pubkey of params.pubkeys) {\n if (pubkey.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n }\n }\n\n const sequence = MinimalScriptNum.encode(BigInt(timelockToSequence(params.timelock)));\n\n const asm: ScriptType = [\n sequence.length === 1 ? sequence[0] : sequence,\n \"CHECKSEQUENCEVERIFY\",\n \"DROP\",\n ];\n const multisigScript = MultisigTapscript.encode(params);\n const script = new Uint8Array([...Script.encode(asm), ...multisigScript.script]);\n\n return {\n type: TapscriptType.CSVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a CSV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const sequence = asm[0];\n const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n let multisig: MultisigTapscript.Type;\n\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n let sequenceNum: number;\n if (typeof sequence === \"number\") {\n sequenceNum = sequence;\n } else {\n sequenceNum = Number(MinimalScriptNum.decode(sequence as Uint8Array));\n }\n const timelock = sequenceToTimelock(sequenceNum);\n\n const reconstructed = encode({\n timelock,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.CSVMultisig,\n params: {\n timelock,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a CSV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.CSVMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 3) {\n return new Error(`Invalid script: too short (expected at least 3)`);\n }\n\n const sequence = asm[0];\n if (typeof sequence === \"string\") {\n return new Error(\"Invalid script: expected sequence number\");\n }\n\n if (asm[1] !== \"CHECKSEQUENCEVERIFY\" || asm[2] !== \"DROP\") {\n return new Error(\"Invalid script: expected CHECKSEQUENCEVERIFY DROP\");\n }\n\n return true;\n }\n}\n\nfunction isConditionScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 1) {\n return new Error(`Invalid script: too short (expected at least 1)`);\n }\n\n if (asm.lastIndexOf(\"VERIFY\") === -1) {\n return new Error(\"Invalid script: missing VERIFY operation\");\n }\n\n return true;\n}\n\n/**\n * Combines a condition script with an exit closure. The resulting script requires\n * the condition to be met, followed by the standard exit closure requirements\n * (timelock and signatures).\n *\n * <conditionScript> VERIFY <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionCSVMultisigTapscript = ConditionCSVMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionCSVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.ConditionCSVMultisig, Params>;\n\n export type Params = {\n conditionScript: Bytes;\n } & CSVMultisigTapscript.Params;\n\n /** Encode a condition + CSV multisig tapscript. */\n export function encode(params: Params): Type {\n const script = new Uint8Array([\n ...params.conditionScript,\n ...Script.encode([\"VERIFY\"]),\n ...CSVMultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.ConditionCSVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a condition + CSV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const verifyIndex = asm.lastIndexOf(\"VERIFY\");\n\n if (verifyIndex === -1) {\n throw Error(\"Invalid script: missing VERIFY operation\");\n }\n\n const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n const csvMultisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n let csvMultisig: CSVMultisigTapscript.Type;\n try {\n csvMultisig = CSVMultisigTapscript.decode(csvMultisigScript);\n } catch (error) {\n throw new Error(\n `Invalid CSV multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const reconstructed = encode({\n conditionScript,\n ...csvMultisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.ConditionCSVMultisig,\n params: {\n conditionScript,\n ...csvMultisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a condition + CSV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.ConditionCSVMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n return isConditionScriptValid(script);\n }\n}\n\n/**\n * Combines a condition script with a forfeit closure. The resulting script requires\n * the condition to be met, followed by the standard forfeit closure requirements\n * (multi-signature).\n *\n * <conditionScript> VERIFY <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionMultisigTapscript = ConditionMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.ConditionMultisig, Params>;\n\n export type Params = {\n conditionScript: Bytes;\n } & MultisigTapscript.Params;\n\n /** Encode a condition + multisig tapscript. */\n export function encode(params: Params): Type {\n const script = new Uint8Array([\n ...params.conditionScript,\n ...Script.encode([\"VERIFY\"]),\n ...MultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.ConditionMultisig,\n params,\n script,\n };\n }\n\n /** Decode a condition + multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const verifyIndex = asm.lastIndexOf(\"VERIFY\");\n\n if (verifyIndex === -1) {\n throw Error(\"Invalid script: missing VERIFY operation\");\n }\n\n const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n const multisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n let multisig: MultisigTapscript.Type;\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const reconstructed = encode({\n conditionScript,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.ConditionMultisig,\n params: {\n conditionScript,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a condition + multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.ConditionMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n return isConditionScriptValid(script);\n }\n}\n\n/**\n * Implements an absolute timelock (CLTV) script combined with a forfeit closure.\n * The script requires waiting until a specific block height/timestamp before the\n * forfeit closure conditions can be met.\n *\n * <locktime> CHECKLOCKTIMEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const cltvMultisigTapscript = CLTVMultisigTapscript.encode({ absoluteTimelock: 144, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CLTVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.CLTVMultisig, Params>;\n\n export type Params = {\n absoluteTimelock: bigint;\n } & MultisigTapscript.Params;\n\n /** Encode a CLTV multisig tapscript. */\n export function encode(params: Params): Type {\n if (params.absoluteTimelock < 0n || params.absoluteTimelock > 0xffffffffn) {\n throw new Error(`absoluteTimelock must fit in 32 bits, got ${params.absoluteTimelock}`);\n }\n const locktime = MinimalScriptNum.encode(params.absoluteTimelock);\n const asm: ScriptType = [\n locktime.length === 1 ? locktime[0] : locktime,\n \"CHECKLOCKTIMEVERIFY\",\n \"DROP\",\n ];\n const timelockedScript = Script.encode(asm);\n\n const script = new Uint8Array([\n ...timelockedScript,\n ...MultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.CLTVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a CLTV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const locktime = asm[0];\n if (typeof locktime === \"string\") {\n throw new Error(\"Invalid script: expected locktime number\");\n }\n\n if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n throw new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n }\n\n const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n let multisig: MultisigTapscript.Type;\n\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n let absoluteTimelock: bigint;\n if (typeof locktime === \"number\") {\n absoluteTimelock = BigInt(locktime);\n } else {\n absoluteTimelock = MinimalScriptNum.decode(locktime as Bytes);\n }\n\n const reconstructed = encode({\n absoluteTimelock,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.CLTVMultisig,\n params: {\n absoluteTimelock,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a CLTV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.CLTVMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 3) {\n return new Error(`Invalid script: too short (expected at least 3)`);\n }\n\n const locktime = asm[0];\n if (typeof locktime === \"string\") {\n return new Error(\"Invalid script: expected locktime as number or bytes\");\n }\n\n if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n return new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n }\n\n return true;\n }\n}\n","import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n\nexport type NetworkName = \"bitcoin\" | \"testnet\" | \"signet\" | \"mutinynet\" | \"regtest\";\n\nexport interface Network {\n hrp: string;\n bech32: string;\n pubKeyHash: number;\n scriptHash: number;\n wif: number;\n /**\n * Canonical name this network was resolved from, when known: the only way to tell the\n * tb-family apart (testnet, signet and mutinynet share every field above). Optional because a\n * hand-built `Network` has none — read a missing one as \"unknown\" and take the strictest branch.\n */\n name?: NetworkName;\n}\nexport const getNetwork = (network: NetworkName): Network => {\n const found = networks[network];\n // Fail closed: an unknown network must never silently fall through to\n // mainnet params (e.g. via Address()'s default) when validating addresses.\n if (!found) throw new Error(`Unsupported network: ${network}`);\n return found;\n};\n\n/**\n * The {@link Network} the operator's info names. {@link getNetwork} fails closed, so an\n * unrecognized network throws here rather than resolving to mainnet parameters downstream.\n * Structurally typed so the network table doesn't depend on the provider layer.\n */\nexport const networkFromOperatorInfo = (info: { network: string }): Network =>\n getNetwork(info.network as NetworkName);\n\n/** @deprecated Use {@link networkFromOperatorInfo}. */\nexport const networkFromArkadeInfo = networkFromOperatorInfo;\n\nexport const networks = {\n bitcoin: withArkPrefix(NETWORK, \"ark\", \"bitcoin\"),\n testnet: withArkPrefix(TEST_NETWORK, \"tark\", \"testnet\"),\n signet: withArkPrefix(TEST_NETWORK, \"tark\", \"signet\"),\n mutinynet: withArkPrefix(TEST_NETWORK, \"tark\", \"mutinynet\"),\n regtest: withArkPrefix(\n {\n ...TEST_NETWORK,\n bech32: \"bcrt\",\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n },\n \"tark\",\n \"regtest\",\n ),\n};\n\nfunction withArkPrefix(\n network: Omit<Network, \"hrp\" | \"name\">,\n prefix: string,\n name: NetworkName,\n): Network {\n return {\n ...network,\n hrp: prefix,\n name,\n };\n}\n\nexport const DEFAULT_ARKADE_SERVER_URL = \"https://arkade.computer\" as const;\n/**\n * The operator's cosigner that emulates Arkade Script on mainnet, resolved by the\n * `{ network: \"bitcoin\" }` service. No trailing slash: `RestEmulatorProvider` appends its paths\n * verbatim. The URL only selects where to ask for a signature; the key covenants commit to is\n * {@link BITCOIN_EMULATOR_PUBKEY}.\n */\nexport const DEFAULT_ARKADE_EMULATOR_URL = \"https://emulator.arkade.computer\" as const;\nexport const DEFAULT_NETWORK = networks.bitcoin;\nexport const DEFAULT_NETWORK_NAME = \"bitcoin\" as const satisfies NetworkName;\n\n/**\n * 33-byte compressed secp256k1 point, lowercase hex. The covenant leaf is indifferent\n * (`computeArkadeScriptPublicKey` truncates by length and `lift_x`es, so even an odd-Y `03` key\n * tweaks the same), but compressed is lossless and what's on the wire: the emulator's `/v1/info`\n * returns `signerPubkey` compressed and `Arkade.connect` keeps all 33 bytes, so a pinned value is\n * byte-identical to a live fetch. x-only loses the parity bit; consumers needing 32 bytes (e.g.\n * the Arkade Intents offer TLV) normalize at their own boundary.\n */\nconst COMPRESSED_PUBKEY = /^0[23][0-9a-f]{64}$/;\n\n/** Key of the operator's cosigner that emulates Arkade Script on mainnet. */\nexport const BITCOIN_EMULATOR_PUBKEY =\n \"0239c196415da47b26456a101daaa12ba9e445bfe153197f1e2b750bf40e52092e\" as const;\n\n/** Key of the operator's cosigner that emulates Arkade Script on mutinynet. */\nexport const MUTINYNET_EMULATOR_PUBKEY =\n \"03f823b9b2febc81f4af967e77aed2f541cbd3397c6d8f5a72e32eb7b471af889a\" as const;\n\n/** Key of the operator's cosigner that emulates Arkade Script in the `arkade-regtest` stack. */\nexport const REGTEST_EMULATOR_PUBKEY =\n \"02999413c46fa10ada5cbc4bcc79a1d09160c2ba3cfc812705d7a13e5e545fb2a9\" as const;\n\n/**\n * The operator's cosigner that emulates Arkade Script, by network: a property of the NETWORK, since\n * every participant on it co-signs with the same key; a per-deployment copy could only introduce\n * disagreement nothing downstream catches. `testnet`/`signet` have no emulator and throw rather\n * than resolve to a neighbour's key.\n */\nconst EMULATOR_PUBKEYS: Partial<Record<NetworkName, string>> = {\n bitcoin: BITCOIN_EMULATOR_PUBKEY,\n mutinynet: MUTINYNET_EMULATOR_PUBKEY,\n regtest: REGTEST_EMULATOR_PUBKEY,\n};\n\n/**\n * The pinned co-signer key for `network`, as 33-byte compressed lowercase hex.\n *\n * @throws if the network carries no name, or names one with no deployed emulator. Fail closed:\n * the key ends up in a covenant leaf deciding who can move the funds. Guessing a tb-family\n * neighbour's key locks funds to a co-signer that never signs; an empty string only moves the\n * failure. Deliberately NOT falling back to the emulator's self-reported key — that is the\n * trust this pin removes, and a silent fallback on an unnamed `Network` (which may carry\n * mainnet-equivalent parameters) would lapse it exactly where it matters most. Callers who mean\n * it pass {@link resolveEmulatorPubkey}'s override, which the thrown message names.\n */\nexport function defaultEmulatorPubkey(network: Network): string {\n const pinned = network.name ? EMULATOR_PUBKEYS[network.name] : undefined;\n if (!pinned) {\n // Name the remedy: whoever hits this usually has a working emulator, so a bare refusal\n // reads as the SDK being broken.\n const cause = network.name\n ? `no emulator is deployed for ${network.name}`\n : `this Network carries no name, so it cannot be matched ` +\n `(build it with getNetwork(...) rather than by hand)`;\n throw new Error(\n `No emulator co-signer key is pinned for this network: ${cause}; ` +\n `pass emulatorPubkey: \"<33-byte compressed hex>\" to Arkade.connect to ` +\n `co-sign with your own emulator instead. Pinned networks: ` +\n `${Object.keys(EMULATOR_PUBKEYS).join(\", \")}`,\n );\n }\n return pinned;\n}\n\n/**\n * Resolve the co-signer key for `network`, letting a caller substitute its own, for:\n *\n * 1. **A network rotated its emulator key before this SDK shipped the new constant.**\n * `Arkade.connect` no longer asks the service, so covenants would keep building against the\n * retired key and fail only at claim time; the override makes rotation a config change.\n * 2. A private or self-hosted emulator, including on unpinned networks.\n * 3. Tests and local stacks.\n *\n * Supplying it means trusting that operator in place of the network's: covenants built from the\n * key can be completed by its holder and no one else. A malformed override throws rather than\n * surfacing later as an unspendable contract.\n */\nexport function resolveEmulatorPubkey(network: Network, override?: string): string {\n if (override === undefined) return defaultEmulatorPubkey(network);\n if (!COMPRESSED_PUBKEY.test(override)) {\n throw new Error(\n `Emulator pubkey override must be 33-byte compressed secp256k1 hex ` +\n `(66 lowercase chars, 02/03 prefix), got ${JSON.stringify(override)}.`,\n );\n }\n return override;\n}\n","import { bech32m } from \"@scure/base\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { Script } from \"@scure/btc-signer/script.js\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\n/**\n * ArkAddress allows creating and decoding bech32m-encoded Arkade addresses: an hrp plus a\n * 65-byte payload of version byte ‖ 32-byte server pubkey ‖ 32-byte VTXO taproot key.\n *\n * @remarks\n * This is an Arkade-specific address format.\n * It is distinct from the Taproot onchain address returned by `VtxoScript.onchainAddress`.\n *\n * @see VtxoScript\n *\n * @example\n * ```typescript\n * const address = new ArkAddress(\n * new Uint8Array(32), // server public key\n * new Uint8Array(32), // vtxo taproot public key\n * \"ark\"\n * );\n *\n * const encoded = address.encode();\n * console.log(\"address: \", encoded);\n *\n * const decoded = ArkAddress.decode(encoded);\n * ```\n */\nexport class ArkAddress {\n /**\n * Create an Arkade address from its server public key, Taproot output key, and prefix.\n *\n * @param serverPubKey - 32-byte Arkade server public key\n * @param vtxoTaprootKey - 32-byte Taproot output key (a.k.a. tweaked public key)\n * @param hrp - Bech32 human-readable prefix\n * @param version - Address version byte\n * @defaultValue `version = 0`\n * @throws Error if either public key is not 32 bytes long\n */\n constructor(\n readonly serverPubKey: Bytes,\n readonly vtxoTaprootKey: Bytes,\n readonly hrp: string = DEFAULT_NETWORK.hrp,\n readonly version: number = 0,\n ) {\n if (serverPubKey.length !== 32) {\n throw new Error(\n \"Invalid server public key length, expected 32 bytes, got \" + serverPubKey.length,\n );\n }\n if (vtxoTaprootKey.length !== 32) {\n throw new Error(\n \"Invalid vtxo taproot public key length, expected 32 bytes, got \" +\n vtxoTaprootKey.length,\n );\n }\n }\n\n /**\n * Decode an Arkade address from its bech32m string form.\n *\n * @param address - Bech32m-encoded Arkade address\n * @returns Decoded Arkade address\n * @throws Error if the address is malformed or has an invalid payload length\n * @see encode\n */\n static decode(address: string): ArkAddress {\n const decoded = bech32m.decodeUnsafe(address, 1023);\n if (!decoded) {\n throw new Error(\"Invalid address\");\n }\n const data = new Uint8Array(bech32m.fromWords(decoded.words));\n\n if (data.length !== 1 + 32 + 32) {\n throw new Error(\"Invalid data length, expected 65 bytes, got \" + data.length);\n }\n\n const version = data[0];\n const serverPubKey = data.slice(1, 33);\n const vtxoTaprootPubKey = data.slice(33, 65);\n\n return new ArkAddress(serverPubKey, vtxoTaprootPubKey, decoded.prefix, version);\n }\n\n /**\n * Encode the address to its bech32m string form.\n *\n * @returns Bech32m-encoded Arkade address\n * @see decode\n */\n encode(): string {\n const data = new Uint8Array(1 + 32 + 32);\n data[0] = this.version;\n data.set(this.serverPubKey, 1);\n data.set(this.vtxoTaprootKey, 33);\n\n const words = bech32m.toWords(data);\n return bech32m.encode(this.hrp, words, 1023);\n }\n\n /** ScriptPubKey used to send non-dust funds to the address. */\n get pkScript(): Bytes {\n return Script.encode([\"OP_1\", this.vtxoTaprootKey]);\n }\n\n /** ScriptPubKey used to send sub-dust funds to the address. */\n get subdustPkScript(): Bytes {\n return Script.encode([\"RETURN\", this.vtxoTaprootKey]);\n }\n}\n","import { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\n\n/** A leaf node in the Taproot script tree, as consumed by `@scure/btc-signer`'s `p2tr`. */\nexport interface TaprootLeaf {\n script: Bytes;\n leafVersion: number;\n}\n\n/** A `p2tr` tree node: a leaf, or a `[left, right]` branch tuple. */\nexport type TaprootTreeNode = TaprootLeaf | [TaprootTreeNode, TaprootTreeNode];\n\n/**\n * Assemble a Taproot script tree with btcd's `txscript.AssembleTaprootScriptTree` algorithm\n * (the one arkd uses).\n *\n * `@scure/btc-signer`'s `taprootListToTree` builds a Huffman tree instead; the two agree only for\n * power-of-2 leaf counts. Any other count yields a different merkle root → different output key\n * → arkd rejects spends with `INVALID_PSBT_INPUT`.\n *\n * @param scripts - Raw tapscript bytes per leaf, in TapTree PSBT field order.\n * @returns The nested-tuple form `p2tr` accepts.\n */\nexport function assembleBtcdTaprootTree(scripts: Bytes[]): TaprootTreeNode {\n if (scripts.length === 0) {\n throw new Error(\"assembleBtcdTaprootTree: empty scripts list\");\n }\n\n const leaves: TaprootLeaf[] = scripts.map((script) => ({\n script,\n leafVersion: TAP_LEAF_VERSION,\n }));\n\n if (leaves.length === 1) {\n return leaves[0];\n }\n\n // ── Phase 1: pair leaves left-to-right ─────────────────────────────\n const branches: TaprootTreeNode[] = [];\n for (let i = 0; i < leaves.length; i += 2) {\n if (i === leaves.length - 1) {\n // Odd trailing leaf merges into the LAST branch, not a fresh pair (as btcd does).\n const last = branches.pop();\n if (last === undefined) {\n throw new Error(\n `assembleBtcdTaprootTree: unexpected odd leaf at i=${i} with no prior branch`,\n );\n }\n branches.push([last, leaves[i]]);\n } else {\n branches.push([leaves[i], leaves[i + 1]]);\n }\n }\n\n // ── Phase 2: FIFO-queue merge branches ─────────────────────────────\n while (branches.length >= 2) {\n const left = branches.shift()!;\n const right = branches.shift()!;\n branches.push([left, right]);\n }\n\n return branches[0];\n}\n\n/**\n * Left-to-right leaf layout of the tree {@link assembleBtcdTaprootTree} builds\n * for `count` leaves: for each position, the leaf's index in the input list\n * and its depth. The shape depends only on the leaf count, never on the\n * scripts, so this also tells where each input leaf lands in any such tree.\n *\n * @param count - Number of leaves\n * @returns One `{ index, depth }` entry per leaf, in left-to-right DFS order\n */\nexport function btcdLeafLayout(count: number): { index: number; depth: number }[] {\n const placeholders = Array.from({ length: count }, () => new Uint8Array());\n const indexOf = new Map<Bytes, number>(placeholders.map((script, index) => [script, index]));\n const layout: { index: number; depth: number }[] = [];\n const walk = (node: TaprootTreeNode, depth: number): void => {\n if (Array.isArray(node)) {\n walk(node[0], depth + 1);\n walk(node[1], depth + 1);\n } else {\n layout.push({ index: indexOf.get(node.script)!, depth });\n }\n };\n walk(assembleBtcdTaprootTree(placeholders), 0);\n return layout;\n}\n","import { Address, p2tr, taprootNumsKey, NETWORK } from \"@scure/btc-signer\";\nimport { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { PSBTOutput } from \"@scure/btc-signer/psbt.js\";\nimport { VarBytes } from \"@scure/btc-signer/script.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport * as P from \"micro-packed\";\nimport { hex } from \"@scure/base\";\nimport { ArkAddress } from \"./address\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport {\n CLTVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n CSVMultisigTapscript,\n} from \"./tapscript\";\nimport { assembleBtcdTaprootTree, btcdLeafLayout } from \"./taprootTree\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\nexport type TapLeafScript = [\n {\n version: number;\n internalKey: Bytes;\n merklePath: Bytes[];\n },\n Bytes,\n];\n\n/**\n * The leaf a proof signs for `coin`. SDK coins carry only `proofTapLeafScript`,\n * so `intentTapLeafScript` is set only where a caller chose a leaf with the old\n * key, and that choice wins.\n */\nexport const proofTapLeafScriptOf = (coin: {\n proofTapLeafScript: TapLeafScript;\n intentTapLeafScript?: TapLeafScript;\n}): TapLeafScript => coin.intentTapLeafScript ?? coin.proofTapLeafScript;\n\nexport const TapTreeCoder: (typeof PSBTOutput.tapTree)[2] = P.array(\n null,\n P.struct({ depth: P.U8, version: P.U8, script: VarBytes }),\n);\n\nexport function scriptFromTapLeafScript(leaf: TapLeafScript): Bytes {\n return leaf[1].subarray(0, leaf[1].length - 1); // remove the version byte\n}\n\n/**\n * VtxoScript is a script that contains a list of tapleaf scripts.\n * It is used to create virtual output scripts.\n *\n * @see ArkAddress\n *\n * @example\n * ```typescript\n * const vtxoScript = new VtxoScript([new Uint8Array(32), new Uint8Array(32)]);\n * ```\n */\nexport class VtxoScript {\n readonly leaves: TapLeafScript[];\n readonly tweakedPublicKey: Bytes;\n readonly pkScript: Bytes;\n\n /**\n * Decode a virtual output script from an encoded TapTree.\n *\n * Leaves are normally read in construction order and their depths\n * ignored: that covers the {@link encode} form (every depth 1) and the\n * placeholder depths other writers use, such as arkd's. The exception is\n * the BIP-371 form {@link toBIP371TapTree} writes, whose leaves are in the\n * tree's DFS order: for some leaf counts (6, 7, 10, ...) that differs from\n * construction order. A tree whose depths are exactly the shape\n * `assembleBtcdTaprootTree` builds is that form, so its leaves are mapped\n * back to construction order first. No construction-order writer produces\n * that depth sequence when the two orders differ, so this never reorders\n * a tree that decoded correctly before.\n *\n * Every leaf must carry the base tapscript version: the tree is rebuilt\n * with {@link TAP_LEAF_VERSION} leaves, so any other version would\n * silently derive a different taproot key.\n *\n * @param tapTree - Encoded TapTree bytes\n * @returns Decoded virtual output script\n * @throws Error if the TapTree cannot be decoded into a valid script set\n * or a leaf carries a version other than {@link TAP_LEAF_VERSION}\n * @see encode\n */\n static decode(tapTree: Bytes): VtxoScript {\n const leaves = TapTreeCoder.decode(tapTree);\n const foreign = leaves.find((leaf) => leaf.version !== TAP_LEAF_VERSION);\n if (foreign) {\n throw new Error(`unsupported tap leaf version 0x${foreign.version.toString(16)}`);\n }\n const scripts = leaves.map((leaf) => leaf.script);\n if (leaves.every((leaf) => leaf.depth === 1)) {\n return new VtxoScript(scripts);\n }\n const layout = btcdLeafLayout(leaves.length);\n if (layout.some((slot, i) => slot.depth !== leaves[i].depth)) {\n return new VtxoScript(scripts);\n }\n const ordered = new Array<Bytes>(leaves.length);\n layout.forEach((slot, i) => {\n ordered[slot.index] = scripts[i];\n });\n return new VtxoScript(ordered);\n }\n\n /**\n * Create a virtual output script from its tapleaf scripts.\n *\n * The Taproot script tree is assembled using btcd's algorithm\n * (`txscript.AssembleTaprootScriptTree`) so the derived taproot output\n * key agrees with arkd for any leaf count. `@scure/btc-signer`'s\n * default `taprootListToTree` is a Huffman builder that only agrees\n * with arkd for power-of-2 leaf counts.\n *\n * @param scripts - Raw tapscript bytes for each leaf\n * @throws Error if the provided leaves cannot produce a valid Taproot tree\n */\n constructor(readonly scripts: Bytes[]) {\n const tapTree = assembleBtcdTaprootTree(scripts);\n\n const payment = p2tr(taprootNumsKey(), tapTree, undefined, true);\n\n if (!payment.tapLeafScript || payment.tapLeafScript.length !== scripts.length) {\n throw new Error(\"invalid scripts\");\n }\n\n this.leaves = payment.tapLeafScript;\n this.tweakedPublicKey = payment.tweakedPubkey;\n this.pkScript = payment.script;\n }\n\n /**\n * Encode the virtual output script to a TapTree byte representation.\n *\n * @returns Encoded TapTree bytes\n * @see decode\n */\n encode(): Bytes {\n const tapTree = TapTreeCoder.encode(\n this.scripts.map((script) => ({\n depth: 1,\n version: TAP_LEAF_VERSION,\n script: script as Uint8Array<ArrayBuffer>,\n })),\n );\n return tapTree;\n }\n\n /**\n * Build the Arkade address corresponding to this virtual output script.\n *\n * @param prefix - Bech32 human-readable prefix\n * @param serverPubKey - 32-byte Arkade server public key\n * @returns Arkade address for this script\n * @see ArkAddress\n */\n address(prefix: string = DEFAULT_NETWORK.hrp, serverPubKey: Bytes): ArkAddress {\n return new ArkAddress(serverPubKey, this.tweakedPublicKey, prefix);\n }\n\n /**\n * Build the Taproot onchain address corresponding to this virtual output script.\n *\n * @param network - Bitcoin network descriptor\n * @returns Taproot onchain address\n * @see address\n */\n onchainAddress(network: typeof NETWORK = DEFAULT_NETWORK): string {\n return Address(network).encode({\n type: \"tr\",\n pubkey: this.tweakedPublicKey,\n });\n }\n\n /**\n * Look up a tapleaf script by its hex-encoded tapscript body.\n *\n * @param scriptHex - Hex-encoded tapscript body without the leaf version byte\n * @returns Matching tapleaf script\n * @throws Error if no matching leaf exists\n */\n findLeaf(scriptHex: string): TapLeafScript {\n const leaf = this.leaves.find(\n (leaf) => hex.encode(scriptFromTapLeafScript(leaf)) === scriptHex,\n )!;\n if (!leaf) {\n throw new Error(`leaf '${scriptHex}' not found`);\n }\n return leaf;\n }\n\n /**\n * Return all unilateral exit paths embedded in the virtual output script.\n *\n * @returns CSV-based exit paths found in the leaves\n * @see getSequence\n */\n exitPaths(): Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> {\n const paths: Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> = [];\n for (const leaf of this.leaves) {\n try {\n const script = scriptFromTapLeafScript(leaf);\n if (CSVMultisigTapscript.isScriptValid(script) === true) {\n const tapScript = CSVMultisigTapscript.decode(script);\n paths.push(tapScript);\n } else if (ConditionCSVMultisigTapscript.isScriptValid(script) === true) {\n const tapScript = ConditionCSVMultisigTapscript.decode(script);\n paths.push(tapScript);\n }\n } catch (e) {\n console.debug(\"Failed to decode script\", e);\n }\n }\n return paths;\n }\n}\n\n/**\n * Convert a `VtxoScript.encode()`-produced TapTree into a BIP-371\n * (`PSBT_OUT_TAP_TREE`) compliant leaf list: entries in left-to-right DFS\n * order, each carrying its *actual* depth in the btcd-assembled tree.\n *\n * `VtxoScript.encode()` stores leaves in the caller's original order with a\n * placeholder `depth: 1` — a format `VtxoScript.decode()` can losslessly\n * invert by re-running `assembleBtcdTaprootTree` over that same order (it\n * decodes this function's output too), but NOT a valid BIP-371 field: for non-power-of-2 leaf counts (e.g. 3, 6) the\n * tree is neither flat nor built in that original order (the algorithm's\n * FIFO merge phase can reorder leaves for counts like 6), so per-index\n * depths cannot be guessed from leaf position. This rebuilds the exact same\n * `VtxoScript` (deterministic from the same script list) to read genuine\n * depths off its `leaves` (populated by `p2tr()` from the real tree), in\n * the tree's true DFS order.\n *\n * @param tapTree - Encoded TapTree bytes from `VtxoScript.encode()`\n * @returns BIP-371-compliant TapTree leaves, ready for a PSBT output's\n * `tapTree` field\n */\nexport function toBIP371TapTree(tapTree: Bytes): ReturnType<typeof TapTreeCoder.decode> {\n const scripts = TapTreeCoder.decode(tapTree).map((leaf) => leaf.script);\n const vtxoScript = new VtxoScript(scripts);\n return vtxoScript.leaves.map((leaf) => ({\n depth: leaf[0].merklePath.length,\n version: TAP_LEAF_VERSION,\n script: scriptFromTapLeafScript(leaf) as Uint8Array<ArrayBuffer>,\n }));\n}\n\nexport type EncodedVtxoScript = { tapTree: Bytes };\n\n/**\n * Extract the timelock value encoded in a timelocked tapleaf, if any.\n *\n * The return value is unit-ambiguous: for a CSV leaf it is a BIP-68\n * nSequence (relative timelock); for a CLTV leaf it is an absolute\n * nLockTime. Callers must know which leaf shape they are inspecting to\n * interpret the number correctly, and must not copy a CSV result into\n * `Transaction.lockTime` (or vice versa).\n *\n * @param tapLeafScript - Tapleaf script to inspect\n * @returns The encoded timelock value, or `undefined` when neither a CSV\n * nor CLTV path is present\n * @see VtxoScript.exitPaths\n */\n// TODO(next-major): return a discriminated union\n// (`{ kind: \"relative\", nSequence } | { kind: \"absolute\", lockTime }`)\n// so callers can't conflate the two. Deferred because changing the\n// return type is a breaking change.\nexport function getSequence(tapLeafScript: TapLeafScript): number | undefined {\n let sequence: number | undefined = undefined;\n\n try {\n const scriptWithLeafVersion = tapLeafScript[1];\n const script = scriptWithLeafVersion.subarray(0, scriptWithLeafVersion.length - 1);\n try {\n const params = CSVMultisigTapscript.decode(script).params;\n sequence = timelockToSequence(params.timelock);\n } catch {\n const params = CLTVMultisigTapscript.decode(script).params;\n sequence = Number(params.absoluteTimelock);\n }\n } catch {}\n\n return sequence;\n}\n"]}
@@ -1 +0,0 @@
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/script/vhtlc.ts","../src/contracts/handlers/vhtlc.ts","../src/contracts/handlers/vhtlcV2.ts","../src/contracts/handlers/boarding.ts","../src/contracts/handlers/arkade.ts","../src/contracts/handlers/index.ts"],"names":["DefaultVtxo","Script","hex","DelegateVtxo","VHTLC"],"mappings":";;;;;;;;AAkBA,IAAM,0BAAN,MAA8B;AAAA,EAClB,QAAA,uBAAe,GAAA,EAAsC;AAAA;AAAA,EAG7D,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,EAEA,IAAI,IAAA,EAAoD;AACpD,IAAA,OA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MACH,oBAAA,EAAsB,IAAA;AAAA,MACtB,kBAAA,EAAoB,IAAA;AAAA,MACpB,OAAA,EAAS,OAAO,MAAA;AAAO,KAC3B;AAAA,EACJ;AACJ;;;ACzLA,gBAAA,CAAiB,SAAS,sBAAsB,CAAA;AAChD,gBAAA,CAAiB,SAAS,uBAAuB,CAAA;AACjD,gBAAA,CAAiB,SAAS,oBAAoB,CAAA;AAC9C,gBAAA,CAAiB,SAAS,sBAAsB,CAAA;AAChD,gBAAA,CAAiB,SAAS,uBAAuB,CAAA;AACjD,gBAAA,CAAiB,SAAS,qBAAqB,CAAA","file":"chunk-HRFWODLP.js","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 /** @throws If a handler for this type is already registered */\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 get(type: string): ContractHandler<unknown> | undefined {\n return this.handlers.get(type);\n }\n\n /** @throws If no handler is registered for this type */\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 has(type: string): boolean {\n return this.handlers.has(type);\n }\n\n getRegisteredTypes(): string[] {\n return Array.from(this.handlers.keys());\n }\n\n /** Unregister a handler (mainly for testing). */\n unregister(type: string): boolean {\n return this.handlers.delete(type);\n }\n\n /** Clear all handlers (mainly for testing). */\n clear(): void {\n this.handlers.clear();\n }\n}\n\n/** Global registry of contract handlers. */\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 {\n Contract,\n DerivedContractTapscripts,\n DiscoveredContract,\n PathContext,\n PathSelection,\n} 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, indexerPages } from \"../../wallet/vtxo\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport type { TapLeafScript } from \"../../script/base\";\nimport type { RelativeTimelock } from \"../../script/tapscript\";\nimport type { VHTLC } from \"../../script/vhtlc\";\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 if (!context.walletDescriptor) return undefined;\n return matchRole(extractRawPubKey(context.walletDescriptor));\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/** The leaves both VHTLC script versions inherit from `VHTLC.BaseScript`, which is not exported. */\ntype VhtlcLeaves = Pick<\n VHTLC.Script,\n | \"claim\"\n | \"refundWithoutReceiver\"\n | \"unilateralClaim\"\n | \"unilateralRefundWithoutReceiver\"\n | \"encode\"\n>;\n\nexport function selectVhtlcPath(\n script: VhtlcLeaves,\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 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\nexport function vhtlcAllSpendingPaths(\n script: VhtlcLeaves,\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 // Collaborative paths (no timelock checks)\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\") {\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\nexport function vhtlcSpendablePaths(\n script: VhtlcLeaves,\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\nexport function deriveVhtlcTapscripts(script: VhtlcLeaves): DerivedContractTapscripts {\n const leaf = script.refundWithoutReceiver();\n return {\n forfeitTapLeafScript: leaf,\n proofTapLeafScript: leaf,\n tapTree: script.encode(),\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 for await (const { vtxos } of indexerPages((pageIndex) =>\n getNormalizedVtxos(indexerProvider, {\n scripts,\n pageIndex,\n pageSize: DEFAULT_PAGE_SIZE,\n }),\n )) {\n for (const vtxo of vtxos) {\n if (remaining.delete(vtxo.script)) used.add(vtxo.script);\n }\n if (remaining.size === 0) break;\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: DefaultContractHandler.serializeParams(c),\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: DelegateContractHandler.serializeParams({ ...c, delegatePubKey }),\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","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. Adds three leaves the emulator co-signs\n * under a covenant pinning the payout to a pre-committed destination:\n *\n * - `nonInteractiveClaim`: `server` + covenant-tweaked emulator, paying\n * `receiverPkScript`; the claim can be pushed without the receiver online.\n * - `nonInteractiveRefund`: `server` + `receiver` + covenant-tweaked emulator, paying\n * `senderPkScript`, no timelock; recoverable even if the sender's key is lost.\n * - `nonInteractiveRefundWithoutReceiver`: `server` + the SAME co-signer as\n * `nonInteractiveRefund`, paying `senderPkScript` after `refundLocktime`; the only\n * refund tier needing no participant signature.\n *\n * One flag, not one per leaf: nothing on the wire says which leaves a quote carries, so\n * each optional leaf multiplies the tree shapes a counterparty must derive to verify an\n * address. All-or-nothing keeps it at two.\n *\n * Leaf order fixes the merkle root: the suite is appended after the six signature leaves\n * (claim, refund, timelocked refund), so a script with it NEVER collides with one without.\n *\n * STABLE PER RELEASE: a future covenant leaf joins only behind a NEW option, so\n * re-deriving a lockup with the SDK that quoted it reproduces its address byte-for-byte.\n */\n nonInteractiveParameters?: {\n /**\n * Emulator public key, 32-byte x-only or 33-byte compressed. ONE key, tweaked per\n * covenant destination, co-signs every suite leaf; BIP-341 sighashes committing to\n * the tapleaf hash keep a signature for one leaf from replaying against another.\n */\n emulatorPubkey: Bytes;\n /** Where the claim covenant pays: the receiver's P2TR pkScript, 34 bytes. */\n receiverPkScript: Bytes;\n /**\n * Where BOTH refund covenants pay: the sender's P2TR pkScript, 34 bytes. Shared, so\n * the two refund leaves cannot diverge.\n */\n senderPkScript: Bytes;\n /**\n * LEGACY REBUILD ONLY, never for a new lockup. Builds the suite WITHOUT the\n * timelocked refund leaf, the shape of lockups funded before it shipped; a leaf can't\n * be retrofitted onto a committed address, so re-deriving those needs this.\n */\n legacy?: \"preTimelockedRefund\";\n };\n /**\n * Denominate this contract in an Arkade ASSET. Only the covenant (non-interactive)\n * leaves change; the signature leaves assert nothing about value.\n *\n * The covenants then also require the output to carry at least the input's amount of\n * THIS asset and exactly one asset. The sat clause is RETAINED: dropping it would let a\n * spend strip the sats, as the sat-only covenant lets a spend strip the asset.\n *\n * ONLY THE BOUND ASSET IS PROTECTED. `INSPECTOUTASSETCOUNT == 1` constrains only the\n * covenant's output; arkd's conservation rule lets extra assets on the funding VTXO be\n * routed to another output the spender chooses. Fund it with the named asset only.\n *\n * A canonical Asset ID is the pair `(genesis txid, group index)`, never a single blob.\n */\n asset?: {\n /**\n * Genesis txid, 32 bytes, in CANONICAL order (the leading 32 bytes of a serialized\n * Asset ID). Do not pre-reverse: the covenant reverses internally for the wire-order\n * opcodes, and a pre-reversed id silently makes the covenant leaves unspendable.\n */\n txid: Bytes;\n /** The asset group index within that genesis transaction. */\n groupIndex: number;\n };\n }\n\n /**\n * Shared construction for every VHTLC script version; versions differ only in the\n * preimage-condition fragment `claim`/`unilateralClaim`/`nonInteractiveClaim` are built from.\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 // Computed once for every preimage-gated leaf so they can't drift within a 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 for both refund covenant leaves: same destination, same key.\n const nirCosigner = computeArkadeScriptPublicKey(\n covenants.emulatorPubkey,\n arkadeScriptNir,\n );\n // No timelock, like `refund`: the covenant replaces the sender's signature and\n // still 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 // `refundWithoutReceiver` with the covenant replacing the sender's signature.\n // Last, because leaf order fixes the merkle root.\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 * Spent through the generic covenant path ({@link EmulatorProvider},\n * {@link ArkadeTransactionBuilder}): build the ark tx on this leaf plus its checkpoint;\n * attach this ArkadeScript to the input in an `EmulatorPacket` (type 1, empty witness:\n * the script pushes its own index with `PUSHCURRENTINPUTINDEX`) inside an `Extension`\n * OP_RETURN; attach the input's creating ark tx as `PrevArkTx` (the emulator can't\n * otherwise resolve its prevout); POST to the emulator's `/v1/tx`. The emulator co-signs\n * for `nirCosigner` only if `enforcePayTo(senderPkScript)` holds, and finalizes with arkd.\n * `server`'s signature is still required at consensus level, outside the covenant.\n *\n * The emulator does not check `refundLocktime`: it co-signs an immature spend and arkd's\n * CLTV refuses it. arkd also refuses a block-height `refundLocktime`\n * (< `CLTV_HEIGHT_THRESHOLD`, 500,000,000) on a forfeit-eligible leaf regardless of\n * maturity: use a seconds-typed (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 * - **nonInteractive\\*** (with `nonInteractiveParameters`): emulator covenant leaves; see\n * {@link VHTLC.Options.nonInteractiveParameters}\n *\n * Prefer {@link ScriptV2} (same leaves and options, plus a claim-preimage length check).\n *\n * **The `vhtlc` contract handler registers none of the covenant leaves**: its params carry\n * no covenant fields, so a V1 script built with `nonInteractiveParameters` can be funded but\n * not registered (`ContractManager` refuses the six-leaf script mismatch). Use the\n * `vhtlc-v2` handler, 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 * {@link Script} built with {@link preimageConditionScriptV2} for every preimage-gated leaf.\n * A separate class rather than a flag: the two give different script bytes (so addresses)\n * for the same keys, which should be a compile-time-visible choice.\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 // Only the covenant leaves can bind an asset. Without them `asset` would silently yield a\n // sat-only contract the caller funds believing the asset is protected.\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 // TS types are no check 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 * {@link preimageConditionScript} plus `OP_SIZE 32 OP_EQUALVERIFY` before `OP_HASH160`, as BOLT3\n * HTLCs do: otherwise the claim leaf accepts any witness whose HASH160 matches regardless of\n * length, while this contract's preimage is always 32 bytes. Used by {@link VHTLC.ScriptV2}.\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 bytes. Length alone\n * isn't enough (subdust `OP_RETURN <32 bytes>` and P2WSH match it), and `enforcePayTo` trusts\n * byte 2 onward as the taproot program.\n */\nfunction isP2trPkScript(pkScript: Bytes): boolean {\n return pkScript.length === 34 && pkScript[0] === 0x51 && pkScript[1] === 0x20;\n}\n\n/**\n * The covenant: \"the output at this input's index pays the given P2TR script, value >= input\",\n * shared by every {@link VHTLC.Options.nonInteractiveParameters} leaf.\n *\n * `PUSHCURRENTINPUTINDEX` imposes the input/output pairing on the spender: a tx without the\n * matching output is unsatisfiable, not fooled. Index alignment is a *liveness* obligation on\n * whoever assembles the spend (this SDK's aggregate refund uses the interactive leaf for that\n * reason, see `refund.ts`), never a safety assumption.\n *\n * `>= input`, not `>= the quoted amount`: conservation, not agreement. Pinning a quote would\n * compile it into the emulator key and so the ADDRESS, moving it on re-quote; misfunding is the\n * sender's exposure, which the counterparty answers by declining the swap; and nothing is\n * claimed without the preimage. A funding-vs-quote gate belongs in the consumer\n * (`lightning-swap-service`'s `lockupIsFunded`).\n */\n/**\n * The sat half of both covenants: the output at this input's index is P2TR, pays\n * `destinationPkScript`, and carries at least the input's value. The ONE copy shared by\n * {@link enforcePayTo} and {@link enforcePayToAsset}, so they cannot drift.\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 // Re-checked though validateOptions did: a wrong destination here is irreversible and only\n // surfaces at spend time.\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 an asset-denominated contract: the sat covenant as its tail, plus\n * \"carries at least the input's amount of exactly this one asset\", so an asset contract never\n * enforces less than a sat one.\n *\n * Two opcode traps:\n * - A canonical Asset ID is TWO stack items, `asset_txid` then `asset_gidx`; one 32-byte blob\n * encodes fine and fails only at spend time, once funded.\n * - `INSPECTOUTASSETLOOKUP` pushes `amount 1`, or `0 0` when ABSENT. The `VERIFY` after each\n * lookup is load-bearing: without it an output with NONE of the asset passes `0 >= 0`. The\n * input lookup gets one too.\n *\n * `INSPECTOUTASSETCOUNT == 1` is deliberately strict: a too-permissive covenant can't be\n * tightened once funded; a 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 canonical order (arkd's `serializeTxHash` reversed\n // it), but the introspection opcodes match WIRE order. Unflipped, the lookup reports ABSENT\n // and the emulator says only `OP_VERIFY failed` (established on regtest against a BTC-only\n // control). A copy, not in place: the caller's id is theirs.\n const inspectionTxid = Uint8Array.from(asset.txid).reverse();\n return ArkadeScript.encode([\n // The output at the input's index carries at least the input's amount of the asset.\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 {\n assertVhtlcSpendableNow,\n deriveVhtlcTapscripts,\n selectVhtlcPath,\n vhtlcAllSpendingPaths,\n vhtlcSpendablePaths,\n} from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/** Typed parameters for VHTLC contracts. */\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. Role comes from `context.role` or from matching\n * `context.walletDescriptor` against sender/receiver.\n */\n selectPath(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectVhtlcPath(script, contract, context);\n },\n\n /** All possible spending paths (no timelock checks); role as in {@link selectPath}. */\n getAllSpendingPaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return vhtlcAllSpendingPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return vhtlcSpendablePaths(script, contract, context);\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: generic selection (send, settle, renewal, offboard) would\n * move the lockup out from under a swap the counterparty may still complete, or race a claim.\n *\n * The stamped leaf is the sender's own CLTV refund, so this is not about destroying the\n * VTXO: an escrowed lockup must not count toward the `available` balance, and generic\n * renewal (`runPeriodicSettle`, unprompted without an explicit `settlementConfig`) must not\n * silently execute a refund nobody asked for.\n *\n * **Inseparable from {@link deriveTapscripts}**: deriving the leaf without closing this gate\n * hands renewal an escrow. Recovery filters on {@link assertSpendableNow} instead; this\n * permanent gate 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 * **Required, not an optimization.** Without it `deriveContractTapscripts` falls back to\n * `script.forfeit()`, which no VHTLC script has, so the contract's VTXOs are dropped before\n * persisting: balance invisible, `getSyncState()` degraded forever.\n *\n * `refundWithoutReceiver` is the only collaborative path this wallet can satisfy as sender\n * (kept in step with `selectPath`): the claim leaves need the preimage, and `refund` /\n * `unilateralRefund` need a counterparty signature the protocol can't request. V1 has no\n * covenant leaves.\n *\n * **It carries a CLTV**: a settlement on it is rejected until `refundLocktime` matures, and\n * the per-contract annotation knows no clock, so `recoverVtxos` filters on\n * {@link assertSpendableNow}. **Role-blind**: a receiver's row gets the same leaf, satisfiable\n * only by the `sender` key holder; anyone else fails at intent registration.\n */\n deriveTapscripts(script: VHTLC.Script): DerivedContractTapscripts {\n return deriveVhtlcTapscripts(script);\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 {\n assertVhtlcSpendableNow,\n deriveVhtlcTapscripts,\n selectVhtlcPath,\n vhtlcAllSpendingPaths,\n vhtlcSpendablePaths,\n} from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Parse the stored `assetGroupIndex` canonically. Bare `Number()` is the trap: `Number(\"\")` and\n * `Number(\" \")` are 0, a valid index naming a DIFFERENT asset, which derives a different script\n * and dies at `upsertContractRow` with an opaque `Script mismatch`. Only the shape this\n * handler's `serializeParams` writes is 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: `VHTLCContractParams` verbatim (both\n * versions take the same {@link VHTLC.Options}), plus the asset and emulator covenant suite the\n * swap corridor's lockup carries.\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}, including `legacy: \"preTimelockedRefund\"` for\n * eight-leaf rows funded before the timelocked refund leaf shipped.\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. A half pair would derive a script with the\n * leaf dropped and fail as an opaque `Script mismatch`; this names the cause. Diagnostic only:\n * `upsertContractRow`'s mismatch check is the real boundary.\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 add `OP_SIZE 32\n * OP_EQUALVERIFY`, built by the RFQ swap corridor (`@arkade-os/swap`'s `lightningSendContract`).\n *\n * A separate type rather than a flag on `vhtlc`: V1 and V2 derive different pkScripts for the same\n * keys and `upsertContractRow` rejects a row whose script doesn't match its params, so one type\n * can't serve both (and they can never collide). A use-named type (`swap-lockup`) loses because\n * contracts are keyed by script: a second use of the same ScriptV2 would fight over one row.\n *\n * Only the four leaves a single-key wallet can sign are offered: `claim`/`unilateralClaim` to the\n * receiver, `refundWithoutReceiver` (CLTV)/`unilateralRefundWithoutReceiver` to the sender.\n * `refund`/`unilateralRefund` need the counterparty's signature and no protocol message asks for\n * one; the three `nonInteractive*` leaves are the emulator's. CSV leaves are offered only in the\n * non-collaborative context. Selection matches the `vhtlc` handler rung-for-rung, pinned by\n * `test/contracts/vhtlcV2-handler.test.ts`.\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 // Per-leaf on-disk keys predate the grouped param and older rows carry exactly these;\n // both emulator columns hold the same key. Spread, not `undefined`, so a repository\n // round-trip never gains \"undefined\" string values.\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 (eight-leaf) marker is this key's ABSENCE, as older SDKs wrote it.\n ...(covenants.legacy === undefined && {\n nonInteractiveRefundWithoutReceiver: \"1\",\n }),\n }),\n // Must round-trip: dropping the asset re-derives the sat-only script and registration\n // dies at `upsertContractRow` with an opaque `Script mismatch`.\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 // An older-SDK row may name one leaf's pair without the other's; it has no group\n // representation, so refuse it rather than silently drop a leaf.\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 // Two different emulator keys were legal for older SDKs but are unrepresentable now;\n // rebuilding with either would move the pkScript.\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 covenants from ONE key, so this row cannot be \" +\n \"rebuilt as a group\",\n );\n }\n // Either half alone is corrupt; reading it as asset-less re-derives the sat-only script.\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 // 0.4.65-0.4.67 rows compile a strict bound into the claim leaf that can't be re-derived\n // here; reading them as non-strict would rebuild a different pkScript. The throw is\n // permanent for such a row, so the message itself must carry the way out.\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 in \" +\n \"0.4.68, so this row — written by 0.4.65-0.4.67 — locks to a script this \" +\n \"build cannot re-derive. To clear it: claim or refund the swap on 0.4.67, \" +\n \"then drop the settled row here with \" +\n \"`contractManager.deleteContract(script)`. Do not delete it first — any \" +\n \"balance it still holds is only reachable from 0.4.67.\",\n );\n }\n // Read as \"not set\", this flag without its suite would re-derive a script missing the 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 ...(params.nonInteractiveRefundWithoutReceiver !== \"1\" && {\n legacy: \"preTimelockedRefund\" as const,\n }),\n },\n }),\n };\n },\n\n /**\n * Select spending path based on context. Role comes from `context.role` or by matching\n * `context.walletDescriptor` against sender/receiver.\n */\n selectPath(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectVhtlcPath(script, contract, context);\n },\n\n /** Get all possible spending paths (no timelock checks); role resolved as in `selectPath`. */\n getAllSpendingPaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return vhtlcAllSpendingPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return vhtlcSpendablePaths(script, contract, context);\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 with the counterparty's claim leaf armed; generic selection\n * (send, settle, renewal, offboard) would move it out from under the swap or race a claim.\n * Recovery isn't covered by this gate: `recoverVtxos` filters on {@link assertSpendableNow},\n * dropping a lockup only while its refund path is shut. Explicit routes (`settle({ inputs })`,\n * `pushRefundWithoutReceiver`) are unaffected.\n */\n isGenericallySpendable: () => false,\n\n /**\n * The annotation leaf stamped onto every VTXO locked to this contract.\n *\n * Required, not an optimization: without {@link TapscriptDeriving} the fallback calls\n * `script.forfeit()`, which no VHTLC version has, so the VTXOs are silently dropped before\n * persisting and `getSyncState()` stays `degraded`.\n *\n * `refundWithoutReceiver` is used (in step with `selectPath`) as the only collaborative leaf\n * the sender can satisfy. It carries a CLTV: settling on it before `refundLocktime` matures is\n * rejected, and this handler has no clock, so `recoverVtxos` filters on\n * {@link assertSpendableNow}. Role-blind: a receiver's row gets the same leaf and fails at\n * intent registration.\n */\n deriveTapscripts(script: VHTLC.ScriptV2): DerivedContractTapscripts {\n return deriveVhtlcTapscripts(script);\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 { rotatedReceiveMetadata } from \"./helpers\";\n\n/**\n * Typed parameters for boarding contracts: the `default` shape, with `csvTimelock` carrying the\n * operator's boarding-exit delay (`OperatorInfo.boardingExitDelay`) instead of the unilateral-exit\n * delay.\n */\nexport type BoardingContractParams = DefaultContractParams;\n\n/**\n * Handler for the boarding contract (registered type `boarding`), which derives the on-chain\n * address used to board funds. Same `DefaultVtxo.Script` shape and path logic as `default`; only\n * the CSV differs (`boardingExitDelay` vs `unilateralExitDelay`).\n *\n * {@link Discoverable.discoverAt} probes the **on-chain** UTXO set at the P2TR address, not the\n * Ark indexer, and no-ops when `deps.boardingTimelock` / `deps.onchainNetwork` are absent.\n *\n * Default/boarding collision: a script owns exactly one repository row. The operator should keep\n * boardingExitDelay > unilateralExitDelay (equal delays expose it to a double-spend); if they\n * coincide the two scripts are byte-identical. Discovery still emits `type: \"boarding\"` and the\n * row is resolved first-wins in {@link ContractManager.upsertContract}; the scan probes boarding\n * first so a both-purpose rotated index keeps its on-chain UTXO and any L2 VTXO recoverable.\n * Funds are spendable either way, but consumers must NOT identify boarding by\n * `contract.type === \"boarding\"` — match by script via `wallet.getBoardingAddress()` /\n * `wallet.boardingTapscript`.\n */\nexport const BoardingContractHandler: ContractHandler<BoardingContractParams, DefaultVtxo.Script> &\n Discoverable = {\n type: \"boarding\",\n defaultScope: \"onchain\",\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 **current** on-chain coin set for a boarding output at this HD index. Only an\n * unspent boarding output needs this: a boarded one became an L2 VTXO at the receive index,\n * which the indexer probe already covers. Always emits `type: \"boarding\"` (see the handler\n * doc on collisions); `deps.csvTimelocks` is intentionally not read.\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\n return [\n {\n type: \"boarding\",\n params: BoardingContractHandler.serializeParams({\n pubKey,\n serverPubKey: deps.serverPubKey,\n csvTimelock: deps.boardingTimelock,\n }),\n script: scriptHex,\n // The Ark address, not the P2TR: must match the row registered at init so the\n // watcher monitors the same L2 script and the VTXO repository bucket lines up.\n address: script.address(deps.network.hrp, deps.serverPubKey).encode(),\n // Tag rotated rows (index > 0) for boot resolution and per-index signing.\n ...rotatedReceiveMetadata(index, descriptor),\n },\n ];\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 } from \"../../identity/descriptor\";\nimport {\n ArkadeProgramScript,\n deserializeArkadeContractParams,\n resolveTimelockValue,\n resolveCsvTimelock,\n serializeArkadeContractParams,\n staticWitness,\n type ArkadeContractParams,\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 if (!context.walletDescriptor) return undefined;\n try {\n return extractPubKey(context.walletDescriptor).toLowerCase();\n } catch {\n return undefined;\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.def.tapscript.witness, script.args);\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 ? resolveCsvTimelock(csvDef, script.args) : 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 proofTapLeafScript: 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"]}