@arkade-os/sdk 0.5.7 → 0.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -6
- package/dist/adapters/expo.cjs +7 -7
- package/dist/adapters/expo.d.cts +2 -2
- package/dist/adapters/expo.d.ts +2 -2
- package/dist/adapters/expo.js +4 -4
- package/dist/{asyncStorageTaskQueue-B9byr6ij.d.cts → asyncStorageTaskQueue-B6rFkXzW.d.cts} +1 -1
- package/dist/{asyncStorageTaskQueue-XP4CCdRY.d.ts → asyncStorageTaskQueue-C0irgPwJ.d.ts} +1 -1
- package/dist/{chunk-MWEDDWFU.js → chunk-2657D67V.js} +9 -7
- package/dist/chunk-2657D67V.js.map +1 -0
- package/dist/{chunk-MWMO2ZQP.js → chunk-3KNSMZWD.js} +24 -13
- package/dist/chunk-3KNSMZWD.js.map +1 -0
- package/dist/{chunk-DNFTHG73.js → chunk-4DUTRRXF.js} +8 -6
- package/dist/chunk-4DUTRRXF.js.map +1 -0
- package/dist/{chunk-MQUATTIM.cjs → chunk-4PSM6ZUC.cjs} +55 -57
- package/dist/chunk-4PSM6ZUC.cjs.map +1 -0
- package/dist/{chunk-FDJ734CH.js → chunk-DPFD5KBK.js} +5 -2
- package/dist/chunk-DPFD5KBK.js.map +1 -0
- package/dist/{chunk-OMPDPBT5.cjs → chunk-DY24A73N.cjs} +296 -240
- package/dist/chunk-DY24A73N.cjs.map +1 -0
- package/dist/{chunk-VMVFRTF4.js → chunk-FUCKDTH7.js} +285 -234
- package/dist/chunk-FUCKDTH7.js.map +1 -0
- package/dist/{chunk-4AJRIM44.js → chunk-GUK33TNC.js} +9 -13
- package/dist/chunk-GUK33TNC.js.map +1 -0
- package/dist/{chunk-RLD7DRSZ.js → chunk-HT35HPXR.js} +19365 -18395
- package/dist/chunk-HT35HPXR.js.map +1 -0
- package/dist/{chunk-3NALVGMJ.cjs → chunk-ODLSVJRU.cjs} +38 -27
- package/dist/chunk-ODLSVJRU.cjs.map +1 -0
- package/dist/{chunk-X6ZI53DZ.cjs → chunk-OMZZQTDM.cjs} +28 -35
- package/dist/chunk-OMZZQTDM.cjs.map +1 -0
- package/dist/{chunk-V3ZLL5VY.js → chunk-PXEFYEKL.js} +22 -29
- package/dist/chunk-PXEFYEKL.js.map +1 -0
- package/dist/{chunk-JFJNB7ZH.cjs → chunk-UPIQZRNJ.cjs} +16 -14
- package/dist/chunk-UPIQZRNJ.cjs.map +1 -0
- package/dist/{chunk-V5WRO3P6.cjs → chunk-UPV4W423.cjs} +14 -18
- package/dist/chunk-UPV4W423.cjs.map +1 -0
- package/dist/{chunk-URGVQ5TQ.cjs → chunk-V2EU5QWF.cjs} +4583 -3610
- package/dist/chunk-V2EU5QWF.cjs.map +1 -0
- package/dist/{chunk-FLPWNMX3.cjs → chunk-WIZCF5IX.cjs} +5 -2
- package/dist/chunk-WIZCF5IX.cjs.map +1 -0
- package/dist/{chunk-MXCB6EVM.cjs → chunk-WZJJZGBT.cjs} +22 -20
- package/dist/chunk-WZJJZGBT.cjs.map +1 -0
- package/dist/{chunk-V2DDN4MV.js → chunk-Z6WDOZZI.js} +10 -12
- package/dist/chunk-Z6WDOZZI.js.map +1 -0
- package/dist/compiler.cjs +4 -4
- package/dist/compiler.d.cts +1 -1
- package/dist/compiler.d.ts +1 -1
- package/dist/compiler.js +3 -3
- package/dist/contracts/handlers/index.cjs +11 -11
- package/dist/contracts/handlers/index.d.cts +3 -4
- package/dist/contracts/handlers/index.d.ts +3 -4
- package/dist/contracts/handlers/index.js +4 -4
- package/dist/{index-18cDMayF.d.ts → index-Bq349_ly.d.cts} +2334 -101
- package/dist/{index-Ccfhdfvj.d.cts → index-D4ahI0W6.d.cts} +2 -3
- package/dist/{index-DDJFHfba.d.cts → index-Mn2POBPj.d.ts} +2334 -101
- package/dist/{index-B_kcptF8.d.ts → index-Yh5y9G4E.d.ts} +2 -3
- package/dist/index.cjs +362 -346
- package/dist/index.d.cts +1505 -1374
- package/dist/index.d.ts +1505 -1374
- package/dist/index.js +7 -7
- package/dist/{program-BARSNg3X.d.ts → program-38A2Twvj.d.ts} +4 -2
- package/dist/{program-znrWkxE4.d.cts → program-DPzf5qsk.d.cts} +4 -2
- package/dist/repositories/realm/index.cjs +40 -40
- package/dist/repositories/realm/index.d.cts +2 -2
- package/dist/repositories/realm/index.d.ts +2 -2
- package/dist/repositories/realm/index.js +8 -8
- package/dist/repositories/sqlite/index.cjs +38 -38
- package/dist/repositories/sqlite/index.d.cts +2 -2
- package/dist/repositories/sqlite/index.d.ts +2 -2
- package/dist/repositories/sqlite/index.js +8 -8
- package/dist/{taskRunner-DUafWu0o.d.ts → taskRunner-BYxEgwM5.d.ts} +1 -1
- package/dist/{taskRunner-JYHaLPne.d.cts → taskRunner-Z3LnHfgs.d.cts} +1 -1
- package/dist/wallet/expo/background.cjs +17 -17
- package/dist/wallet/expo/background.d.cts +3 -3
- package/dist/wallet/expo/background.d.ts +3 -3
- package/dist/wallet/expo/background.js +9 -9
- package/dist/wallet/expo/index.cjs +18 -18
- package/dist/wallet/expo/index.d.cts +3 -5
- package/dist/wallet/expo/index.d.ts +3 -5
- package/dist/wallet/expo/index.js +8 -8
- package/dist/worker/expo/index.cjs +12 -12
- package/dist/worker/expo/index.d.cts +4 -4
- package/dist/worker/expo/index.d.ts +4 -4
- package/dist/worker/expo/index.js +8 -8
- package/package.json +1 -1
- package/dist/chunk-3NALVGMJ.cjs.map +0 -1
- package/dist/chunk-4AJRIM44.js.map +0 -1
- package/dist/chunk-DNFTHG73.js.map +0 -1
- package/dist/chunk-FDJ734CH.js.map +0 -1
- package/dist/chunk-FLPWNMX3.cjs.map +0 -1
- package/dist/chunk-JFJNB7ZH.cjs.map +0 -1
- package/dist/chunk-MQUATTIM.cjs.map +0 -1
- package/dist/chunk-MWEDDWFU.js.map +0 -1
- package/dist/chunk-MWMO2ZQP.js.map +0 -1
- package/dist/chunk-MXCB6EVM.cjs.map +0 -1
- package/dist/chunk-OMPDPBT5.cjs.map +0 -1
- package/dist/chunk-RLD7DRSZ.js.map +0 -1
- package/dist/chunk-URGVQ5TQ.cjs.map +0 -1
- package/dist/chunk-V2DDN4MV.js.map +0 -1
- package/dist/chunk-V3ZLL5VY.js.map +0 -1
- package/dist/chunk-V5WRO3P6.cjs.map +0 -1
- package/dist/chunk-VMVFRTF4.js.map +0 -1
- package/dist/chunk-X6ZI53DZ.cjs.map +0 -1
- package/dist/delegate-gGkUnYpi.d.cts +0 -92
- package/dist/delegate-iyDum4fw.d.ts +0 -92
- package/dist/keyringDescriptorProvider-DL-jAiRO.d.ts +0 -2082
- package/dist/keyringDescriptorProvider-Dtv0JWrT.d.cts +0 -2082
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/keys.ts","../src/arkade/opcodes.ts","../src/arkade/bignum.ts","../src/arkade/script.ts","../src/arkade/tweak.ts","../src/arkade/program.ts"],"names":["OP","ScriptNum","hex"],"mappings":";;;;;;;;;AAmBO,SAAS,OAAA,CAAQ,GAAA,EAAiB,KAAA,GAAQ,YAAA,EAA0B;AACvE,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,EAAA,EAAI,OAAO,GAAA;AAC9B,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,EAAA,KAAO,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,IAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAA,EAAO,OAAO,GAAA,CAAI,SAAS,CAAC,CAAA;AACpF,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,EAAG,KAAK,CAAA,yCAAA,CAA2C,CAAA;AACvE;ACVO,IAAM,SAAA,GAAY;AAAA;AAAA,EAErB,kBAAA,EAAoB,GAAA;AAAA,EAEpB,GAAA,EAAK,GAAA;AAAA;AAAA,EAGL,MAAA,EAAQ,GAAA;AAAA;AAAA,EAGR,gBAAA,EAAkB,GAAA;AAAA,EAClB,YAAA,EAAc,GAAA;AAAA,EACd,cAAA,EAAgB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CAAA,6CAAA,EAAgD,CAAC,CAAA,CAAA,CAAG,CAAA;AAC/E,MAAA,IAAA,CAAK,CAAC,CAAA,GAAI,kBAAA,CAAmB,CAAA,EAAG,MAAM,CAAC,CAAA;AAAA,IAC3C;AAAA,EACJ;AACA,EAAA,OAAO;AAAA,IACH,OAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAA,EAAWA,GAAAA,CAAI,MAAA,CAAO,MAAA,CAAO,SAAS,CAAA;AAAA,IACtC,GAAI,MAAA,CAAO,OAAA,GAAU,EAAE,OAAA,EAASA,GAAAA,CAAI,MAAA,CAAO,MAAA,CAAO,OAAO,CAAA,EAAE,GAAI,EAAC;AAAA,IAChE,GAAI,MAAA,CAAO,WAAA,GAAc,EAAE,WAAA,EAAaA,GAAAA,CAAI,MAAA,CAAO,MAAA,CAAO,WAAW,CAAA,EAAE,GAAI;AAAC,GAChF;AACJ","file":"chunk-DNFTHG73.js","sourcesContent":["/**\n * Normalize a secp256k1 public key to the 32-byte x-only form every tapscript,\n * covenant param and `params.serverPubKey` in this SDK is denominated in.\n *\n * A compressed key drops its parity prefix; an x-only key passes through. Both\n * arrive over the same wires — arkd advertises `signerPubkey` either way,\n * `Identity.xOnlyPublicKey` implementations vary, and solver-supplied fields\n * are whatever the peer sent — so the caller usually cannot know which it\n * holds. Anything else is refused rather than silently truncated: a 65-byte\n * uncompressed key, stripped of one byte, yields a plausible 32-byte value\n * that is not the key, which surfaces as an address nobody funded.\n *\n * The result may alias `key` rather than copy it; callers that mutate either\n * value after normalization should copy first.\n *\n * @param key - 32-byte x-only or 33-byte compressed public key\n * @param label - Name used in the error, e.g. `\"ark signer key\"`\n * @see toXOnlySignerHex for the hex-in, hex-out signer-rotation equivalent\n */\nexport function toXOnly(key: Uint8Array, label = \"public key\"): Uint8Array {\n if (key.length === 32) return key;\n if (key.length === 33 && (key[0] === 0x02 || key[0] === 0x03)) return key.subarray(1);\n throw new Error(`${label} is not a compressed or x-only public key`);\n}\n","/**\n * Arkade Script Opcodes\n *\n * This module defines ONLY Arkade-specific opcodes (0xb3, 0xbb, 0xc3-0xf8).\n * Standard Bitcoin opcodes are imported from @scure/btc-signer.\n *\n * Reference: arkade-os/emulator pkg/arkade/opcode.go.\n * Byte 0xdc is OP_CHECKTIME, matching emulator v0.0.8 and compiler artifacts.\n */\n\nimport { OP } from \"@scure/btc-signer\";\nexport { OP };\n\nexport const ARKADE_OP = {\n // Merkle Branch Verification (0xb3 — repurposed NOP4 slot)\n MERKLEBRANCHVERIFY: 0xb3,\n\n PUT: 0xbb,\n\n // Digest (0xc3)\n DIGEST: 0xc3,\n\n // SHA256 Streaming (0xc4-0xc6)\n SHA256INITIALIZE: 0xc4,\n SHA256UPDATE: 0xc5,\n SHA256FINALIZE: 0xc6,\n\n // Input Introspection (0xc7-0xcb)\n INSPECTINPUTOUTPOINT: 0xc7,\n INSPECTINPUTARKADESCRIPTHASH: 0xc8,\n INSPECTINPUTVALUE: 0xc9,\n INSPECTINPUTSCRIPTPUBKEY: 0xca,\n INSPECTINPUTSEQUENCE: 0xcb,\n\n // Signatures (0xcc-0xcd)\n CHECKSIGFROMSTACK: 0xcc,\n PUSHCURRENTINPUTINDEX: 0xcd,\n\n // Input Arkade Witness Introspection (0xce)\n INSPECTINPUTARKADEWITNESSHASH: 0xce,\n\n // Output Introspection (0xcf, 0xd1)\n INSPECTOUTPUTVALUE: 0xcf,\n INSPECTOUTPUTSCRIPTPUBKEY: 0xd1,\n\n // Transaction Introspection (0xd2-0xd6)\n INSPECTVERSION: 0xd2,\n INSPECTLOCKTIME: 0xd3,\n INSPECTNUMINPUTS: 0xd4,\n INSPECTNUMOUTPUTS: 0xd5,\n TXWEIGHT: 0xd6,\n\n // Byte/Number Conversion & Arithmetic (0xd7-0xda)\n NUM2BIN: 0xd7,\n BIN2NUM: 0xd8,\n REVERSEBYTES: 0xd9,\n MODEXP: 0xda,\n // VTXO Expiry & Emulator Clock (0xdb-0xdc)\n PUSHEXPIRY: 0xdb,\n CHECKTIME: 0xdc,\n // 0xdd-0xdf are unassigned (OP_UNKNOWN221-223)\n\n // EC Operations (0xe0-0xe2)\n ECADD: 0xe0,\n ECMUL: 0xe1,\n ECPAIRING: 0xe2,\n\n // EC Operations (0xe3-0xe4)\n ECMULSCALARVERIFY: 0xe3,\n TWEAKVERIFY: 0xe4,\n\n // Asset Groups (0xe5-0xf2)\n INSPECTNUMASSETGROUPS: 0xe5,\n INSPECTASSETGROUPASSETID: 0xe6,\n INSPECTASSETGROUPCTRL: 0xe7,\n FINDASSETGROUPBYASSETID: 0xe8,\n INSPECTASSETGROUPMETADATAHASH: 0xe9,\n INSPECTASSETGROUPNUM: 0xea,\n INSPECTASSETGROUP: 0xeb,\n INSPECTASSETGROUPSUM: 0xec,\n INSPECTOUTASSETCOUNT: 0xed,\n INSPECTOUTASSETAT: 0xee,\n INSPECTOUTASSETLOOKUP: 0xef,\n INSPECTINASSETCOUNT: 0xf0,\n INSPECTINASSETAT: 0xf1,\n INSPECTINASSETLOOKUP: 0xf2,\n\n // Transaction ID (0xf3)\n TXID: 0xf3,\n\n // Packet Introspection (0xf4-0xf5) — added in emulator v0.0.1\n INSPECTPACKET: 0xf4,\n INSPECTINPUTPACKET: 0xf5,\n\n // Signature Hash (0xf6)\n SIGHASH: 0xf6,\n\n // Continuation & Intent Introspection (0xf7-0xf8)\n TUNNEL: 0xf7,\n INSPECTINTENTMESSAGE: 0xf8,\n} as const;\n\nexport const ARKADE_OPCODES: number[] = Object.values(ARKADE_OP);\n\nexport const ARKADE_OPCODE_NAMES: Record<number, string> = Object.fromEntries(\n Object.entries(ARKADE_OP).map(([name, value]) => [value, name]),\n);\n\nexport const ARKADE_OPCODE_VALUES: Record<string, number> = Object.fromEntries(\n Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [name, Number(value)]),\n);\n\nfunction buildBitcoinOpcodeNames(): Record<number, string> {\n const names: Record<number, string> = {};\n\n // Standard opcodes from @scure/btc-signer\n for (const [key, value] of Object.entries(OP)) {\n if (typeof value === \"number\") {\n // @scure uses names without OP_ prefix (e.g., \"DUP\", \"HASH160\")\n // We need to add OP_ prefix for consistency\n const name = key.startsWith(\"OP_\") ? key : `OP_${key}`;\n names[value] = name;\n }\n }\n\n // Special case: OP_0 is stored as \"OP_0\" in @scure\n names[0x00] = \"OP_0\";\n\n return names;\n}\n\nfunction buildBitcoinOpcodeValues(): Record<string, number> {\n const values: Record<string, number> = {};\n\n for (const [key, value] of Object.entries(OP)) {\n if (typeof value === \"number\") {\n const name = key.startsWith(\"OP_\") ? key : `OP_${key}`;\n values[name] = value;\n // Also support name without prefix\n values[key] = value;\n }\n }\n\n return values;\n}\n\nconst BITCOIN_OPCODE_NAMES = buildBitcoinOpcodeNames();\nconst BITCOIN_OPCODE_VALUES = buildBitcoinOpcodeValues();\n\n/**\n * Combined map from opcode value to name (with OP_ prefix)\n * Includes both Bitcoin and Arkade opcodes\n */\nexport const OPCODE_NAMES: Record<number, string> = {\n ...BITCOIN_OPCODE_NAMES,\n // Add Arkade opcodes with OP_ prefix\n ...Object.fromEntries(\n Object.entries(ARKADE_OPCODE_NAMES).map(([value, name]) => [Number(value), `OP_${name}`]),\n ),\n};\n\n/**\n * Combined map from opcode name to value\n * Supports both with and without OP_ prefix\n * Includes both Bitcoin and Arkade opcodes\n */\nexport const OPCODE_VALUES: Record<string, number> = {\n ...BITCOIN_OPCODE_VALUES,\n // Add Arkade opcodes with and without OP_ prefix\n ...ARKADE_OPCODE_VALUES,\n ...Object.fromEntries(\n Object.entries(ARKADE_OPCODE_VALUES).map(([name, value]) => [`OP_${name}`, value]),\n ),\n};\n\n/**\n * Get the name of an opcode from its value\n * Returns OP_DATA_N for data push opcodes (0x01-0x4b)\n *\n * @param value Opcode byte value\n * @returns Opcode name with OP_ prefix, or undefined if unknown\n */\nexport function getOpcodeName(value: number): string | undefined {\n // Handle data push opcodes (0x01-0x4b) as OP_DATA_N\n if (value >= 0x01 && value <= 0x4b) {\n return `OP_DATA_${value}`;\n }\n\n // Check combined mappings\n return OPCODE_NAMES[value];\n}\n\n/**\n * Get the value of an opcode from its name\n * Supports OP_DATA_N pattern for data push opcodes\n *\n * @param name Opcode name (with or without OP_ prefix)\n * @returns Opcode byte value, or undefined if unknown\n */\nexport function getOpcodeValue(name: string): number | undefined {\n // Handle OP_DATA_N pattern\n const dataMatch = name.match(/^OP_DATA_(\\d+)$/);\n if (dataMatch) {\n const n = parseInt(dataMatch[1], 10);\n if (n >= 1 && n <= 75) {\n return n;\n }\n return undefined;\n }\n\n // Check combined mappings\n return OPCODE_VALUES[name];\n}\n","/**\n * BigNum — arbitrary-precision sign-magnitude little-endian encoding used by\n * the arkade VM in emulator v0.0.1. Up to 520 bytes (= MaxScriptElementSize).\n *\n * Wire format:\n * - empty bytes = 0\n * - last byte's high bit (0x80) is the sign (set = negative)\n * - remaining bits are magnitude, little-endian\n * - minimal: no trailing zero magnitude byte; `[0x80]` (negative zero) is rejected\n *\n * Wraps `@scure/btc-signer`'s `ScriptNum` with a 520-byte cap. Use the\n * standalone API when you need to round-trip values outside of script encoding;\n * inside `ArkadeScript.encode([...])`, plain `bigint` literals work directly.\n */\n\nimport { ScriptNum } from \"@scure/btc-signer\";\n\n/** Maximum number of bytes for a BigNum (= MaxScriptElementSize). */\nexport const BIGNUM_MAX_BYTES = 520;\n\nconst codec = ScriptNum(BIGNUM_MAX_BYTES, /* forceMinimal */ true);\n\n/**\n * Encode `value` as a minimal sign-magnitude little-endian byte string.\n * Throws if the encoding would exceed 520 bytes.\n */\nexport function encode(value: bigint): Uint8Array {\n const result = codec.encode(value);\n if (result.length > BIGNUM_MAX_BYTES) {\n throw new Error(`BigNum value exceeds 520 bytes (encoded to ${result.length} bytes)`);\n }\n return result;\n}\n\n/**\n * Decode a minimal sign-magnitude little-endian byte string into a bigint.\n * Throws on non-minimal encodings or values longer than 520 bytes.\n */\nexport function decode(value: Uint8Array): bigint {\n return codec.decode(value);\n}\n","/**\n * Arkade Script Encoding and Decoding\n *\n * This module provides script encoding/decoding and ASM conversion helpers\n * that work with both standard Bitcoin opcodes and Arkade extension opcodes.\n *\n * Note: We use our own decoder for scripts because @scure/btc-signer doesn't\n * recognize Arkade opcodes (0xb3, 0xc4-0xf3) and would treat them as data pushes.\n */\n\nimport * as P from \"micro-packed\";\nimport { Script, type ScriptType, OP } from \"@scure/btc-signer\";\nimport { hex } from \"@scure/base\";\nimport { ARKADE_OP } from \"./opcodes\";\nimport * as BigNum from \"./bignum\";\n\n// Re-export Script and ScriptType from @scure\nexport { Script, type ScriptType };\n\n/**\n * Combined OP map: standard Bitcoin opcodes + Arkade extension opcodes.\n * Keys follow @scure convention (without OP_ prefix for most).\n */\nexport const ARKADE_OPS = { ...OP, ...ARKADE_OP } as const;\n\n/** Reverse lookup: byte value → opcode name */\nconst ArkadeOPNames: Record<number, string> = {};\nfor (const [k, v] of Object.entries(ARKADE_OPS)) {\n if (typeof v === \"number\") ArkadeOPNames[v] = k;\n}\n\n/** A single script operation: opcode string key, raw bytes, number, or bigint */\nexport type ArkadeScriptOP = keyof typeof ARKADE_OPS | Uint8Array | number | bigint;\n\n/** Array of script operations — the type that ArkadeScript encodes/decodes */\nexport type ArkadeScriptType = ArkadeScriptOP[];\n\n/**\n * Script CoderType with Arkade extension opcodes.\n *\n * Same API as `Script` from @scure/btc-signer, but with Arkade extension opcodes.\n *\n * @example\n * ```typescript\n * const script: ArkadeScriptType = ['DUP', 'HASH160', pubkeyHash, 'EQUALVERIFY', 'NUM2BIN'];\n * const bytes = ArkadeScript.encode(script);\n * const decoded = ArkadeScript.decode(bytes);\n * ```\n */\nexport const ArkadeScript: P.CoderType<ArkadeScriptType> = P.wrap({\n encodeStream: (w: P.Writer, value: ArkadeScriptType) => {\n for (let o of value) {\n if (typeof o === \"string\") {\n const v = ARKADE_OPS[o as keyof typeof ARKADE_OPS];\n if (v === undefined) throw new Error(`Unknown opcode=${o}`);\n w.byte(v);\n continue;\n } else if (typeof o === \"number\" || typeof o === \"bigint\") {\n // Encode numbers via BigNum (520-byte cap).\n const big = typeof o === \"number\" ? BigInt(o) : o;\n o = BigNum.encode(big);\n }\n if (!(o instanceof Uint8Array)) throw new Error(`Wrong Script OP=${o} (${typeof o})`);\n // Bytes (data push)\n const len = o.length;\n // Arkade VM enforces MINIMALDATA for small script numbers.\n if (len === 1 && o[0] >= 1 && o[0] <= 16) {\n w.byte(OP.OP_1 - 1 + o[0]);\n continue;\n } else if (len === 1 && o[0] === 0x81) {\n w.byte(OP[\"1NEGATE\"]);\n continue;\n } else if (len < OP.PUSHDATA1) w.byte(len);\n else if (len <= 0xff) {\n w.byte(OP.PUSHDATA1);\n w.byte(len);\n } else if (len <= 0xffff) {\n w.byte(OP.PUSHDATA2);\n w.bytes(P.U16LE.encode(len));\n } else {\n w.byte(OP.PUSHDATA4);\n w.bytes(P.U32LE.encode(len));\n }\n w.bytes(o);\n }\n },\n decodeStream: (r: P.Reader): ArkadeScriptType => {\n const out: ArkadeScriptType = [];\n while (!r.isEnd()) {\n const cur = r.byte();\n // Data push: 0 < cur <= PUSHDATA4\n if (OP.OP_0 < cur && cur <= OP.PUSHDATA4) {\n let len;\n if (cur < OP.PUSHDATA1) len = cur;\n else if (cur === OP.PUSHDATA1) len = P.U8.decodeStream(r);\n else if (cur === OP.PUSHDATA2) len = P.U16LE.decodeStream(r);\n else if (cur === OP.PUSHDATA4) len = P.U32LE.decodeStream(r);\n else throw new Error(\"Should be not possible\");\n out.push(r.bytes(len));\n } else if (cur === 0x00) {\n out.push(0);\n } else if (OP.OP_1 <= cur && cur <= OP.OP_16) {\n out.push(cur - (OP.OP_1 - 1));\n } else if (cur === OP[\"1NEGATE\"]) {\n out.push(-1);\n } else {\n const op = ArkadeOPNames[cur] as keyof typeof ARKADE_OPS;\n if (op === undefined) throw new Error(`Unknown opcode=${cur.toString(16)}`);\n out.push(op);\n }\n }\n return out;\n },\n});\n\n/**\n * Convert script operations to ASM (assembly) format.\n * Supports both Bitcoin and Arkade opcodes.\n *\n * @example\n * ```typescript\n * toASM(['DUP', 'HASH160', 'INSPECTOUTPUTVALUE']) // \"OP_DUP OP_HASH160 OP_INSPECTOUTPUTVALUE\"\n * toASM(ArkadeScript.decode(bytes))\n * ```\n */\nexport function toASM(script: ArkadeScriptType): string {\n const parts: string[] = [];\n\n for (const op of script) {\n if (typeof op === \"string\") {\n // Opcode name from ArkadeOPNames — add OP_ prefix for ASM format\n const name = op.startsWith(\"OP_\") ? op : `OP_${op}`;\n parts.push(name);\n } else if (typeof op === \"number\" || typeof op === \"bigint\") {\n if (op === 0 || op === 0n) {\n parts.push(\"OP_0\");\n } else if (op >= 1 && op <= 16) {\n parts.push(`OP_${op}`);\n } else if (op === -1 || op === -1n) {\n parts.push(\"OP_1NEGATE\");\n } else {\n // A bare decimal token would not survive fromASM (it parses\n // hex or opcodes only) — render the minimal script-num bytes,\n // which re-encode byte-identically to the number itself.\n parts.push(hex.encode(BigNum.encode(BigInt(op))));\n }\n } else {\n // Uint8Array data\n parts.push(hex.encode(op));\n }\n }\n\n return parts.join(\" \");\n}\n\n/**\n * Parse ASM (assembly) format to script operations.\n * Supports both Bitcoin and Arkade opcodes.\n *\n * @example\n * ```typescript\n * fromASM(\"OP_DUP OP_HASH160 deadbeef OP_NUM2BIN\")\n * // => ['DUP', 'HASH160', Uint8Array, 'NUM2BIN']\n * ```\n */\nexport function fromASM(asm: string): ArkadeScriptType {\n const tokens = asm.trim().split(/\\s+/).filter(Boolean);\n const out: ArkadeScriptType = [];\n\n for (const token of tokens) {\n // OP_0 → number 0\n if (token === \"OP_0\" || token === \"OP_FALSE\") {\n out.push(0);\n continue;\n }\n\n // OP_TRUE → number 1\n if (token === \"OP_TRUE\") {\n out.push(1);\n continue;\n }\n\n // OP_1 through OP_16 → number\n const numMatch = token.match(/^OP_(\\d+)$/);\n if (numMatch) {\n const n = parseInt(numMatch[1], 10);\n if (n >= 1 && n <= 16) {\n out.push(n);\n continue;\n }\n }\n\n // Try opcode lookup: strip OP_ prefix to get the key in ARKADE_OPS\n let key: string | undefined;\n if (token.startsWith(\"OP_\")) {\n key = token.slice(3);\n } else {\n key = token;\n }\n\n if (key in ARKADE_OPS) {\n out.push(key as keyof typeof ARKADE_OPS);\n continue;\n }\n\n // Try to parse as hex data\n if (/^[0-9a-fA-F]+$/.test(token) && token.length % 2 === 0) {\n try {\n out.push(hex.decode(token));\n continue;\n } catch {\n // Not valid hex, fall through\n }\n }\n\n throw new Error(`Invalid ASM token: ${token}`);\n }\n\n return out;\n}\n\n/**\n * Convert ASM string directly to script bytes\n */\nexport function asmToBytes(asm: string): Uint8Array {\n return ArkadeScript.encode(fromASM(asm));\n}\n\n/**\n * Convert script bytes directly to ASM string\n */\nexport function bytesToASM(script: Uint8Array): string {\n return toASM(ArkadeScript.decode(script));\n}\n","/**\n * Arkade Script Tweak\n *\n * Computes the tweaked public key for Arkade scripts.\n * The tweak is: tweakedPubKey = P + taggedHash(\"ArkScriptHash\", script) * G\n *\n * This is NOT taproot tweaking — it's a simple EC point addition used by\n * the emulator service to bind a script to a signing key.\n */\n\nimport { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesToNumberBE } from \"@noble/curves/utils.js\";\n\nimport { toXOnly } from \"../utils/keys\";\n\nconst TAG_SCRIPT = \"ArkScriptHash\";\nconst TAG_WITNESS = \"ArkWitnessHash\";\n\n/**\n * Compute the tagged hash of an Arkade script.\n * Uses BIP-340 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || script)\n *\n * @param script - The raw Arkade script bytes\n * @returns 32-byte hash\n */\nexport function arkadeScriptHash(script: Uint8Array): Uint8Array {\n return schnorr.utils.taggedHash(TAG_SCRIPT, script);\n}\n\n/**\n * Compute the tagged hash of an Arkade witness.\n * Uses BIP-340 tagged hash: SHA256(SHA256(tag) || SHA256(tag) || witness)\n *\n * @param witness - The raw Arkade witness bytes\n * @returns 32-byte hash, or 32 zero bytes if witness is empty\n */\nexport function arkadeWitnessHash(witness: Uint8Array): Uint8Array {\n if (witness.length === 0) {\n return new Uint8Array(32);\n }\n return schnorr.utils.taggedHash(TAG_WITNESS, witness);\n}\n\n/**\n * Compute the Arkade script tweaked public key.\n * result = pubKey + taggedHash(\"ArkScriptHash\", script) * G\n *\n * The input pubKey should be a compressed (33-byte) or x-only (32-byte) public key.\n * Returns a 32-byte x-only public key.\n *\n * @param pubKey - The emulator's base public key (32 or 33 bytes)\n * @param script - The raw Arkade script bytes\n * @returns 32-byte x-only tweaked public key\n */\nexport function computeArkadeScriptPublicKey(pubKey: Uint8Array, script: Uint8Array): Uint8Array {\n const hash = arkadeScriptHash(script);\n\n const point = schnorr.utils.lift_x(bytesToNumberBE(toXOnly(pubKey, \"emulator key\")));\n\n // tweak = (scriptHash mod n) * G\n const scalar = bytesToNumberBE(hash) % secp256k1.Point.CURVE().n;\n const tweak = secp256k1.Point.BASE.multiply(scalar);\n\n return schnorr.utils.pointToBytes(point.add(tweak));\n}\n","/**\n * Arkade Program model & compiler.\n *\n * A {@link Program} is the normalized SDK model: named functions, each\n * split into a `tapscript` segment enforced\n * on-chain and an optional `arkadeScript` segment emulated by the co-signing\n * service. This module owns everything that is *pure data → script*:\n *\n * - the Program/segment/token types,\n * - `$param` resolution ({@link resolveAsm}), witness and timelock resolution,\n * - program validation ({@link validateProgram}) — every referenced constructor\n * parameter must be declared and bound,\n * - {@link ArkadeProgramScript} — a {@link VtxoScript} compiled from a\n * program, its constructor args and the signer keys,\n * - artifact JSON (de)serialization ({@link parseArtifact} /\n * {@link stringifyArtifact}) and the string-keyed contract params used to\n * persist a program contract through the `src/contracts` pipeline.\n *\n * Keeping this free of provider/transaction imports lets the generic\n * `arkade` contract handler (src/contracts/handlers/arkade.ts) and the\n * high-level `ArkadeContract` client share one compilation path.\n *\n * @module arkade/program\n */\n\nimport { hex } from \"@scure/base\";\nimport { ScriptNum } from \"@scure/btc-signer\";\nimport { equalBytes } from \"@scure/btc-signer/utils.js\";\n\nimport {\n MultisigTapscript,\n CSVMultisigTapscript,\n CLTVMultisigTapscript,\n ConditionMultisigTapscript,\n ConditionCSVMultisigTapscript,\n type ArkTapscript,\n type RelativeTimelock,\n type TapscriptType,\n} from \"../script/tapscript\";\nimport { VtxoScript, type TapLeafScript } from \"../script/base\";\nimport { sequenceToCanonicalTimelock } from \"../utils/timelock\";\nimport { ArkadeScript } from \"./script\";\nimport { ARKADE_OP } from \"./opcodes\";\nimport { computeArkadeScriptPublicKey } from \"./tweak\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n// --- Normalized Program model ---------------------------------------------\n\n/** A token in an `asm` array: an opcode name, a number/bigint push, raw bytes, or a `$param` placeholder. */\nexport type AsmToken = string | number | bigint | Uint8Array;\n\n/** A constructor argument or resolved value. */\nexport type ArkadeParamValue = Uint8Array | bigint | number;\n\n/** A function call argument (function input). */\nexport type ArkadeArgValue = Uint8Array | bigint | number;\n\n/** Native scalar types and their compiler witness encodings. */\nexport const ARKADE_TYPE_ENCODINGS = {\n pubkey: \"raw\",\n signature: \"schnorr-64\",\n bytes: \"raw\",\n bytes20: \"raw-20\",\n bytes32: \"raw-32\",\n asset: \"raw-32\",\n int: \"scriptnum\",\n bool: \"scriptnum\",\n AssetGroup: \"scriptnum\",\n} as const;\n\n/** A native Arkade scalar type for a constructor parameter or call input. */\nexport type ArkadeArgType = keyof typeof ARKADE_TYPE_ENCODINGS;\n\n/**\n * Maps an {@link ArkadeArgType} to its TypeScript argument type.\n * @internal\n */\nexport interface ArkadeValueType {\n bytes: Uint8Array;\n pubkey: Uint8Array;\n signature: Uint8Array;\n bytes20: Uint8Array;\n bytes32: Uint8Array;\n asset: Uint8Array;\n int: bigint | number;\n bool: bigint | number;\n AssetGroup: bigint | number;\n}\n\n/** A typed function input or constructor param: a name plus its {@link ArkadeArgType}. */\nexport interface InputDef {\n name: string;\n type: ArkadeArgType;\n}\n\n/** A typed function input or constructor parameter. */\nexport type InputRef = InputDef;\n\n/** Constructor pubkey `$param` tweaked by `fn`'s covenant. */\nexport interface TweakedSigner {\n tweak: string;\n fn: string;\n}\n\n/** A `\"$param\"` reference, literal x-only bytes, or a {@link TweakedSigner}. */\nexport type SignerRef = string | Uint8Array | TweakedSigner;\n\n/** A witness-stack item: a function-input name, a `\"$param\"`, a literal number/bigint (minimal script-num), or raw bytes. */\nexport type WitnessRef = string | number | bigint | Uint8Array;\n\n/** Bitcoin Script segment of a spending path — enforced on-chain. */\nexport interface TapscriptSegment {\n /**\n * Required signers. A path with `arkadeScript` also inserts the emulator\n * co-signer at `emulatorIndex` (last by default), unless `emulator` is `null`.\n */\n signers: SignerRef[];\n /** Caller signature ABI; satisfied through PSBT signing, never ConditionWitness. */\n signatures?: InputDef[];\n /**\n * Covenant named by `<EMULATOR_KEY:fn>`. `null` when this leaf belongs to a\n * covenant but signs with a constructor-key tweak instead. Omitted on\n * hand-written programs, which still append the co-signer.\n */\n emulator?: string | null;\n /** Emulator's position in the full signer list; omitted to append it. */\n emulatorIndex?: number;\n /**\n * Optional standard-opcode condition (e.g. a hashlock), encoded into a\n * ConditionMultisig leaf — or ConditionCSVMultisig when combined with `csv`.\n */\n asm?: AsmToken[];\n /**\n * Relative timelock (CSV). The value is a literal or a `\"$param\"` reference\n * resolved against the constructor args (same convention as {@link SignerRef}).\n * `\"blocks\"` and `\"seconds\"` are counts; `\"sequence\"` is a raw BIP68\n * sequence, which is what an `arkadec` CSV operand holds.\n * Combinable with `asm` (condition + CSV); mutually exclusive with `cltv`.\n */\n csv?: { type: \"blocks\" | \"seconds\" | \"sequence\"; value: bigint | string };\n /**\n * Absolute timelock (CLTV): a literal or a `\"$param\"` reference.\n * Mutually exclusive with `csv`/`asm`.\n */\n cltv?: bigint | string;\n /** Items satisfying the condition (e.g. an HTLC preimage); set via the ConditionWitness PSBT field. */\n witness?: WitnessRef[];\n}\n\n/** Arkade Script segment of a spending path — emulated, bound via the key tweak. */\nexport interface ArkadeSegment {\n /** Raw Arkade opcodes with `$param` placeholders. */\n asm: AsmToken[];\n /** The arkade-script witness stack (e.g. an output index). */\n witness?: WitnessRef[];\n /**\n * Where each statement's tokens in `asm` came from, read from the compiler's debug file.\n * ponytail: in memory only; stringifyArtifact does not write it, so a restored contract has\n * none. Persist it if apps need source positions after a restore.\n */\n sourceMap?: SourceRange[];\n}\n\n/** One statement's tokens in a covenant's `asm` and its place in the entry file. */\nexport interface SourceRange {\n /** Half-open `[start, end)` indexes into the covenant's `asm`. */\n asm: [number, number];\n /** 1-based `[line, column]` in the entry file, with UTF-16 columns. */\n start: [number, number];\n end: [number, number];\n /** The `require()` message, when it has one. */\n message?: string;\n}\n\n/** One named spending path. */\nexport interface ArkadeFunction {\n /** Compiler spend group, used to resolve named covenant commitments. */\n group?: string;\n /** Ordered typed call arguments; absent for nullary paths. */\n inputs?: readonly InputDef[];\n tapscript: TapscriptSegment;\n /** Present for covenant paths; absent for pure-tapscript paths (cancel/exit). */\n arkadeScript?: ArkadeSegment;\n}\n\n/** Supported normalized Program version. */\nexport const SUPPORTED_PROGRAM_VERSION = 1;\n\n/**\n * A Program written for a version this SDK cannot read. Typed so a stored row in that format is\n * reported as unsupported rather than broken: its script stays unknown until it is recovered with\n * an SDK that reads that version, or re-created from fresh params.\n */\nexport class UnsupportedProgramVersionError extends Error {\n readonly name = \"UnsupportedProgramVersionError\";\n constructor(\n readonly version: unknown,\n context: string,\n ) {\n super(\n `${context}: unsupported program version ${String(version)}; this SDK supports version ${SUPPORTED_PROGRAM_VERSION}. ` +\n `Recover it with an SDK that reads version ${String(version)}, re-create it with current params, or delete it.`,\n );\n }\n}\n\n/** An Arkade contract program (hand-written or compiler-emitted). */\nexport interface Program {\n version: number;\n /**\n * Optional program name — metadata only: round-tripped through the\n * artifact JSON, never used in compilation or the taproot tree.\n */\n name?: string;\n /** Ordered typed constructor parameters. */\n params?: readonly InputDef[];\n functions: Record<string, ArkadeFunction>;\n}\n\n// --- helpers ---------------------------------------------------------------\n\n/** Look up a `$param` / function-input value in a bind map; throws when unbound. */\nexport function bindValue(bind: Record<string, ArkadeParamValue>, name: string): ArkadeParamValue {\n const v = Object.hasOwn(bind, name) ? bind[name] : undefined;\n if (v === undefined) throw new Error(`unbound parameter '${name}'`);\n return v;\n}\n\n/**\n * Resolve a timelock value to a bigint: bigints pass through; a `\"$param\"`\n * string resolves against the program's constructor args and must be bound to\n * a bigint/number. Any other string is an error.\n */\nexport function resolveTimelockValue(\n value: bigint | string,\n args: Record<string, ArkadeParamValue>,\n): bigint {\n if (typeof value === \"bigint\") return value;\n if (value.startsWith(\"$\")) {\n const v = bindValue(args, value.slice(1));\n if (typeof v === \"bigint\" || typeof v === \"number\") return BigInt(v);\n throw new Error(`timelock value '${value}' must resolve to a number`);\n }\n throw new Error(\n `invalid timelock value '${value}' — expected a bigint or a '$param' reference`,\n );\n}\n\n/**\n * Resolve a CSV segment to a {@link RelativeTimelock}. A `\"sequence\"` kind holds\n * the raw BIP68 sequence that `arkadec` and the delegatee push for a CSV\n * operand, so it is decoded here instead of being read as a count.\n */\nexport function resolveCsvTimelock(\n csv: NonNullable<TapscriptSegment[\"csv\"]>,\n args: Record<string, ArkadeParamValue>,\n): RelativeTimelock {\n const value = resolveTimelockValue(csv.value, args);\n if (csv.type !== \"sequence\") return { type: csv.type, value };\n const timelock = sequenceToCanonicalTimelock(value);\n if (!timelock) {\n throw new Error(\n `csv '${csv.value}' resolved to ${value}, which is not a canonical BIP68 sequence`,\n );\n }\n return timelock;\n}\n\n/**\n * Resolve an `asm` array to bytes: substitute `$param` placeholders from `bind`,\n * pass everything else (opcode names, numbers, raw byte pushes) through to the\n * Arkade script encoder. The SDK does not interpret opcodes — this is pure\n * substitution + encoding. To embed a signer key (server, user, or any\n * other), pass it as a `$param` in the constructor args. Compiler `<...>`\n * placeholders are normalized by {@link programFromArtifact} before this step.\n */\nexport function resolveAsm(asm: AsmToken[], bind: Record<string, ArkadeParamValue>): Uint8Array {\n const tokens = asm.map((t) => {\n if (typeof t === \"string\" && t.startsWith(\"$\")) {\n return bindValue(bind, t.slice(1));\n }\n if (t === \"<SELF>\") {\n // Continuation covenants don't hard-code their own address (that would\n // be a non-converging fixpoint); express them with input introspection\n // (PUSHCURRENTINPUTINDEX + INSPECTINPUTSCRIPTPUBKEY) instead.\n throw new Error(\n \"<SELF> is not a placeholder; use INSPECTINPUTSCRIPTPUBKEY for continuation covenants\",\n );\n }\n return t;\n });\n return ArkadeScript.encode(tokens as never);\n}\n\n/**\n * Resolve one witness-stack item to bytes.\n *\n * - raw bytes pass through;\n * - numbers/bigints encode as minimal script-nums;\n * - `\"$param\"` strings resolve against the program's constructor args;\n * - any other string is a function-input name and resolves against `callArgs`\n * (throws when the input is unbound — e.g. outside a function call).\n */\nexport function witnessRefToBytes(\n ref: WitnessRef,\n callArgs: Record<string, ArkadeArgValue>,\n programArgs: Record<string, ArkadeParamValue>,\n): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (typeof ref === \"number\" || typeof ref === \"bigint\") {\n return MinimalScriptNum.encode(BigInt(ref));\n }\n const v = ref.startsWith(\"$\") ? bindValue(programArgs, ref.slice(1)) : bindValue(callArgs, ref);\n if (v instanceof Uint8Array) return v;\n return MinimalScriptNum.encode(BigInt(v));\n}\n\n/**\n * Resolve a witness stack without call arguments: literals and `$param` references resolve,\n * function-input references exist only at call time, so a stack naming one yields `null`.\n */\nexport function staticWitness(\n refs: readonly WitnessRef[] | undefined,\n programArgs: Record<string, ArkadeParamValue>,\n): Uint8Array[] | null {\n try {\n return (refs ?? []).map((ref) => witnessRefToBytes(ref, {}, programArgs));\n } catch {\n return null;\n }\n}\n\n/**\n * Validate a tapscript segment with its resolved signers; `asm` may combine with\n * `csv` (the condition + CSV closure) but `cltv` conflicts with both (arkd\n * recognizes no condition+CLTV or dual-timelock closure); the `asm` may not\n * contain Arkade opcodes (those are `OP_SUCCESS` on-chain and belong in the\n * `arkadeScript` segment).\n */\nexport function validateTapscript(seg: TapscriptSegment): void {\n if (!seg.signers || seg.signers.length === 0) {\n throw new Error(\"tapscript: at least one signer is required\");\n }\n if (seg.asm !== undefined && seg.cltv !== undefined) {\n throw new Error(\n \"tapscript: `asm` and `cltv` conflict — arkd has no condition+CLTV closure\",\n );\n }\n if (seg.csv !== undefined && seg.cltv !== undefined) {\n throw new Error(\"tapscript: `csv` and `cltv` conflict — use at most one timelock\");\n }\n for (const t of seg.asm ?? []) {\n if (typeof t === \"string\" && t in ARKADE_OP) {\n throw new Error(\n `tapscript: arkade opcode '${t}' is not enforceable on-chain — move it to arkadeScript`,\n );\n }\n }\n}\n\n/** Collect every `\"$name\"` reference in a program's signers, asm, witness and timelock values. */\nfunction collectParamRefs(program: Program): Set<string> {\n const refs = new Set<string>();\n const collect = (items: readonly (AsmToken | WitnessRef | SignerRef)[] | undefined) => {\n for (const t of items ?? []) {\n if (typeof t === \"string\" && t.startsWith(\"$\")) refs.add(t.slice(1));\n else if (isTweakedSigner(t) && t.tweak.startsWith(\"$\")) refs.add(t.tweak.slice(1));\n }\n };\n for (const fn of Object.values(program.functions)) {\n const tap = fn.tapscript;\n collect(tap.signers);\n collect(tap.asm);\n collect(tap.witness);\n collect(tap.csv ? [tap.csv.value] : undefined);\n collect(tap.cltv !== undefined ? [tap.cltv] : undefined);\n collect(fn.arkadeScript?.asm);\n collect(fn.arkadeScript?.witness);\n }\n return refs;\n}\n\n/** The SDK restricts pubkeys to 32-byte x-only keys, including constructor values. */\nconst TYPED_BYTE_LENGTHS: Partial<Record<ArkadeArgType, number>> = {\n pubkey: 32,\n signature: 64,\n bytes20: 20,\n bytes32: 32,\n asset: 32,\n};\n\n/** Validate a bound value against its typed declaration; errors name the parameter. */\nexport function validateParamValue(def: InputDef, value: ArkadeParamValue): void {\n if (typeof def.type !== \"string\" || !Object.hasOwn(ARKADE_TYPE_ENCODINGS, def.type)) {\n throw new Error(`program parameter '${def.name}': unknown type '${def.type}'`);\n }\n if (ARKADE_TYPE_ENCODINGS[def.type] === \"scriptnum\") {\n if (typeof value !== \"bigint\" && typeof value !== \"number\") {\n throw new Error(`program parameter '${def.name}' expects ${def.type}, got bytes`);\n }\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n throw new Error(\n `program parameter '${def.name}' expects a safe integer; use bigint for larger values`,\n );\n }\n if (def.type === \"bool\" && value !== 0 && value !== 1 && value !== 0n && value !== 1n) {\n throw new Error(`program parameter '${def.name}' expects a boolean encoded as 0 or 1`);\n }\n return;\n }\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `program parameter '${def.name}' expects ${def.type} bytes, got ${typeof value}`,\n );\n }\n const length = TYPED_BYTE_LENGTHS[def.type];\n if (length !== undefined && value.length !== length) {\n throw new Error(\n `program parameter '${def.name}' expects a ${length}-byte ${def.type}, got ${value.length} bytes`,\n );\n }\n}\n\n/** Validate declared constructor values and reject undeclared references. */\nexport function validateProgram(program: Program, args: Record<string, ArkadeParamValue>): void {\n const params = program.params ?? [];\n\n const declared = new Set(params.map((p) => p.name));\n for (const name of declared) {\n if (!Object.hasOwn(args, name) || args[name] === undefined) {\n throw new Error(`program parameter '${name}' is declared but not bound in args`);\n }\n }\n for (const ref of collectParamRefs(program)) {\n if (!declared.has(ref)) {\n throw new Error(`'$${ref}' is referenced but not declared in program params`);\n }\n }\n for (const p of params) {\n validateParamValue(p, args[p.name]);\n }\n for (const name of Object.keys(args)) {\n if (!declared.has(name)) throw new Error(`program: undeclared argument '${name}'`);\n }\n}\n\n// --- Compilation -----------------------------------------------------------\n\n/** The signer keys a program is compiled against. */\nexport interface ProgramKeys {\n /** The Arkade Service signer key (x-only) — used for address derivation and collaborative-path detection, not for `$param` resolution. */\n serverKey: Uint8Array;\n /** The wallet's x-only key — identifies which inputs the wallet signs. */\n userKey?: Uint8Array;\n /** The co-signer (emulator) key — required only for covenant (`arkadeScript`) functions. */\n emulatorKey?: Uint8Array;\n}\n\n/**\n * A single spending path, fully resolved at compilation: its definition, the\n * committed leaf body, the per-path arkade-script bytes (covenant paths only),\n * and the {@link TapLeafScript} (control block) for spending it.\n */\nexport interface CompiledProgramFunction {\n name: string;\n def: ArkadeFunction;\n /** The committed leaf script (body). */\n leafScript: Uint8Array;\n /** Resolved arkade-script bytes; undefined for pure-tapscript paths. */\n arkadeScript?: Uint8Array;\n /** Resolved signer keys (x-only), in the declared `signers` order. */\n signerKeys: Uint8Array[];\n /** Resolved once — the taproot leaf + control block for this path. */\n tapLeafScript: TapLeafScript;\n}\n\nfunction isTweakedSigner(ref: unknown): ref is TweakedSigner {\n if (typeof ref !== \"object\" || ref === null || ref instanceof Uint8Array) return false;\n const { tweak, fn } = ref as TweakedSigner;\n return typeof tweak === \"string\" && typeof fn === \"string\";\n}\n\n/** Resolve a pubkey signer to x-only key bytes against the program's constructor args. */\nfunction resolveSigner(\n ref: string | Uint8Array,\n args: Record<string, ArkadeParamValue>,\n): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (typeof ref !== \"string\" || !ref.startsWith(\"$\")) {\n throw new Error(`unknown signer reference '${ref}' — use a '$param' or key bytes`);\n }\n const v = bindValue(args, ref.slice(1));\n if (!(v instanceof Uint8Array)) {\n throw new Error(`signer ${ref} must be a pubkey (bytes)`);\n }\n return v;\n}\n\nfunction encodeTapscriptSegment(\n seg: TapscriptSegment,\n pubkeys: Uint8Array[],\n args: Record<string, ArkadeParamValue>,\n): ArkTapscript<TapscriptType, any> {\n if (seg.csv) {\n const timelock = resolveCsvTimelock(seg.csv, args);\n if (seg.asm) {\n // The fifth arkd closure: condition + CSV.\n return ConditionCSVMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n timelock,\n pubkeys,\n });\n }\n return CSVMultisigTapscript.encode({ timelock, pubkeys });\n }\n if (seg.cltv !== undefined) {\n return CLTVMultisigTapscript.encode({\n absoluteTimelock: resolveTimelockValue(seg.cltv, args),\n pubkeys,\n });\n }\n if (seg.asm) {\n return ConditionMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n pubkeys,\n });\n }\n return MultisigTapscript.encode({ pubkeys });\n}\n\nfunction compileFunctions(\n program: Program,\n args: Record<string, ArkadeParamValue>,\n keys: ProgramKeys,\n): Omit<CompiledProgramFunction, \"tapLeafScript\">[] {\n if (program.version !== SUPPORTED_PROGRAM_VERSION) {\n throw new UnsupportedProgramVersionError(program.version, \"ArkadeContract\");\n }\n const functions: Record<string, ArkadeFunction> = program.functions;\n const names = Object.keys(functions);\n if (names.length === 0) {\n throw new Error(\"ArkadeContract: program has no functions\");\n }\n validateProgram(program, args);\n if (\n args.server !== undefined &&\n (!(args.server instanceof Uint8Array) || !equalBytes(args.server, keys.serverKey))\n ) {\n throw new Error(\n \"ArkadeContract: reserved server parameter must match the contract server key\",\n );\n }\n const defs = names.map((n) => functions[n]);\n\n const covenants = new Map<string, Uint8Array>();\n for (const [name, def] of Object.entries(functions)) {\n if (!def.arkadeScript) continue;\n const script = resolveAsm(def.arkadeScript.asm, args);\n for (const target of [name, ...(def.group ? [def.group] : [])]) {\n const previous = covenants.get(target);\n if (previous && !equalBytes(previous, script)) {\n throw new Error(`ArkadeContract: ambiguous covenant '${target}'`);\n }\n covenants.set(target, script);\n }\n }\n\n const covenant = names.find(\n (_, i) => defs[i].arkadeScript && defs[i].tapscript.emulator !== null,\n );\n if (covenant && !keys.emulatorKey) {\n throw new Error(\n `ArkadeContract: function '${covenant}' has an arkadeScript but no emulator is configured — pass an \\`emulator\\` to Arkade.connect`,\n );\n }\n\n return defs.map((def, i) => {\n const pubkeys = def.tapscript.signers.map((signer) => {\n if (!isTweakedSigner(signer)) return resolveSigner(signer, args);\n const script = covenants.get(signer.fn);\n if (!script) {\n throw new Error(\n `ArkadeContract: function '${names[i]}' tweaks '${signer.fn}', which has no arkade script`,\n );\n }\n return computeArkadeScriptPublicKey(resolveSigner(signer.tweak, args), script);\n });\n\n const arkadeScript = def.arkadeScript ? covenants.get(names[i]) : undefined;\n const leafPubkeys = [...pubkeys];\n if (arkadeScript && def.tapscript.emulator !== null) {\n const position = def.tapscript.emulatorIndex ?? pubkeys.length;\n if (!Number.isInteger(position) || position < 0 || position > pubkeys.length) {\n throw new Error(\n `ArkadeContract: function '${names[i]}' has an invalid emulator position ${position}`,\n );\n }\n const target = def.group\n ? covenants.get(def.tapscript.emulator ?? def.group)\n : arkadeScript;\n if (!target || !equalBytes(target, arkadeScript)) {\n throw new Error(\n `ArkadeContract: function '${names[i]}' has an invalid emulator covenant '${def.tapscript.emulator}'`,\n );\n }\n leafPubkeys.splice(\n position,\n 0,\n computeArkadeScriptPublicKey(keys.emulatorKey!, target),\n );\n } else if (def.tapscript.emulatorIndex !== undefined) {\n throw new Error(\n `ArkadeContract: function '${names[i]}' specifies an emulator position without an emulator`,\n );\n }\n validateTapscript({ ...def.tapscript, signers: leafPubkeys });\n const leafScript = encodeTapscriptSegment(def.tapscript, leafPubkeys, args).script;\n return { name: names[i], def, leafScript, arkadeScript, signerKeys: pubkeys };\n });\n}\n\n/**\n * A {@link VtxoScript} compiled from an Arkade {@link Program}, its\n * constructor args and the signer keys.\n *\n * This is the single compilation path shared by the high-level\n * `ArkadeContract` client and the `\"arkade\"` contract handler: both produce\n * byte-identical taproot trees for the same (program, args, keys), so a\n * contract registered through the `src/contracts` pipeline re-derives the\n * exact script it was created with.\n */\nexport class ArkadeProgramScript extends VtxoScript {\n /** Spending paths in declaration order. */\n readonly compiled: CompiledProgramFunction[];\n\n constructor(\n readonly program: Program,\n readonly args: Record<string, ArkadeParamValue>,\n readonly keys: ProgramKeys,\n ) {\n const partial = compileFunctions(program, args, keys);\n super(partial.map((p) => p.leafScript));\n this.compiled = partial.map((p) => ({\n ...p,\n tapLeafScript: this.findLeaf(hex.encode(p.leafScript)),\n }));\n }\n\n /** The compiled spending path with the given function name, if any. */\n functionByName(name: string): CompiledProgramFunction | undefined {\n return this.compiled.find((f) => f.name === name);\n }\n}\n\n// --- Artifact JSON ----------------------------------------------------------\n\n/**\n * Convert a Program JSON artifact into a {@link Program}. Byte values are\n * encoded as `0x`-prefixed hex strings in `asm`/`witness`/`signers`; opcode names,\n * `$param` placeholders and numbers pass through unchanged.\n *\n * This is *not* the JSON `arkadec` writes. That artifact lists spend groups in\n * an array and uses `<param>` placeholders and raw leaf assembly; pass it to\n * {@link programFromArtifact} instead.\n */\nexport function parseArtifact(artifact: {\n version?: number;\n name?: string;\n params?: readonly InputDef[];\n functions: unknown;\n}): Program {\n // An arkadec ContractJson would otherwise become functions named \"0\", \"1\", \"2\".\n if (Array.isArray(artifact.functions)) {\n throw new Error(\n \"parseArtifact: `functions` is an array, which is the arkadec artifact shape, not an SDK program — read it with programFromArtifact instead\",\n );\n }\n if (typeof artifact.functions !== \"object\" || artifact.functions === null) {\n throw new Error(\"parseArtifact: `functions` must be an object keyed by function name\");\n }\n const hexToken = (t: unknown): any =>\n typeof t === \"string\" && t.startsWith(\"0x\") ? hex.decode(t.slice(2)) : t;\n const signerRef = (s: unknown): SignerRef => {\n if (s instanceof Uint8Array || typeof s === \"string\") return hexToken(s);\n if (isTweakedSigner(s)) return { tweak: s.tweak, fn: s.fn };\n throw new Error(\"parseArtifact: a tweaked signer needs string `tweak` and `fn`\");\n };\n // A \"$param\" timelock stays a reference (resolved at compile time); anything\n // else is a literal.\n const timelockValue = (v: unknown): bigint | string =>\n typeof v === \"string\" && v.startsWith(\"$\") ? v : BigInt(v as string | number);\n\n if (artifact.version !== undefined && artifact.version !== SUPPORTED_PROGRAM_VERSION) {\n throw new UnsupportedProgramVersionError(artifact.version, \"parseArtifact\");\n }\n const declarations: unknown[] = [artifact.params];\n for (const [name, fn] of Object.entries(artifact.functions as Record<string, any>)) {\n if (!fn || typeof fn !== \"object\" || Array.isArray(fn)) {\n throw new Error(`parseArtifact: function '${name}' must be an object`);\n }\n const tap = fn.tapscript;\n if (tap !== undefined && (!tap || typeof tap !== \"object\" || Array.isArray(tap))) {\n throw new Error(`parseArtifact: function '${name}' tapscript must be an object`);\n }\n declarations.push(fn.inputs, tap?.signatures);\n if (\n tap?.emulatorIndex !== undefined &&\n (!Number.isInteger(tap.emulatorIndex) || tap.emulatorIndex < 0)\n ) {\n throw new Error(`parseArtifact: function '${name}' has an invalid emulator position`);\n }\n }\n for (const defs of declarations) {\n if (defs === undefined) continue;\n if (!Array.isArray(defs)) {\n throw new Error(\n \"parseArtifact: parameters, inputs and signatures require arrays of typed declarations\",\n );\n }\n for (const def of defs) {\n if (\n !def ||\n typeof def.name !== \"string\" ||\n def.name.length === 0 ||\n typeof def.type !== \"string\" ||\n !Object.hasOwn(ARKADE_TYPE_ENCODINGS, def.type)\n ) {\n throw new Error(\n \"parseArtifact: parameters, inputs and signatures require typed { name, type } declarations\",\n );\n }\n }\n }\n const functions: Record<string, ArkadeFunction> = Object.create(null);\n for (const [name, fn] of Object.entries(artifact.functions as Record<string, any>)) {\n const tap = fn.tapscript ?? {};\n const tapscript: TapscriptSegment = {\n signers: (tap.signers ?? []).map(signerRef),\n ...(tap.signatures ? { signatures: tap.signatures } : {}),\n ...(tap.asm ? { asm: tap.asm.map(hexToken) } : {}),\n ...(tap.witness ? { witness: tap.witness.map(hexToken) } : {}),\n ...(tap.csv\n ? { csv: { type: tap.csv.type, value: timelockValue(tap.csv.value) } }\n : {}),\n ...(tap.cltv !== undefined ? { cltv: timelockValue(tap.cltv) } : {}),\n ...(\"emulator\" in tap ? { emulator: tap.emulator as string | null } : {}),\n ...(tap.emulatorIndex !== undefined ? { emulatorIndex: tap.emulatorIndex } : {}),\n };\n const arkadeScript = fn.arkadeScript\n ? {\n asm: fn.arkadeScript.asm.map(hexToken),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(hexToken) }\n : {}),\n }\n : undefined;\n functions[name] = {\n ...(fn.group !== undefined ? { group: fn.group } : {}),\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript,\n ...(arkadeScript ? { arkadeScript } : {}),\n };\n }\n return {\n version: artifact.version ?? SUPPORTED_PROGRAM_VERSION,\n ...(artifact.name !== undefined ? { name: artifact.name } : {}),\n ...(artifact.params ? { params: artifact.params } : {}),\n functions,\n };\n}\n\n/**\n * Serialize a {@link Program} to normalized Program JSON — the inverse of\n * {@link parseArtifact}: bytes become `0x`-hex strings; bigint tokens become\n * plain numbers (or, above `Number.MAX_SAFE_INTEGER`, `0x`-hex of their\n * minimal script-num bytes, which the script encoder pushes identically);\n * literal timelock values serialize as decimal strings while `\"$param\"`\n * timelock references are emitted as-is.\n */\nexport function stringifyArtifact(program: Program): string {\n const token = (t: AsmToken | WitnessRef | SignerRef): unknown => {\n if (t instanceof Uint8Array) return \"0x\" + hex.encode(t);\n if (typeof t === \"bigint\") {\n if (t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(t);\n }\n // Out of JSON-safe integer range: a plain decimal string would be\n // misread as an opcode name, so emit the equivalent byte push.\n return \"0x\" + hex.encode(MinimalScriptNum.encode(t));\n }\n return t;\n };\n\n const functions: Record<string, unknown> = Object.create(null);\n for (const [name, fn] of Object.entries(program.functions)) {\n const tap = fn.tapscript;\n functions[name] = {\n ...(fn.group !== undefined ? { group: fn.group } : {}),\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript: {\n signers: tap.signers.map(token),\n ...(tap.signatures ? { signatures: tap.signatures } : {}),\n ...(tap.asm ? { asm: tap.asm.map(token) } : {}),\n ...(tap.witness ? { witness: tap.witness.map(token) } : {}),\n ...(tap.csv\n ? { csv: { type: tap.csv.type, value: tap.csv.value.toString() } }\n : {}),\n ...(tap.cltv !== undefined ? { cltv: tap.cltv.toString() } : {}),\n ...(tap.emulator !== undefined ? { emulator: tap.emulator } : {}),\n ...(tap.emulatorIndex !== undefined ? { emulatorIndex: tap.emulatorIndex } : {}),\n },\n ...(fn.arkadeScript\n ? {\n arkadeScript: {\n asm: fn.arkadeScript.asm.map(token),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(token) }\n : {}),\n },\n }\n : {}),\n };\n }\n\n return JSON.stringify({\n version: program.version,\n ...(program.name !== undefined ? { name: program.name } : {}),\n ...(program.params ? { params: program.params } : {}),\n functions,\n });\n}\n\n// --- Persisted contract params ----------------------------------------------\n\n/**\n * Typed parameters of an `\"arkade\"` contract as persisted through the\n * `src/contracts` pipeline. The program serializes as artifact JSON, args as\n * a JSON map (`0x`-hex bytes, decimal-string bigints), keys as hex — so a\n * stored contract row re-derives its script fully offline.\n */\nexport interface ArkadeContractParams {\n program: Program;\n args: Record<string, ArkadeParamValue>;\n serverKey: Uint8Array;\n userKey?: Uint8Array;\n emulatorKey?: Uint8Array;\n}\n\nfunction serializeArgValue(v: ArkadeParamValue): string | number {\n if (v instanceof Uint8Array) return \"0x\" + hex.encode(v);\n if (typeof v === \"bigint\") return v.toString();\n return v;\n}\n\n/**\n * Decode a persisted arg by its declared type — no `0x`/BigInt guessing. A\n * bytes-like param whose serialized value lacks the `0x` prefix is an error.\n */\nfunction parseTypedArgValue(name: string, type: ArkadeArgType, v: unknown): ArkadeParamValue {\n if (ARKADE_TYPE_ENCODINGS[type] === \"scriptnum\") {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") return BigInt(v);\n throw new Error(\n `arkade contract params: '${name}' expects ${type}, got ${JSON.stringify(v)}`,\n );\n }\n if (typeof v === \"string\" && v.startsWith(\"0x\")) return hex.decode(v.slice(2));\n throw new Error(\n `arkade contract params: '${name}' expects ${type} as 0x-prefixed hex, got ${JSON.stringify(v)}`,\n );\n}\n\n/** Serialize {@link ArkadeContractParams} to the string map `Contract.params` requires. */\nexport function serializeArkadeContractParams(typed: ArkadeContractParams): Record<string, string> {\n const args: Record<string, string | number> = Object.create(null);\n for (const [k, v] of Object.entries(typed.args)) {\n args[k] = serializeArgValue(v);\n }\n return {\n program: stringifyArtifact(typed.program),\n args: JSON.stringify(args),\n serverKey: hex.encode(typed.serverKey),\n ...(typed.userKey ? { userKey: hex.encode(typed.userKey) } : {}),\n ...(typed.emulatorKey ? { emulatorKey: hex.encode(typed.emulatorKey) } : {}),\n };\n}\n\n/** Parse the string map persisted in `Contract.params` back into typed params. */\nexport function deserializeArkadeContractParams(\n params: Record<string, string>,\n): ArkadeContractParams {\n if (!params.program) {\n throw new Error(\"arkade contract params: missing 'program'\");\n }\n if (!params.serverKey) {\n throw new Error(\"arkade contract params: missing 'serverKey'\");\n }\n const program = parseArtifact(JSON.parse(params.program));\n const paramTypes = new Map((program.params ?? []).map((p) => [p.name, p.type]));\n const args: Record<string, ArkadeParamValue> = Object.create(null);\n if (params.args) {\n for (const [k, v] of Object.entries(JSON.parse(params.args))) {\n const type = paramTypes.get(k);\n if (!type) throw new Error(`arkade contract params: undeclared argument '${k}'`);\n args[k] = parseTypedArgValue(k, type, v);\n }\n }\n return {\n program,\n args,\n serverKey: hex.decode(params.serverKey),\n ...(params.userKey ? { userKey: hex.decode(params.userKey) } : {}),\n ...(params.emulatorKey ? { emulatorKey: hex.decode(params.emulatorKey) } : {}),\n };\n}\n"]}
|
|
@@ -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,EAAM,QAAA,EAAU,OAAO,MAAA,CA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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-FDJ734CH.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 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"]}
|