@arkade-os/sdk 0.4.64 → 0.4.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/adapters/expo.cjs +5 -5
  2. package/dist/adapters/expo.js +3 -3
  3. package/dist/adapters/indexedDB.cjs +5 -5
  4. package/dist/adapters/indexedDB.js +4 -4
  5. package/dist/{chunk-HQ2DDMQN.js → chunk-3G5V564P.js} +141 -3
  6. package/dist/chunk-3G5V564P.js.map +1 -0
  7. package/dist/{chunk-WJN2BLEI.js → chunk-5YTSQSLE.js} +226 -353
  8. package/dist/chunk-5YTSQSLE.js.map +1 -0
  9. package/dist/{chunk-35YIP6OA.cjs → chunk-7X744EFF.cjs} +10 -10
  10. package/dist/{chunk-35YIP6OA.cjs.map → chunk-7X744EFF.cjs.map} +1 -1
  11. package/dist/{chunk-WXCVS6PD.cjs → chunk-BABJ77NG.cjs} +196 -57
  12. package/dist/chunk-BABJ77NG.cjs.map +1 -0
  13. package/dist/{chunk-FZFSGOTZ.cjs → chunk-G552MISJ.cjs} +3 -3
  14. package/dist/{chunk-FZFSGOTZ.cjs.map → chunk-G552MISJ.cjs.map} +1 -1
  15. package/dist/{chunk-LPEE2H2M.cjs → chunk-GFZNEMGL.cjs} +629 -748
  16. package/dist/chunk-GFZNEMGL.cjs.map +1 -0
  17. package/dist/{chunk-USXWE2EJ.js → chunk-RESN6QHP.js} +4 -4
  18. package/dist/{chunk-USXWE2EJ.js.map → chunk-RESN6QHP.js.map} +1 -1
  19. package/dist/{chunk-4N45WCSJ.cjs → chunk-SJQM5AVB.cjs} +17 -17
  20. package/dist/{chunk-4N45WCSJ.cjs.map → chunk-SJQM5AVB.cjs.map} +1 -1
  21. package/dist/{chunk-XJCBV4AA.js → chunk-TFSVXMTM.js} +3 -3
  22. package/dist/{chunk-XJCBV4AA.js.map → chunk-TFSVXMTM.js.map} +1 -1
  23. package/dist/{chunk-ZUEGFM3T.js → chunk-TYTPVPKD.js} +4 -4
  24. package/dist/{chunk-ZUEGFM3T.js.map → chunk-TYTPVPKD.js.map} +1 -1
  25. package/dist/{chunk-LN2VZP63.js → chunk-XMOIRDLF.js} +151 -12
  26. package/dist/chunk-XMOIRDLF.js.map +1 -0
  27. package/dist/{chunk-RXITDAV4.cjs → chunk-XN55B6EP.cjs} +155 -17
  28. package/dist/chunk-XN55B6EP.cjs.map +1 -0
  29. package/dist/contracts/handlers/index.cjs +9 -9
  30. package/dist/contracts/handlers/index.d.cts +1 -1
  31. package/dist/contracts/handlers/index.d.ts +1 -1
  32. package/dist/contracts/handlers/index.js +2 -2
  33. package/dist/{index-aZycGEsQ.d.cts → index-BtTtQFUX.d.cts} +109 -0
  34. package/dist/{index-Bxe9kBFs.d.ts → index-fDDiA1-L.d.ts} +109 -0
  35. package/dist/index.cjs +300 -268
  36. package/dist/index.d.cts +187 -13
  37. package/dist/index.d.ts +187 -13
  38. package/dist/index.js +4 -4
  39. package/dist/repositories/realm/index.cjs +19 -19
  40. package/dist/repositories/realm/index.js +5 -5
  41. package/dist/repositories/sqlite/index.cjs +18 -18
  42. package/dist/repositories/sqlite/index.js +5 -5
  43. package/dist/wallet/expo/background.cjs +14 -14
  44. package/dist/wallet/expo/background.js +6 -6
  45. package/dist/wallet/expo/index.cjs +14 -14
  46. package/dist/wallet/expo/index.js +5 -5
  47. package/dist/worker/expo/index.cjs +9 -9
  48. package/dist/worker/expo/index.js +5 -5
  49. package/package.json +1 -1
  50. package/dist/chunk-HQ2DDMQN.js.map +0 -1
  51. package/dist/chunk-LN2VZP63.js.map +0 -1
  52. package/dist/chunk-LPEE2H2M.cjs.map +0 -1
  53. package/dist/chunk-RXITDAV4.cjs.map +0 -1
  54. package/dist/chunk-WJN2BLEI.js.map +0 -1
  55. package/dist/chunk-WXCVS6PD.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contracts/handlers/registry.ts","../src/script/default.ts","../src/identity/descriptor.ts","../src/contracts/metadata.ts","../src/contracts/handlers/helpers.ts","../src/contracts/handlers/default.ts","../src/script/delegate.ts","../src/contracts/handlers/delegate.ts","../../../node_modules/micro-packed/src/index.ts","../src/arkade/opcodes.ts","../src/arkade/bignum.ts","../src/arkade/script.ts","../src/arkade/tweak.ts","../src/script/vhtlc.ts","../src/contracts/handlers/vhtlc.ts","../src/contracts/handlers/vhtlcV2.ts","../src/contracts/handlers/boarding.ts","../src/arkade/program.ts","../src/contracts/handlers/arkade.ts","../src/contracts/handlers/index.ts"],"names":["DefaultVtxo","Script","VtxoScript","MultisigTapscript","CSVMultisigTapscript","hex","expand","networks","sequenceToTimelock","SCRIPT_QUERY_CHUNK_SIZE","getNormalizedVtxos","DEFAULT_PAGE_SIZE","timelockToSequence","DelegateVtxo","i","baseHex","view","OP","__export","ScriptNum","schnorr","bytesToNumberBE","secp256k1","VHTLC","ConditionMultisigTapscript","CLTVMultisigTapscript","ConditionCSVMultisigTapscript"],"mappings":";;;;;;;;;;;AAkBA,IAAM,0BAAN,MAA8B;AAAA,EAClB,QAAA,uBAAe,GAAA,EAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ7D,SAAS,OAAA,EAAyC;AAC9C,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAA,CAAQ,IAAI,CAAA,uBAAA,CAAyB,CAAA;AAAA,IACvF;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,IAAA,EAAoD;AACpD,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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;AAChD,gBAAA,CAAiB,SAAS,uBAAuB,CAAA;AACjD,gBAAA,CAAiB,SAAS,qBAAqB,CAAA","file":"chunk-BABJ77NG.cjs","sourcesContent":["import { ContractHandler } from \"../types\";\n\n/**\n * Registry for contract handlers.\n *\n * Each contract type (\"default\", \"vhtlc\", etc.) has a handler that knows\n * how to create VtxoScripts, serialize params, and select spending paths.\n *\n * @example\n * ```typescript\n * // Register a custom handler\n * contractHandlers.register(myCustomHandler);\n *\n * // Get handler for a type\n * const handler = contractHandlers.get(\"vhtlc\");\n * const script = handler.createScript(contract.params);\n * ```\n */\nclass ContractHandlerRegistry {\n private handlers = new Map<string, ContractHandler<unknown>>();\n\n /**\n * Register a contract handler.\n *\n * @param handler - The handler to register\n * @throws If a handler for this type is already registered\n */\n register(handler: ContractHandler<unknown>): void {\n if (this.handlers.has(handler.type)) {\n throw new Error(`Contract handler for type '${handler.type}' is already registered`);\n }\n this.handlers.set(handler.type, handler);\n }\n\n /**\n * Get a handler by type.\n *\n * @param type - The contract type\n * @returns The handler, or undefined if not found\n */\n get(type: string): ContractHandler<unknown> | undefined {\n return this.handlers.get(type);\n }\n\n /**\n * Get a handler by type, throwing if not found.\n *\n * @param type - The contract type\n * @returns The handler\n * @throws If no handler is registered for this type\n */\n getOrThrow(type: string): ContractHandler<unknown> {\n const handler = this.get(type);\n if (!handler) {\n throw new Error(`No contract handler registered for type '${type}'`);\n }\n return handler;\n }\n\n /**\n * Check if a handler is registered.\n *\n * @param type - The contract type\n */\n has(type: string): boolean {\n return this.handlers.has(type);\n }\n\n /**\n * Get all registered types.\n */\n getRegisteredTypes(): string[] {\n return Array.from(this.handlers.keys());\n }\n\n /**\n * Unregister a handler (mainly for testing).\n */\n unregister(type: string): boolean {\n return this.handlers.delete(type);\n }\n\n /**\n * Clear all handlers (mainly for testing).\n */\n clear(): void {\n this.handlers.clear();\n }\n}\n\n/**\n * Global registry of contract handlers.\n */\nexport const contractHandlers = new ContractHandlerRegistry();\n","import { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { CSVMultisigTapscript, MultisigTapscript, RelativeTimelock } from \"./tapscript\";\nimport { hex } from \"@scure/base\";\n\n/**\n * DefaultVtxo is the default implementation of a VtxoScript.\n * It contains 1 forfeit path and 1 exit path.\n * - forfeit = (Alice + Server)\n * - exit = (Alice) after csvTimelock\n */\nexport namespace DefaultVtxo {\n /**\n * Options is the options for the DefaultVtxo.Script class.\n * csvTimelock is the exit path timelock, default is 144 blocks (1 day).\n */\n export interface Options {\n pubKey: Bytes;\n serverPubKey: Bytes;\n csvTimelock: RelativeTimelock;\n }\n\n /**\n * DefaultVtxo.Script is the class letting to create the vtxo script.\n * @example\n * ```typescript\n * const vtxoScript = new DefaultVtxo.Script({\n * pubKey: new Uint8Array(32),\n * serverPubKey: new Uint8Array(32),\n * csvTimelock: {\n * value: 605184n,\n * type: \"seconds\"\n * }\n * });\n *\n * console.log(\"script pub key:\", vtxoScript.pkScript)\n * ```\n */\n export class Script extends VtxoScript {\n static readonly DEFAULT_TIMELOCK: RelativeTimelock = {\n value: 144n,\n type: \"blocks\",\n }; // 1 day in blocks\n\n readonly forfeitScript: string;\n readonly exitScript: string;\n\n /** Create the default virtual output script with one forfeit path and one exit path. */\n constructor(readonly options: Options) {\n const { pubKey, serverPubKey, csvTimelock } = options;\n\n const forfeitScript = MultisigTapscript.encode({\n pubkeys: [pubKey, serverPubKey],\n }).script;\n\n const exitScript = CSVMultisigTapscript.encode({\n timelock: csvTimelock,\n pubkeys: [pubKey],\n }).script;\n\n super([forfeitScript, exitScript]);\n\n this.forfeitScript = hex.encode(forfeitScript);\n this.exitScript = hex.encode(exitScript);\n }\n\n /** Return the forfeit tapleaf script. */\n forfeit(): TapLeafScript {\n return this.findLeaf(this.forfeitScript);\n }\n\n /** Return the unilateral exit tapleaf script. */\n exit(): TapLeafScript {\n return this.findLeaf(this.exitScript);\n }\n }\n}\n","import { expand, networks } from \"@bitcoinerlab/descriptors-scure\";\nimport { hex } from \"@scure/base\";\n\n/**\n * True iff `descriptor` is a Bitcoin mainnet descriptor (xpub-prefixed\n * BIP32 key).\n *\n * Note: testnet, signet, regtest, mutinynet, and other non-mainnet\n * networks all share the same `tpub` BIP32 version bytes — they cannot\n * be distinguished from one another at the descriptor level. Callers\n * that need a `Network` constants object for `expand()` pick\n * `networks.bitcoin` vs `networks.testnet` themselves; callers that\n * need the *actual* network the wallet is on must track that\n * out-of-band.\n */\nexport function isMainnetDescriptor(descriptor: string): boolean {\n return !descriptor.includes(\"tpub\");\n}\n\n/**\n * Shared \"does `candidate` belong to the identity backed by\n * `ourDescriptor`?\" predicate.\n *\n * - HD descriptors (expanding to a `bip32` key) match by account xpub\n * on both sides — index-agnostic, so a wildcard template and any\n * concrete index under it all collapse to the same xpub.\n * - Bare `tr(pubkey)` candidates fall back to comparing the candidate\n * pubkey against `ourXOnlyPubkey` (the cached pubkey on the identity\n * side, since pulling it from `ourDescriptor` would require an index\n * substitution the caller already performed).\n */\nexport function descriptorIsOurs(\n candidate: string,\n ourDescriptor: string,\n ourXOnlyPubkey: Uint8Array,\n): boolean {\n if (!isDescriptor(candidate)) return false;\n try {\n const candidateInfo = expand({\n descriptor: candidate,\n network: isMainnetDescriptor(candidate) ? networks.bitcoin : networks.testnet,\n }).expansionMap?.[\"@0\"];\n if (!candidateInfo) return false;\n\n if (candidateInfo.bip32) {\n const ourBip32 = expand({\n descriptor: ourDescriptor,\n network: isMainnetDescriptor(ourDescriptor) ? networks.bitcoin : networks.testnet,\n }).expansionMap?.[\"@0\"]?.bip32;\n if (!ourBip32) return false;\n return ourBip32.toBase58() === candidateInfo.bip32.toBase58();\n }\n if (candidateInfo.pubkey) {\n // For tr() the library hands back a 32-byte x-only key, but\n // strip a leading parity byte defensively so a 33-byte\n // compressed key (mismatched length) doesn't silently\n // false-negative against our 32-byte x-only side.\n const candidatePub =\n candidateInfo.pubkey.length === 33\n ? candidateInfo.pubkey.subarray(1)\n : candidateInfo.pubkey;\n if (candidatePub.length !== ourXOnlyPubkey.length) return false;\n return hex.encode(candidatePub) === hex.encode(ourXOnlyPubkey);\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a string is a descriptor of the shape `tr(...)`.\n *\n * This is a shape check only — it does not validate the inner key material.\n * Use {@link expand} (via {@link extractPubKey} / {@link parseHDDescriptor})\n * for full parsing. The guard rejects empty bodies and missing/trailing\n * parentheses so callers can safely branch on descriptor vs. raw pubkey.\n */\nexport function isDescriptor(value: string): boolean {\n if (typeof value !== \"string\") return false;\n if (!value.startsWith(\"tr(\") || !value.endsWith(\")\")) return false;\n // body length > 0 after stripping \"tr(\" and \")\"\n return value.length > \"tr()\".length;\n}\n\n/**\n * Normalize a value to descriptor format.\n * If already a descriptor, return as-is. If hex pubkey, wrap as tr(pubkey).\n * Throws when the value is empty or not a string so we never produce\n * malformed descriptors like `tr()` that downstream parsers would reject.\n */\nexport function normalizeToDescriptor(value: string): string {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new Error(\"normalizeToDescriptor: expected a non-empty string value\");\n }\n if (isDescriptor(value)) {\n return value;\n }\n return `tr(${value})`;\n}\n\n/**\n * Extract the public key from a simple descriptor.\n * For simple descriptors (tr(pubkey)), extracts the pubkey using the library.\n * For HD descriptors, throws — use DescriptorProvider to derive the key.\n */\nexport function extractPubKey(descriptor: string): string {\n if (!isDescriptor(descriptor)) {\n return descriptor;\n }\n\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n const expansion = expand({ descriptor, network });\n\n if (!expansion.expansionMap) {\n throw new Error(\"Cannot extract pubkey from descriptor: expansion failed.\");\n }\n\n const key = expansion.expansionMap[\"@0\"];\n\n // HD descriptors (have a bip32 key) require DescriptorProvider for derivation\n if (key?.bip32) {\n throw new Error(\n \"Cannot extract pubkey from HD descriptor without derivation. \" +\n \"Use DescriptorProvider to derive the key from the xpub.\",\n );\n }\n\n if (!key?.pubkey) {\n throw new Error(\"Cannot extract pubkey from descriptor: no key found.\");\n }\n\n return hex.encode(key.pubkey);\n}\n\n/**\n * Extract the x-only (32-byte) pubkey from a materialized descriptor.\n * Handles both static `tr(pubkey)` and materialized HD\n * `tr([fp/..]xpub/0/<i>)` shapes via the descriptors-scure expansion map.\n * Throws a plain Error when the descriptor is non-rangeable / unparseable;\n * callers that need a typed error wrap this.\n */\nexport function deriveDescriptorLeafPubKey(descriptor: string): Uint8Array {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n let expansion;\n try {\n expansion = expand({ descriptor, network });\n } catch (e) {\n throw new Error(\n `Cannot derive leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `ensure it is materialized (no wildcard) and parsable.`,\n { cause: e },\n );\n }\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.pubkey) {\n throw new Error(\n `Cannot derive leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `parsed but no '@0' pubkey in the expansion map.`,\n );\n }\n return key.pubkey;\n}\n\n/**\n * Compressed (33-byte) counterpart of {@link deriveDescriptorLeafPubKey}, for\n * protocols that key on the parity byte (Boltz swap keys).\n *\n * Only HD descriptors are supported: a bare `tr(xonly)` has lost its parity and\n * synthesizing `02||xonly` would silently produce the wrong key half the time.\n */\nexport function deriveDescriptorLeafCompressedPubKey(descriptor: string): Uint8Array {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n let expansion;\n try {\n expansion = expand({ descriptor, network });\n } catch (e) {\n throw new Error(\n `Cannot derive compressed leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `ensure it is materialized (no wildcard) and parsable.`,\n { cause: e },\n );\n }\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.bip32) {\n throw new Error(\n `Cannot derive compressed leaf pubkey from descriptor (length=${descriptor.length}): ` +\n `not an HD descriptor, so the key parity is unrecoverable.`,\n );\n }\n // derivePath returns a fresh node; keyPath is relative to the xpub and the\n // library's derivePath prepends \"m/\" itself.\n return key.keyPath\n ? key.bip32.derivePath(key.keyPath.replace(/^\\//, \"\")).publicKey\n : key.bip32.publicKey;\n}\n\n/** Parsed HD descriptor components. */\nexport interface ParsedHDDescriptor {\n fingerprint: string;\n basePath: string;\n xpub: string;\n derivationPath: string;\n}\n\n/**\n * Parse an HD descriptor into its components.\n * HD descriptors have the format: tr([fingerprint/path']xpub/derivation)\n * Returns null if the descriptor is not in HD format.\n */\nexport function parseHDDescriptor(descriptor: string): ParsedHDDescriptor | null {\n if (!isDescriptor(descriptor)) {\n return null;\n }\n\n let expansion;\n try {\n const network = isMainnetDescriptor(descriptor) ? networks.bitcoin : networks.testnet;\n expansion = expand({ descriptor, network });\n } catch {\n return null;\n }\n\n const key = expansion.expansionMap?.[\"@0\"];\n if (!key?.masterFingerprint || !key.originPath || !key.keyPath || !key.bip32) {\n return null;\n }\n\n return {\n fingerprint: hex.encode(key.masterFingerprint),\n basePath: key.originPath.replace(/^\\//, \"\"),\n xpub: key.bip32.toBase58(),\n derivationPath: key.keyPath.replace(/^\\//, \"\"),\n };\n}\n\n/**\n * The descriptor that names an identity's own key: the whole of a static\n * wallet's key policy, and the descriptor a record bound before an `auto`\n * wallet became HD carries.\n *\n * One spelling, deliberately. Every site that mints this must produce\n * byte-identical output for one identity, or a stored descriptor stops\n * round-tripping through `signerForDescriptor` and `contractSigner`'s\n * pubkey-equality check — a record the wallet can sign for, refused as\n * foreign.\n */\nexport async function identityDescriptor(identity: {\n xOnlyPublicKey(): Promise<Uint8Array>;\n}): Promise<string> {\n return normalizeToDescriptor(hex.encode(await identity.xOnlyPublicKey()));\n}\n","/**\n * Sentinel stored in `contract.metadata.source` to mark a contract the\n * wallet generated for its own rotating receive address. Lives here (the\n * contracts layer) so contract handlers can tag/discover without importing\n * the wallet module. Re-exported from `wallet/walletReceiveRotator` for\n * backward compatibility of existing import paths.\n *\n * Tagging makes the boot lookup unambiguous — the rotator filters on\n * `metadata.source === WALLET_RECEIVE_SOURCE` rather than on \"any active\n * default contract\", so a contract repo that also holds default contracts\n * created for other reasons (legacy timelock variants, external\n * integrations) doesn't confuse the wallet's display state.\n */\nexport const WALLET_RECEIVE_SOURCE = \"wallet-receive\";\n","import { hex } from \"@scure/base\";\nimport { sequenceToTimelock } from \"../../utils/timelock\";\nimport { Contract, DiscoveredContract, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, Discoverable, DiscoveryDeps } from \"../types\";\nimport {\n isDescriptor,\n extractPubKey,\n normalizeToDescriptor,\n deriveDescriptorLeafPubKey,\n} from \"../../identity/descriptor\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport { getNormalizedVtxos } from \"../../wallet/vtxo\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport type { TapLeafScript } from \"../../script/base\";\nimport type { RelativeTimelock } from \"../../script/tapscript\";\nimport { WALLET_RECEIVE_SOURCE } from \"../metadata\";\nimport { DEFAULT_PAGE_SIZE, SCRIPT_QUERY_CHUNK_SIZE } from \"../constants\";\n\n/**\n * Extract raw hex pubkey from a value that may be a descriptor or raw hex.\n * Returns undefined for HD descriptors or unparseable values so role\n * resolution stays best-effort and never throws.\n */\nfunction extractRawPubKey(value: string): string | undefined {\n if (!isDescriptor(value)) {\n return value.toLowerCase();\n }\n try {\n return extractPubKey(value).toLowerCase();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve wallet's role from explicit role or by matching descriptor/pubkey.\n */\nexport function resolveRole(\n contract: Contract,\n context: PathContext,\n): \"sender\" | \"receiver\" | undefined {\n // Explicit role takes precedence\n if (context.role === \"sender\" || context.role === \"receiver\") {\n return context.role;\n }\n\n const senderKey = contract.params.sender ? extractRawPubKey(contract.params.sender) : undefined;\n const receiverKey = contract.params.receiver\n ? extractRawPubKey(contract.params.receiver)\n : undefined;\n\n const matchRole = (rawWalletKey: string | undefined): \"sender\" | \"receiver\" | undefined => {\n if (!rawWalletKey) return undefined;\n if (senderKey && rawWalletKey === senderKey) {\n return \"sender\";\n }\n if (receiverKey && rawWalletKey === receiverKey) {\n return \"receiver\";\n }\n return undefined;\n };\n\n // Try the preferred descriptor first. If it cannot be resolved\n // (for example an HD descriptor without derivation support), fall back\n // to walletPubKey for backward compatibility.\n if (context.walletDescriptor) {\n const walletDescriptorKey = extractRawPubKey(context.walletDescriptor);\n const matchedRole = matchRole(walletDescriptorKey);\n if (matchedRole) {\n return matchedRole;\n }\n\n if (!walletDescriptorKey && context.walletPubKey) {\n return matchRole(extractRawPubKey(context.walletPubKey));\n }\n return undefined;\n }\n\n if (context.walletPubKey) {\n return matchRole(extractRawPubKey(context.walletPubKey));\n }\n\n return undefined;\n}\n\n/**\n * Extract pubkey bytes from a persisted param that may hold either a\n * descriptor or a raw hex key.\n *\n * Shared by every descriptor-capable handler (`default` / `delegate` /\n * `boarding` — see `DESCRIPTOR_CAPABLE_CONTRACT_TYPES`) so a rotated row whose\n * key param was persisted in descriptor form deserializes identically\n * whichever handler owns it.\n */\nexport function extractPubKeyBytes(value: string): Uint8Array {\n return hex.decode(extractPubKey(normalizeToDescriptor(value)));\n}\n\n/**\n * Decode a persisted `csvTimelock` param, restoring the default when absent.\n *\n * The param may be missing or empty on legacy/minimal rows (e.g. hex pubkeys\n * written with no timelock). The script classes no longer apply their own\n * fallback, and an unguarded decode does *not* fail loudly: `Number(\"\")` /\n * `Number(undefined)` is `NaN`, and `bip68.decode(NaN)` returns\n * `{ blocks: 0 }`, so `sequenceToTimelock` silently yields a zero timelock —\n * an exit path that reads as immediately spendable. Restore the documented\n * default instead of decoding a NaN.\n */\nexport function deserializeCsvTimelock(value: string | undefined): RelativeTimelock {\n return value !== undefined && value !== \"\"\n ? sequenceToTimelock(Number(value))\n : DefaultVtxo.Script.DEFAULT_TIMELOCK;\n}\n\n/**\n * BIP65 threshold: locktime values below this are interpreted as block heights,\n * values at or above are interpreted as Unix timestamps (seconds).\n */\nconst CLTV_HEIGHT_THRESHOLD = 500_000_000n;\n\n/**\n * Check if an absolute (CLTV) locktime is currently satisfied.\n *\n * Following the BIP65 convention:\n * - locktime < 500_000_000 → interpreted as a block height; compared against `context.blockHeight`\n * - locktime >= 500_000_000 → interpreted as a Unix timestamp (seconds); compared against `context.currentTime`\n *\n * Returns false if the relevant context field is missing.\n */\nexport function isCltvSatisfied(context: PathContext, locktime: bigint): boolean {\n // Deliberately the same clock `cltvMaturity` reads. Offering a path and\n // refusing one are two answers to one question, and sourcing them from\n // different clocks lets a wallet offer a leaf its own guard would reject.\n return cltvMaturity(context, locktime) === \"satisfied\";\n}\n\n/**\n * How an absolute (CLTV) locktime stands against `context`, keeping \"not yet\"\n * and \"cannot tell\" apart.\n *\n * {@link isCltvSatisfied} folds both into `false`, which is the right answer\n * for OFFERING a path — an unknown maturity is not an invitation to spend. It\n * is the wrong answer for REFUSING one: a height-typed locktime with no\n * `blockHeight` in context is unreadable, not immature, and turning that into a\n * refusal would reject spends that are perfectly valid. Anything that fails a\n * caller rather than merely withholding an option must ask this instead.\n *\n * - `satisfied` — matured; the leaf behind it is spendable now.\n * - `pending` — definitively not matured yet, with a maturity to quote.\n * - `unknown` — height-typed with no chain tip supplied. Say nothing.\n */\nexport type CltvMaturity = \"satisfied\" | \"pending\" | \"unknown\";\n\nexport function cltvMaturity(context: PathContext, locktime: bigint): CltvMaturity {\n if (locktime < CLTV_HEIGHT_THRESHOLD) {\n if (context.blockHeight === undefined) return \"unknown\";\n return BigInt(context.blockHeight) >= locktime ? \"satisfied\" : \"pending\";\n }\n // Chain time where we have it. The wall-clock fallback is a decent estimate\n // and a poor authority: the server matures this against median-time-past,\n // which trails wall clock, so a drifting host reads the boundary wrong in\n // whichever direction it drifted — including \"not yet\" for something the\n // chain already accepts.\n return nowSeconds(context) >= locktime ? \"satisfied\" : \"pending\";\n}\n\n/** Chain time if the context carries it, else the local clock. Seconds. */\nfunction nowSeconds(context: PathContext): bigint {\n return BigInt(Math.floor(context.chainTime ?? context.currentTime / 1000));\n}\n\n/** Whether `locktime` is height-typed (BIP65), for phrasing a maturity. */\nexport function isHeightLocktime(locktime: bigint): boolean {\n return locktime < CLTV_HEIGHT_THRESHOLD;\n}\n\n/**\n * The VHTLC spendability refusal, shared by the v1 and v2 handlers.\n *\n * Both versions gate the sender's only collaborative leaf —\n * `refundWithoutReceiver` — on `refundLocktime`. Before it matures the sender\n * has nothing collaborative to spend: `claim` belongs to the receiver and needs\n * a preimage, and `refund` / `nonInteractiveRefund` need the receiver's\n * signature, which is precisely what a refunding sender cannot get. So an\n * explicit `settle({ inputs })` naming that lockup is refusable with certainty\n * rather than guessed at.\n *\n * Lives here rather than in either handler because v1 and v2 differ only in\n * which preimage fragment their claim leaves are built from; a rule applied to\n * one and not the other is the realistic drift, and the same reasoning already\n * keeps their path selection in step.\n *\n * Silent in every case that is not a certainty:\n * - not collaborative — a unilateral spend answers to its CSV, not this\n * - not the sender — the receiver's claim turns on a preimage this cannot see\n * - maturity `unknown` — height-typed with no chain tip; unreadable, not immature\n */\nexport function assertVhtlcSpendableNow(contract: Contract, context: PathContext): void {\n if (!context.collaborative) return;\n if (resolveRole(contract, context) !== \"sender\") return;\n\n const raw = contract.params?.refundLocktime;\n if (raw === undefined) return;\n let refundLocktime: bigint;\n try {\n refundLocktime = BigInt(raw);\n } catch {\n // Unparseable params are someone else's error to report, not ours to\n // guess at — createScript already refuses them with a better message.\n return;\n }\n\n if (cltvMaturity(context, refundLocktime) !== \"pending\") return;\n\n const [matures, now] = isHeightLocktime(refundLocktime)\n ? [`block ${refundLocktime}`, `${context.blockHeight}`]\n : [\n `${new Date(Number(refundLocktime) * 1000).toISOString()}`,\n new Date(context.currentTime).toISOString(),\n ];\n // Addressed to the sender — the only role that reaches here. Do not offer\n // them the preimage claim: that is the receiver's leaf and the receiver's\n // secret, and suggesting it sends the reader looking for a key they will\n // never hold.\n throw new Error(\n `vhtlc ${contract.script} cannot be spent yet: its refund path opens at ${matures}, ` +\n `now ${now}. Until then the lockup is the receiver's to claim, and the server ` +\n `rejects a spend of it. Retry after ${matures}, or wait for the receiver to ` +\n `claim it with the preimage.`,\n );\n}\n\n/**\n * Check if a CSV timelock is currently satisfied for the given context/virtual output.\n */\nexport function isCsvSpendable(context: PathContext, sequence?: number): boolean {\n if (sequence === undefined) return true;\n if (!context.vtxo) return false;\n const timelock = sequenceToTimelock(sequence);\n\n if (timelock.type === \"blocks\") {\n if (context.blockHeight === undefined || context.vtxo.status.block_height === undefined) {\n return false;\n }\n return context.blockHeight - context.vtxo.status.block_height >= Number(timelock.value);\n }\n\n if (timelock.type === \"seconds\") {\n // The input's own confirmation time is the CSV's origin — a relative\n // timelock is measured from when THIS coin confirmed, not from now.\n // Absent, the age is unknowable and the answer is no.\n const blockTime = context.vtxo.status.block_time;\n if (blockTime === undefined) return false;\n return Number(nowSeconds(context)) - blockTime >= Number(timelock.value);\n }\n\n return false;\n}\n\n/**\n * The tapleaf surface shared by `DefaultVtxo.Script` and\n * `DelegateVtxo.Script`. Structural rather than nominal: the two classes are\n * siblings (delegate wraps a default rather than extending it), so a shared\n * interface is what lets both feed the forfeit/exit path helpers below.\n */\nexport interface ForfeitExitScript {\n forfeit(): TapLeafScript;\n exit(): TapLeafScript;\n}\n\n/**\n * BIP68 sequence for a contract's exit path, or `undefined` when the contract\n * carries no `csvTimelock` param (an exit with no relative timelock).\n */\nexport function exitSequence(contract: Contract): number | undefined {\n return contract.params.csvTimelock ? Number(contract.params.csvTimelock) : undefined;\n}\n\n/**\n * The `forfeit`-or-`exit` selection every forfeit/exit contract shares:\n * collaborative spending takes the forfeit path, otherwise the exit path once\n * its CSV has matured. Returns null when neither is available.\n */\nexport function selectForfeitOrExitPath(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection | null {\n if (context.collaborative) {\n return { leaf: script.forfeit() };\n }\n\n const sequence = exitSequence(contract);\n if (!isCsvSpendable(context, sequence)) {\n return null;\n }\n return { leaf: script.exit(), sequence };\n}\n\n/**\n * Every forfeit/exit path that exists at all: forfeit when the server\n * cooperates, plus exit unconditionally (its CSV is checked at tx build time,\n * not here).\n */\nexport function forfeitExitAllPaths(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection[] {\n const paths: PathSelection[] = [];\n\n if (context.collaborative) {\n paths.push({ leaf: script.forfeit() });\n }\n\n const exitPath: PathSelection = { leaf: script.exit() };\n const sequence = exitSequence(contract);\n if (sequence !== undefined) {\n exitPath.sequence = sequence;\n }\n paths.push(exitPath);\n\n return paths;\n}\n\n/**\n * The subset of {@link forfeitExitAllPaths} spendable *right now* — the exit\n * path is dropped until its CSV has matured.\n */\nexport function forfeitExitSpendablePaths(\n script: ForfeitExitScript,\n contract: Contract,\n context: PathContext,\n): PathSelection[] {\n const paths: PathSelection[] = [];\n\n if (context.collaborative) {\n paths.push({ leaf: script.forfeit() });\n }\n\n const sequence = exitSequence(contract);\n if (isCsvSpendable(context, sequence)) {\n const exitPath: PathSelection = { leaf: script.exit() };\n if (sequence !== undefined) {\n exitPath.sequence = sequence;\n }\n paths.push(exitPath);\n }\n\n return paths;\n}\n\n/**\n * Batched discovery probe: given candidate pkScripts a discovery pass built\n * (the signer × CSV-timelock cross-product, possibly across several wallet\n * indices), return the subset the indexer has at least one VTXO for — in any\n * state, since restore counts a spent-but-used script as activity.\n *\n * Collapses what used to be one `getVtxos` call per candidate script into a\n * single call per page, the same batching shape as\n * {@link ContractManager.fetchContractVtxosBulk}: the indexer reports each\n * returned VTXO's `script`, which is matched back to the candidate set. It\n * pages only as far as needed to observe every candidate (stopping early once\n * all are seen), and otherwise to the end of history, so the discovered set is\n * identical to the prior per-script path — a heavily-reused candidate cannot\n * starve another candidate off the first page.\n *\n * Scripts beyond {@link SCRIPT_QUERY_CHUNK_SIZE} are split into sequential\n * chunks (a URL-length budget, see the constant). Chunks are issued serially,\n * not concurrently: pacing the indexer is the point of batching here. A chunk\n * rejecting rejects the whole call — callers treat a partial answer as\n * indeterminate, so there is no partial-result channel to leak into.\n */\nexport async function detectUsedScripts(\n indexerProvider: IndexerProvider,\n scriptHexes: string[],\n): Promise<Set<string>> {\n const used = new Set<string>();\n // Distinct indices can derive the same script (e.g. an unrotated signer),\n // and a duplicate would only pad the query string.\n const unique = [...new Set(scriptHexes)];\n\n for (let offset = 0; offset < unique.length; offset += SCRIPT_QUERY_CHUNK_SIZE) {\n const scripts = unique.slice(offset, offset + SCRIPT_QUERY_CHUNK_SIZE);\n // `scripts` stays the full chunk across pages so the indexer's\n // pagination is consistent; `remaining` only drives the early stop.\n const remaining = new Set(scripts);\n let pageIndex = 0;\n let hasMore = true;\n while (hasMore && remaining.size > 0) {\n const { vtxos, page } = await getNormalizedVtxos(indexerProvider, {\n scripts,\n pageIndex,\n pageSize: DEFAULT_PAGE_SIZE,\n });\n for (const vtxo of vtxos) {\n if (remaining.delete(vtxo.script)) used.add(vtxo.script);\n }\n // Same end-of-history heuristic as fetchContractVtxosBulk: a short\n // page (or absent page metadata) means there is nothing left to\n // fetch.\n hasMore = page ? vtxos.length === DEFAULT_PAGE_SIZE : false;\n pageIndex++;\n }\n }\n return used;\n}\n\n/**\n * Shared body of an indexer-backed handler's `discoverAt` / `discoverRange`.\n *\n * Both verbs are this one function — per-index discovery is just a range of\n * one — so the two paths cannot drift into reporting different contracts for\n * the same wallet state. Every I/O the pass needs is the single\n * {@link detectUsedScripts} call over the union of all indices' candidates,\n * which is what turns a 10-index window's ~20 concurrent 2-script requests\n * into 1-2 sequential batched ones.\n *\n * The returned map covers **every** requested index (empty array when nothing\n * hit), satisfying the `discoverRange` coverage contract the scanner enforces.\n */\nexport async function discoverIndexerCandidates<C extends { script: string }>(\n indexerProvider: IndexerProvider,\n entries: readonly { index: number; descriptor: string }[],\n buildCandidates: (index: number, descriptor: string) => C[],\n emit: (candidate: C, index: number, descriptor: string) => DiscoveredContract,\n): Promise<Map<number, DiscoveredContract[]>> {\n const perIndex = entries.map((entry) => ({\n ...entry,\n candidates: buildCandidates(entry.index, entry.descriptor),\n }));\n\n const used = await detectUsedScripts(\n indexerProvider,\n perIndex.flatMap((e) => e.candidates.map((c) => c.script)),\n );\n\n const out = new Map<number, DiscoveredContract[]>();\n for (const { index, descriptor, candidates } of perIndex) {\n out.set(\n index,\n candidates.filter((c) => used.has(c.script)).map((c) => emit(c, index, descriptor)),\n );\n }\n return out;\n}\n\n/**\n * One probe candidate: a built script plus the (signer, timelock) pair that\n * produced it, so the matched signer can be threaded into the emitted\n * contract's params and address.\n */\nexport interface SignerCandidate<S> {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n script: S;\n scriptHex: string;\n}\n\n/**\n * Candidate scripts for one wallet index: the current signer first, then any\n * deprecated signers (so a VTXO minted under a now-rotated server key is still\n * discovered), each crossed with the CSV-timelock matrix.\n *\n * Dedup by scriptHex — a deprecated signer that produced no rotation yields\n * the same scripts as the current key, so it must neither be probed nor\n * emitted twice; the current signer wins the attribution by being first.\n *\n * `makeScript` is the only per-contract-type part, which is what lets\n * `default` and `delegate` share one cross-product.\n */\nexport function buildSignerTimelockCandidates<S extends { pkScript: Uint8Array }>(\n descriptor: string,\n deps: CandidateDeps,\n makeScript: (opts: {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n }) => S,\n): SignerCandidate<S>[] {\n const pubKey = deriveDescriptorLeafPubKey(descriptor);\n const signers = [deps.serverPubKey, ...(deps.deprecatedSignerPubKeys ?? [])];\n const seen = new Set<string>();\n const candidates: SignerCandidate<S>[] = [];\n for (const serverPubKey of signers) {\n for (const csvTimelock of deps.csvTimelocks) {\n const script = makeScript({ pubKey, serverPubKey, csvTimelock });\n const scriptHex = hex.encode(script.pkScript);\n if (seen.has(scriptHex)) continue;\n seen.add(scriptHex);\n candidates.push({ pubKey, serverPubKey, csvTimelock, script, scriptHex });\n }\n }\n return candidates;\n}\n\n/**\n * Metadata tagging a discovered contract as one of the wallet's own rotating\n * receive addresses — spread into a {@link DiscoveredContract} literal.\n *\n * Only *rotated* rows (index > 0) are tagged, so boot resolution can find the\n * newest address and descriptor-aware signing can recover the per-index key.\n * The index-0 baseline stays untagged across every handler.\n */\nexport function rotatedReceiveMetadata(\n index: number,\n descriptor: string,\n): Pick<DiscoveredContract, \"metadata\"> {\n return index > 0\n ? { metadata: { source: WALLET_RECEIVE_SOURCE, signingDescriptor: descriptor } }\n : {};\n}\n\n/**\n * Metadata for a *speculative* candidate the look-ahead band watches: the\n * signing descriptor, so a promoted row stays spendable, and never\n * {@link WALLET_RECEIVE_SOURCE} — the tag would make the next boot advertise a\n * third party's invoice address as the wallet's own. Unconditional on the\n * index, unlike {@link rotatedReceiveMetadata}: an unpersisted entry has no\n * display-address meaning to protect at index 0.\n */\nexport function speculativeReceiveMetadata(\n descriptor: string,\n): Pick<DiscoveredContract, \"metadata\"> {\n return { metadata: { signingDescriptor: descriptor } };\n}\n\n/**\n * Derive a handler's {@link Discoverable.discoverAt} from its\n * {@link Discoverable.discoverRange}: per-index discovery is just a range of\n * one, so the two verbs cannot drift into reporting different contracts for\n * the same wallet state.\n *\n * The `?? []` mirrors `discoverRange`'s coverage contract from the caller's\n * side — a range that omitted the requested index reports a miss here rather\n * than `undefined`.\n */\nexport function discoverAtViaRange(\n discoverRange: NonNullable<Discoverable[\"discoverRange\"]>,\n): Discoverable[\"discoverAt\"] {\n return async (index: number, descriptor: string, deps: DiscoveryDeps) =>\n (await discoverRange([{ index, descriptor }], deps)).get(index) ?? [];\n}\n","import { hex } from \"@scure/base\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport {\n discoverIndexerCandidates,\n discoverAtViaRange,\n extractPubKeyBytes,\n deserializeCsvTimelock,\n rotatedReceiveMetadata,\n buildSignerTimelockCandidates,\n selectForfeitOrExitPath,\n forfeitExitAllPaths,\n forfeitExitSpendablePaths,\n} from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for DefaultVtxo contracts.\n */\nexport interface DefaultContractParams {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n}\n\n/**\n * Handler for default wallet VTXOs.\n *\n * Default contracts use the standard forfeit + exit tapscript:\n * - forfeit: (Alice + Server) multisig for collaborative spending\n * - exit: (Alice) + CSV timelock for unilateral exit\n */\nexport const DefaultContractHandler: ContractHandler<DefaultContractParams, DefaultVtxo.Script> &\n Discoverable = {\n type: \"default\",\n\n createScript(params: Record<string, string>): DefaultVtxo.Script {\n const typed = this.deserializeParams(params);\n return new DefaultVtxo.Script(typed);\n },\n\n serializeParams(params: DefaultContractParams): Record<string, string> {\n return {\n pubKey: hex.encode(params.pubKey),\n serverPubKey: hex.encode(params.serverPubKey),\n csvTimelock: timelockToSequence(params.csvTimelock).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): DefaultContractParams {\n return {\n pubKey: extractPubKeyBytes(params.pubKey),\n serverPubKey: extractPubKeyBytes(params.serverPubKey),\n csvTimelock: deserializeCsvTimelock(params.csvTimelock),\n };\n },\n\n selectPath(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectForfeitOrExitPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitAllPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitSpendablePaths(script, contract, context);\n },\n\n /** The wallet's own money. */\n isGenericallySpendable: () => true,\n\n discoverAt: discoverAtViaRange(discoverDefaultRange),\n\n discoverRange: discoverDefaultRange,\n\n candidatesAt: defaultCandidatesAt,\n};\n\n/**\n * The signer × CSV-timelock cross-product under the index's leaf key. Each\n * candidate's own signer is threaded through its params and address so\n * signing/forfeit later resolves the right key.\n */\nfunction defaultCandidatesAt(\n _index: number,\n descriptor: string,\n deps: CandidateDeps,\n): DiscoveredContract[] {\n return buildSignerTimelockCandidates(\n descriptor,\n deps,\n (opts) => new DefaultVtxo.Script(opts),\n ).map((c) => ({\n type: \"default\",\n params: {\n pubKey: hex.encode(c.pubKey),\n serverPubKey: hex.encode(c.serverPubKey),\n csvTimelock: timelockToSequence(c.csvTimelock).toString(),\n },\n script: c.scriptHex,\n address: c.script.address(deps.network.hrp, c.serverPubKey).encode(),\n }));\n}\n\nfunction discoverDefaultRange(\n entries: readonly { index: number; descriptor: string }[],\n deps: DiscoveryDeps,\n): Promise<Map<number, DiscoveredContract[]>> {\n return discoverIndexerCandidates(\n deps.indexerProvider,\n entries,\n (index, descriptor) => defaultCandidatesAt(index, descriptor, deps),\n (c, index, descriptor) => ({ ...c, ...rotatedReceiveMetadata(index, descriptor) }),\n );\n}\n","import { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { DefaultVtxo } from \"./default\";\nimport { MultisigTapscript } from \"./tapscript\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { hex } from \"@scure/base\";\n\n/**\n * DelegateVtxo extends DefaultVtxo with an extra delegate path\n */\nexport namespace DelegateVtxo {\n /**\n * Options extends DefaultVtxo.Options and adds a delegatePubKey\n */\n export interface Options extends DefaultVtxo.Options {\n delegatePubKey: Bytes;\n }\n\n /**\n * DelegateVtxo.Script extends DefaultVtxo.Script and adds a delegate path.\n * @example\n * ```typescript\n * const vtxoScript = new DelegateVtxo.Script({\n * pubKey: new Uint8Array(32),\n * serverPubKey: new Uint8Array(32),\n * delegatePubKey: new Uint8Array(32),\n * csvTimelock: {\n * value: 605184n,\n * type: \"seconds\"\n * }\n * });\n *\n * console.log(\"script pub key:\", vtxoScript.pkScript)\n * ```\n */\n export class Script extends VtxoScript {\n readonly defaultVtxo: DefaultVtxo.Script;\n readonly delegateScript: string;\n\n /** Create a delegated virtual output script with forfeit, exit, and delegate paths. */\n constructor(readonly options: Options) {\n const defaultVtxo = new DefaultVtxo.Script(options);\n const { delegatePubKey, pubKey, serverPubKey } = options;\n const delegateScript = MultisigTapscript.encode({\n pubkeys: [pubKey, delegatePubKey, serverPubKey],\n }).script;\n\n super([...defaultVtxo.scripts, delegateScript]);\n\n this.defaultVtxo = defaultVtxo;\n this.delegateScript = hex.encode(delegateScript);\n }\n\n /** Return the forfeit tapleaf script. */\n forfeit(): TapLeafScript {\n return this.findLeaf(this.defaultVtxo.forfeitScript);\n }\n\n /** Return the unilateral exit tapleaf script. */\n exit(): TapLeafScript {\n return this.findLeaf(this.defaultVtxo.exitScript);\n }\n\n /** Return the delegate tapleaf script. */\n delegate(): TapLeafScript {\n return this.findLeaf(this.delegateScript);\n }\n }\n}\n","import { hex } from \"@scure/base\";\nimport { DelegateVtxo } from \"../../script/delegate\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { CandidateDeps, DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport {\n discoverIndexerCandidates,\n discoverAtViaRange,\n extractPubKeyBytes,\n deserializeCsvTimelock,\n rotatedReceiveMetadata,\n buildSignerTimelockCandidates,\n selectForfeitOrExitPath,\n forfeitExitAllPaths,\n forfeitExitSpendablePaths,\n} from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for DelegateVtxo contracts.\n */\nexport interface DelegateContractParams {\n pubKey: Uint8Array;\n serverPubKey: Uint8Array;\n delegatePubKey: Uint8Array;\n csvTimelock: RelativeTimelock;\n}\n\n/**\n * Handler for delegate wallet virtual outputs.\n *\n * Delegate contracts extend the default tapscript with an additional delegate path:\n * - forfeit: (Alice + Server) multisig for collaborative spending\n * - exit: (Alice) + CSV timelock for unilateral exit\n * - delegate: (Alice + Delegate + Server) multisig for delegated renewal\n */\nexport const DelegateContractHandler: ContractHandler<DelegateContractParams, DelegateVtxo.Script> &\n Discoverable = {\n type: \"delegate\",\n\n createScript(params: Record<string, string>): DelegateVtxo.Script {\n const typed = this.deserializeParams(params);\n return new DelegateVtxo.Script(typed);\n },\n\n serializeParams(params: DelegateContractParams): Record<string, string> {\n return {\n pubKey: hex.encode(params.pubKey),\n serverPubKey: hex.encode(params.serverPubKey),\n delegatePubKey: hex.encode(params.delegatePubKey),\n csvTimelock: timelockToSequence(params.csvTimelock).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): DelegateContractParams {\n return {\n pubKey: extractPubKeyBytes(params.pubKey),\n serverPubKey: extractPubKeyBytes(params.serverPubKey),\n delegatePubKey: extractPubKeyBytes(params.delegatePubKey),\n csvTimelock: deserializeCsvTimelock(params.csvTimelock),\n };\n },\n\n selectPath(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return selectForfeitOrExitPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return [\n ...forfeitExitAllPaths(script, contract, context),\n // Delegate path (Alice + Delegate + Server) — collaborative only,\n // and last so the shared forfeit/exit ordering is unchanged.\n ...(context.collaborative ? [{ leaf: script.delegate() }] : []),\n ];\n },\n\n getSpendablePaths(\n script: DelegateVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return forfeitExitSpendablePaths(script, contract, context);\n },\n\n /** The wallet's own money, delegated signing. */\n isGenericallySpendable: () => true,\n\n discoverAt: discoverAtViaRange(discoverDelegateRange),\n\n discoverRange: discoverDelegateRange,\n\n candidatesAt: delegateCandidatesAt,\n};\n\n/**\n * The `default` cross-product (@see DefaultContractHandler.candidatesAt) under\n * the wallet's delegate key. Empty for a non-delegate wallet.\n */\nfunction delegateCandidatesAt(\n _index: number,\n descriptor: string,\n deps: CandidateDeps,\n): DiscoveredContract[] {\n const delegatePubKey = deps.delegatePubKey;\n if (!delegatePubKey) return [];\n\n return buildSignerTimelockCandidates(\n descriptor,\n deps,\n (opts) => new DelegateVtxo.Script({ ...opts, delegatePubKey }),\n ).map((c) => ({\n type: \"delegate\",\n params: {\n pubKey: hex.encode(c.pubKey),\n serverPubKey: hex.encode(c.serverPubKey),\n delegatePubKey: hex.encode(delegatePubKey),\n csvTimelock: timelockToSequence(c.csvTimelock).toString(),\n },\n script: c.scriptHex,\n address: c.script.address(deps.network.hrp, c.serverPubKey).encode(),\n }));\n}\n\nfunction discoverDelegateRange(\n entries: readonly { index: number; descriptor: string }[],\n deps: DiscoveryDeps,\n): Promise<Map<number, DiscoveredContract[]>> {\n // Not a delegate wallet: still answer for every requested index, since an\n // omission would read as indeterminate and truncate the scan.\n if (!deps.delegatePubKey) {\n return Promise.resolve(new Map(entries.map((e) => [e.index, []])));\n }\n\n return discoverIndexerCandidates(\n deps.indexerProvider,\n entries,\n (index, descriptor) => delegateCandidatesAt(index, descriptor, deps),\n (c, index, descriptor) => ({ ...c, ...rotatedReceiveMetadata(index, descriptor) }),\n );\n}\n","import { hex as baseHex, utf8, type Coder as BaseCoder } from '@scure/base';\n\n/**\n * Define complex binary structures using composable primitives.\n * Main ideas:\n * - Encode / decode can be chained, same as in `scure-base`\n * - A complex structure can be created from an array and struct of primitive types\n * - Strings / bytes are arrays with specific optimizations: we can just read bytes directly\n * without creating plain array first and reading each byte separately.\n * - Types are inferred from definition\n * @module\n * @example\n * import * as P from 'micro-packed';\n * const s = P.struct({\n * field1: P.U32BE, // 32-bit unsigned big-endian integer\n * field2: P.string(P.U8), // String with U8 length prefix\n * field3: P.bytes(32), // 32 bytes\n * field4: P.array(P.U16BE, P.struct({ // Array of structs with U16BE length\n * subField1: P.U64BE, // 64-bit unsigned big-endian integer\n * subField2: P.string(10) // 10-byte string\n * }))\n * });\n */\n\n// TODO: remove dependency on scure-base & inline?\n\n/*\nExports can be groupped like this:\n\n- Primitive types: P.bytes, P.string, P.hex, P.constant, P.pointer\n- Complex types: P.array, P.struct, P.tuple, P.map, P.tag, P.mappedTag\n- Padding, prefix, magic: P.padLeft, P.padRight, P.prefix, P.magic, P.magicBytes\n- Flags: P.flag, P.flagged, P.optional\n- Wrappers: P.apply, P.wrap, P.lazy\n- Bit fiddling: P.bits, P.bitset\n- utils: P.validate, coders.decimal\n- Debugger\n*/\n\n/** Shortcut to zero-length (empty) byte array */\nexport const EMPTY: Uint8Array = /* @__PURE__ */ Uint8Array.of();\n/** Shortcut to one-element (element is 0) byte array */\nexport const NULL: Uint8Array = /* @__PURE__ */ Uint8Array.of(0);\n\n/** Checks if two Uint8Arrays are equal. Not constant-time. */\nfunction equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n/** Checks if the given value is a Uint8Array. */\nfunction isBytes(a: unknown): a is Bytes {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/**\n * Concatenates multiple Uint8Arrays.\n * Engines limit functions to 65K+ arguments.\n * @param arrays Array of Uint8Array elements\n * @returns Concatenated Uint8Array\n */\nfunction concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Creates DataView from Uint8Array\n * @param arr - bytes\n * @returns DataView\n */\nconst createView = (arr: Uint8Array) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n/**\n * Checks if the provided value is a plain object, not created from any class or special constructor.\n * Array, Uint8Array and others are not plain objects.\n * @param obj - The value to be checked.\n */\nfunction isPlainObject(obj: any): boolean {\n return Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nfunction isNum(num: unknown): num is number {\n return Number.isSafeInteger(num);\n}\n\nexport const utils: {\n equalBytes: typeof equalBytes;\n isBytes: typeof isBytes;\n isCoder: typeof isCoder;\n checkBounds: typeof checkBounds;\n concatBytes: typeof concatBytes;\n createView: (arr: Uint8Array) => DataView;\n isPlainObject: typeof isPlainObject;\n} = {\n equalBytes,\n isBytes,\n isCoder,\n checkBounds,\n concatBytes,\n createView,\n isPlainObject,\n};\n\n// Types\nexport type Bytes = Uint8Array;\nexport type Option<T> = T | undefined;\n/**\n * Coder encodes and decodes between two types.\n * @property {(from: F) => T} encode - Encodes (converts) F to T\n * @property {(to: T) => F} decode - Decodes (converts) T to F\n */\nexport interface Coder<F, T> {\n encode(from: F): T;\n decode(to: T): F;\n}\n/**\n * BytesCoder converts value between a type and a byte array\n * @property {number} [size] - Size hint for the element.\n * @property {(data: T) => Bytes} encode - Encodes a value of type T to a byte array\n * @property {(data: Bytes, opts?: ReaderOpts) => T} decode - Decodes a byte array to a value of type T\n */\nexport interface BytesCoder<T> extends Coder<T, Bytes> {\n size?: number; // Size hint element\n encode: (data: T) => Bytes;\n decode: (data: Bytes, opts?: ReaderOpts) => T;\n}\n/**\n * BytesCoderStream converts value between a type and a byte array, using streams.\n * @property {number} [size] - Size hint for the element.\n * @property {(w: Writer, value: T) => void} encodeStream - Encodes a value of type T to a byte array using a Writer stream.\n * @property {(r: Reader) => T} decodeStream - Decodes a byte array to a value of type T using a Reader stream.\n */\nexport interface BytesCoderStream<T> {\n size?: number;\n encodeStream: (w: Writer, value: T) => void;\n decodeStream: (r: Reader) => T;\n}\nexport type CoderType<T> = BytesCoderStream<T> & BytesCoder<T>;\nexport type Sized<T> = CoderType<T> & { size: number };\nexport type UnwrapCoder<T> = T extends CoderType<infer U> ? U : T;\n/**\n * Validation function. Should return value after validation.\n * Can be used to narrow types\n */\nexport type Validate<T> = (elm: T) => T;\n\nexport type Length = CoderType<number> | CoderType<bigint> | number | Bytes | string | null;\n\n// NOTE: we can't have terminator separate function, since it won't know about boundaries\n// E.g. array of U16LE ([1,2,3]) would be [1, 0, 2, 0, 3, 0]\n// But terminator will find array at index '1', which happens to be inside of an element itself\n/**\n * Can be:\n * - Dynamic (CoderType)\n * - Fixed (number)\n * - Terminated (usually zero): Uint8Array with terminator\n * - Field path to field with length (string)\n * - Infinity (null) - decodes until end of buffer\n * Used in:\n * - bytes (string, prefix is implementation of bytes)\n * - array\n */\nconst lengthCoder = (len: Length) => {\n if (len !== null && typeof len !== 'string' && !isCoder(len) && !isBytes(len) && !isNum(len)) {\n throw new Error(\n `lengthCoder: expected null | number | Uint8Array | CoderType, got ${len} (${typeof len})`\n );\n }\n return {\n encodeStream(w: Writer, value: number | null) {\n if (len === null) return;\n if (isCoder(len)) return len.encodeStream(w, value);\n let byteLen;\n if (typeof len === 'number') byteLen = len;\n else if (typeof len === 'string') byteLen = Path.resolve((w as _Writer).stack, len);\n if (typeof byteLen === 'bigint') byteLen = Number(byteLen);\n if (byteLen === undefined || byteLen !== value)\n throw w.err(`Wrong length: ${byteLen} len=${len} exp=${value} (${typeof value})`);\n },\n decodeStream(r: Reader) {\n let byteLen;\n if (isCoder(len)) byteLen = Number(len.decodeStream(r));\n else if (typeof len === 'number') byteLen = len;\n else if (typeof len === 'string') byteLen = Path.resolve((r as _Reader).stack, len);\n if (typeof byteLen === 'bigint') byteLen = Number(byteLen);\n if (typeof byteLen !== 'number') throw r.err(`Wrong length: ${byteLen}`);\n return byteLen;\n },\n };\n};\n\ntype ArrLike<T> = Array<T> | ReadonlyArray<T>;\n// prettier-ignore\nexport type TypedArray =\n | Uint8Array | Int8Array | Uint8ClampedArray\n | Uint16Array | Int16Array\n | Uint32Array | Int32Array;\n\n/** Writable version of a type, where readonly properties are made writable. */\nexport type Writable<T> = T extends {}\n ? T extends TypedArray\n ? T\n : {\n -readonly [P in keyof T]: Writable<T[P]>;\n }\n : T;\nexport type Values<T> = T[keyof T];\nexport type NonUndefinedKey<T, K extends keyof T> = T[K] extends undefined ? never : K;\nexport type NullableKey<T, K extends keyof T> = T[K] extends NonNullable<T[K]> ? never : K;\n// Opt: value !== undefined, but value === T|undefined\nexport type OptKey<T, K extends keyof T> = NullableKey<T, K> & NonUndefinedKey<T, K>;\nexport type ReqKey<T, K extends keyof T> = T[K] extends NonNullable<T[K]> ? K : never;\n\nexport type OptKeys<T> = Pick<T, { [K in keyof T]: OptKey<T, K> }[keyof T]>;\nexport type ReqKeys<T> = Pick<T, { [K in keyof T]: ReqKey<T, K> }[keyof T]>;\nexport type StructInput<T extends Record<string, any>> = { [P in keyof ReqKeys<T>]: T[P] } & {\n [P in keyof OptKeys<T>]?: T[P];\n};\nexport type StructRecord<T extends Record<string, any>> = {\n [P in keyof T]: CoderType<T[P]>;\n};\n\nexport type StructOut = Record<string, any>;\n/** Padding function that takes an index and returns a padding value. */\nexport type PadFn = (i: number) => number;\n\n/**\n * Small bitset structure to store position of ranges that have been read.\n * Can be more efficient when internal trees are utilized at the cost of complexity.\n * Needs `O(N/8)` memory for parsing.\n * Purpose: if there are pointers in parsed structure,\n * they can cause read of two distinct ranges:\n * [0-32, 64-128], which means 'pos' is not enough to handle them\n */\nconst Bitset = {\n BITS: 32,\n FULL_MASK: -1 >>> 0, // 1<<32 will overflow\n len: (len: number) => Math.ceil(len / 32),\n create: (len: number) => new Uint32Array(Bitset.len(len)),\n clean: (bs: Uint32Array) => bs.fill(0),\n debug: (bs: Uint32Array) => Array.from(bs).map((i) => (i >>> 0).toString(2).padStart(32, '0')),\n checkLen: (bs: Uint32Array, len: number) => {\n if (Bitset.len(len) === bs.length) return;\n throw new Error(`wrong length=${bs.length}. Expected: ${Bitset.len(len)}`);\n },\n chunkLen: (bsLen: number, pos: number, len: number) => {\n if (pos < 0) throw new Error(`wrong pos=${pos}`);\n if (pos + len > bsLen) throw new Error(`wrong range=${pos}/${len} of ${bsLen}`);\n },\n set: (bs: Uint32Array, chunk: number, value: number, allowRewrite = true) => {\n if (!allowRewrite && (bs[chunk] & value) !== 0) return false;\n bs[chunk] |= value;\n return true;\n },\n pos: (pos: number, i: number) => ({\n chunk: Math.floor((pos + i) / 32),\n mask: 1 << (32 - ((pos + i) % 32) - 1),\n }),\n indices: (bs: Uint32Array, len: number, invert = false) => {\n Bitset.checkLen(bs, len);\n const { FULL_MASK, BITS } = Bitset;\n const left = BITS - (len % BITS);\n const lastMask = left ? (FULL_MASK >>> left) << left : FULL_MASK;\n const res = [];\n for (let i = 0; i < bs.length; i++) {\n let c = bs[i];\n if (invert) c = ~c; // allows to gen unset elements\n // apply mask to last element, so we won't iterate non-existent items\n if (i === bs.length - 1) c &= lastMask;\n if (c === 0) continue; // fast-path\n for (let j = 0; j < BITS; j++) {\n const m = 1 << (BITS - j - 1);\n if (c & m) res.push(i * BITS + j);\n }\n }\n return res;\n },\n range: (arr: number[]) => {\n const res = [];\n let cur;\n for (const i of arr) {\n if (cur === undefined || i !== cur.pos + cur.length) res.push((cur = { pos: i, length: 1 }));\n else cur.length += 1;\n }\n return res;\n },\n rangeDebug: (bs: Uint32Array, len: number, invert = false) =>\n `[${Bitset.range(Bitset.indices(bs, len, invert))\n .map((i) => `(${i.pos}/${i.length})`)\n .join(', ')}]`,\n setRange: (bs: Uint32Array, bsLen: number, pos: number, len: number, allowRewrite = true) => {\n Bitset.chunkLen(bsLen, pos, len);\n const { FULL_MASK, BITS } = Bitset;\n // Try to set range with maximum efficiency:\n // - first chunk is always '0000[1111]' (only right ones)\n // - middle chunks are set to '[1111 1111]' (all ones)\n // - last chunk is always '[1111]0000' (only left ones)\n // - max operations: (N/32) + 2 (first and last)\n const first = pos % BITS ? Math.floor(pos / BITS) : undefined;\n const lastPos = pos + len;\n const last = lastPos % BITS ? Math.floor(lastPos / BITS) : undefined;\n // special case, whole range inside single chunk\n if (first !== undefined && first === last)\n return Bitset.set(\n bs,\n first,\n (FULL_MASK >>> (BITS - len)) << (BITS - len - pos),\n allowRewrite\n );\n if (first !== undefined) {\n if (!Bitset.set(bs, first, FULL_MASK >>> pos % BITS, allowRewrite)) return false; // first chunk\n }\n // middle chunks\n const start = first !== undefined ? first + 1 : pos / BITS;\n const end = last !== undefined ? last : lastPos / BITS;\n for (let i = start; i < end; i++) if (!Bitset.set(bs, i, FULL_MASK, allowRewrite)) return false;\n if (last !== undefined && first !== last)\n if (!Bitset.set(bs, last, FULL_MASK << (BITS - (lastPos % BITS)), allowRewrite)) return false; // last chunk\n return true;\n },\n};\n\n/** Path related utils (internal) */\ntype Path = { obj: StructOut; field?: string };\ntype PathStack = Path[];\nexport type _PathObjFn = (cb: (field: string, fieldFn: Function) => void) => void;\nconst Path = {\n /**\n * Internal method for handling stack of paths (debug, errors, dynamic fields via path)\n * This is looks ugly (callback), but allows us to force stack cleaning by construction (.pop always after function).\n * Also, this makes impossible:\n * - pushing field when stack is empty\n * - pushing field inside of field (real bug)\n * NOTE: we don't want to do '.pop' on error!\n */\n pushObj: (stack: PathStack, obj: StructOut, objFn: _PathObjFn): void => {\n const last: Path = { obj };\n stack.push(last);\n objFn((field: string, fieldFn: Function) => {\n last.field = field;\n fieldFn();\n last.field = undefined;\n });\n stack.pop();\n },\n path: (stack: PathStack): string => {\n const res = [];\n for (const i of stack) if (i.field !== undefined) res.push(i.field);\n return res.join('/');\n },\n err: (name: string, stack: PathStack, msg: string | Error): Error => {\n const err = new Error(\n `${name}(${Path.path(stack)}): ${typeof msg === 'string' ? msg : msg.message}`\n );\n if (msg instanceof Error && msg.stack) err.stack = msg.stack;\n return err;\n },\n resolve: (stack: PathStack, path: string): StructOut | undefined => {\n const parts = path.split('/');\n const objPath = stack.map((i) => i.obj);\n let i = 0;\n for (; i < parts.length; i++) {\n if (parts[i] === '..') objPath.pop();\n else break;\n }\n let cur = objPath.pop();\n for (; i < parts.length; i++) {\n if (!cur || cur[parts[i]] === undefined) return undefined;\n cur = cur[parts[i]];\n }\n return cur;\n },\n};\n\n/**\n * Options for the Reader class.\n * @property {boolean} [allowUnreadBytes: false] - If there are remaining unparsed bytes, the decoding is probably wrong.\n * @property {boolean} [allowMultipleReads: false] - The check enforces parser termination. If pointers can read the same region of memory multiple times, you can cause combinatorial explosion by creating an array of pointers to the same address and cause DoS.\n */\nexport type ReaderOpts = {\n allowUnreadBytes?: boolean;\n allowMultipleReads?: boolean;\n};\n// These are safe API for external usage\nexport type Reader = {\n // Utils\n /** Current position in the buffer. */\n readonly pos: number;\n /** Number of bytes left in the buffer. */\n readonly leftBytes: number;\n /** Total number of bytes in the buffer. */\n readonly totalBytes: number;\n /** Checks if the end of the buffer has been reached. */\n isEnd(): boolean;\n /**\n * Creates an error with the given message. Adds information about current field path.\n * If Error object provided, saves original stack trace.\n * @param msg - The error message or an Error object.\n * @returns The created Error object.\n */\n err(msg: string | Error): Error;\n /**\n * Reads a specified number of bytes from the buffer.\n *\n * WARNING: Uint8Array is subarray of original buffer. Do not modify.\n * @param n - The number of bytes to read.\n * @param peek - If `true`, the bytes are read without advancing the position.\n * @returns The read bytes as a Uint8Array.\n */\n bytes(n: number, peek?: boolean): Uint8Array;\n /**\n * Reads a single byte from the buffer.\n * @param peek - If `true`, the byte is read without advancing the position.\n * @returns The read byte as a number.\n */\n byte(peek?: boolean): number;\n /**\n * Reads a specified number of bits from the buffer.\n * @param bits - The number of bits to read.\n * @returns The read bits as a number.\n */\n bits(bits: number): number;\n /**\n * Finds the first occurrence of a needle in the buffer.\n * @param needle - The needle to search for.\n * @param pos - The starting position for the search.\n * @returns The position of the first occurrence of the needle, or `undefined` if not found.\n */\n find(needle: Bytes, pos?: number): number | undefined;\n /**\n * Creates a new Reader instance at the specified offset.\n * Complex and unsafe API: currently only used in eth ABI parsing of pointers.\n * Required to break pointer boundaries inside arrays for complex structure.\n * Please use only if absolutely necessary!\n * @param n - The offset to create the new Reader at.\n * @returns A new Reader instance at the specified offset.\n */\n offsetReader(n: number): Reader;\n};\n\nexport type Writer = {\n /**\n * Creates an error with the given message. Adds information about current field path.\n * If Error object provided, saves original stack trace.\n * @param msg - The error message or an Error object.\n * @returns The created Error object.\n */\n err(msg: string | Error): Error;\n /**\n * Writes a byte array to the buffer.\n * @param b - The byte array to write.\n */\n bytes(b: Bytes): void;\n /**\n * Writes a single byte to the buffer.\n * @param b - The byte to write.\n */\n byte(b: number): void;\n /**\n * Writes a specified number of bits to the buffer.\n * @param value - The value to write.\n * @param bits - The number of bits to write.\n */\n bits(value: number, bits: number): void;\n};\n\n/**\n * Internal structure. Reader class for reading from a byte array.\n * `stack` is internal: for debugger and logging\n * @class Reader\n */\nclass _Reader implements Reader {\n pos = 0;\n readonly data: Bytes;\n readonly opts: ReaderOpts;\n readonly stack: PathStack;\n private parent: _Reader | undefined;\n private parentOffset: number;\n private bitBuf = 0;\n private bitPos = 0;\n private bs: Uint32Array | undefined; // bitset\n private view: DataView;\n constructor(\n data: Bytes,\n opts: ReaderOpts = {},\n stack: PathStack = [],\n parent: _Reader | undefined = undefined,\n parentOffset: number = 0\n ) {\n this.data = data;\n this.opts = opts;\n this.stack = stack;\n this.parent = parent;\n this.parentOffset = parentOffset;\n this.view = createView(data);\n }\n /** Internal method for pointers. */\n _enablePointers(): void {\n if (this.parent) return this.parent._enablePointers();\n if (this.bs) return;\n this.bs = Bitset.create(this.data.length);\n Bitset.setRange(this.bs, this.data.length, 0, this.pos, this.opts.allowMultipleReads);\n }\n private markBytesBS(pos: number, len: number): boolean {\n if (this.parent) return this.parent.markBytesBS(this.parentOffset + pos, len);\n if (!len) return true;\n if (!this.bs) return true;\n return Bitset.setRange(this.bs, this.data.length, pos, len, false);\n }\n private markBytes(len: number): boolean {\n const pos = this.pos;\n this.pos += len;\n const res = this.markBytesBS(pos, len);\n if (!this.opts.allowMultipleReads && !res)\n throw this.err(`multiple read pos=${this.pos} len=${len}`);\n return res;\n }\n\n pushObj(obj: StructOut, objFn: _PathObjFn): void {\n return Path.pushObj(this.stack, obj, objFn);\n }\n readView(n: number, fn: (view: DataView, pos: number) => number): number {\n if (!Number.isFinite(n)) throw this.err(`readView: wrong length=${n}`);\n if (this.pos + n > this.data.length) throw this.err('readView: Unexpected end of buffer');\n const res = fn(this.view, this.pos);\n this.markBytes(n);\n return res;\n }\n // read bytes by absolute offset\n absBytes(n: number): Uint8Array {\n if (n > this.data.length) throw new Error('Unexpected end of buffer');\n return this.data.subarray(n);\n }\n finish(): void {\n if (this.opts.allowUnreadBytes) return;\n if (this.bitPos) {\n throw this.err(\n `${this.bitPos} bits left after unpack: ${baseHex.encode(this.data.slice(this.pos))}`\n );\n }\n if (this.bs && !this.parent) {\n const notRead = Bitset.indices(this.bs, this.data.length, true);\n if (notRead.length) {\n const formatted = Bitset.range(notRead)\n .map(\n ({ pos, length }) =>\n `(${pos}/${length})[${baseHex.encode(this.data.subarray(pos, pos + length))}]`\n )\n .join(', ');\n throw this.err(`unread byte ranges: ${formatted} (total=${this.data.length})`);\n } else return; // all bytes read, everything is ok\n }\n // Default: no pointers enabled\n if (!this.isEnd()) {\n throw this.err(\n `${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${baseHex.encode(\n this.data.slice(this.pos)\n )}`\n );\n }\n }\n // User methods\n err(msg: string | Error): Error {\n return Path.err('Reader', this.stack, msg);\n }\n offsetReader(n: number): _Reader {\n if (n > this.data.length) throw this.err('offsetReader: Unexpected end of buffer');\n return new _Reader(this.absBytes(n), this.opts, this.stack, this, n);\n }\n bytes(n: number, peek = false): Uint8Array {\n if (this.bitPos) throw this.err('readBytes: bitPos not empty');\n if (!Number.isFinite(n)) throw this.err(`readBytes: wrong length=${n}`);\n if (this.pos + n > this.data.length) throw this.err('readBytes: Unexpected end of buffer');\n const slice = this.data.subarray(this.pos, this.pos + n);\n if (!peek) this.markBytes(n);\n return slice;\n }\n byte(peek = false): number {\n if (this.bitPos) throw this.err('readByte: bitPos not empty');\n if (this.pos + 1 > this.data.length) throw this.err('readBytes: Unexpected end of buffer');\n const data = this.data[this.pos];\n if (!peek) this.markBytes(1);\n return data;\n }\n get leftBytes(): number {\n return this.data.length - this.pos;\n }\n get totalBytes(): number {\n return this.data.length;\n }\n isEnd(): boolean {\n return this.pos >= this.data.length && !this.bitPos;\n }\n // bits are read in BE mode (left to right): (0b1000_0000).readBits(1) == 1\n bits(bits: number): number {\n if (bits > 32) throw this.err('BitReader: cannot read more than 32 bits in single call');\n let out = 0;\n while (bits) {\n if (!this.bitPos) {\n this.bitBuf = this.byte();\n this.bitPos = 8;\n }\n const take = Math.min(bits, this.bitPos);\n this.bitPos -= take;\n out = (out << take) | ((this.bitBuf >> this.bitPos) & (2 ** take - 1));\n this.bitBuf &= 2 ** this.bitPos - 1;\n bits -= take;\n }\n // Fix signed integers\n return out >>> 0;\n }\n find(needle: Bytes, pos: number = this.pos): number | undefined {\n if (!isBytes(needle)) throw this.err(`find: needle is not bytes! ${needle}`);\n if (this.bitPos) throw this.err('findByte: bitPos not empty');\n if (!needle.length) throw this.err(`find: needle is empty`);\n // indexOf should be faster than full equalBytes check\n for (let idx = pos; (idx = this.data.indexOf(needle[0], idx)) !== -1; idx++) {\n if (idx === -1) return;\n const leftBytes = this.data.length - idx;\n if (leftBytes < needle.length) return;\n if (equalBytes(needle, this.data.subarray(idx, idx + needle.length))) return idx;\n }\n return;\n }\n}\n\n/**\n * Internal structure. Writer class for writing to a byte array.\n * The `stack` argument of constructor is internal, for debugging and logs.\n * @class Writer\n */\nclass _Writer implements Writer {\n pos: number = 0;\n readonly stack: PathStack;\n // We could have a single buffer here and re-alloc it with\n // x1.5-2 size each time it full, but it will be slower:\n // basic/encode bench: 395ns -> 560ns\n private buffers: Bytes[] = [];\n ptrs: { pos: number; ptr: CoderType<number>; buffer: Bytes }[] = [];\n private bitBuf = 0;\n private bitPos = 0;\n private viewBuf = new Uint8Array(8);\n private view: DataView;\n private finished = false;\n constructor(stack: PathStack = []) {\n this.stack = stack;\n this.view = createView(this.viewBuf);\n }\n pushObj(obj: StructOut, objFn: _PathObjFn): void {\n return Path.pushObj(this.stack, obj, objFn);\n }\n writeView(len: number, fn: (view: DataView) => void): void {\n if (this.finished) throw this.err('buffer: finished');\n if (!isNum(len) || len > 8) throw new Error(`wrong writeView length=${len}`);\n fn(this.view);\n this.bytes(this.viewBuf.slice(0, len));\n this.viewBuf.fill(0);\n }\n // User methods\n err(msg: string | Error): Error {\n if (this.finished) throw this.err('buffer: finished');\n return Path.err('Reader', this.stack, msg);\n }\n bytes(b: Bytes): void {\n if (this.finished) throw this.err('buffer: finished');\n if (this.bitPos) throw this.err('writeBytes: ends with non-empty bit buffer');\n this.buffers.push(b);\n this.pos += b.length;\n }\n byte(b: number): void {\n if (this.finished) throw this.err('buffer: finished');\n if (this.bitPos) throw this.err('writeByte: ends with non-empty bit buffer');\n this.buffers.push(new Uint8Array([b]));\n this.pos++;\n }\n finish(clean = true): Bytes {\n if (this.finished) throw this.err('buffer: finished');\n if (this.bitPos) throw this.err('buffer: ends with non-empty bit buffer');\n // Can't use concatBytes, because it limits amount of arguments (65K).\n const buffers = this.buffers.concat(this.ptrs.map((i) => i.buffer));\n const sum = buffers.map((b) => b.length).reduce((a, b) => a + b, 0);\n const buf = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < buffers.length; i++) {\n const a = buffers[i];\n buf.set(a, pad);\n pad += a.length;\n }\n\n for (let pos = this.pos, i = 0; i < this.ptrs.length; i++) {\n const ptr = this.ptrs[i];\n buf.set(ptr.ptr.encode(pos), ptr.pos);\n pos += ptr.buffer.length;\n }\n // Cleanup\n if (clean) {\n // We cannot cleanup buffers here, since it can be static user provided buffer.\n // Only '.byte' and '.bits' create buffer which we can safely clean.\n // for (const b of this.buffers) b.fill(0);\n this.buffers = [];\n for (const p of this.ptrs) p.buffer.fill(0);\n this.ptrs = [];\n this.finished = true;\n this.bitBuf = 0;\n }\n return buf;\n }\n bits(value: number, bits: number): void {\n if (bits > 32) throw this.err('writeBits: cannot write more than 32 bits in single call');\n if (value >= 2 ** bits) throw this.err(`writeBits: value (${value}) >= 2**bits (${bits})`);\n while (bits) {\n const take = Math.min(bits, 8 - this.bitPos);\n this.bitBuf = (this.bitBuf << take) | (value >> (bits - take));\n this.bitPos += take;\n bits -= take;\n value &= 2 ** bits - 1;\n if (this.bitPos === 8) {\n this.bitPos = 0;\n this.buffers.push(new Uint8Array([this.bitBuf]));\n this.pos++;\n }\n }\n }\n}\n// Immutable LE<->BE\nconst swapEndianness = (b: Bytes): Bytes => Uint8Array.from(b).reverse();\n/** Internal function for checking bit bounds of bigint in signed/unsinged form */\nfunction checkBounds(value: bigint, bits: bigint, signed: boolean): void {\n if (signed) {\n // [-(2**(32-1)), 2**(32-1)-1]\n const signBit = 2n ** (bits - 1n);\n if (value < -signBit || value >= signBit)\n throw new Error(`value out of signed bounds. Expected ${-signBit} <= ${value} < ${signBit}`);\n } else {\n // [0, 2**32-1]\n if (0n > value || value >= 2n ** bits)\n throw new Error(`value out of unsigned bounds. Expected 0 <= ${value} < ${2n ** bits}`);\n }\n}\n\nfunction _wrap<T>(inner: BytesCoderStream<T>): CoderType<T> {\n return {\n // NOTE: we cannot export validate here, since it is likely mistake.\n encodeStream: inner.encodeStream,\n decodeStream: inner.decodeStream,\n size: inner.size,\n encode: (value: T): Bytes => {\n const w = new _Writer();\n inner.encodeStream(w, value);\n return w.finish();\n },\n decode: (data: Bytes, opts: ReaderOpts = {}): T => {\n const r = new _Reader(data, opts);\n const res = inner.decodeStream(r);\n r.finish();\n return res;\n },\n };\n}\n\n/**\n * Validates a value before encoding and after decoding using a provided function.\n * @param inner - The inner CoderType.\n * @param fn - The validation function.\n * @returns CoderType which check value with validation function.\n * @example\n * const val = (n: number) => {\n * if (n > 10) throw new Error(`${n} > 10`);\n * return n;\n * };\n *\n * const RangedInt = P.validate(P.U32LE, val); // Will check if value is <= 10 during encoding and decoding\n */\nexport function validate<T>(inner: CoderType<T>, fn: Validate<T>): CoderType<T> {\n if (!isCoder(inner)) throw new Error(`validate: invalid inner value ${inner}`);\n if (typeof fn !== 'function') throw new Error('validate: fn should be function');\n return _wrap({\n size: inner.size,\n encodeStream: (w: Writer, value: T) => {\n let res;\n try {\n res = fn(value);\n } catch (e) {\n throw w.err(e as Error);\n }\n inner.encodeStream(w, res);\n },\n decodeStream: (r: Reader): T => {\n const res = inner.decodeStream(r);\n try {\n return fn(res);\n } catch (e) {\n throw r.err(e as Error);\n }\n },\n });\n}\n\n/**\n * Wraps a stream encoder into a generic encoder and optionally validation function\n * @param {inner} inner BytesCoderStream & { validate?: Validate<T> }.\n * @returns The wrapped CoderType.\n * @example\n * const U8 = P.wrap({\n * encodeStream: (w: Writer, value: number) => w.byte(value),\n * decodeStream: (r: Reader): number => r.byte()\n * });\n * const checkedU8 = P.wrap({\n * encodeStream: (w: Writer, value: number) => w.byte(value),\n * decodeStream: (r: Reader): number => r.byte()\n * validate: (n: number) => {\n * if (n > 10) throw new Error(`${n} > 10`);\n * return n;\n * }\n * });\n */\nexport const wrap = <T>(inner: BytesCoderStream<T> & { validate?: Validate<T> }): CoderType<T> => {\n const res = _wrap(inner);\n return inner.validate ? validate(res, inner.validate) : res;\n};\n\nconst isBaseCoder = (elm: any) =>\n isPlainObject(elm) && typeof elm.decode === 'function' && typeof elm.encode === 'function';\n\n/**\n * Checks if the given value is a CoderType.\n * @param elm - The value to check.\n * @returns True if the value is a CoderType, false otherwise.\n */\nexport function isCoder<T>(elm: any): elm is CoderType<T> {\n return (\n isPlainObject(elm) &&\n isBaseCoder(elm) &&\n typeof elm.encodeStream === 'function' &&\n typeof elm.decodeStream === 'function' &&\n (elm.size === undefined || isNum(elm.size))\n );\n}\n\n// Coders (like in @scure/base) for common operations\n\n/**\n * Base coder for working with dictionaries (records, objects, key-value map)\n * Dictionary is dynamic type like: `[key: string, value: any][]`\n * @returns base coder that encodes/decodes between arrays of key-value tuples and dictionaries.\n * @example\n * const dict: P.CoderType<Record<string, number>> = P.apply(\n * P.array(P.U16BE, P.tuple([P.cstring, P.U32LE] as const)),\n * P.coders.dict()\n * );\n */\nfunction dict<T>(): BaseCoder<[string, T][], Record<string, T>> {\n return {\n encode: (from: [string, T][]): Record<string, T> => {\n if (!Array.isArray(from)) throw new Error('array expected');\n const to: Record<string, T> = {};\n for (const item of from) {\n if (!Array.isArray(item) || item.length !== 2)\n throw new Error(`array of two elements expected`);\n const name = item[0];\n const value = item[1];\n if (to[name] !== undefined) throw new Error(`key(${name}) appears twice in struct`);\n to[name] = value;\n }\n return to;\n },\n decode: (to: Record<string, T>): [string, T][] => {\n if (!isPlainObject(to)) throw new Error(`expected plain object, got ${to}`);\n return Object.entries(to);\n },\n };\n}\n/**\n * Safely converts bigint to number.\n * Sometimes pointers / tags use u64 or other big numbers which cannot be represented by number,\n * but we still can use them since real value will be smaller than u32\n */\nconst numberBigint: BaseCoder<bigint, number> = {\n encode: (from: bigint): number => {\n if (typeof from !== 'bigint') throw new Error(`expected bigint, got ${typeof from}`);\n if (from > BigInt(Number.MAX_SAFE_INTEGER))\n throw new Error(`element bigger than MAX_SAFE_INTEGER=${from}`);\n return Number(from);\n },\n decode: (to: number): bigint => {\n if (!isNum(to)) throw new Error('element is not a safe integer');\n return BigInt(to);\n },\n};\n// TODO: replace map with this?\ntype Enum = { [k: string]: number | string } & { [k: number]: string };\n// Doesn't return numeric keys, so it's fine\ntype EnumKeys<T extends Enum> = keyof T;\n/**\n * Base coder for working with TypeScript enums.\n * @param e - TypeScript enum.\n * @returns base coder that encodes/decodes between numbers and enum keys.\n * @example\n * enum Color { Red, Green, Blue }\n * const colorCoder = P.coders.tsEnum(Color);\n * colorCoder.encode(Color.Red); // 'Red'\n * colorCoder.decode('Green'); // 1\n */\nfunction tsEnum<T extends Enum>(e: T): BaseCoder<number, EnumKeys<T>> {\n if (!isPlainObject(e)) throw new Error('plain object expected');\n return {\n encode: (from: number): string => {\n if (!isNum(from) || !(from in e)) throw new Error(`wrong value ${from}`);\n return e[from];\n },\n decode: (to: string): number => {\n if (typeof to !== 'string') throw new Error(`wrong value ${typeof to}`);\n return e[to] as number;\n },\n };\n}\n/**\n * Base coder for working with decimal numbers.\n * @param precision - Number of decimal places.\n * @param round - Round fraction part if bigger than precision (throws error by default)\n * @returns base coder that encodes/decodes between bigints and decimal strings.\n * @example\n * const decimal8 = P.coders.decimal(8);\n * decimal8.encode(630880845n); // '6.30880845'\n * decimal8.decode('6.30880845'); // 630880845n\n */\nfunction decimal(precision: number, round = false): Coder<bigint, string> {\n if (!isNum(precision)) throw new Error(`decimal/precision: wrong value ${precision}`);\n if (typeof round !== 'boolean')\n throw new Error(`decimal/round: expected boolean, got ${typeof round}`);\n const decimalMask = 10n ** BigInt(precision);\n return {\n encode: (from: bigint): string => {\n if (typeof from !== 'bigint') throw new Error(`expected bigint, got ${typeof from}`);\n let s = (from < 0n ? -from : from).toString(10);\n let sep = s.length - precision;\n if (sep < 0) {\n s = s.padStart(s.length - sep, '0');\n sep = 0;\n }\n let i = s.length - 1;\n for (; i >= sep && s[i] === '0'; i--);\n let int = s.slice(0, sep);\n let frac = s.slice(sep, i + 1);\n if (!int) int = '0';\n if (from < 0n) int = '-' + int;\n if (!frac) return int;\n return `${int}.${frac}`;\n },\n decode: (to: string): bigint => {\n if (typeof to !== 'string') throw new Error(`expected string, got ${typeof to}`);\n if (to === '-0') throw new Error(`negative zero is not allowed`);\n let neg = false;\n if (to.startsWith('-')) {\n neg = true;\n to = to.slice(1);\n }\n if (!/^(0|[1-9]\\d*)(\\.\\d+)?$/.test(to)) throw new Error(`wrong string value=${to}`);\n let sep = to.indexOf('.');\n sep = sep === -1 ? to.length : sep;\n // split by separator and strip trailing zeros from fraction. always returns [string, string] (.split doesn't).\n const intS = to.slice(0, sep);\n const fracS = to.slice(sep + 1).replace(/0+$/, '');\n const int = BigInt(intS) * decimalMask;\n if (!round && fracS.length > precision) {\n throw new Error(\n `fractional part cannot be represented with this precision (num=${to}, prec=${precision})`\n );\n }\n const fracLen = Math.min(fracS.length, precision);\n const frac = BigInt(fracS.slice(0, fracLen)) * 10n ** BigInt(precision - fracLen);\n const value = int + frac;\n return neg ? -value : value;\n },\n };\n}\n\n// TODO: export from @scure/base?\ntype BaseInput<F> = F extends BaseCoder<infer T, any> ? T : never;\ntype BaseOutput<F> = F extends BaseCoder<any, infer T> ? T : never;\n\n/**\n * Combines multiple coders into a single coder, allowing conditional encoding/decoding based on input.\n * Acts as a parser combinator, splitting complex conditional coders into smaller parts.\n *\n * `encode = [Ae, Be]; decode = [Ad, Bd]`\n * ->\n * `match([{encode: Ae, decode: Ad}, {encode: Be; decode: Bd}])`\n *\n * @param lst - Array of coders to match.\n * @returns Combined coder for conditional encoding/decoding.\n */\nfunction match<\n L extends BaseCoder<unknown | undefined, unknown | undefined>[],\n I = { [K in keyof L]: NonNullable<BaseInput<L[K]>> }[number],\n O = { [K in keyof L]: NonNullable<BaseOutput<L[K]>> }[number],\n>(lst: L): BaseCoder<I, O> {\n if (!Array.isArray(lst)) throw new Error(`expected array, got ${typeof lst}`);\n for (const i of lst) if (!isBaseCoder(i)) throw new Error(`wrong base coder ${i}`);\n return {\n encode: (from: I): O => {\n for (const c of lst) {\n const elm = c.encode(from);\n if (elm !== undefined) return elm as O;\n }\n throw new Error(`match/encode: cannot find match in ${from}`);\n },\n decode: (to: O): I => {\n for (const c of lst) {\n const elm = c.decode(to);\n if (elm !== undefined) return elm as I;\n }\n throw new Error(`match/decode: cannot find match in ${to}`);\n },\n };\n}\n/** Reverses direction of coder */\nconst reverse = <F, T>(coder: Coder<F, T>): Coder<T, F> => {\n if (!isBaseCoder(coder)) throw new Error('BaseCoder expected');\n return { encode: coder.decode, decode: coder.encode };\n};\n\nexport const coders: {\n dict: typeof dict;\n numberBigint: BaseCoder<bigint, number>;\n tsEnum: typeof tsEnum;\n decimal: typeof decimal;\n match: typeof match;\n reverse: <F, T>(coder: Coder<F, T>) => Coder<T, F>;\n} = { dict, numberBigint, tsEnum, decimal, match, reverse };\n\n/**\n * CoderType for parsing individual bits.\n * NOTE: Structure should parse whole amount of bytes before it can start parsing byte-level elements.\n * @param len - Number of bits to parse.\n * @returns CoderType representing the parsed bits.\n * @example\n * const s = P.struct({ magic: P.bits(1), version: P.bits(1), tag: P.bits(4), len: P.bits(2) });\n */\nexport const bits = (len: number): CoderType<number> => {\n if (!isNum(len)) throw new Error(`bits: wrong length ${len} (${typeof len})`);\n return wrap({\n encodeStream: (w: Writer, value: number) => w.bits(value, len),\n decodeStream: (r: Reader): number => r.bits(len),\n validate: (value) => {\n if (!isNum(value)) throw new Error(`bits: wrong value ${value}`);\n return value;\n },\n });\n};\n\n/**\n * CoderType for working with bigint values.\n * Unsized bigint values should be wrapped in a container (e.g., bytes or string).\n *\n * `0n = Uint8Array.of()`\n *\n * `1n = new Uint8Array([1n])`\n *\n * Please open issue, if you need different behavior for zero.\n *\n * @param size - Size of the bigint in bytes.\n * @param le - Whether to use little-endian byte order.\n * @param signed - Whether the bigint is signed.\n * @param sized - Whether the bigint should have a fixed size.\n * @returns CoderType representing the bigint value.\n * @example\n * const U512BE = P.bigint(64, false, true, true); // Define a CoderType for a 512-bit unsigned big-endian integer\n */\nexport const bigint = (\n size: number,\n le = false,\n signed = false,\n sized = true\n): CoderType<bigint> => {\n if (!isNum(size)) throw new Error(`bigint/size: wrong value ${size}`);\n if (typeof le !== 'boolean') throw new Error(`bigint/le: expected boolean, got ${typeof le}`);\n if (typeof signed !== 'boolean')\n throw new Error(`bigint/signed: expected boolean, got ${typeof signed}`);\n if (typeof sized !== 'boolean')\n throw new Error(`bigint/sized: expected boolean, got ${typeof sized}`);\n const bLen = BigInt(size);\n const signBit = 2n ** (8n * bLen - 1n);\n return wrap({\n size: sized ? size : undefined,\n encodeStream: (w: Writer, value: bigint) => {\n if (signed && value < 0) value = value | signBit;\n const b = [];\n for (let i = 0; i < size; i++) {\n b.push(Number(value & 255n));\n value >>= 8n;\n }\n let res = new Uint8Array(b).reverse();\n if (!sized) {\n let pos = 0;\n for (pos = 0; pos < res.length; pos++) if (res[pos] !== 0) break;\n res = res.subarray(pos); // remove leading zeros\n }\n w.bytes(le ? res.reverse() : res);\n },\n decodeStream: (r: Reader): bigint => {\n // TODO: for le we can read until first zero?\n const value = r.bytes(sized ? size : Math.min(size, r.leftBytes));\n const b = le ? value : swapEndianness(value);\n let res = 0n;\n for (let i = 0; i < b.length; i++) res |= BigInt(b[i]) << (8n * BigInt(i));\n if (signed && res & signBit) res = (res ^ signBit) - signBit;\n return res;\n },\n validate: (value) => {\n if (typeof value !== 'bigint') throw new Error(`bigint: invalid value: ${value}`);\n checkBounds(value, 8n * bLen, !!signed);\n return value;\n },\n });\n};\n/** Unsigned 256-bit little-endian integer CoderType. */\nexport const U256LE: CoderType<bigint> = /* @__PURE__ */ bigint(32, true);\n/** Unsigned 256-bit big-endian integer CoderType. */\nexport const U256BE: CoderType<bigint> = /* @__PURE__ */ bigint(32, false);\n/** Signed 256-bit little-endian integer CoderType. */\nexport const I256LE: CoderType<bigint> = /* @__PURE__ */ bigint(32, true, true);\n/** Signed 256-bit big-endian integer CoderType. */\nexport const I256BE: CoderType<bigint> = /* @__PURE__ */ bigint(32, false, true);\n/** Unsigned 128-bit little-endian integer CoderType. */\nexport const U128LE: CoderType<bigint> = /* @__PURE__ */ bigint(16, true);\n/** Unsigned 128-bit big-endian integer CoderType. */\nexport const U128BE: CoderType<bigint> = /* @__PURE__ */ bigint(16, false);\n/** Signed 128-bit little-endian integer CoderType. */\nexport const I128LE: CoderType<bigint> = /* @__PURE__ */ bigint(16, true, true);\n/** Signed 128-bit big-endian integer CoderType. */\nexport const I128BE: CoderType<bigint> = /* @__PURE__ */ bigint(16, false, true);\n/** Unsigned 64-bit little-endian integer CoderType. */\nexport const U64LE: CoderType<bigint> = /* @__PURE__ */ bigint(8, true);\n/** Unsigned 64-bit big-endian integer CoderType. */\nexport const U64BE: CoderType<bigint> = /* @__PURE__ */ bigint(8, false);\n/** Signed 64-bit little-endian integer CoderType. */\nexport const I64LE: CoderType<bigint> = /* @__PURE__ */ bigint(8, true, true);\n/** Signed 64-bit big-endian integer CoderType. */\nexport const I64BE: CoderType<bigint> = /* @__PURE__ */ bigint(8, false, true);\n\n/**\n * CoderType for working with numbber values (up to 6 bytes/48 bits).\n * Unsized int values should be wrapped in a container (e.g., bytes or string).\n *\n * `0 = Uint8Array.of()`\n *\n * `1 = new Uint8Array([1n])`\n *\n * Please open issue, if you need different behavior for zero.\n *\n * @param size - Size of the number in bytes.\n * @param le - Whether to use little-endian byte order.\n * @param signed - Whether the number is signed.\n * @param sized - Whether the number should have a fixed size.\n * @returns CoderType representing the number value.\n * @example\n * const uint64BE = P.bigint(8, false, true); // Define a CoderType for a 64-bit unsigned big-endian integer\n */\nexport const int = (size: number, le = false, signed = false, sized = true): CoderType<number> => {\n if (!isNum(size)) throw new Error(`int/size: wrong value ${size}`);\n if (typeof le !== 'boolean') throw new Error(`int/le: expected boolean, got ${typeof le}`);\n if (typeof signed !== 'boolean')\n throw new Error(`int/signed: expected boolean, got ${typeof signed}`);\n if (typeof sized !== 'boolean')\n throw new Error(`int/sized: expected boolean, got ${typeof sized}`);\n if (size > 6) throw new Error('int supports size up to 6 bytes (48 bits): use bigints instead');\n return apply(bigint(size, le, signed, sized), coders.numberBigint);\n};\n\ntype ViewCoder = {\n read: (view: DataView, pos: number) => number;\n write: (view: DataView, value: number) => void;\n validate?: (value: number) => void;\n};\n\nconst view = (len: number, opts: ViewCoder) =>\n wrap({\n size: len,\n encodeStream: (w, value: number) =>\n (w as _Writer).writeView(len, (view) => opts.write(view, value)),\n decodeStream: (r) => (r as _Reader).readView(len, opts.read),\n validate: (value: number) => {\n if (typeof value !== 'number')\n throw new Error(`viewCoder: expected number, got ${typeof value}`);\n if (opts.validate) opts.validate(value);\n return value;\n },\n });\n\nconst intView = (len: number, signed: boolean, opts: ViewCoder) => {\n const bits = len * 8;\n const signBit = 2 ** (bits - 1);\n // Inlined checkBounds for integer\n const validateSigned = (value: number) => {\n if (!isNum(value)) throw new Error(`sintView: value is not safe integer: ${value}`);\n if (value < -signBit || value >= signBit) {\n throw new Error(\n `sintView: value out of bounds. Expected ${-signBit} <= ${value} < ${signBit}`\n );\n }\n };\n const maxVal = 2 ** bits;\n const validateUnsigned = (value: number) => {\n if (!isNum(value)) throw new Error(`uintView: value is not safe integer: ${value}`);\n if (0 > value || value >= maxVal) {\n throw new Error(`uintView: value out of bounds. Expected 0 <= ${value} < ${maxVal}`);\n }\n };\n return view(len, {\n write: opts.write,\n read: opts.read,\n validate: signed ? validateSigned : validateUnsigned,\n });\n};\n\n/** Unsigned 32-bit little-endian integer CoderType. */\nexport const U32LE: CoderType<number> = /* @__PURE__ */ intView(4, false, {\n read: (view, pos) => view.getUint32(pos, true),\n write: (view, value) => view.setUint32(0, value, true),\n});\n/** Unsigned 32-bit big-endian integer CoderType. */\nexport const U32BE: CoderType<number> = /* @__PURE__ */ intView(4, false, {\n read: (view, pos) => view.getUint32(pos, false),\n write: (view, value) => view.setUint32(0, value, false),\n});\n/** Signed 32-bit little-endian integer CoderType. */\nexport const I32LE: CoderType<number> = /* @__PURE__ */ intView(4, true, {\n read: (view, pos) => view.getInt32(pos, true),\n write: (view, value) => view.setInt32(0, value, true),\n});\n/** Signed 32-bit big-endian integer CoderType. */\nexport const I32BE: CoderType<number> = /* @__PURE__ */ intView(4, true, {\n read: (view, pos) => view.getInt32(pos, false),\n write: (view, value) => view.setInt32(0, value, false),\n});\n/** Unsigned 16-bit little-endian integer CoderType. */\nexport const U16LE: CoderType<number> = /* @__PURE__ */ intView(2, false, {\n read: (view, pos) => view.getUint16(pos, true),\n write: (view, value) => view.setUint16(0, value, true),\n});\n/** Unsigned 16-bit big-endian integer CoderType. */\nexport const U16BE: CoderType<number> = /* @__PURE__ */ intView(2, false, {\n read: (view, pos) => view.getUint16(pos, false),\n write: (view, value) => view.setUint16(0, value, false),\n});\n/** Signed 16-bit little-endian integer CoderType. */\nexport const I16LE: CoderType<number> = /* @__PURE__ */ intView(2, true, {\n read: (view, pos) => view.getInt16(pos, true),\n write: (view, value) => view.setInt16(0, value, true),\n});\n/** Signed 16-bit big-endian integer CoderType. */\nexport const I16BE: CoderType<number> = /* @__PURE__ */ intView(2, true, {\n read: (view, pos) => view.getInt16(pos, false),\n write: (view, value) => view.setInt16(0, value, false),\n});\n/** Unsigned 8-bit integer CoderType. */\nexport const U8: CoderType<number> = /* @__PURE__ */ intView(1, false, {\n read: (view, pos) => view.getUint8(pos),\n write: (view, value) => view.setUint8(0, value),\n});\n/** Signed 8-bit integer CoderType. */\nexport const I8: CoderType<number> = /* @__PURE__ */ intView(1, true, {\n read: (view, pos) => view.getInt8(pos),\n write: (view, value) => view.setInt8(0, value),\n});\n\n// Floats\nconst f32 = (le?: boolean) =>\n view(4, {\n read: (view, pos) => view.getFloat32(pos, le),\n write: (view, value) => view.setFloat32(0, value, le),\n validate: (value) => {\n if (Math.fround(value) !== value && !Number.isNaN(value))\n throw new Error(`f32: wrong value=${value}`);\n },\n });\nconst f64 = (le?: boolean) =>\n view(8, {\n read: (view, pos) => view.getFloat64(pos, le),\n write: (view, value) => view.setFloat64(0, value, le),\n });\n\n/** 32-bit big-endian floating point CoderType (\"binary32\", IEEE 754-2008). */\nexport const F32BE: CoderType<number> = /* @__PURE__ */ f32(false);\n/** 32-bit little-endian floating point CoderType (\"binary32\", IEEE 754-2008). */\nexport const F32LE: CoderType<number> = /* @__PURE__ */ f32(true);\n/** A 64-bit big-endian floating point type (\"binary64\", IEEE 754-2008). Any JS number can be encoded. */\nexport const F64BE: CoderType<number> = /* @__PURE__ */ f64(false);\n/** A 64-bit little-endian floating point type (\"binary64\", IEEE 754-2008). Any JS number can be encoded. */\nexport const F64LE: CoderType<number> = /* @__PURE__ */ f64(true);\n\n/** Boolean CoderType. */\nexport const bool: CoderType<boolean> = /* @__PURE__ */ wrap({\n size: 1,\n encodeStream: (w: Writer, value: boolean) => w.byte(value ? 1 : 0),\n decodeStream: (r: Reader): boolean => {\n const value = r.byte();\n if (value !== 0 && value !== 1) throw r.err(`bool: invalid value ${value}`);\n return value === 1;\n },\n validate: (value) => {\n if (typeof value !== 'boolean') throw new Error(`bool: invalid value ${value}`);\n return value;\n },\n});\n\n/**\n * Bytes CoderType with a specified length and endianness.\n * The bytes can have:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - CoderType, number, Uint8Array (terminator) or null\n * @param le - Whether to use little-endian byte order.\n * @returns CoderType representing the bytes.\n * @example\n * // Dynamic size bytes (prefixed with P.U16BE number of bytes length)\n * const dynamicBytes = P.bytes(P.U16BE, false);\n * const fixedBytes = P.bytes(32, false); // Fixed size bytes\n * const unknownBytes = P.bytes(null, false); // Unknown size bytes, will parse until end of buffer\n * const zeroTerminatedBytes = P.bytes(Uint8Array.of(0), false); // Zero-terminated bytes\n */\nconst createBytes = (len: Length, le = false): CoderType<Bytes> => {\n if (typeof le !== 'boolean') throw new Error(`bytes/le: expected boolean, got ${typeof le}`);\n const _length = lengthCoder(len);\n const _isb = isBytes(len);\n return wrap({\n size: typeof len === 'number' ? len : undefined,\n encodeStream: (w: Writer, value: Bytes) => {\n if (!_isb) _length.encodeStream(w, value.length);\n w.bytes(le ? swapEndianness(value) : value);\n if (_isb) w.bytes(len);\n },\n decodeStream: (r: Reader): Bytes => {\n let bytes: Bytes;\n if (_isb) {\n const tPos = r.find(len);\n if (!tPos) throw r.err(`bytes: cannot find terminator`);\n bytes = r.bytes(tPos - r.pos);\n r.bytes(len.length);\n } else {\n bytes = r.bytes(len === null ? r.leftBytes : _length.decodeStream(r));\n }\n return le ? swapEndianness(bytes) : bytes;\n },\n validate: (value) => {\n if (!isBytes(value)) throw new Error(`bytes: invalid value ${value}`);\n return value;\n },\n });\n};\n\nexport { createBytes as bytes, createHex as hex };\n\n/**\n * Prefix-encoded value using a length prefix and an inner CoderType.\n * The prefix can have:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - Length CoderType (dynamic size), number (fixed size), Uint8Array (for terminator), or null (will parse until end of buffer)\n * @param inner - CoderType for the actual value to be prefix-encoded.\n * @returns CoderType representing the prefix-encoded value.\n * @example\n * const dynamicPrefix = P.prefix(P.U16BE, P.bytes(null)); // Dynamic size prefix (prefixed with P.U16BE number of bytes length)\n * const fixedPrefix = P.prefix(10, P.bytes(null)); // Fixed size prefix (always 10 bytes)\n */\nexport function prefix<T>(len: Length, inner: CoderType<T>): CoderType<T> {\n if (!isCoder(inner)) throw new Error(`prefix: invalid inner value ${inner}`);\n return apply(createBytes(len), reverse(inner)) as CoderType<T>;\n}\n\n/**\n * String CoderType with a specified length and endianness.\n * The string can be:\n * - Dynamic size (prefixed with a length CoderType like U16BE)\n * - Fixed size (specified by a number)\n * - Unknown size (null, will parse until end of buffer)\n * - Zero-terminated (terminator can be any Uint8Array)\n * @param len - Length CoderType (dynamic size), number (fixed size), Uint8Array (for terminator), or null (will parse until end of buffer)\n * @param le - Whether to use little-endian byte order.\n * @returns CoderType representing the string.\n * @example\n * const dynamicString = P.string(P.U16BE, false); // Dynamic size string (prefixed with P.U16BE number of string length)\n * const fixedString = P.string(10, false); // Fixed size string\n * const unknownString = P.string(null, false); // Unknown size string, will parse until end of buffer\n * const nullTerminatedString = P.cstring; // NUL-terminated string\n * const _cstring = P.string(Uint8Array.of(0)); // Same thing\n */\nexport const string = (len: Length, le = false): CoderType<string> =>\n validate(apply(createBytes(len, le), utf8), (value) => {\n // TextEncoder/TextDecoder will fail on non-string, but we create more readable errors earlier\n if (typeof value !== 'string') throw new Error(`expected string, got ${typeof value}`);\n return value;\n });\n\n/** NUL-terminated string CoderType. */\nexport const cstring: CoderType<string> = /* @__PURE__ */ string(NULL);\n\ntype HexOpts = { isLE?: boolean; with0x?: boolean };\n/**\n * Hexadecimal string CoderType with a specified length, endianness, and optional 0x prefix.\n * @param len - Length CoderType (dynamic size), number (fixed size), Uint8Array (for terminator), or null (will parse until end of buffer)\n * @param le - Whether to use little-endian byte order.\n * @param withZero - Whether to include the 0x prefix.\n * @returns CoderType representing the hexadecimal string.\n * @example\n * const dynamicHex = P.hex(P.U16BE, {isLE: false, with0x: true}); // Hex string with 0x prefix and U16BE length\n * const fixedHex = P.hex(32, {isLE: false, with0x: false}); // Fixed-length 32-byte hex string without 0x prefix\n */\nconst createHex = (\n len: Length,\n options: HexOpts = { isLE: false, with0x: false }\n): CoderType<string> => {\n let inner = apply(createBytes(len, options.isLE), baseHex);\n const prefix = options.with0x;\n if (typeof prefix !== 'boolean')\n throw new Error(`hex/with0x: expected boolean, got ${typeof prefix}`);\n if (prefix) {\n inner = apply(inner, {\n encode: (value) => `0x${value}`,\n decode: (value) => {\n if (!value.startsWith('0x'))\n throw new Error('hex(with0x=true).encode input should start with 0x');\n return value.slice(2);\n },\n });\n }\n return inner;\n};\n\n/**\n * Applies a base coder to a CoderType.\n * @param inner - The inner CoderType.\n * @param b - The base coder to apply.\n * @returns CoderType representing the transformed value.\n * @example\n * import { hex } from '@scure/base';\n * const hex = P.apply(P.bytes(32), hex); // will decode bytes into a hex string\n */\nexport function apply<T, F>(inner: CoderType<T>, base: BaseCoder<T, F>): CoderType<F> {\n if (!isCoder(inner)) throw new Error(`apply: invalid inner value ${inner}`);\n if (!isBaseCoder(base)) throw new Error(`apply: invalid base value ${inner}`);\n return wrap({\n size: inner.size,\n encodeStream: (w: Writer, value: F) => {\n let innerValue;\n try {\n innerValue = base.decode(value);\n } catch (e) {\n throw w.err('' + e);\n }\n return inner.encodeStream(w, innerValue);\n },\n decodeStream: (r: Reader): F => {\n const innerValue = inner.decodeStream(r);\n try {\n return base.encode(innerValue);\n } catch (e) {\n throw r.err('' + e);\n }\n },\n });\n}\n\n/**\n * Lazy CoderType that is evaluated at runtime.\n * @param fn - A function that returns the CoderType.\n * @returns CoderType representing the lazy value.\n * @example\n * type Tree = { name: string; children: Tree[] };\n * const tree = P.struct({\n * name: P.cstring,\n * children: P.array(\n * P.U16BE,\n * P.lazy((): P.CoderType<Tree> => tree)\n * ),\n * });\n */\nexport function lazy<T>(fn: () => CoderType<T>): CoderType<T> {\n if (typeof fn !== 'function') throw new Error(`lazy: expected function, got ${typeof fn}`);\n return wrap({\n encodeStream: (w: Writer, value: T) => fn().encodeStream(w, value),\n decodeStream: (r: Reader): T => fn().decodeStream(r),\n });\n}\n\n/**\n * Flag CoderType that encodes/decodes a boolean value based on the presence of a marker.\n * @param flagValue - Marker value.\n * @param xor - Whether to invert the flag behavior.\n * @returns CoderType representing the flag value.\n * @example\n * const flag = P.flag(new Uint8Array([0x01, 0x02])); // Encodes true as u8a([0x01, 0x02]), false as u8a([])\n * const flagXor = P.flag(new Uint8Array([0x01, 0x02]), true); // Encodes true as u8a([]), false as u8a([0x01, 0x02])\n * // Conditional encoding with flagged\n * const s = P.struct({ f: P.flag(new Uint8Array([0x0, 0x1])), f2: P.flagged('f', P.U32BE) });\n */\nexport const flag = (flagValue: Bytes, xor = false): CoderType<boolean | undefined> => {\n if (!isBytes(flagValue))\n throw new Error(`flag/flagValue: expected Uint8Array, got ${typeof flagValue}`);\n if (typeof xor !== 'boolean') throw new Error(`flag/xor: expected boolean, got ${typeof xor}`);\n return wrap({\n size: flagValue.length,\n encodeStream: (w: Writer, value: boolean | undefined) => {\n if (!!value !== xor) w.bytes(flagValue);\n },\n decodeStream: (r: Reader): boolean | undefined => {\n let hasFlag = r.leftBytes >= flagValue.length;\n if (hasFlag) {\n hasFlag = equalBytes(r.bytes(flagValue.length, true), flagValue);\n // Found flag, advance cursor position\n if (hasFlag) r.bytes(flagValue.length);\n }\n return hasFlag !== xor; // hasFlag ^ xor\n },\n validate: (value) => {\n if (value !== undefined && typeof value !== 'boolean')\n throw new Error(`flag: expected boolean value or undefined, got ${typeof value}`);\n return value;\n },\n });\n};\n\n/**\n * Conditional CoderType that encodes/decodes a value only if a flag is present.\n * @param path - Path to the flag value or a CoderType for the flag.\n * @param inner - Inner CoderType for the value.\n * @param def - Optional default value to use if the flag is not present.\n * @returns CoderType representing the conditional value.\n * @example\n * const s = P.struct({\n * f: P.flag(new Uint8Array([0x0, 0x1])),\n * f2: P.flagged('f', P.U32BE)\n * });\n *\n * @example\n * const s2 = P.struct({\n * f: P.flag(new Uint8Array([0x0, 0x1])),\n * f2: P.flagged('f', P.U32BE, 123)\n * });\n */\nexport function flagged<T>(\n path: string | CoderType<boolean>,\n inner: CoderType<T>,\n def?: T\n): CoderType<Option<T>> {\n if (!isCoder(inner)) throw new Error(`flagged: invalid inner value ${inner}`);\n if (typeof path !== 'string' && !isCoder(inner)) throw new Error(`flagged: wrong path=${path}`);\n return wrap({\n encodeStream: (w: Writer, value: Option<T>) => {\n if (typeof path === 'string') {\n if (Path.resolve((w as _Writer).stack, path)) inner.encodeStream(w, value);\n else if (def) inner.encodeStream(w, def);\n } else {\n path.encodeStream(w, !!value);\n if (!!value) inner.encodeStream(w, value);\n else if (def) inner.encodeStream(w, def);\n }\n },\n decodeStream: (r: Reader): Option<T> => {\n let hasFlag = false;\n if (typeof path === 'string') hasFlag = !!Path.resolve((r as _Reader).stack, path);\n else hasFlag = path.decodeStream(r);\n // If there is a flag -- decode and return value\n if (hasFlag) return inner.decodeStream(r);\n else if (def) inner.decodeStream(r);\n return;\n },\n });\n}\n/**\n * Optional CoderType that encodes/decodes a value based on a flag.\n * @param flag - CoderType for the flag value.\n * @param inner - Inner CoderType for the value.\n * @param def - Optional default value to use if the flag is not present.\n * @returns CoderType representing the optional value.\n * @example\n * // Will decode into P.U32BE only if flag present\n * const optional = P.optional(P.flag(new Uint8Array([0x0, 0x1])), P.U32BE);\n *\n * @example\n * // If no flag present, will decode into default value\n * const optionalWithDefault = P.optional(P.flag(new Uint8Array([0x0, 0x1])), P.U32BE, 123);\n */\nexport function optional<T>(\n flag: CoderType<boolean>,\n inner: CoderType<T>,\n def?: T\n): CoderType<Option<T>> {\n if (!isCoder(flag) || !isCoder(inner))\n throw new Error(`optional: invalid flag or inner value flag=${flag} inner=${inner}`);\n return wrap({\n size: def !== undefined && flag.size && inner.size ? flag.size + inner.size : undefined,\n encodeStream: (w: Writer, value: Option<T>) => {\n flag.encodeStream(w, !!value);\n if (value) inner.encodeStream(w, value);\n else if (def !== undefined) inner.encodeStream(w, def);\n },\n decodeStream: (r: Reader): Option<T> => {\n if (flag.decodeStream(r)) return inner.decodeStream(r);\n else if (def !== undefined) inner.decodeStream(r);\n return;\n },\n });\n}\n/**\n * Magic value CoderType that encodes/decodes a constant value.\n * This can be used to check for a specific magic value or sequence of bytes at the beginning of a data structure.\n * @param inner - Inner CoderType for the value.\n * @param constant - Constant value.\n * @param check - Whether to check the decoded value against the constant.\n * @returns CoderType representing the magic value.\n * @example\n * // Always encodes constant as bytes using inner CoderType, throws if encoded value is not present\n * const magicU8 = P.magic(P.U8, 0x42);\n */\nexport function magic<T>(inner: CoderType<T>, constant: T, check = true): CoderType<undefined> {\n if (!isCoder(inner)) throw new Error(`magic: invalid inner value ${inner}`);\n if (typeof check !== 'boolean') throw new Error(`magic: expected boolean, got ${typeof check}`);\n return wrap({\n size: inner.size,\n encodeStream: (w: Writer, _value: undefined) => inner.encodeStream(w, constant),\n decodeStream: (r: Reader): undefined => {\n const value = inner.decodeStream(r);\n if (\n (check && typeof value !== 'object' && value !== constant) ||\n (isBytes(constant) && !equalBytes(constant, value as any))\n ) {\n throw r.err(`magic: invalid value: ${value} !== ${constant}`);\n }\n return;\n },\n validate: (value) => {\n if (value !== undefined) throw new Error(`magic: wrong value=${typeof value}`);\n return value;\n },\n });\n}\n/**\n * Magic bytes CoderType that encodes/decodes a constant byte array or string.\n * @param constant - Constant byte array or string.\n * @returns CoderType representing the magic bytes.\n * @example\n * // Always encodes undefined into byte representation of string 'MAGIC'\n * const magicBytes = P.magicBytes('MAGIC');\n */\nexport const magicBytes = (constant: Bytes | string): CoderType<undefined> => {\n const c = typeof constant === 'string' ? utf8.decode(constant) : constant;\n return magic(createBytes(c.length), c);\n};\n\n/**\n * Creates a CoderType for a constant value. The function enforces this value during encoding,\n * ensuring it matches the provided constant. During decoding, it always returns the constant value.\n * The actual value is not written to or read from any byte stream; it's used only for validation.\n *\n * @param c - Constant value.\n * @returns CoderType representing the constant value.\n * @example\n * // Always return 123 on decode, throws on encoding anything other than 123\n * const constantU8 = P.constant(123);\n */\nexport function constant<T>(c: T): CoderType<T> {\n return wrap({\n encodeStream: (_w: Writer, value: T) => {\n if (value !== c) throw new Error(`constant: invalid value ${value} (exp: ${c})`);\n },\n decodeStream: (_r: Reader): T => c,\n });\n}\n\nfunction sizeof(fields: CoderType<any>[]): Option<number> {\n let size: Option<number> = 0;\n for (const f of fields) {\n if (f.size === undefined) return;\n if (!isNum(f.size)) throw new Error(`sizeof: wrong element size=${size}`);\n size += f.size;\n }\n return size;\n}\n/**\n * Structure of composable primitives (C/Rust struct)\n * @param fields - Object mapping field names to CoderTypes.\n * @returns CoderType representing the structure.\n * @example\n * // Define a structure with a 32-bit big-endian unsigned integer, a string, and a nested structure\n * const myStruct = P.struct({\n * id: P.U32BE,\n * name: P.string(P.U8),\n * nested: P.struct({\n * flag: P.bool,\n * value: P.I16LE\n * })\n * });\n */\nexport function struct<T extends Record<string, any>>(\n fields: StructRecord<T>\n): CoderType<StructInput<T>> {\n if (!isPlainObject(fields)) throw new Error(`struct: expected plain object, got ${fields}`);\n for (const name in fields) {\n if (!isCoder(fields[name])) throw new Error(`struct: field ${name} is not CoderType`);\n }\n return wrap({\n size: sizeof(Object.values(fields)),\n encodeStream: (w: Writer, value: StructInput<T>) => {\n (w as _Writer).pushObj(value, (fieldFn) => {\n for (const name in fields)\n fieldFn(name, () => fields[name].encodeStream(w, (value as T)[name]));\n });\n },\n decodeStream: (r: Reader): StructInput<T> => {\n const res: Partial<T> = {};\n (r as _Reader).pushObj(res, (fieldFn) => {\n for (const name in fields) fieldFn(name, () => (res[name] = fields[name].decodeStream(r)));\n });\n return res as T;\n },\n validate: (value) => {\n if (typeof value !== 'object' || value === null)\n throw new Error(`struct: invalid value ${value}`);\n return value;\n },\n });\n}\n/**\n * Tuple (unnamed structure) of CoderTypes. Same as struct but with unnamed fields.\n * @param fields - Array of CoderTypes.\n * @returns CoderType representing the tuple.\n * @example\n * const myTuple = P.tuple([P.U8, P.U16LE, P.string(P.U8)]);\n */\nexport function tuple<\n T extends ArrLike<CoderType<any>>,\n O = Writable<{ [K in keyof T]: UnwrapCoder<T[K]> }>,\n>(fields: T): CoderType<O> {\n if (!Array.isArray(fields))\n throw new Error(`Packed.Tuple: got ${typeof fields} instead of array`);\n for (let i = 0; i < fields.length; i++) {\n if (!isCoder(fields[i])) throw new Error(`tuple: field ${i} is not CoderType`);\n }\n return wrap({\n size: sizeof(fields),\n encodeStream: (w: Writer, value: O) => {\n // TODO: fix types\n if (!Array.isArray(value)) throw w.err(`tuple: invalid value ${value}`);\n (w as _Writer).pushObj(value, (fieldFn) => {\n for (let i = 0; i < fields.length; i++)\n fieldFn(`${i}`, () => fields[i].encodeStream(w, value[i]));\n });\n },\n decodeStream: (r: Reader): O => {\n const res: any = [];\n (r as _Reader).pushObj(res, (fieldFn) => {\n for (let i = 0; i < fields.length; i++)\n fieldFn(`${i}`, () => res.push(fields[i].decodeStream(r)));\n });\n return res;\n },\n validate: (value) => {\n if (!Array.isArray(value)) throw new Error(`tuple: invalid value ${value}`);\n if (value.length !== fields.length)\n throw new Error(`tuple: wrong length=${value.length}, expected ${fields.length}`);\n return value;\n },\n });\n}\n\n/**\n * Array of items (inner type) with a specified length.\n * @param len - Length CoderType (dynamic size), number (fixed size), Uint8Array (for terminator), or null (will parse until end of buffer)\n * @param inner - CoderType for encoding/decoding each array item.\n * @returns CoderType representing the array.\n * @example\n * const a1 = P.array(P.U16BE, child); // Dynamic size array (prefixed with P.U16BE number of array length)\n * const a2 = P.array(4, child); // Fixed size array\n * const a3 = P.array(null, child); // Unknown size array, will parse until end of buffer\n * const a4 = P.array(Uint8Array.of(0), child); // zero-terminated array (NOTE: terminator can be any buffer)\n */\nexport function array<T>(len: Length, inner: CoderType<T>): CoderType<T[]> {\n if (!isCoder(inner)) throw new Error(`array: invalid inner value ${inner}`);\n // By construction length is inside array (otherwise there will be various incorrect stack states)\n // But forcing users always write '..' seems like bad idea. Also, breaking change.\n const _length = lengthCoder(typeof len === 'string' ? `../${len}` : len);\n return wrap({\n size: typeof len === 'number' && inner.size ? len * inner.size : undefined,\n encodeStream: (w: Writer, value: T[]) => {\n const _w = w as _Writer;\n _w.pushObj(value, (fieldFn) => {\n if (!isBytes(len)) _length.encodeStream(w, value.length);\n for (let i = 0; i < value.length; i++) {\n fieldFn(`${i}`, () => {\n const elm = value[i];\n const startPos = (w as _Writer).pos;\n inner.encodeStream(w, elm);\n if (isBytes(len)) {\n // Terminator is bigger than elm size, so skip\n if (len.length > _w.pos - startPos) return;\n const data = _w.finish(false).subarray(startPos, _w.pos);\n // There is still possible case when multiple elements create terminator,\n // but it is hard to catch here, will be very slow\n if (equalBytes(data.subarray(0, len.length), len))\n throw _w.err(\n `array: inner element encoding same as separator. elm=${elm} data=${data}`\n );\n }\n });\n }\n });\n if (isBytes(len)) w.bytes(len);\n },\n decodeStream: (r: Reader): T[] => {\n const res: T[] = [];\n (r as _Reader).pushObj(res, (fieldFn) => {\n if (len === null) {\n for (let i = 0; !r.isEnd(); i++) {\n fieldFn(`${i}`, () => res.push(inner.decodeStream(r)));\n if (inner.size && r.leftBytes < inner.size) break;\n }\n } else if (isBytes(len)) {\n for (let i = 0; ; i++) {\n if (equalBytes(r.bytes(len.length, true), len)) {\n // Advance cursor position if terminator found\n r.bytes(len.length);\n break;\n }\n fieldFn(`${i}`, () => res.push(inner.decodeStream(r)));\n }\n } else {\n let length: number;\n fieldFn('arrayLen', () => (length = _length.decodeStream(r)));\n for (let i = 0; i < length!; i++) fieldFn(`${i}`, () => res.push(inner.decodeStream(r)));\n }\n });\n return res;\n },\n validate: (value) => {\n if (!Array.isArray(value)) throw new Error(`array: invalid value ${value}`);\n return value;\n },\n });\n}\n/**\n * Mapping between encoded values and string representations.\n * @param inner - CoderType for encoded values.\n * @param variants - Object mapping string representations to encoded values.\n * @returns CoderType representing the mapping.\n * @example\n * // Map between numbers and strings\n * const numberMap = P.map(P.U8, {\n * 'one': 1,\n * 'two': 2,\n * 'three': 3\n * });\n *\n * // Map between byte arrays and strings\n * const byteMap = P.map(P.bytes(2, false), {\n * 'ab': Uint8Array.from([0x61, 0x62]),\n * 'cd': Uint8Array.from([0x63, 0x64])\n * });\n */\nexport function map<T>(inner: CoderType<T>, variants: Record<string, T>): CoderType<string> {\n if (!isCoder(inner)) throw new Error(`map: invalid inner value ${inner}`);\n if (!isPlainObject(variants)) throw new Error(`map: variants should be plain object`);\n const variantNames: Map<T, string> = new Map();\n for (const k in variants) variantNames.set(variants[k], k);\n return wrap({\n size: inner.size,\n encodeStream: (w: Writer, value: string) => inner.encodeStream(w, variants[value]),\n decodeStream: (r: Reader): string => {\n const variant = inner.decodeStream(r);\n const name = variantNames.get(variant);\n if (name === undefined)\n throw r.err(`Enum: unknown value: ${variant} ${Array.from(variantNames.keys())}`);\n return name;\n },\n validate: (value) => {\n if (typeof value !== 'string') throw new Error(`map: invalid value ${value}`);\n if (!(value in variants)) throw new Error(`Map: unknown variant: ${value}`);\n return value;\n },\n });\n}\n/**\n * Tagged union of CoderTypes, where the tag value determines which CoderType to use.\n * The decoded value will have the structure `{ TAG: number, data: ... }`.\n * @param tag - CoderType for the tag value.\n * @param variants - Object mapping tag values to CoderTypes.\n * @returns CoderType representing the tagged union.\n * @example\n * // Tagged union of array, string, and number\n * // Depending on the value of the first byte, it will be decoded as an array, string, or number.\n * const taggedUnion = P.tag(P.U8, {\n * 0x01: P.array(P.U16LE, P.U8),\n * 0x02: P.string(P.U8),\n * 0x03: P.U32BE\n * });\n *\n * const encoded = taggedUnion.encode({ TAG: 0x01, data: 'hello' }); // Encodes the string 'hello' with tag 0x01\n * const decoded = taggedUnion.decode(encoded); // Decodes the encoded value back to { TAG: 0x01, data: 'hello' }\n */\nexport function tag<\n T extends Values<{\n [P in keyof Variants]: { TAG: P; data: UnwrapCoder<Variants[P]> };\n }>,\n TagValue extends string | number,\n Variants extends Record<TagValue, CoderType<any>>,\n>(tag: CoderType<TagValue>, variants: Variants): CoderType<T> {\n if (!isCoder(tag)) throw new Error(`tag: invalid tag value ${tag}`);\n if (!isPlainObject(variants)) throw new Error(`tag: variants should be plain object`);\n for (const name in variants) {\n if (!isCoder(variants[name])) throw new Error(`tag: variant ${name} is not CoderType`);\n }\n return wrap({\n size: tag.size,\n encodeStream: (w: Writer, value: T) => {\n const { TAG, data } = value;\n const dataType = variants[TAG];\n tag.encodeStream(w, TAG as any);\n dataType.encodeStream(w, data);\n },\n decodeStream: (r: Reader): T => {\n const TAG = tag.decodeStream(r);\n const dataType = variants[TAG];\n if (!dataType) throw r.err(`Tag: invalid tag ${TAG}`);\n return { TAG, data: dataType.decodeStream(r) } as any;\n },\n validate: (value) => {\n const { TAG } = value;\n const dataType = variants[TAG];\n if (!dataType) throw new Error(`Tag: invalid tag ${TAG.toString()}`);\n return value;\n },\n });\n}\n\n/**\n * Mapping between encoded values, string representations, and CoderTypes using a tag CoderType.\n * @param tagCoder - CoderType for the tag value.\n * @param variants - Object mapping string representations to [tag value, CoderType] pairs.\n * * @returns CoderType representing the mapping.\n * @example\n * const cborValue: P.CoderType<CborValue> = P.mappedTag(P.bits(3), {\n * uint: [0, cborUint], // An unsigned integer in the range 0..264-1 inclusive.\n * negint: [1, cborNegint], // A negative integer in the range -264..-1 inclusive\n * bytes: [2, P.lazy(() => cborLength(P.bytes, cborValue))], // A byte string.\n * string: [3, P.lazy(() => cborLength(P.string, cborValue))], // A text string (utf8)\n * array: [4, cborArrLength(P.lazy(() => cborValue))], // An array of data items\n * map: [5, P.lazy(() => cborArrLength(P.tuple([cborValue, cborValue])))], // A map of pairs of data items\n * tag: [6, P.tuple([cborUint, P.lazy(() => cborValue)] as const)], // A tagged data item (\"tag\") whose tag number\n * simple: [7, cborSimple], // Floating-point numbers and simple values, as well as the \"break\" stop code\n * });\n */\nexport function mappedTag<\n T extends Values<{\n [P in keyof Variants]: { TAG: P; data: UnwrapCoder<Variants[P][1]> };\n }>,\n TagValue extends string | number,\n Variants extends Record<string, [TagValue, CoderType<any>]>,\n>(tagCoder: CoderType<TagValue>, variants: Variants): CoderType<T> {\n if (!isCoder(tagCoder)) throw new Error(`mappedTag: invalid tag value ${tag}`);\n if (!isPlainObject(variants)) throw new Error(`mappedTag: variants should be plain object`);\n const mapValue: Record<string, TagValue> = {};\n const tagValue: Record<string, CoderType<any>> = {};\n for (const key in variants) {\n const v = variants[key];\n mapValue[key] = v[0];\n tagValue[key] = v[1];\n }\n return tag(map(tagCoder, mapValue), tagValue) as any as CoderType<T>;\n}\n\n/**\n * Bitset of boolean values with optional padding.\n * @param names - An array of string names for the bitset values.\n * @param pad - Whether to pad the bitset to a multiple of 8 bits.\n * @returns CoderType representing the bitset.\n * @template Names\n * @example\n * const myBitset = P.bitset(['flag1', 'flag2', 'flag3', 'flag4'], true);\n */\nexport function bitset<Names extends readonly string[]>(\n names: Names,\n pad = false\n): CoderType<Record<Names[number], boolean>> {\n if (typeof pad !== 'boolean') throw new Error(`bitset/pad: expected boolean, got ${typeof pad}`);\n if (!Array.isArray(names)) throw new Error('bitset/names: expected array');\n for (const name of names) {\n if (typeof name !== 'string') throw new Error('bitset/names: expected array of strings');\n }\n return wrap({\n encodeStream: (w: Writer, value: Record<Names[number], boolean>) => {\n for (let i = 0; i < names.length; i++) w.bits(+(value as any)[names[i]], 1);\n if (pad && names.length % 8) w.bits(0, 8 - (names.length % 8));\n },\n decodeStream: (r: Reader): Record<Names[number], boolean> => {\n const out: Record<string, boolean> = {};\n for (let i = 0; i < names.length; i++) out[names[i]] = !!r.bits(1);\n if (pad && names.length % 8) r.bits(8 - (names.length % 8));\n return out;\n },\n validate: (value) => {\n if (!isPlainObject(value)) throw new Error(`bitset: invalid value ${value}`);\n for (const v of Object.values(value)) {\n if (typeof v !== 'boolean') throw new Error('expected boolean');\n }\n return value;\n },\n });\n}\n/** Padding function which always returns zero */\nexport const ZeroPad: PadFn = (_) => 0;\n\nfunction padLength(blockSize: number, len: number): number {\n if (len % blockSize === 0) return 0;\n return blockSize - (len % blockSize);\n}\n/**\n * Pads a CoderType with a specified block size and padding function on the left side.\n * @param blockSize - Block size for padding (positive safe integer).\n * @param inner - Inner CoderType to pad.\n * @param padFn - Padding function to use. If not provided, zero padding is used.\n * @returns CoderType representing the padded value.\n * @example\n * // Pad a U32BE with a block size of 4 and zero padding\n * const paddedU32BE = P.padLeft(4, P.U32BE);\n *\n * // Pad a string with a block size of 16 and custom padding\n * const paddedString = P.padLeft(16, P.string(P.U8), (i) => i + 1);\n */\nexport function padLeft<T>(\n blockSize: number,\n inner: CoderType<T>,\n padFn: Option<PadFn>\n): CoderType<T> {\n if (!isNum(blockSize) || blockSize <= 0) throw new Error(`padLeft: wrong blockSize=${blockSize}`);\n if (!isCoder(inner)) throw new Error(`padLeft: invalid inner value ${inner}`);\n if (padFn !== undefined && typeof padFn !== 'function')\n throw new Error(`padLeft: wrong padFn=${typeof padFn}`);\n const _padFn = padFn || ZeroPad;\n if (!inner.size) throw new Error('padLeft cannot have dynamic size');\n return wrap({\n size: inner.size + padLength(blockSize, inner.size),\n encodeStream: (w: Writer, value: T) => {\n const padBytes = padLength(blockSize, inner.size!);\n for (let i = 0; i < padBytes; i++) w.byte(_padFn(i));\n inner.encodeStream(w, value);\n },\n decodeStream: (r: Reader): T => {\n r.bytes(padLength(blockSize, inner.size!));\n return inner.decodeStream(r);\n },\n });\n}\n/**\n * Pads a CoderType with a specified block size and padding function on the right side.\n * @param blockSize - Block size for padding (positive safe integer).\n * @param inner - Inner CoderType to pad.\n * @param padFn - Padding function to use. If not provided, zero padding is used.\n * @returns CoderType representing the padded value.\n * @example\n * // Pad a U16BE with a block size of 2 and zero padding\n * const paddedU16BE = P.padRight(2, P.U16BE);\n *\n * // Pad a bytes with a block size of 8 and custom padding\n * const paddedBytes = P.padRight(8, P.bytes(null), (i) => i + 1);\n */\nexport function padRight<T>(\n blockSize: number,\n inner: CoderType<T>,\n padFn: Option<PadFn>\n): CoderType<T> {\n if (!isCoder(inner)) throw new Error(`padRight: invalid inner value ${inner}`);\n if (!isNum(blockSize) || blockSize <= 0) throw new Error(`padLeft: wrong blockSize=${blockSize}`);\n if (padFn !== undefined && typeof padFn !== 'function')\n throw new Error(`padRight: wrong padFn=${typeof padFn}`);\n const _padFn = padFn || ZeroPad;\n return wrap({\n size: inner.size ? inner.size + padLength(blockSize, inner.size) : undefined,\n encodeStream: (w: Writer, value: T) => {\n const _w = w as _Writer;\n const pos = _w.pos;\n inner.encodeStream(w, value);\n const padBytes = padLength(blockSize, _w.pos - pos);\n for (let i = 0; i < padBytes; i++) w.byte(_padFn(i));\n },\n decodeStream: (r: Reader): T => {\n const start = r.pos;\n const res = inner.decodeStream(r);\n r.bytes(padLength(blockSize, r.pos - start));\n return res;\n },\n });\n}\n1;\n/**\n * Pointer to a value using a pointer CoderType and an inner CoderType.\n * Pointers are scoped, and the next pointer in the dereference chain is offset by the previous one.\n * By default (if no 'allowMultipleReads' in ReaderOpts is set) is safe, since\n * same region of memory cannot be read multiple times.\n * @param ptr - CoderType for the pointer value.\n * @param inner - CoderType for encoding/decoding the pointed value.\n * @param sized - Whether the pointer should have a fixed size.\n * @returns CoderType representing the pointer to the value.\n * @example\n * const pointerToU8 = P.pointer(P.U16BE, P.U8); // Pointer to a single U8 value\n */\nexport function pointer<T>(\n ptr: CoderType<number>,\n inner: CoderType<T>,\n sized = false\n): CoderType<T> {\n if (!isCoder(ptr)) throw new Error(`pointer: invalid ptr value ${ptr}`);\n if (!isCoder(inner)) throw new Error(`pointer: invalid inner value ${inner}`);\n if (typeof sized !== 'boolean')\n throw new Error(`pointer/sized: expected boolean, got ${typeof sized}`);\n if (!ptr.size) throw new Error('unsized pointer');\n return wrap({\n size: sized ? ptr.size : undefined,\n encodeStream: (w: Writer, value: T) => {\n const _w = w as _Writer;\n const start = _w.pos;\n ptr.encodeStream(w, 0);\n _w.ptrs.push({ pos: start, ptr, buffer: inner.encode(value) });\n },\n decodeStream: (r: Reader): T => {\n const ptrVal = ptr.decodeStream(r);\n (r as _Reader)._enablePointers();\n return inner.decodeStream(r.offsetReader(ptrVal));\n },\n });\n}\n\n// Internal methods for test purposes only\nexport const _TEST: {\n _bitset: {\n BITS: number;\n FULL_MASK: number;\n len: (len: number) => number;\n create: (len: number) => Uint32Array;\n clean: (bs: Uint32Array) => Uint32Array;\n debug: (bs: Uint32Array) => string[];\n checkLen: (bs: Uint32Array, len: number) => void;\n chunkLen: (bsLen: number, pos: number, len: number) => void;\n set: (bs: Uint32Array, chunk: number, value: number, allowRewrite?: boolean) => boolean;\n pos: (\n pos: number,\n i: number\n ) => {\n chunk: number;\n mask: number;\n };\n indices: (bs: Uint32Array, len: number, invert?: boolean) => number[];\n range: (arr: number[]) => {\n pos: number;\n length: number;\n }[];\n rangeDebug: (bs: Uint32Array, len: number, invert?: boolean) => string;\n setRange: (\n bs: Uint32Array,\n bsLen: number,\n pos: number,\n len: number,\n allowRewrite?: boolean\n ) => boolean;\n };\n _Reader: typeof _Reader;\n _Writer: typeof _Writer;\n Path: {\n /**\n * Internal method for handling stack of paths (debug, errors, dynamic fields via path)\n * This is looks ugly (callback), but allows us to force stack cleaning by construction (.pop always after function).\n * Also, this makes impossible:\n * - pushing field when stack is empty\n * - pushing field inside of field (real bug)\n * NOTE: we don't want to do '.pop' on error!\n */\n pushObj: (stack: PathStack, obj: StructOut, objFn: _PathObjFn) => void;\n path: (stack: PathStack) => string;\n err(name: string, stack: PathStack, msg: string | Error): Error;\n resolve: (stack: PathStack, path: string) => StructOut | undefined;\n };\n} = { _bitset: Bitset, _Reader, _Writer, Path };\n","/**\n * Arkade Script Opcodes\n *\n * This module defines ONLY Arkade-specific opcodes (0xb3, 0xc3-0xf6).\n * Standard Bitcoin opcodes are imported from @scure/btc-signer.\n *\n * Reference: arkade-os/emulator v0.0.4 pkg/arkade/opcode.go\n */\n\nimport { OP } from \"@scure/btc-signer\";\nexport { OP };\n\nexport const ARKADE_OP = {\n // Merkle Branch Verification (0xb3 — repurposed NOP4 slot)\n MERKLEBRANCHVERIFY: 0xb3,\n\n // Digest (0xc3)\n DIGEST: 0xc3,\n\n // SHA256 Streaming (0xc4-0xc6)\n SHA256INITIALIZE: 0xc4,\n SHA256UPDATE: 0xc5,\n SHA256FINALIZE: 0xc6,\n\n // Input Introspection (0xc7-0xcb)\n INSPECTINPUTOUTPOINT: 0xc7,\n INSPECTINPUTARKADESCRIPTHASH: 0xc8,\n INSPECTINPUTVALUE: 0xc9,\n INSPECTINPUTSCRIPTPUBKEY: 0xca,\n INSPECTINPUTSEQUENCE: 0xcb,\n\n // Signatures (0xcc-0xcd)\n CHECKSIGFROMSTACK: 0xcc,\n PUSHCURRENTINPUTINDEX: 0xcd,\n\n // Input Arkade Witness Introspection (0xce)\n INSPECTINPUTARKADEWITNESSHASH: 0xce,\n\n // Output Introspection (0xcf, 0xd1)\n INSPECTOUTPUTVALUE: 0xcf,\n INSPECTOUTPUTSCRIPTPUBKEY: 0xd1,\n\n // Transaction Introspection (0xd2-0xd6)\n INSPECTVERSION: 0xd2,\n INSPECTLOCKTIME: 0xd3,\n INSPECTNUMINPUTS: 0xd4,\n INSPECTNUMOUTPUTS: 0xd5,\n TXWEIGHT: 0xd6,\n\n // Byte/Number Conversion & Arithmetic (0xd7-0xda)\n NUM2BIN: 0xd7,\n BIN2NUM: 0xd8,\n REVERSEBYTES: 0xd9,\n MODEXP: 0xda,\n // 0xdb-0xdf are unassigned (OP_UNKNOWN219-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} 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\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 xOnly = pubKey.length === 33 ? pubKey.subarray(1) : pubKey;\n const point = schnorr.utils.lift_x(bytesToNumberBE(xOnly));\n\n // tweak = (scriptHash mod n) * G\n const scalar = bytesToNumberBE(hash) % secp256k1.Point.CURVE().n;\n const tweak = secp256k1.Point.BASE.multiply(scalar);\n\n return schnorr.utils.pointToBytes(point.add(tweak));\n}\n","import { Script } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport {\n CLTVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n ConditionMultisigTapscript,\n CSVMultisigTapscript,\n MultisigTapscript,\n RelativeTimelock,\n} from \"./tapscript\";\nimport { hex } from \"@scure/base\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\nimport { ArkadeScript, type ArkadeScriptType } from \"../arkade/script\";\nimport { computeArkadeScriptPublicKey } from \"../arkade/tweak\";\n\n/** Virtual Hash Time Lock Contract (VHTLC) namespace. */\nexport namespace VHTLC {\n export interface Options {\n sender: Bytes;\n receiver: Bytes;\n server: Bytes;\n preimageHash: Bytes;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n /**\n * Optional non-interactive claim leaf: `server` plus a covenant-tweaked\n * emulator co-signer, pinned to `receiverPkScript`. Lets the receiver's\n * claim be pushed by the emulator without the receiver being online.\n */\n nonInteractiveClaim?: {\n receiverPkScript: Bytes;\n emulatorPubkey: Bytes;\n /**\n * OPT-IN: also require the claim to pay at least these amounts.\n *\n * The covenant's default bound is conservation (`out >= in`) — see\n * {@link enforcePayTo} for why a quote is normally not the\n * covenant's business. This is the escape hatch for a consumer that\n * wants the quote enforced in script rather than at its own\n * admission layer.\n *\n * ADDITIVE, NEVER A REPLACEMENT. The conservation bound stays. On\n * its own, `out >= quoted` leaves everything ABOVE the quote\n * unconstrained, so an overfunded lockup's surplus could be routed\n * anywhere by whoever assembles the spend — trading an underfunding\n * hole for a skimming one. Both bounds together admit neither.\n *\n * WHAT IT COSTS, and it is not only opcodes:\n *\n * - THE ADDRESS BECOMES A FUNCTION OF THE QUOTE. These amounts\n * compile into the leaf, hence the emulator key, hence the\n * pkScript. A re-quote is a different address, and cannot be\n * applied to a lockup already funded.\n * - AN UNDERFUNDED LOCKUP BECOMES UNCLAIMABLE. Its only exit is the\n * refund path, which waits out the CLTV. That is the intended\n * incentive and it lands on whoever misfunded — but it converts\n * \"claim the short amount now and settle up\" into \"wait for the\n * timelock\".\n *\n * Omit for the default. Omitting leaves every script byte unchanged,\n * so contracts already funded keep their addresses.\n */\n strict?: {\n /** Sats the claim must pay. Positive. */\n amount: bigint;\n /**\n * Asset base units the claim must pay.\n *\n * Required iff {@link VHTLC.Options.asset} is set, and refused\n * otherwise. Strict-on-sats-only against an asset-denominated\n * contract would pin the sat CARRIER and say nothing about the\n * asset that is the actual amount — half-enforcement that reads\n * like enforcement, which is the failure this option exists to\n * avoid rather than introduce.\n */\n assetAmount?: bigint;\n };\n };\n /**\n * Optional non-interactive refund leaf: `server` + `receiver` + a\n * covenant-tweaked emulator co-signer, pinned to `senderPkScript`, no\n * timelock. Every OTHER refund-side leaf in this contract requires\n * the sender's own signature — if the sender permanently loses that\n * key, none of them are reachable. This leaf is the one exception:\n * it needs neither the sender's presence nor their key, so funds\n * remain recoverable to the sender's pre-committed address even\n * then. It still needs the receiver (unlike `nonInteractiveClaim`,\n * which needs only server + emulator) — deliberately: this is what\n * lets server + receiver release the refund immediately, the moment\n * they agree the swap has failed, rather than making the sender wait\n * out `refundLocktime` the way {@link Script.refundWithoutReceiver}\n * does.\n */\n nonInteractiveRefund?: {\n senderPkScript: Bytes;\n emulatorPubkey: Bytes;\n };\n /**\n * Optional: denominate this contract in an Arkade ASSET rather than in\n * sats alone.\n *\n * Only the two NON-INTERACTIVE leaves change. Every other leaf is a\n * signature path that asserts nothing about value, so an asset makes no\n * difference to them — which is why this option reaches exactly the\n * leaves whose covenant the emulator enforces.\n *\n * When set, those covenants additionally require the output to carry at\n * least the input's amount of THIS asset, and to carry exactly one\n * asset. The sat clause is RETAINED, not replaced: an asset-carrying\n * VTXO carries sats too, so dropping it would let a spend satisfy the\n * asset covenant while stripping the sats — exactly as the sat-only\n * covenant lets a spend strip the asset.\n *\n * ONE ASSET IS BOUND, AND ONLY THAT ONE IS PROTECTED. If a VTXO funded to\n * this contract carries ADDITIONAL assets alongside the bound one, those\n * are not covered: whoever assembles a covenant spend chooses where they\n * go, and can send them anywhere.\n *\n * `INSPECTOUTASSETCOUNT == 1` does not close that. It constrains the\n * covenant's OUTPUT to exactly one asset — so the extras cannot ride\n * along with the bound asset — but arkd's conservation rule is satisfied\n * by routing them to a different output, which the covenant says nothing\n * about. The bound asset arrives; the rest is the spender's to direct.\n *\n * So fund an asset contract with the asset it names and nothing else. A\n * multi-asset VTXO behind this covenant is a loss waiting for whoever\n * pushes the spend.\n *\n * The id is the pair the introspection opcodes take. A canonical Asset\n * ID is `(genesis txid, group index)`, never a single blob.\n */\n asset?: {\n /**\n * The asset's genesis transaction id, 32 bytes, in CANONICAL order\n * — exactly the leading 32 bytes of a serialized Asset ID, no flip.\n *\n * The covenant reverses it internally because the introspection\n * opcodes match wire order; callers never do that themselves, and a\n * caller who pre-reverses gets a contract that is unspendable on its\n * covenant leaves with nothing in the error naming why.\n */\n txid: Bytes;\n /** The asset group index within that genesis transaction. */\n groupIndex: number;\n };\n }\n\n /**\n * Shared construction and accessors for every VHTLC script version. The\n * only thing that varies between versions is which preimage-condition\n * fragment `claim`/`unilateralClaim`/`nonInteractiveClaim` are built\n * from — everything else (the multisig/timelock leaves, the\n * non-interactive covenant leaves, the accessor methods) is identical,\n * so versions are expressed as thin subclasses over one builder rather\n * than as separate, independently-maintained copies of this class.\n */\n abstract class BaseScript extends VtxoScript {\n readonly options: Options;\n readonly claimScript: string;\n readonly refundScript: string;\n readonly refundWithoutReceiverScript: string;\n readonly unilateralClaimScript: string;\n readonly unilateralRefundScript: string;\n readonly unilateralRefundWithoutReceiverScript: string;\n readonly nonInteractiveClaimScript?: string;\n readonly nonInteractiveClaimArkadeScript?: Bytes;\n readonly nonInteractiveRefundScript?: string;\n readonly nonInteractiveRefundArkadeScript?: Bytes;\n\n protected constructor(options: Options, preimageCondition: (hash: Bytes) => Bytes) {\n validateOptions(options);\n\n const {\n sender,\n receiver,\n server,\n preimageHash,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n } = options;\n\n // The one leaf-condition fragment `claim`, `unilateralClaim`, and\n // (when present) `nonInteractiveClaim` all reuse below — computed\n // once so all three can never drift from one another within the\n // same script version.\n const conditionScript = preimageCondition(preimageHash);\n\n const claimScript = ConditionMultisigTapscript.encode({\n conditionScript,\n pubkeys: [receiver, server],\n }).script;\n\n const refundScript = MultisigTapscript.encode({\n pubkeys: [sender, receiver, server],\n }).script;\n\n const refundWithoutReceiverScript = CLTVMultisigTapscript.encode({\n absoluteTimelock: refundLocktime,\n pubkeys: [sender, server],\n }).script;\n\n const unilateralClaimScript = ConditionCSVMultisigTapscript.encode({\n conditionScript,\n timelock: unilateralClaimDelay,\n pubkeys: [receiver],\n }).script;\n\n const unilateralRefundScript = CSVMultisigTapscript.encode({\n timelock: unilateralRefundDelay,\n pubkeys: [sender, receiver],\n }).script;\n\n const unilateralRefundWithoutReceiverScript = CSVMultisigTapscript.encode({\n timelock: unilateralRefundWithoutReceiverDelay,\n pubkeys: [sender],\n }).script;\n\n const scripts = [\n claimScript,\n refundScript,\n refundWithoutReceiverScript,\n unilateralClaimScript,\n unilateralRefundScript,\n unilateralRefundWithoutReceiverScript,\n ];\n\n let arkadeScriptNic: Bytes | undefined;\n let nonInteractiveClaimScript: Bytes | undefined;\n if (options.nonInteractiveClaim) {\n arkadeScriptNic = enforcePayToMaybeAsset(\n options.nonInteractiveClaim.receiverPkScript,\n options.asset,\n options.nonInteractiveClaim.strict,\n );\n nonInteractiveClaimScript = ConditionMultisigTapscript.encode({\n conditionScript,\n pubkeys: [\n server,\n computeArkadeScriptPublicKey(\n options.nonInteractiveClaim.emulatorPubkey,\n arkadeScriptNic,\n ),\n ],\n }).script;\n scripts.push(nonInteractiveClaimScript);\n }\n\n let arkadeScriptNir: Bytes | undefined;\n let nonInteractiveRefundScript: Bytes | undefined;\n if (options.nonInteractiveRefund) {\n arkadeScriptNir = enforcePayToMaybeAsset(\n options.nonInteractiveRefund.senderPkScript,\n options.asset,\n );\n // No timelock: server + receiver together can release this\n // immediately, same as `refund` above, just without needing\n // the sender's own signature — the covenant is what still\n // guarantees the payout can only reach the sender.\n nonInteractiveRefundScript = MultisigTapscript.encode({\n pubkeys: [\n server,\n receiver,\n computeArkadeScriptPublicKey(\n options.nonInteractiveRefund.emulatorPubkey,\n arkadeScriptNir,\n ),\n ],\n }).script;\n scripts.push(nonInteractiveRefundScript);\n }\n\n super(scripts);\n\n this.options = options;\n this.claimScript = hex.encode(claimScript);\n this.refundScript = hex.encode(refundScript);\n this.refundWithoutReceiverScript = hex.encode(refundWithoutReceiverScript);\n this.unilateralClaimScript = hex.encode(unilateralClaimScript);\n this.unilateralRefundScript = hex.encode(unilateralRefundScript);\n this.unilateralRefundWithoutReceiverScript = hex.encode(\n unilateralRefundWithoutReceiverScript,\n );\n if (nonInteractiveClaimScript) {\n this.nonInteractiveClaimScript = hex.encode(nonInteractiveClaimScript);\n this.nonInteractiveClaimArkadeScript = arkadeScriptNic;\n }\n if (nonInteractiveRefundScript) {\n this.nonInteractiveRefundScript = hex.encode(nonInteractiveRefundScript);\n this.nonInteractiveRefundArkadeScript = arkadeScriptNir;\n }\n }\n\n /** Return the collaborative claim tapleaf script. */\n claim(): TapLeafScript {\n return this.findLeaf(this.claimScript);\n }\n\n /** Return the collaborative refund tapleaf script. */\n refund(): TapLeafScript {\n return this.findLeaf(this.refundScript);\n }\n\n /** Return the refund-without-receiver tapleaf script. */\n refundWithoutReceiver(): TapLeafScript {\n return this.findLeaf(this.refundWithoutReceiverScript);\n }\n\n /** Return the unilateral claim tapleaf script. */\n unilateralClaim(): TapLeafScript {\n return this.findLeaf(this.unilateralClaimScript);\n }\n\n /** Return the unilateral refund tapleaf script. */\n unilateralRefund(): TapLeafScript {\n return this.findLeaf(this.unilateralRefundScript);\n }\n\n /** Return the unilateral refund-without-receiver tapleaf script. */\n unilateralRefundWithoutReceiver(): TapLeafScript {\n return this.findLeaf(this.unilateralRefundWithoutReceiverScript);\n }\n\n /** Return the non-interactive claim tapleaf script as well as the ArkadeScript. */\n nonInteractiveClaim(): [TapLeafScript, Bytes] {\n if (!this.nonInteractiveClaimScript || !this.nonInteractiveClaimArkadeScript) {\n throw new Error(\"VHTLC has no non-interactive claim leaf\");\n }\n return [\n this.findLeaf(this.nonInteractiveClaimScript),\n this.nonInteractiveClaimArkadeScript,\n ];\n }\n\n /** Return the non-interactive refund tapleaf script as well as the ArkadeScript. */\n nonInteractiveRefund(): [TapLeafScript, Bytes] {\n if (!this.nonInteractiveRefundScript || !this.nonInteractiveRefundArkadeScript) {\n throw new Error(\"VHTLC has no non-interactive refund leaf\");\n }\n return [\n this.findLeaf(this.nonInteractiveRefundScript),\n this.nonInteractiveRefundArkadeScript,\n ];\n }\n }\n\n /**\n * Virtual Hash Time Lock Contract (VHTLC) script implementation.\n *\n * VHTLC enables atomic swaps and conditional payments in the Arkade protocol.\n * It provides multiple spending paths:\n *\n * - **claim**: Receiver can claim funds by revealing the preimage\n * - **refund**: Sender and receiver can collaboratively refund\n * - **refundWithoutReceiver**: Sender can refund after locktime expires\n * - **unilateralClaim**: Receiver can claim unilaterally after delay\n * - **unilateralRefund**: Sender and receiver can refund unilaterally after delay\n * - **unilateralRefundWithoutReceiver**: Sender can refund unilaterally after delay\n * - **nonInteractiveClaim** (optional): server + emulator can push the\n * receiver's claim, pinned to a pre-committed destination\n * - **nonInteractiveRefund** (optional): server + receiver + emulator\n * can push the sender's refund immediately, no timelock, pinned to a\n * pre-committed destination — recoverable even if the sender's own key\n * is lost\n *\n * See {@link ScriptV2} for the current recommended construction — same\n * leaf ladder, same options shape, an added length check on the claim\n * preimage. This class is unchanged and stays available as-is.\n *\n * @example\n * ```typescript\n * const vhtlc = new VHTLC.Script({\n * sender: alicePubKey,\n * receiver: bobPubKey,\n * server: serverPubKey,\n * preimageHash: hash160(secret),\n * refundLocktime: BigInt(chainTip + 10),\n * unilateralClaimDelay: { type: 'blocks', value: 100n },\n * unilateralRefundDelay: { type: 'blocks', value: 102n },\n * unilateralRefundWithoutReceiverDelay: { type: 'blocks', value: 103n }\n * });\n * ```\n */\n export class Script extends BaseScript {\n constructor(options: Options) {\n super(options, preimageConditionScript);\n }\n }\n\n /**\n * Same leaf ladder as {@link Script}, built with {@link\n * preimageConditionScriptV2} instead of {@link preimageConditionScript}\n * for every leaf that gates on the preimage (`claim`, `unilateralClaim`,\n * and, when present, `nonInteractiveClaim`) — see that function's doc\n * comment for what differs and why. A distinct class rather than a flag\n * on {@link Script}: the two produce different script bytes (and so\n * different addresses) for the same participant keys, and keeping them\n * as separate types makes that a compile-time-visible choice at every\n * call site instead of a runtime option that's easy to get wrong.\n */\n export class ScriptV2 extends BaseScript {\n constructor(options: Options) {\n super(options, preimageConditionScriptV2);\n }\n }\n\n function validateOptions(options: Options): void {\n const {\n sender,\n receiver,\n server,\n preimageHash,\n refundLocktime,\n unilateralClaimDelay,\n unilateralRefundDelay,\n unilateralRefundWithoutReceiverDelay,\n } = options;\n\n if (!preimageHash || preimageHash.length !== 20) {\n throw new Error(\"preimage hash must be 20 bytes\");\n }\n // The two non-interactive leaves are the ONLY ones carrying a covenant\n // — the signature leaves assert nothing about value — so they are the\n // only place an asset can be bound. Accepting `asset` without either of\n // them would emit a sat-only contract and say nothing about it: the\n // caller funds it believing the asset is protected, and any spend that\n // satisfies the sat covenant walks off with the asset. The one outward\n // difference is a pkScript matching a non-asset address, which is not\n // something a caller thinks to check. Refuse instead of dropping it.\n if (\n options.asset !== undefined &&\n !options.nonInteractiveClaim &&\n !options.nonInteractiveRefund\n ) {\n throw new Error(\n \"asset has no effect without nonInteractiveClaim or nonInteractiveRefund\",\n );\n }\n\n // The opt-in quoted bound, and every way of asking for half of it.\n const strict = options.nonInteractiveClaim?.strict;\n if (strict !== undefined) {\n // `out >= 0` is satisfied by every output, so a zero would compile a\n // bound that reads like enforcement and enforces nothing.\n if (strict.amount <= 0n) {\n throw new Error(`strict claim amount must be positive, got ${strict.amount}`);\n }\n // Strict on the sat carrier while the ASSET — the actual amount —\n // goes unbounded. The most dangerous shape here, because the caller\n // has explicitly asked for enforcement and would get it on the wrong\n // quantity.\n if (options.asset !== undefined && strict.assetAmount === undefined) {\n throw new Error(\n \"strict claim needs assetAmount when the contract is denominated in an asset: \" +\n \"bounding only the sats would leave the asset amount unenforced\",\n );\n }\n if (options.asset === undefined && strict.assetAmount !== undefined) {\n throw new Error(\"strict claim assetAmount has no effect without asset\");\n }\n if (strict.assetAmount !== undefined && strict.assetAmount <= 0n) {\n throw new Error(\n `strict claim assetAmount must be positive, got ${strict.assetAmount}`,\n );\n }\n }\n if (options.nonInteractiveClaim) {\n const { emulatorPubkey, receiverPkScript } = options.nonInteractiveClaim;\n if (!emulatorPubkey || (emulatorPubkey.length !== 32 && emulatorPubkey.length !== 33)) {\n throw new Error(\"Invalid public key length (emulator)\");\n }\n if (!receiverPkScript || !isP2trPkScript(receiverPkScript)) {\n throw new Error(\"Invalid P2TR script\");\n }\n }\n if (options.nonInteractiveRefund) {\n const { emulatorPubkey, senderPkScript } = options.nonInteractiveRefund;\n if (!emulatorPubkey || (emulatorPubkey.length !== 32 && emulatorPubkey.length !== 33)) {\n throw new Error(\"Invalid public key length (emulator)\");\n }\n if (!senderPkScript || !isP2trPkScript(senderPkScript)) {\n throw new Error(\"Invalid P2TR script\");\n }\n }\n if (!receiver || receiver.length !== 32) {\n throw new Error(\"Invalid public key length (receiver)\");\n }\n if (!sender || sender.length !== 32) {\n throw new Error(\"Invalid public key length (sender)\");\n }\n if (!server || server.length !== 32) {\n throw new Error(\"Invalid public key length (server)\");\n }\n if (typeof refundLocktime !== \"bigint\" || refundLocktime <= 0n) {\n throw new Error(\"refund locktime must be greater than 0\");\n }\n if (\n !unilateralClaimDelay ||\n typeof unilateralClaimDelay.value !== \"bigint\" ||\n unilateralClaimDelay.value <= 0n\n ) {\n throw new Error(\"unilateral claim delay must greater than 0\");\n }\n if (unilateralClaimDelay.type === \"seconds\" && unilateralClaimDelay.value % 512n !== 0n) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (unilateralClaimDelay.type === \"seconds\" && unilateralClaimDelay.value < 512n) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n if (\n !unilateralRefundDelay ||\n typeof unilateralRefundDelay.value !== \"bigint\" ||\n unilateralRefundDelay.value <= 0n\n ) {\n throw new Error(\"unilateral refund delay must greater than 0\");\n }\n if (unilateralRefundDelay.type === \"seconds\" && unilateralRefundDelay.value % 512n !== 0n) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (unilateralRefundDelay.type === \"seconds\" && unilateralRefundDelay.value < 512n) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n if (\n !unilateralRefundWithoutReceiverDelay ||\n typeof unilateralRefundWithoutReceiverDelay.value !== \"bigint\" ||\n unilateralRefundWithoutReceiverDelay.value <= 0n\n ) {\n throw new Error(\"unilateral refund without receiver delay must greater than 0\");\n }\n if (\n unilateralRefundWithoutReceiverDelay.type === \"seconds\" &&\n unilateralRefundWithoutReceiverDelay.value % 512n !== 0n\n ) {\n throw new Error(\"seconds timelock must be multiple of 512\");\n }\n if (\n unilateralRefundWithoutReceiverDelay.type === \"seconds\" &&\n unilateralRefundWithoutReceiverDelay.value < 512n\n ) {\n throw new Error(\"seconds timelock must be greater or equal to 512\");\n }\n }\n}\n\nfunction preimageConditionScript(preimageHash: Bytes): Bytes {\n return Script.encode([\"HASH160\", preimageHash, \"EQUAL\"]);\n}\n\n/**\n * Same as {@link preimageConditionScript}, plus an explicit length check on\n * the witness item before it's hashed: `OP_SIZE 32 OP_EQUALVERIFY` ahead of\n * the `OP_HASH160` check, the same prefix real-world HTLC scripts (e.g.\n * BOLT3's) carry for the same reason — the claim leaf otherwise accepts any\n * witness value whose HASH160 matches, regardless of length, and this\n * contract's preimage is always exactly 32 bytes by construction. Used by\n * {@link VHTLC.ScriptV2} for every leaf gated on the preimage.\n */\nfunction preimageConditionScriptV2(preimageHash: Bytes): Bytes {\n return Script.encode([\"SIZE\", 32, \"EQUALVERIFY\", \"HASH160\", preimageHash, \"EQUAL\"]);\n}\n\n/**\n * A v1 P2TR pkScript is exactly `OP_1 <32-byte-program>` (0x51 0x20 ...) — 34\n * bytes total. Length alone isn't enough: any other 34-byte value (e.g.\n * {@link ArkAddress.subdustPkScript}'s `OP_RETURN <32 bytes>`, or a P2WSH\n * script) has the same length but a different witness version, and\n * `enforcePayTo` below trusts byte 2 onward as the taproot program\n * unconditionally.\n */\nfunction isP2trPkScript(pkScript: Bytes): boolean {\n return pkScript.length === 34 && pkScript[0] === 0x51 && pkScript[1] === 0x20;\n}\n\n/**\n * The covenant: \"this input's output pays the given P2TR script, value >=\n * input\". Shared by {@link VHTLC.Options.nonInteractiveClaim} and {@link\n * VHTLC.Options.nonInteractiveRefund} — only the destination and the tier it\n * gates differ.\n *\n * `PUSHCURRENTINPUTINDEX` as the output index is not an assumption about how\n * the Ark round pairs inputs with outputs — the covenant imposes the pairing\n * on the spender. Whatever index a spending tx places this input at, the\n * output at that same index must pay the destination at least the input's\n * value, or the ArkadeScript fails and the server never co-signs. A tx with no\n * output at that index fails the same way: the leaf is unsatisfiable, not\n * fooled. Index alignment is therefore a *liveness* obligation on whoever\n * assembles the spend (the solver, for both leaves — this SDK never builds\n * them; its own aggregate refund uses the interactive leaf precisely because\n * it lacks this per-index constraint, see `refund.ts`), never a safety\n * assumption.\n *\n * WHY `>= input` AND NOT `>= the quoted amount`. This bound is CONSERVATION,\n * not agreement: it says the spend may not skim, and says nothing about what\n * any quote promised. That is deliberate, on both leaves, and it is a question\n * worth answering here because the covenant reads like the natural place to\n * pin a quote and is not.\n *\n * - A QUOTE IS NOT THE COVENANT'S TO KNOW. Pinning one compiles it into the\n * leaf, hence into the emulator key, hence into the ADDRESS. Re-quoting\n * would move the address of a contract that may already be funded.\n * - MISFUNDING IS THE SENDER'S EXPOSURE. They chose the amount. A lockup that\n * over- or underpays the quote is theirs to have created, and the\n * counterparty's protection is to decline it — refuse the swap and let it\n * refund — which is an application-layer decision, taken where a quote\n * actually lives, and revisable without moving anyone's address.\n * - NOTHING IS CLAIMED WITHOUT THE PREIMAGE. Both covenant leaves sit behind\n * the hash condition, so an underfunded lockup cannot be claimed out from\n * under the counterparty on the covenant's say-so. The covenant's job is to\n * stop a spend that satisfies the condition from redirecting the value; it\n * is not to adjudicate whether the trade was fair.\n *\n * So a funding gate that compares a lockup against its quote belongs in the\n * consumer, not here. `lightning-swap-service`'s `lockupIsFunded` is that gate.\n */\n/**\n * The sat half of both covenants: the output at this input's index is P2TR,\n * pays `destinationPkScript`, and carries at least the input's value.\n *\n * ONE COPY, shared by {@link enforcePayTo} and {@link enforcePayToAsset}. The\n * asset covenant used to restate these tokens inline under a comment promising\n * they matched \"byte-for-byte\" — a promise nothing enforced, and one that an\n * option added to one and forgotten on the other would have broken silently.\n *\n * `quotedSats` is the opt-in bound from\n * {@link VHTLC.Options.nonInteractiveClaim.strict}. It is ADDED to the\n * conservation comparison, never substituted for it: alone, `out >= quoted`\n * leaves everything above the quote unconstrained, so an overfunded lockup's\n * surplus could be routed anywhere by whoever assembles the spend.\n */\nfunction satClause(destinationPkScript: Bytes, quotedSats?: bigint): ArkadeScriptType {\n return [\n \"PUSHCURRENTINPUTINDEX\",\n \"DUP\",\n \"INSPECTOUTPUTSCRIPTPUBKEY\",\n 1,\n \"EQUALVERIFY\",\n destinationPkScript.subarray(2),\n \"EQUALVERIFY\",\n \"INSPECTOUTPUTVALUE\",\n // `DUP` because the output value is needed twice: once against the\n // quote, once against the input.\n ...(quotedSats === undefined\n ? []\n : ([\"DUP\", quotedSats, \"GREATERTHANOREQUAL\", \"VERIFY\"] as ArkadeScriptType)),\n \"PUSHCURRENTINPUTINDEX\",\n \"INSPECTINPUTVALUE\",\n \"GREATERTHANOREQUAL\",\n ];\n}\n\nfunction enforcePayTo(destinationPkScript: Bytes, quotedSats?: bigint): Bytes {\n // validateOptions already checked this for both current call sites — kept\n // here too, since this covenant is the one place a wrong destination\n // becomes irreversible (a mis-typed leaf, unlike a rejected constructor\n // call, only surfaces once someone tries to spend it).\n if (!isP2trPkScript(destinationPkScript)) {\n throw new Error(\"invalid P2TR script\");\n }\n return ArkadeScript.encode(satClause(destinationPkScript, quotedSats));\n}\n\n/**\n * {@link enforcePayTo} for a contract denominated in an Arkade ASSET: the same\n * covenant, plus \"carries at least the input's amount of exactly this one\n * asset\".\n *\n * The sat covenant is this one's TAIL, restated inline below, so an asset\n * contract enforces everything a sat contract does and never less. That\n * matters because an asset-carrying VTXO carries sats too: a covenant\n * constraining only the asset would let a spend strip the sats, and the\n * sat-only covenant lets a spend strip the ASSET -- the loss this exists to\n * prevent.\n *\n * Two opcode details decide whether it is safe, and the intuitive reading gets\n * both wrong:\n *\n * - A canonical Asset ID is TWO stack items, `asset_txid` then `asset_gidx`.\n * Pushing it as one 32-byte blob encodes cleanly and fails only at spend\n * time, once the contract is already funded.\n * - `INSPECTOUTASSETLOOKUP` pushes `amount 1`, or `0 0` when the asset is\n * ABSENT. The `VERIFY` after each lookup pops that success flag and is\n * load-bearing, not defensive: without it an output carrying NONE of the\n * asset reports amount 0, `0 >= 0` passes, and the stripping spend succeeds\n * anyway. Applied to the input lookup too, so an input whose asset is\n * undeclared cannot compare `0 >= 0` either.\n *\n * `INSPECTOUTASSETCOUNT == 1` bounds the output to the single asset bound, so\n * nothing can be injected alongside it. Deliberately strict: a covenant that\n * is too permissive cannot be tightened once funds are locked to it, while a\n * strict one can be relaxed in a later contract version.\n */\nfunction enforcePayToAsset(\n destinationPkScript: Bytes,\n asset: { txid: Bytes; groupIndex: number },\n /** @see VHTLC.Options.nonInteractiveClaim.strict */\n strict?: { amount: bigint; assetAmount?: bigint },\n): Bytes {\n if (!isP2trPkScript(destinationPkScript)) {\n throw new Error(\"invalid P2TR script\");\n }\n if (asset.txid.length !== 32) {\n throw new Error(`asset txid must be 32 bytes, got ${asset.txid.length}`);\n }\n if (!Number.isInteger(asset.groupIndex) || asset.groupIndex < 0 || asset.groupIndex > 0xffff) {\n throw new Error(\n `asset group index must be an integer in [0, 65535], got ${asset.groupIndex}`,\n );\n }\n // REVERSED, once, here. `asset.txid` is the id in CANONICAL order -- the\n // leading 32 bytes of the serialized Asset ID, which arkd's `serializeTxHash`\n // already reversed \"to match the canonical txid format\". The introspection\n // opcodes match against WIRE order, which is those bytes reversed back. Push\n // the canonical bytes unflipped and the lookup reports the asset ABSENT\n // (`0 0`), so the covenant fails and the contract it guards is unspendable. Nothing in the failure says so: the emulator returns only\n // `OP_VERIFY failed`, and returns it whatever the amount comparison says.\n // Established on regtest against a real minted asset, by elimination against\n // a passing BTC-only control.\n //\n // A copy rather than an in-place reverse: the caller's id is theirs.\n const inspectionTxid = Uint8Array.from(asset.txid).reverse();\n return ArkadeScript.encode([\n // The output carries at least as much of the asset as the input did.\n // Output index is the input's -- the same index alignment the sat\n // covenant relies on, and the same liveness obligation on whoever\n // assembles the spend.\n \"PUSHCURRENTINPUTINDEX\",\n inspectionTxid,\n asset.groupIndex,\n \"INSPECTOUTASSETLOOKUP\",\n \"VERIFY\", // PRESENT on the output, not merely \"zero of it\"\n // The quoted bound, when the caller opted in — added to the input\n // comparison below, not substituted for it. `DUP` because the output's\n // asset amount is needed twice.\n ...(strict?.assetAmount === undefined\n ? []\n : ([\"DUP\", strict.assetAmount, \"GREATERTHANOREQUAL\", \"VERIFY\"] as ArkadeScriptType)),\n \"PUSHCURRENTINPUTINDEX\",\n inspectionTxid,\n asset.groupIndex,\n \"INSPECTINASSETLOOKUP\",\n \"VERIFY\", // ...and on the input, so the comparison means something\n \"GREATERTHANOREQUAL\",\n \"VERIFY\",\n // Exactly one asset out: nothing injected alongside the one bound.\n \"PUSHCURRENTINPUTINDEX\",\n \"INSPECTOUTASSETCOUNT\",\n 1,\n \"EQUALVERIFY\",\n // ...then the sat covenant, the same tokens `enforcePayTo` emits.\n ...satClause(destinationPkScript, strict?.amount),\n ]);\n}\n\n/** Pick the covenant this contract's denomination calls for. */\nfunction enforcePayToMaybeAsset(\n destinationPkScript: Bytes,\n asset: { txid: Bytes; groupIndex: number } | undefined,\n /**\n * Present only for the CLAIM leaf, and only when the caller opted in. The\n * refund leaf never receives one: a refund returns what arrived, so a quote\n * has no place in it — see {@link enforcePayTo}.\n */\n strict?: { amount: bigint; assetAmount?: bigint },\n): Bytes {\n return asset === undefined\n ? enforcePayTo(destinationPkScript, strict?.amount)\n : enforcePayToAsset(destinationPkScript, asset, strict);\n}\n","import { hex } from \"@scure/base\";\nimport { VHTLC } from \"../../script/vhtlc\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { assertVhtlcSpendableNow, isCltvSatisfied, isCsvSpendable, resolveRole } from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * Typed parameters for VHTLC contracts.\n */\nexport interface VHTLCContractParams {\n sender: Uint8Array;\n receiver: Uint8Array;\n server: Uint8Array;\n preimageHash: Uint8Array;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n}\n\n/**\n * Handler for Virtual Hash Time Lock Contract (VHTLC).\n *\n * VHTLC supports multiple spending paths:\n *\n * Collaborative paths (with server):\n * - claim: Receiver + Server with preimage\n * - refund: Sender + Receiver + Server\n * - refundWithoutReceiver: Sender + Server after CLTV locktime\n *\n * Unilateral paths (without server):\n * - unilateralClaim: Receiver with preimage after CSV delay\n * - unilateralRefund: Sender + Receiver after CSV delay\n * - unilateralRefundWithoutReceiver: Sender after CSV delay\n */\nexport const VHTLCContractHandler: ContractHandler<VHTLCContractParams, VHTLC.Script> &\n TapscriptDeriving<VHTLC.Script> = {\n type: \"vhtlc\",\n\n createScript(params: Record<string, string>): VHTLC.Script {\n const typed = this.deserializeParams(params);\n return new VHTLC.Script(typed);\n },\n\n serializeParams(params: VHTLCContractParams): Record<string, string> {\n return {\n sender: hex.encode(params.sender),\n receiver: hex.encode(params.receiver),\n server: hex.encode(params.server),\n hash: hex.encode(params.preimageHash),\n refundLocktime: params.refundLocktime.toString(),\n claimDelay: timelockToSequence(params.unilateralClaimDelay).toString(),\n refundDelay: timelockToSequence(params.unilateralRefundDelay).toString(),\n refundNoReceiverDelay: timelockToSequence(\n params.unilateralRefundWithoutReceiverDelay,\n ).toString(),\n };\n },\n\n deserializeParams(params: Record<string, string>): VHTLCContractParams {\n return {\n sender: hex.decode(params.sender),\n receiver: hex.decode(params.receiver),\n server: hex.decode(params.server),\n preimageHash: hex.decode(params.hash),\n refundLocktime: BigInt(params.refundLocktime),\n unilateralClaimDelay: sequenceToTimelock(Number(params.claimDelay)),\n unilateralRefundDelay: sequenceToTimelock(Number(params.refundDelay)),\n unilateralRefundWithoutReceiverDelay: sequenceToTimelock(\n Number(params.refundNoReceiverDelay),\n ),\n };\n },\n\n /**\n * Select spending path based on context.\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n selectPath(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const role = resolveRole(contract, context);\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (!role) {\n return null;\n }\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n return {\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n };\n }\n\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n return {\n leaf: script.refundWithoutReceiver(),\n };\n }\n\n return null;\n }\n\n // Unilateral paths\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n };\n }\n\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n };\n }\n\n return null;\n },\n\n /**\n * Get all possible spending paths (no timelock checks).\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n getAllSpendingPaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n\n if (context.collaborative) {\n // Collaborative paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\") {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n } else {\n // Unilateral paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n getSpendablePaths(\n script: VHTLC.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n return paths;\n }\n\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n /**\n * Refuse an explicit spend of a lockup whose refund path has not opened.\n * Shared with the v2 handler so the two cannot drift.\n * @see assertVhtlcSpendableNow for why this is the one certain case.\n */\n assertSpendableNow(_script: VHTLC.Script, contract: Contract, context: PathContext): void {\n assertVhtlcSpendableNow(contract, context);\n },\n\n /**\n * Never. A live VHTLC is escrow: the counterparty's claim leaf is armed,\n * and generic selection — send, settle, renewal, offboard — would move the\n * lockup out from under a swap the counterparty is still entitled to\n * complete, or race a claim already in flight.\n *\n * Two narrow reasons, and neither is \"spending this would destroy the\n * VTXO\". It would not: the leaf {@link deriveTapscripts} stamps is\n * `refundWithoutReceiver` — `CLTV[sender, server]`, the sender's OWN\n * refund, which the server rejects until `refundLocktime` matures. The\n * reasons are that an escrowed lockup must not count toward the\n * `available` balance bucket, and that generic RENEWAL must not silently\n * execute a refund the caller never asked for — `runPeriodicSettle` selects\n * through `getSpendableVtxos`, which this gate filters, and it runs\n * unprompted whenever a wallet is built without an explicit\n * `settlementConfig`.\n *\n * **Inseparable from {@link deriveTapscripts}.** Deriving the leaf without\n * closing the gate hands generic renewal an escrow it had never been\n * offered before; before that method existed the answer here was\n * unobservable, so the two only ever made sense together.\n *\n * Recovery is filtered on {@link assertSpendableNow}, not on this: the gate\n * is permanent, and applying it there would strand a matured lockup.\n */\n isGenericallySpendable: () => false,\n\n /**\n * The annotation leaf stamped onto every VTXO locked to this contract.\n *\n * **Without this the contract is unusable, not merely unoptimized.**\n * `deriveContractTapscripts` falls back to `script.forfeit()` for any\n * handler that does not implement {@link TapscriptDeriving}, and no VHTLC\n * script version has a `forfeit()` — `VtxoScript` does not define one and\n * `VHTLC.BaseScript` does not add one. The fallback therefore threw\n * `legacy.forfeit is not a function`, `annotatableIn` caught it, and\n * `fetchContractVtxosBulk` dropped this contract's VTXOs before they were\n * persisted. The row existed and was watched while its balance stayed\n * permanently invisible, and `getSyncState()` reported `degraded` forever.\n *\n * `refundWithoutReceiver` is the leaf, for both roles the annotation\n * serves, because it is the only collaborative path this wallet can\n * actually satisfy as the sender — the same conclusion `selectPath`\n * reaches, kept in step with it deliberately. The claim leaves belong to\n * the receiver and need a preimage the sender does not have; `refund` and\n * `unilateralRefund` both need the counterparty's signature, which this\n * protocol has no message to ask for. V1 has no covenant leaves at all.\n *\n * **It carries a CLTV, and callers must respect it.** A settlement built\n * on this leaf is only valid once `refundLocktime` has matured, so a\n * recovery round that sweeps this VTXO early is rejected by the server.\n * Nothing in this handler can enforce that, because the annotation is\n * derived per contract and knows no clock; `recoverVtxos` filters on\n * {@link assertSpendableNow} for it.\n *\n * **Role-blind.** A receiver's row gets the same leaf, which names keys that\n * wallet does not hold, so it is satisfiable only by the wallet holding the\n * lockup's `sender` key and fails at intent registration for anyone else.\n */\n deriveTapscripts(script: VHTLC.Script): DerivedContractTapscripts {\n const leaf = script.refundWithoutReceiver();\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","import { hex } from \"@scure/base\";\nimport { VHTLC } from \"../../script/vhtlc\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { assertVhtlcSpendableNow, isCltvSatisfied, isCsvSpendable, resolveRole } from \"./helpers\";\nimport { sequenceToTimelock, timelockToSequence } from \"../../utils/timelock\";\n\n/**\n * The stored `assetGroupIndex`, as a number, or a throw naming the row.\n *\n * `Number()` alone is not enough here, and it fails in exactly one direction\n * that matters. `VHTLC.ScriptV2` already refuses a non-integer, a negative or\n * anything past `0xffff`, so `\"abc\"`, `\"1.5\"` and `\"-1\"` die one frame down with\n * a clear message. What survives is `Number(\"\")`, `Number(\" \")` and\n * `Number(\"\\t\")` — all of which are **0**, a perfectly valid group index.\n *\n * A blank field therefore does not fail: it silently names group 0 of the same\n * genesis transaction, which is a DIFFERENT asset. The contract then derives a\n * different script from the one the row was written against, and registration\n * dies at `upsertContractRow` with an opaque `Script mismatch` — the same\n * silent-drop class the both-halves-or-neither check above exists to close, one\n * value further in.\n *\n * Anchored and canonical: no sign, no point, no exponent, no leading zero, so a\n * row that round-tripped through this handler's own `serializeParams` is the\n * only shape accepted back.\n */\nconst parseGroupIndex = (raw: string): number => {\n if (!/^(0|[1-9][0-9]*)$/.test(raw)) {\n throw new Error(\n `assetGroupIndex must be a canonical decimal integer, got ${JSON.stringify(raw)}`,\n );\n }\n return Number(raw);\n};\n\n/**\n * Typed parameters for {@link VHTLC.ScriptV2} contracts.\n *\n * The eight mandatory fields are `VHTLCContractParams` verbatim — the two\n * script versions take the same {@link VHTLC.Options}, so a divergent shape\n * here would be a difference with no cause. What V1's handler has no field for\n * is the two optional covenant leaves, and those are exactly what the swap\n * corridor's lockup carries, so leaving them out would make this handler unable\n * to round-trip the contract it exists to serve.\n */\nexport interface VHTLCV2ContractParams {\n sender: Uint8Array;\n receiver: Uint8Array;\n server: Uint8Array;\n preimageHash: Uint8Array;\n refundLocktime: bigint;\n unilateralClaimDelay: RelativeTimelock;\n unilateralRefundDelay: RelativeTimelock;\n unilateralRefundWithoutReceiverDelay: RelativeTimelock;\n /**\n * The Arkade asset the covenant leaves bind, if any.\n *\n * @see VHTLC.Options.asset\n */\n asset?: {\n /** The asset's genesis txid, 32 bytes, canonical order — as the serialized Asset ID carries it. */\n txid: Uint8Array;\n /** The asset group index within that genesis transaction. */\n groupIndex: number;\n };\n /** @see VHTLC.Options.nonInteractiveClaim */\n nonInteractiveClaim?: {\n receiverPkScript: Uint8Array;\n emulatorPubkey: Uint8Array;\n /** @see VHTLC.Options.nonInteractiveClaim.strict */\n strict?: { amount: bigint; assetAmount?: bigint };\n };\n /** @see VHTLC.Options.nonInteractiveRefund */\n nonInteractiveRefund?: {\n senderPkScript: Uint8Array;\n emulatorPubkey: Uint8Array;\n };\n}\n\n/**\n * Both halves of an optional covenant leaf, or neither.\n *\n * A row carrying one half of the pair would derive a script with that leaf\n * DROPPED — a different taproot tree, a different pkScript, and so a\n * `Script mismatch` from `upsertContractRow` naming two hex strings and no\n * cause. Rejecting the half-specified pair here names it instead. It is a\n * diagnostic, not a safety boundary: the mismatch check is what actually stops\n * a wrong script from being persisted, and it stops this case too.\n */\nfunction decodeCovenantLeaf<K extends string>(\n params: Record<string, string>,\n destinationKey: K,\n emulatorKey: string,\n label: string,\n): { destination: Uint8Array; emulatorPubkey: Uint8Array } | undefined {\n const destination = params[destinationKey];\n const emulator = params[emulatorKey];\n if (!destination && !emulator) return undefined;\n if (!destination || !emulator) {\n throw new Error(`${label} needs both '${destinationKey}' and '${emulatorKey}', or neither`);\n }\n return { destination: hex.decode(destination), emulatorPubkey: hex.decode(emulator) };\n}\n\n/**\n * Handler for {@link VHTLC.ScriptV2} — the VHTLC whose preimage leaves carry an\n * explicit `OP_SIZE 32 OP_EQUALVERIFY` before the hash check, and which the RFQ\n * swap corridor builds (`@arkade-os/swap`'s `lightningSendVtxoScript`).\n *\n * **Why a separate type string rather than a flag on `vhtlc`.** A handler's\n * `type` names the script class it derives, the way every other registered type\n * does (`default` → `DefaultVtxo.Script`, `vhtlc` → `VHTLC.Script`, `boarding`,\n * `arkade`). V1 and V2 produce different script bytes — and so different\n * pkScripts — for identical participant keys, and `upsertContractRow` derives\n * the script from `params` and refuses any row whose supplied `script` does not\n * match. One type cannot serve both. `vhtlc-v2` also cannot COLLIDE with\n * `vhtlc`: a colliding row needs one pkScript claimed by two types, and the two\n * versions' preimage conditions differ in every tree, so no parameters make\n * them equal. A use-named type (`swap-lockup`) was the alternative and is\n * worse: contracts are keyed by script, so the moment a second use registered\n * the same ScriptV2 the two uses would fight over one row.\n *\n * **Which leaves this offers, and why the set is smaller than the ladder.**\n * ScriptV2 has eight leaves; a wallet holding ONE of the two participant keys\n * can satisfy four of them, and offering a leaf whose signature the caller\n * cannot produce is worse than offering fewer — it turns a refusal into a\n * transaction that gets built and then rejected.\n *\n * | leaf | needs | offered |\n * |-----------------------------------|--------------------------------|---------|\n * | `claim` | receiver + server, preimage | yes, to the receiver |\n * | `refund` | sender + receiver + server | no — needs the counterparty live |\n * | `refundWithoutReceiver` | sender + server, CLTV | yes, to the sender |\n * | `unilateralClaim` | receiver, CSV | yes, to the receiver |\n * | `unilateralRefund` | sender + receiver, CSV | no — needs the counterparty live |\n * | `unilateralRefundWithoutReceiver` | sender, CSV | yes, to the sender |\n * | `nonInteractiveClaim` | server + emulator | no — the wallet holds neither key |\n * | `nonInteractiveRefund` | server + receiver + emulator | no — the wallet holds neither key |\n *\n * The two omitted interactive leaves are the same two the `vhtlc` handler\n * omits, for the same reason: `refund` and `unilateralRefund` both need the\n * OTHER party's signature, and this protocol has no message that asks for one\n * (see `@arkade-os/swap`'s `refund.ts` module doc). The two covenant leaves are\n * pushed by the emulator on the counterparty's behalf and are not this wallet's\n * to build at all.\n *\n * So `refundWithoutReceiver` is the sender's only collaborative way out, gated\n * on the CLTV the quote committed to — which is exactly the leaf\n * `pushRefundWithoutReceiver` builds. The CSV leaves are offered only in the\n * non-collaborative context, where the caller has already accepted that\n * spending them means a real unilateral exit first.\n *\n * The selection discipline is deliberately identical to the `vhtlc` handler's,\n * and `test/contracts/vhtlcV2-handler.test.ts` pins the two against each other\n * rung-for-rung across every role and timelock context so they cannot drift.\n */\nexport const VHTLCV2ContractHandler: ContractHandler<VHTLCV2ContractParams, VHTLC.ScriptV2> &\n TapscriptDeriving<VHTLC.ScriptV2> = {\n type: \"vhtlc-v2\",\n\n createScript(params: Record<string, string>): VHTLC.ScriptV2 {\n const typed = this.deserializeParams(params);\n return new VHTLC.ScriptV2(typed);\n },\n\n serializeParams(params: VHTLCV2ContractParams): Record<string, string> {\n return {\n sender: hex.encode(params.sender),\n receiver: hex.encode(params.receiver),\n server: hex.encode(params.server),\n hash: hex.encode(params.preimageHash),\n refundLocktime: params.refundLocktime.toString(),\n claimDelay: timelockToSequence(params.unilateralClaimDelay).toString(),\n refundDelay: timelockToSequence(params.unilateralRefundDelay).toString(),\n refundNoReceiverDelay: timelockToSequence(\n params.unilateralRefundWithoutReceiverDelay,\n ).toString(),\n // Spread rather than written as `undefined`: a `Record<string,\n // string>` round-tripped through a repository must not gain keys\n // whose value is the string \"undefined\".\n ...(params.nonInteractiveClaim && {\n nonInteractiveClaimReceiverPkScript: hex.encode(\n params.nonInteractiveClaim.receiverPkScript,\n ),\n nonInteractiveClaimEmulatorPubkey: hex.encode(\n params.nonInteractiveClaim.emulatorPubkey,\n ),\n // The opt-in quoted bound. Dropping it re-derives the DEFAULT\n // claim covenant — a strictly weaker one — and registration dies\n // at `upsertContractRow` with an opaque `Script mismatch`. Same\n // silent-drop class as the asset keys above.\n ...(params.nonInteractiveClaim.strict && {\n strictClaimAmount: params.nonInteractiveClaim.strict.amount.toString(),\n ...(params.nonInteractiveClaim.strict.assetAmount !== undefined && {\n strictClaimAssetAmount:\n params.nonInteractiveClaim.strict.assetAmount.toString(),\n }),\n }),\n }),\n ...(params.nonInteractiveRefund && {\n nonInteractiveRefundSenderPkScript: hex.encode(\n params.nonInteractiveRefund.senderPkScript,\n ),\n nonInteractiveRefundEmulatorPubkey: hex.encode(\n params.nonInteractiveRefund.emulatorPubkey,\n ),\n }),\n // The asset must round-trip, and its absence here used to be silent\n // in the worst way. `ContractManager` re-derives a contract from\n // these params; dropping the asset derives the SAT-ONLY script, so\n // registration died at `upsertContractRow` with a `Script mismatch`\n // naming two hex strings and no cause. Same silent-drop class\n // `validateOptions` refuses one layer up.\n //\n // Two keys rather than one blob, mirroring the script's own view of\n // an Asset ID as a (txid, groupIndex) pair.\n ...(params.asset && {\n assetTxid: hex.encode(params.asset.txid),\n assetGroupIndex: params.asset.groupIndex.toString(),\n }),\n };\n },\n\n deserializeParams(params: Record<string, string>): VHTLCV2ContractParams {\n const claim = decodeCovenantLeaf(\n params,\n \"nonInteractiveClaimReceiverPkScript\",\n \"nonInteractiveClaimEmulatorPubkey\",\n \"nonInteractiveClaim\",\n );\n const refund = decodeCovenantLeaf(\n params,\n \"nonInteractiveRefundSenderPkScript\",\n \"nonInteractiveRefundEmulatorPubkey\",\n \"nonInteractiveRefund\",\n );\n // Both halves or neither: a txid without its group index names no asset,\n // and an index without a txid names nothing at all. Either alone is a\n // corrupt row rather than a contract that happens to lack an asset, and\n // reading it as the latter re-derives the sat-only script — the exact\n // silent drop this round-trip exists to close.\n if ((params.assetTxid === undefined) !== (params.assetGroupIndex === undefined)) {\n throw new Error(\n \"asset params are incomplete: assetTxid and assetGroupIndex must both be present or both absent\",\n );\n }\n if (params.strictClaimAssetAmount !== undefined && params.strictClaimAmount === undefined) {\n throw new Error(\n \"strictClaimAssetAmount without strictClaimAmount: reading this as 'not strict' \" +\n \"would re-derive the default claim covenant, which is weaker than the row asked for\",\n );\n }\n const asset =\n params.assetTxid !== undefined && params.assetGroupIndex !== undefined\n ? {\n txid: hex.decode(params.assetTxid),\n groupIndex: parseGroupIndex(params.assetGroupIndex),\n }\n : undefined;\n return {\n sender: hex.decode(params.sender),\n receiver: hex.decode(params.receiver),\n server: hex.decode(params.server),\n preimageHash: hex.decode(params.hash),\n refundLocktime: BigInt(params.refundLocktime),\n ...(asset && { asset }),\n unilateralClaimDelay: sequenceToTimelock(Number(params.claimDelay)),\n unilateralRefundDelay: sequenceToTimelock(Number(params.refundDelay)),\n unilateralRefundWithoutReceiverDelay: sequenceToTimelock(\n Number(params.refundNoReceiverDelay),\n ),\n ...(claim && {\n nonInteractiveClaim: {\n receiverPkScript: claim.destination,\n emulatorPubkey: claim.emulatorPubkey,\n ...(params.strictClaimAmount !== undefined && {\n strict: {\n amount: BigInt(params.strictClaimAmount),\n ...(params.strictClaimAssetAmount !== undefined && {\n assetAmount: BigInt(params.strictClaimAssetAmount),\n }),\n },\n }),\n },\n }),\n ...(refund && {\n nonInteractiveRefund: {\n senderPkScript: refund.destination,\n emulatorPubkey: refund.emulatorPubkey,\n },\n }),\n };\n },\n\n /**\n * Select spending path based on context.\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n selectPath(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const role = resolveRole(contract, context);\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (!role) {\n return null;\n }\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n return {\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n };\n }\n\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n return {\n leaf: script.refundWithoutReceiver(),\n };\n }\n\n return null;\n }\n\n // Unilateral paths\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n };\n }\n\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (!isCsvSpendable(context, sequence)) return null;\n return {\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n };\n }\n\n return null;\n },\n\n /**\n * Get all possible spending paths (no timelock checks).\n *\n * Role is determined from `context.role` or by matching\n * `context.walletDescriptor` (preferred) / `context.walletPubKey`\n * against sender/receiver in contract params.\n */\n getAllSpendingPaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n\n if (context.collaborative) {\n // Collaborative paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\") {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n } else {\n // Unilateral paths (no timelock checks)\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n getSpendablePaths(\n script: VHTLC.ScriptV2,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n const role = resolveRole(contract, context);\n const paths: PathSelection[] = [];\n\n if (!role) {\n return paths;\n }\n\n const preimage = contract.params?.preimage;\n const refundLocktime = BigInt(contract.params.refundLocktime);\n\n if (context.collaborative) {\n if (role === \"receiver\" && preimage) {\n paths.push({\n leaf: script.claim(),\n extraWitness: [hex.decode(preimage)],\n });\n }\n if (role === \"sender\" && isCltvSatisfied(context, refundLocktime)) {\n paths.push({\n leaf: script.refundWithoutReceiver(),\n });\n }\n return paths;\n }\n\n if (role === \"receiver\" && preimage) {\n const sequence = Number(contract.params.claimDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralClaim(),\n extraWitness: [hex.decode(preimage)],\n sequence,\n });\n }\n }\n if (role === \"sender\") {\n const sequence = Number(contract.params.refundNoReceiverDelay);\n if (isCsvSpendable(context, sequence)) {\n paths.push({\n leaf: script.unilateralRefundWithoutReceiver(),\n sequence,\n });\n }\n }\n\n return paths;\n },\n\n /**\n * Refuse an explicit spend of a lockup whose refund path has not opened.\n * @see assertVhtlcSpendableNow for why this is the one certain case.\n */\n assertSpendableNow(_script: VHTLC.ScriptV2, contract: Contract, context: PathContext): void {\n assertVhtlcSpendableNow(contract, context);\n },\n\n /**\n * Never. A live VHTLC is escrow: the counterparty's claim leaf is armed,\n * and generic selection — send, settle, RENEWAL, offboard — would move the\n * lockup out from under a swap the counterparty is still entitled to\n * complete, or race a claim already in flight. The `vhtlc` handler now\n * answers the same, for the same reason.\n *\n * The gate covers `available` and renewal. Recovery is generic and names\n * nothing, so it is not covered here: `recoverVtxos` filters on\n * {@link assertSpendableNow} instead, which drops a lockup only while its\n * refund path is shut rather than forever. The explicit routes out —\n * `settle({ inputs })`, or `@arkade-os/swap`'s `pushRefundWithoutReceiver`\n * over `findLockupVtxos`' outpoints — are unaffected either way.\n */\n isGenericallySpendable: () => false,\n\n /**\n * The annotation leaf stamped onto every VTXO locked to this contract.\n *\n * **Without this the contract is unusable, not merely unoptimized.**\n * `deriveContractTapscripts` falls back to `script.forfeit()` for any\n * handler that does not implement {@link TapscriptDeriving}, and no VHTLC\n * script version has a `forfeit()` — `VtxoScript` does not define one and\n * `VHTLC.BaseScript` does not add one. The fallback therefore throws\n * `legacy.forfeit is not a function`, `annotatableIn` catches it, and\n * `fetchContractVtxosBulk` drops this contract's VTXOs before they are\n * persisted. The row would exist and be watched while its balance stayed\n * permanently invisible, and `getSyncState()` would report `degraded`\n * forever. (The `vhtlc` handler had the same gap and now closes it the same\n * way; nothing registers V1 rows through `ContractManager` in this repo, so\n * it was never hit here.)\n *\n * `refundWithoutReceiver` is the leaf, for both roles the annotation\n * serves, because it is the only collaborative path this wallet can\n * actually satisfy as the sender — the same conclusion `selectPath`\n * reaches, kept in step with it deliberately. The claim leaves belong to\n * the receiver and need a preimage the sender does not have; `refund` and\n * `unilateralRefund` need the counterparty; the covenant leaves are the\n * emulator's.\n *\n * **It carries a CLTV, and callers must respect it.** A settlement built on\n * this leaf is only valid once `refundLocktime` has matured, so a recovery\n * round that sweeps this VTXO early is rejected by the server. That is the\n * same constraint `packages/boltz-swap` encodes as \"pre-CLTV recoverable →\n * skipped\"; nothing in this handler can enforce it, because the annotation\n * is derived per contract and knows no clock. `recoverVtxos` filters on\n * {@link assertSpendableNow} for it.\n *\n * **Role-blind.** A receiver's row gets the same leaf, which names keys that\n * wallet does not hold, so it is satisfiable only by the wallet holding the\n * lockup's `sender` key and fails at intent registration for anyone else.\n */\n deriveTapscripts(script: VHTLC.ScriptV2): DerivedContractTapscripts {\n const leaf = script.refundWithoutReceiver();\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","import { hex } from \"@scure/base\";\nimport { DefaultVtxo } from \"../../script/default\";\nimport { Contract, ContractHandler, Discoverable, PathContext, PathSelection } from \"../types\";\nimport type { DiscoveredContract, DiscoveryDeps } from \"../types\";\nimport { DefaultContractHandler, DefaultContractParams } from \"./default\";\nimport { deriveDescriptorLeafPubKey } from \"../../identity/descriptor\";\nimport { timelockToSequence } from \"../../utils/timelock\";\nimport { rotatedReceiveMetadata } from \"./helpers\";\n\n/**\n * Typed parameters for boarding contracts.\n *\n * Boarding reuses the exact `default` contract parameter shape\n * (`pubKey` / `serverPubKey` / `csvTimelock`) rather than inventing\n * boarding-specific names — the boarding semantics come from the\n * contract type and from populating `csvTimelock` with the server's\n * boarding-exit delay (`ArkInfo.boardingExitDelay`) instead of the\n * offchain unilateral-exit delay.\n */\nexport type BoardingContractParams = DefaultContractParams;\n\n/**\n * Handler for the boarding contract (registered type `boarding`).\n *\n * The boarding contract derives the on-chain Bitcoin address used to\n * board funds onto Arkade. It shares the exact `DefaultVtxo.Script`\n * shape with the `default` contract — a Taproot output co-owned by the\n * wallet and the Ark server, with a CSV exit path back to the wallet —\n * and therefore reuses the `default` handler's path logic (forfeit via\n * server cooperation, exit after the boarding CSV).\n *\n * Boarding semantics come entirely from the contract type and from\n * sourcing the CSV timelock from the server's boarding-exit delay\n * (`ArkInfo.boardingExitDelay`), not from renamed parameters. The\n * offchain `default` contract is built from `ArkInfo.unilateralExitDelay`\n * instead, so the two share a script shape but differ in their CSV\n * timelock value. Parameters round-trip through the same\n * `timelockToSequence` / `sequenceToTimelock` helpers and BIP68 sequence\n * encoding as `default` / `delegate`.\n *\n * Like `default` / `delegate`, the boarding handler implements\n * {@link Discoverable.discoverAt} so `wallet.restore()` can rediscover\n * used boarding indices from authoritative on-chain data. It differs from\n * the L2 handlers in its source of truth: boarding probes the **on-chain**\n * UTXO set at its P2TR address (`OnchainProvider.getCoins`) rather than the\n * Ark indexer, and builds its candidate from the boarding-exit CSV\n * (`deps.boardingTimelock`). When boarding discovery is not plumbed (no\n * `deps.boardingTimelock` / `deps.onchainNetwork`) `discoverAt` no-ops.\n *\n * Identity & the default/boarding collision: a contract's `script` (pkScript)\n * is its unique identity — a script owns exactly one repository row. `boarding`\n * is a first-class type with its own row **when its script is distinct** from\n * the wallet's `default` baseline — the real-world case, since a sound Ark\n * server keeps boardingExitDelay strictly longer than unilateralExitDelay (equal\n * delays would expose the provider to a double-spend). Should those delays ever\n * coincide (a misconfigured/malicious server), the boarding script is\n * byte-identical to the default script. `discoverAt` does NOT pre-coalesce that\n * collision: it always emits `type: \"boarding\"`, and the single shared row is\n * resolved FIRST-WINS at the persistence layer\n * ({@link ContractManager.upsertContract}) — whichever purpose is persisted\n * first keeps the row, and the scan deliberately probes boarding first\n * (see docs/hd-wallets_onchain_rotation_collision_fix.md §5.1–5.2). Either way\n * the funds are equally spendable through the shared `DefaultVtxo.Script` paths.\n * Consumers must NOT rely on `contract.type === \"boarding\"` to identify the\n * boarding purpose — resolve the boarding script via\n * `wallet.getBoardingAddress()` / `wallet.boardingTapscript` (which never depend\n * on the persisted contract's type) and match by script when needed.\n */\nexport const BoardingContractHandler: ContractHandler<BoardingContractParams, DefaultVtxo.Script> &\n Discoverable = {\n type: \"boarding\",\n\n createScript(params: Record<string, string>): DefaultVtxo.Script {\n return DefaultContractHandler.createScript(params);\n },\n\n serializeParams(params: BoardingContractParams): Record<string, string> {\n return DefaultContractHandler.serializeParams(params);\n },\n\n deserializeParams(params: Record<string, string>): BoardingContractParams {\n return DefaultContractHandler.deserializeParams(params);\n },\n\n selectPath(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n return DefaultContractHandler.selectPath(script, contract, context);\n },\n\n getAllSpendingPaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return DefaultContractHandler.getAllSpendingPaths(script, contract, context);\n },\n\n getSpendablePaths(\n script: DefaultVtxo.Script,\n contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return DefaultContractHandler.getSpendablePaths(script, contract, context);\n },\n\n /** Preserves today's settle/board behaviour. */\n isGenericallySpendable: () => true,\n\n /**\n * Probe the on-chain UTXO set for a boarding output at this HD index.\n *\n * Boarding's source of truth is the **current** on-chain coin set\n * (`OnchainProvider.getCoins`), not the Ark indexer: a boarded (spent)\n * boarding output becomes an L2 VTXO at the receive index, so the\n * indexer probe already keeps the gap window open for it; only an\n * *unspent* boarding output needs the on-chain probe (see plan §2).\n *\n * No-ops (returns `[]`) when boarding discovery is not plumbed — i.e.\n * `deps.boardingTimelock` or `deps.onchainNetwork` is absent — so the\n * scanner unit harness (which sets neither) is unaffected.\n *\n * Always emits `type: \"boarding\"`, even in the degenerate equal-delay case\n * where the boarding script is byte-identical to a `default` script at this\n * index (`boardingExitDelay === unilateralExitDelay`). The collision is no\n * longer pre-judged in discovery; it is tolerated FIRST-WINS at the\n * persistence layer ({@link ContractManager.upsertContract}). `deps.csvTimelocks`\n * is intentionally not read here.\n */\n async discoverAt(\n index: number,\n descriptor: string,\n deps: DiscoveryDeps,\n ): Promise<DiscoveredContract[]> {\n if (!deps.boardingTimelock || !deps.onchainNetwork) return [];\n\n const pubKey = deriveDescriptorLeafPubKey(descriptor);\n const script = new DefaultVtxo.Script({\n pubKey,\n serverPubKey: deps.serverPubKey,\n csvTimelock: deps.boardingTimelock,\n });\n const onchainAddress = script.onchainAddress(deps.onchainNetwork);\n\n const coins = await deps.onchainProvider.getCoins(onchainAddress);\n if (coins.length === 0) return [];\n\n const scriptHex = hex.encode(script.pkScript);\n const boardingSeq = timelockToSequence(deps.boardingTimelock);\n\n // Always `type: \"boarding\"` (see method doc). The equal-delay\n // same-script collision is resolved first-wins at persistence, and the\n // scan probes boarding before default so a both-purpose rotated index\n // resolves to a `boarding` row — keeping both the on-chain UTXO and any\n // L2 VTXO recoverable (docs/hd-wallets_onchain_rotation_collision_fix.md\n // §5.2, §5.4).\n return [\n {\n type: \"boarding\",\n params: {\n pubKey: hex.encode(pubKey),\n serverPubKey: hex.encode(deps.serverPubKey),\n csvTimelock: boardingSeq.toString(),\n },\n script: scriptHex,\n // The persisted row's `address` is the *Ark* address (not the\n // on-chain P2TR), matching the row registered at init so the\n // ContractWatcher keeps monitoring the same L2 script and the\n // VTXO repository bucket lines up (plan §6-I.4). The P2TR is\n // recomputed from params only for the `getCoins` probe.\n address: script.address(deps.network.hrp, deps.serverPubKey).encode(),\n // Tag rotated rows (index > 0) so boot resolution can find the\n // newest boarding address and descriptor-aware signing can\n // recover the per-index key (plan §6-II/§6-III.3). The index-0\n // baseline stays untagged, matching `default`/`delegate`.\n ...rotatedReceiveMetadata(index, descriptor),\n },\n ];\n },\n};\n","/**\n * Arkade Program model & compiler.\n *\n * A {@link Program} is the artifact shape shared with the ArkadeScript\n * compiler: named functions, each split into a `tapscript` segment enforced\n * on-chain and an optional `arkadeScript` segment emulated by the co-signing\n * service. This module owns everything that is *pure data → script*:\n *\n * - the Program/segment/token types,\n * - `$param` resolution ({@link resolveAsm}), witness and timelock resolution,\n * - program validation ({@link validateProgram}) — typed constructor params\n * are authoritative when present,\n * - {@link ArkadeProgramScript} — a {@link VtxoScript} compiled from a\n * program, its constructor args and the signer keys,\n * - artifact JSON (de)serialization ({@link parseArtifact} /\n * {@link stringifyArtifact}) and the string-keyed contract params used to\n * persist a program contract through the `src/contracts` pipeline.\n *\n * Keeping this free of provider/transaction imports lets the generic\n * `arkade` contract handler (src/contracts/handlers/arkade.ts) and the\n * high-level `ArkadeContract` client share one compilation path.\n *\n * @module arkade/program\n */\n\nimport { hex } from \"@scure/base\";\nimport { ScriptNum } from \"@scure/btc-signer\";\n\nimport {\n MultisigTapscript,\n CSVMultisigTapscript,\n CLTVMultisigTapscript,\n ConditionMultisigTapscript,\n ConditionCSVMultisigTapscript,\n type ArkTapscript,\n type TapscriptType,\n} from \"../script/tapscript\";\nimport { VtxoScript, type TapLeafScript } from \"../script/base\";\nimport { ArkadeScript } from \"./script\";\nimport { ARKADE_OP } from \"./opcodes\";\nimport { computeArkadeScriptPublicKey } from \"./tweak\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n// --- Program model (mirrors the compiler artifact) -------------------------\n\n/** A token in an `asm` array: an opcode name, a number/bigint push, raw bytes, or a `$param` placeholder. */\nexport type AsmToken = string | number | bigint | Uint8Array;\n\n/** A constructor argument or resolved value. */\nexport type ArkadeParamValue = Uint8Array | bigint | number;\n\n/** A function call argument (function input). */\nexport type ArkadeArgValue = Uint8Array | bigint | number;\n\n/**\n * The declared type of a function input, used to derive the static TS type of\n * the corresponding `functions.<name>(...)` argument. Byte-like types map to\n * `Uint8Array`; `int` maps to `bigint | number`.\n */\nexport type ArkadeArgType = \"bytes\" | \"pubkey\" | \"sig\" | \"hash\" | \"int\";\n\n/**\n * Maps an {@link ArkadeArgType} to its TypeScript argument type.\n * @internal\n */\nexport interface ArkadeValueType {\n bytes: Uint8Array;\n pubkey: Uint8Array;\n sig: Uint8Array;\n hash: Uint8Array;\n int: bigint | number;\n}\n\n/** A typed function input or constructor param: a name plus its {@link ArkadeArgType}. */\nexport interface InputDef {\n name: string;\n type: ArkadeArgType;\n}\n\n/**\n * A function input or constructor param declaration: either a typed descriptor\n * `{ name, type }` (the argument is statically typed and its bound value is\n * validated) or a bare name string (the argument falls back to the loose\n * {@link ArkadeArgValue}).\n */\nexport type InputRef = string | InputDef;\n\n/** Reference to a signer key: a `\"$param\"` reference or literal x-only bytes. */\nexport type SignerRef = string | Uint8Array;\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 /** Required signers. The tweaked co-signer is appended automatically when the path has an `arkadeScript`. */\n signers: SignerRef[];\n /**\n * Optional standard-opcode condition (e.g. a hashlock), encoded into a\n * ConditionMultisig leaf — or ConditionCSVMultisig when combined with `csv`.\n */\n asm?: AsmToken[];\n /**\n * Relative timelock (CSV). The value is a literal or a `\"$param\"` reference\n * resolved against the constructor args (same convention as {@link SignerRef}).\n * Combinable with `asm` (condition + CSV); mutually exclusive with `cltv`.\n */\n csv?: { type: \"blocks\" | \"seconds\"; value: bigint | string };\n /**\n * Absolute timelock (CLTV): a literal or a `\"$param\"` reference.\n * Mutually exclusive with `csv`/`asm`.\n */\n cltv?: bigint | string;\n /** Items satisfying the condition (e.g. an HTLC preimage); set via the ConditionWitness PSBT field. */\n witness?: WitnessRef[];\n}\n\n/** Arkade Script segment of a spending path — emulated, bound via the key tweak. */\nexport interface ArkadeSegment {\n /** Raw Arkade opcodes with `$param` placeholders. */\n asm: AsmToken[];\n /** The arkade-script witness stack (e.g. an output index). */\n witness?: WitnessRef[];\n}\n\n/** One named spending path. */\nexport interface ArkadeFunction {\n /**\n * The function ABI: an ordered list of call arguments. Each entry is a typed\n * descriptor `{ name, type }` (which gives the matching `functions.<name>`\n * argument a precise static type) or a bare name string (loose\n * {@link ArkadeArgValue}). Absent for nullary paths (e.g. exit/cancel).\n */\n inputs?: readonly InputRef[];\n tapscript: TapscriptSegment;\n /** Present for covenant paths; absent for pure-tapscript paths (cancel/exit). */\n arkadeScript?: ArkadeSegment;\n}\n\nexport const SUPPORTED_PROGRAM_VERSION = 0;\n\n/** An Arkade contract program (hand-written or compiler-emitted). */\nexport interface Program {\n version: number;\n /**\n * Optional program name — metadata only: round-tripped through the\n * artifact JSON, never used in compilation or the taproot tree.\n */\n name?: string;\n /**\n * Ordered constructor parameters. Bare name strings are documentation only\n * (the legacy hand-written form); typed descriptors `{ name, type }` make\n * the list authoritative — see {@link validateProgram}.\n */\n params?: readonly InputRef[];\n functions: Record<string, ArkadeFunction>;\n}\n\n// --- helpers ---------------------------------------------------------------\n\n/** The declared name of a function input or constructor param, whether typed descriptor or bare string. */\nexport function inputName(ref: InputRef): string {\n return typeof ref === \"string\" ? ref : ref.name;\n}\n\n/** Look up a `$param` / function-input value in a bind map; throws when unbound. */\nexport function bindValue(bind: Record<string, ArkadeParamValue>, name: string): ArkadeParamValue {\n const v = bind[name];\n if (v === undefined) throw new Error(`unbound parameter '${name}'`);\n return v;\n}\n\n/**\n * Resolve a timelock value to a bigint: bigints pass through; a `\"$param\"`\n * string resolves against the program's constructor args and must be bound to\n * a bigint/number. Any other string is an error.\n */\nexport function resolveTimelockValue(\n value: bigint | string,\n args: Record<string, ArkadeParamValue>,\n): bigint {\n if (typeof value === \"bigint\") return value;\n if (value.startsWith(\"$\")) {\n const v = bindValue(args, value.slice(1));\n if (typeof v === \"bigint\" || typeof v === \"number\") return BigInt(v);\n throw new Error(`timelock value '${value}' must resolve to a number`);\n }\n throw new Error(\n `invalid timelock value '${value}' — expected a bigint or a '$param' reference`,\n );\n}\n\n/**\n * Resolve an `asm` array to bytes: substitute `$param` placeholders from `bind`,\n * pass everything else (opcode names, numbers, raw byte pushes) through to the\n * Arkade script encoder. The SDK does not interpret opcodes — this is pure\n * substitution + encoding. To embed a signer key (server, user, or any\n * other), pass it as a `$param` in the constructor args; there is no\n * `<SERVER_KEY>`/`<COSIGNER_KEY>` token.\n */\nexport function resolveAsm(asm: AsmToken[], bind: Record<string, ArkadeParamValue>): Uint8Array {\n const tokens = asm.map((t) => {\n if (typeof t === \"string\" && t.startsWith(\"$\")) {\n return bindValue(bind, t.slice(1));\n }\n if (t === \"<SELF>\") {\n // Continuation covenants don't hard-code their own address (that would\n // be a non-converging fixpoint); express them with input introspection\n // (PUSHCURRENTINPUTINDEX + INSPECTINPUTSCRIPTPUBKEY) instead.\n throw new Error(\n \"<SELF> is not a placeholder; use INSPECTINPUTSCRIPTPUBKEY for continuation covenants\",\n );\n }\n return t;\n });\n return ArkadeScript.encode(tokens as never);\n}\n\n/**\n * Resolve one witness-stack item to bytes.\n *\n * - raw bytes pass through;\n * - numbers/bigints encode as minimal script-nums;\n * - `\"$param\"` strings resolve against the program's constructor args;\n * - any other string is a function-input name and resolves against `callArgs`\n * (throws when the input is unbound — e.g. outside a function call).\n */\nexport function witnessRefToBytes(\n ref: WitnessRef,\n callArgs: Record<string, ArkadeArgValue>,\n programArgs: Record<string, ArkadeParamValue>,\n): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (typeof ref === \"number\" || typeof ref === \"bigint\") {\n return MinimalScriptNum.encode(BigInt(ref));\n }\n const v = ref.startsWith(\"$\") ? bindValue(programArgs, ref.slice(1)) : bindValue(callArgs, ref);\n if (v instanceof Uint8Array) return v;\n return MinimalScriptNum.encode(BigInt(v));\n}\n\n/**\n * Validate a tapscript segment: it must have signers; `asm` may combine with\n * `csv` (the condition + CSV closure) but `cltv` conflicts with both (arkd\n * recognizes no condition+CLTV or dual-timelock closure); the `asm` may not\n * contain Arkade opcodes (those are `OP_SUCCESS` on-chain and belong in the\n * `arkadeScript` segment).\n */\nexport function validateTapscript(seg: TapscriptSegment): void {\n if (!seg.signers || seg.signers.length === 0) {\n throw new Error(\"tapscript: at least one signer is required\");\n }\n if (seg.asm !== undefined && seg.cltv !== undefined) {\n throw new Error(\n \"tapscript: `asm` and `cltv` conflict — arkd has no condition+CLTV closure\",\n );\n }\n if (seg.csv !== undefined && seg.cltv !== undefined) {\n throw new Error(\"tapscript: `csv` and `cltv` conflict — use at most one timelock\");\n }\n for (const t of seg.asm ?? []) {\n if (typeof t === \"string\" && t in ARKADE_OP) {\n throw new Error(\n `tapscript: arkade opcode '${t}' is not enforceable on-chain — move it to arkadeScript`,\n );\n }\n }\n}\n\n/** Collect every `\"$name\"` reference in a program's signers, asm, witness and timelock values. */\nfunction collectParamRefs(program: Program): Set<string> {\n const refs = new Set<string>();\n const collect = (items: readonly (AsmToken | WitnessRef | SignerRef)[] | undefined) => {\n for (const t of items ?? []) {\n if (typeof t === \"string\" && t.startsWith(\"$\")) refs.add(t.slice(1));\n }\n };\n for (const fn of Object.values(program.functions)) {\n const tap = fn.tapscript;\n collect(tap.signers);\n collect(tap.asm);\n collect(tap.witness);\n collect(tap.csv ? [tap.csv.value] : undefined);\n collect(tap.cltv !== undefined ? [tap.cltv] : undefined);\n collect(fn.arkadeScript?.asm);\n collect(fn.arkadeScript?.witness);\n }\n return refs;\n}\n\n/** Byte lengths enforced for typed values (x-only pubkey, BIP340 signature). */\nconst TYPED_BYTE_LENGTHS: Partial<Record<ArkadeArgType, number>> = { pubkey: 32, sig: 64 };\n\n/** Validate a bound value against its typed declaration; errors name the parameter. */\nfunction validateParamValue(def: InputDef, value: ArkadeParamValue): void {\n if (def.type === \"int\") {\n if (typeof value !== \"bigint\" && typeof value !== \"number\") {\n throw new Error(`program parameter '${def.name}' expects an int, got bytes`);\n }\n return;\n }\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `program parameter '${def.name}' expects ${def.type} bytes, got ${typeof value}`,\n );\n }\n const length = TYPED_BYTE_LENGTHS[def.type];\n if (length !== undefined && value.length !== length) {\n throw new Error(\n `program parameter '${def.name}' expects a ${length}-byte ${def.type}, got ${value.length} bytes`,\n );\n }\n}\n\n/**\n * Validate a program's constructor-parameter declarations against the bound\n * args. A `params` list of bare name strings is documentation only (the\n * legacy hand-written form — no checks). When at least one entry is a typed\n * descriptor (the compiler-emitted form), the list is authoritative: every\n * declared param must be bound in `args`, every `\"$name\"` reference in the\n * program must be declared, and typed entries validate their bound value\n * (bytes-like types require a Uint8Array — 32 bytes for `pubkey`, 64 for\n * `sig`; `int` requires a bigint/number).\n */\nexport function validateProgram(program: Program, args: Record<string, ArkadeParamValue>): void {\n const params = program.params;\n if (!params || !params.some((p) => typeof p !== \"string\")) return;\n\n const declared = new Set(params.map(inputName));\n for (const name of declared) {\n if (args[name] === undefined) {\n throw new Error(`program parameter '${name}' is declared but not bound in args`);\n }\n }\n for (const ref of collectParamRefs(program)) {\n if (!declared.has(ref)) {\n throw new Error(`'$${ref}' is referenced but not declared in program params`);\n }\n }\n for (const p of params) {\n if (typeof p !== \"string\") validateParamValue(p, args[p.name]);\n }\n}\n\n// --- Compilation -----------------------------------------------------------\n\n/** The signer keys a program is compiled against. */\nexport interface ProgramKeys {\n /** The Arkade Service signer key (x-only) — used for address derivation and collaborative-path detection, not for `$param` resolution. */\n serverKey: Uint8Array;\n /** The wallet's x-only key — identifies which inputs the wallet signs. */\n userKey?: Uint8Array;\n /** The co-signer (emulator) key — required only for covenant (`arkadeScript`) functions. */\n emulatorKey?: Uint8Array;\n}\n\n/**\n * A single spending path, fully resolved at compilation: its definition, the\n * committed leaf body, the per-path arkade-script bytes (covenant paths only),\n * and the {@link TapLeafScript} (control block) for spending it.\n */\nexport interface CompiledProgramFunction {\n name: string;\n def: ArkadeFunction;\n /** The committed leaf script (body). */\n leafScript: Uint8Array;\n /** Resolved arkade-script bytes; undefined for pure-tapscript paths. */\n arkadeScript?: Uint8Array;\n /** Resolved signer keys (x-only), in the declared `signers` order. */\n signerKeys: Uint8Array[];\n /** Resolved once — the taproot leaf + control block for this path. */\n tapLeafScript: TapLeafScript;\n}\n\n/** Resolve a {@link SignerRef} to x-only key bytes against the program's constructor args. */\nfunction resolveSigner(ref: SignerRef, args: Record<string, ArkadeParamValue>): Uint8Array {\n if (ref instanceof Uint8Array) return ref;\n if (!ref.startsWith(\"$\")) {\n throw new Error(`unknown signer reference '${ref}' — use '$${ref}'`);\n }\n const v = bindValue(args, ref.slice(1));\n if (!(v instanceof Uint8Array)) {\n throw new Error(`signer ${ref} must be a pubkey (bytes)`);\n }\n return v;\n}\n\nfunction encodeTapscriptSegment(\n seg: TapscriptSegment,\n pubkeys: Uint8Array[],\n args: Record<string, ArkadeParamValue>,\n): ArkTapscript<TapscriptType, any> {\n if (seg.csv) {\n const timelock = { type: seg.csv.type, value: resolveTimelockValue(seg.csv.value, args) };\n if (seg.asm) {\n // The fifth arkd closure: condition + CSV.\n return ConditionCSVMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n timelock,\n pubkeys,\n });\n }\n return CSVMultisigTapscript.encode({ timelock, pubkeys });\n }\n if (seg.cltv !== undefined) {\n return CLTVMultisigTapscript.encode({\n absoluteTimelock: resolveTimelockValue(seg.cltv, args),\n pubkeys,\n });\n }\n if (seg.asm) {\n return ConditionMultisigTapscript.encode({\n conditionScript: resolveAsm(seg.asm, args),\n pubkeys,\n });\n }\n return MultisigTapscript.encode({ pubkeys });\n}\n\nfunction compileFunctions(\n program: Program,\n args: Record<string, ArkadeParamValue>,\n keys: ProgramKeys,\n): Omit<CompiledProgramFunction, \"tapLeafScript\">[] {\n if (program.version !== SUPPORTED_PROGRAM_VERSION) {\n throw new Error(\n `ArkadeContract: unsupported program version ${program.version} — this SDK supports version ${SUPPORTED_PROGRAM_VERSION}`,\n );\n }\n const functions: Record<string, ArkadeFunction> = program.functions;\n const names = Object.keys(functions);\n if (names.length === 0) {\n throw new Error(\"ArkadeContract: program has no functions\");\n }\n validateProgram(program, args);\n const defs = names.map((n) => functions[n]);\n\n // Covenant functions need the emulator's co-signer key for the tweak.\n const covenant = names.find((_, i) => defs[i].arkadeScript);\n if (covenant && !keys.emulatorKey) {\n throw new Error(\n `ArkadeContract: function '${covenant}' has an arkadeScript but no emulator is configured — pass an \\`emulator\\` to Arkade.connect`,\n );\n }\n\n return defs.map((def, i) => {\n validateTapscript(def.tapscript);\n const pubkeys = def.tapscript.signers.map((s) => resolveSigner(s, args));\n\n // Covenant leaf: bind the emulator's co-signer key to the arkade\n // script via the tagged-hash tweak, then append it to the leaf's\n // signer set.\n const arkadeScript = def.arkadeScript ? resolveAsm(def.arkadeScript.asm, args) : undefined;\n const leafPubkeys = arkadeScript\n ? [...pubkeys, computeArkadeScriptPublicKey(keys.emulatorKey!, arkadeScript)]\n : pubkeys;\n const leafScript = encodeTapscriptSegment(def.tapscript, leafPubkeys, args).script;\n return { name: names[i], def, leafScript, arkadeScript, signerKeys: pubkeys };\n });\n}\n\n/**\n * A {@link VtxoScript} compiled from an Arkade {@link Program}, its\n * constructor args and the signer keys.\n *\n * This is the single compilation path shared by the high-level\n * `ArkadeContract` client and the `\"arkade\"` contract handler: both produce\n * byte-identical taproot trees for the same (program, args, keys), so a\n * contract registered through the `src/contracts` pipeline re-derives the\n * exact script it was created with.\n */\nexport class ArkadeProgramScript extends VtxoScript {\n /** Spending paths in declaration order. */\n readonly compiled: CompiledProgramFunction[];\n\n constructor(\n readonly program: Program,\n readonly args: Record<string, ArkadeParamValue>,\n readonly keys: ProgramKeys,\n ) {\n const partial = compileFunctions(program, args, keys);\n super(partial.map((p) => p.leafScript));\n this.compiled = partial.map((p) => ({\n ...p,\n tapLeafScript: this.findLeaf(hex.encode(p.leafScript)),\n }));\n }\n\n /** The compiled spending path with the given function name, if any. */\n functionByName(name: string): CompiledProgramFunction | undefined {\n return this.compiled.find((f) => f.name === name);\n }\n}\n\n// --- Artifact JSON ----------------------------------------------------------\n\n/**\n * Convert a compiler-style 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 */\nexport function parseArtifact(artifact: {\n version?: number;\n name?: string;\n params?: readonly InputRef[];\n functions: Record<string, any>;\n}): Program {\n const hexToken = (t: unknown): any =>\n typeof t === \"string\" && t.startsWith(\"0x\") ? hex.decode(t.slice(2)) : t;\n // A \"$param\" timelock stays a reference (resolved at compile time); anything\n // else is a literal.\n const timelockValue = (v: unknown): bigint | string =>\n typeof v === \"string\" && v.startsWith(\"$\") ? v : BigInt(v as string | number);\n\n const functions: Record<string, ArkadeFunction> = {};\n for (const [name, fn] of Object.entries(artifact.functions)) {\n const tap = fn.tapscript ?? {};\n const tapscript: TapscriptSegment = {\n signers: (tap.signers ?? []).map(hexToken),\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 };\n const arkadeScript = fn.arkadeScript\n ? {\n asm: fn.arkadeScript.asm.map(hexToken),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(hexToken) }\n : {}),\n }\n : undefined;\n functions[name] = {\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript,\n ...(arkadeScript ? { arkadeScript } : {}),\n };\n }\n return {\n version: artifact.version ?? SUPPORTED_PROGRAM_VERSION,\n ...(artifact.name !== undefined ? { name: artifact.name } : {}),\n ...(artifact.params ? { params: artifact.params } : {}),\n functions,\n };\n}\n\n/**\n * Serialize a {@link Program} to compiler-artifact JSON — the inverse of\n * {@link parseArtifact}: bytes become `0x`-hex strings; bigint tokens become\n * plain numbers (or, above `Number.MAX_SAFE_INTEGER`, `0x`-hex of their\n * minimal script-num bytes, which the script encoder pushes identically);\n * literal timelock values serialize as decimal strings while `\"$param\"`\n * timelock references are emitted as-is.\n */\nexport function stringifyArtifact(program: Program): string {\n const token = (t: AsmToken | WitnessRef | SignerRef): unknown => {\n if (t instanceof Uint8Array) return \"0x\" + hex.encode(t);\n if (typeof t === \"bigint\") {\n if (t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(t);\n }\n // Out of JSON-safe integer range: a plain decimal string would be\n // misread as an opcode name, so emit the equivalent byte push.\n return \"0x\" + hex.encode(MinimalScriptNum.encode(t));\n }\n return t;\n };\n\n const functions: Record<string, unknown> = {};\n for (const [name, fn] of Object.entries(program.functions)) {\n const tap = fn.tapscript;\n functions[name] = {\n ...(fn.inputs ? { inputs: fn.inputs } : {}),\n tapscript: {\n signers: tap.signers.map(token),\n ...(tap.asm ? { asm: tap.asm.map(token) } : {}),\n ...(tap.witness ? { witness: tap.witness.map(token) } : {}),\n ...(tap.csv\n ? { csv: { type: tap.csv.type, value: tap.csv.value.toString() } }\n : {}),\n ...(tap.cltv !== undefined ? { cltv: tap.cltv.toString() } : {}),\n },\n ...(fn.arkadeScript\n ? {\n arkadeScript: {\n asm: fn.arkadeScript.asm.map(token),\n ...(fn.arkadeScript.witness\n ? { witness: fn.arkadeScript.witness.map(token) }\n : {}),\n },\n }\n : {}),\n };\n }\n\n return JSON.stringify({\n version: program.version,\n ...(program.name !== undefined ? { name: program.name } : {}),\n ...(program.params ? { params: program.params } : {}),\n functions,\n });\n}\n\n// --- Persisted contract params ----------------------------------------------\n\n/**\n * Typed parameters of an `\"arkade\"` contract as persisted through the\n * `src/contracts` pipeline. The program serializes as artifact JSON, args as\n * a JSON map (`0x`-hex bytes, decimal-string bigints), keys as hex — so a\n * stored contract row re-derives its script fully offline.\n */\nexport interface ArkadeContractParams {\n program: Program;\n args: Record<string, ArkadeParamValue>;\n serverKey: Uint8Array;\n userKey?: Uint8Array;\n emulatorKey?: Uint8Array;\n}\n\nfunction serializeArgValue(v: ArkadeParamValue): string | number {\n if (v instanceof Uint8Array) return \"0x\" + hex.encode(v);\n if (typeof v === \"bigint\") return v.toString();\n return v;\n}\n\nfunction parseArgValue(v: unknown): ArkadeParamValue {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") {\n if (v.startsWith(\"0x\")) return hex.decode(v.slice(2));\n return BigInt(v);\n }\n throw new Error(`invalid arkade arg value: ${JSON.stringify(v)}`);\n}\n\n/**\n * Decode a persisted arg by its declared type — no `0x`/BigInt guessing. A\n * bytes-like param whose serialized value lacks the `0x` prefix is an error\n * (the untyped heuristic would silently decode such a value as a bigint).\n */\nfunction parseTypedArgValue(name: string, type: ArkadeArgType, v: unknown): ArkadeParamValue {\n if (type === \"int\") {\n if (typeof v === \"number\") return v;\n if (typeof v === \"string\") return BigInt(v);\n throw new Error(\n `arkade contract params: '${name}' expects an int, got ${JSON.stringify(v)}`,\n );\n }\n if (typeof v === \"string\" && v.startsWith(\"0x\")) return hex.decode(v.slice(2));\n throw new Error(\n `arkade contract params: '${name}' expects ${type} as 0x-prefixed hex, got ${JSON.stringify(v)}`,\n );\n}\n\n/** Serialize {@link ArkadeContractParams} to the string map `Contract.params` requires. */\nexport function serializeArkadeContractParams(typed: ArkadeContractParams): Record<string, string> {\n const args: Record<string, string | number> = {};\n for (const [k, v] of Object.entries(typed.args)) {\n args[k] = serializeArgValue(v);\n }\n return {\n program: stringifyArtifact(typed.program),\n args: JSON.stringify(args),\n serverKey: hex.encode(typed.serverKey),\n ...(typed.userKey ? { userKey: hex.encode(typed.userKey) } : {}),\n ...(typed.emulatorKey ? { emulatorKey: hex.encode(typed.emulatorKey) } : {}),\n };\n}\n\n/** Parse the string map persisted in `Contract.params` back into typed params. */\nexport function deserializeArkadeContractParams(\n params: Record<string, string>,\n): ArkadeContractParams {\n if (!params.program) {\n throw new Error(\"arkade contract params: missing 'program'\");\n }\n if (!params.serverKey) {\n throw new Error(\"arkade contract params: missing 'serverKey'\");\n }\n const program = parseArtifact(JSON.parse(params.program));\n // Typed param declarations direct how their persisted args decode;\n // untyped params keep the legacy 0x/BigInt heuristic.\n const paramTypes = new Map<string, ArkadeArgType>();\n for (const p of program.params ?? []) {\n if (typeof p !== \"string\") paramTypes.set(p.name, p.type);\n }\n const args: Record<string, ArkadeParamValue> = {};\n if (params.args) {\n for (const [k, v] of Object.entries(JSON.parse(params.args))) {\n const type = paramTypes.get(k);\n args[k] = type ? parseTypedArgValue(k, type, v) : parseArgValue(v);\n }\n }\n return {\n program,\n args,\n serverKey: hex.decode(params.serverKey),\n ...(params.userKey ? { userKey: hex.decode(params.userKey) } : {}),\n ...(params.emulatorKey ? { emulatorKey: hex.decode(params.emulatorKey) } : {}),\n };\n}\n","import { hex } from \"@scure/base\";\nimport {\n Contract,\n ContractHandler,\n DerivedContractTapscripts,\n PathContext,\n PathSelection,\n TapscriptDeriving,\n} from \"../types\";\nimport { isCltvSatisfied, isCsvSpendable } from \"./helpers\";\nimport { timelockToSequence } from \"../../utils/timelock\";\nimport { extractPubKey, isDescriptor } from \"../../identity/descriptor\";\nimport {\n ArkadeProgramScript,\n deserializeArkadeContractParams,\n resolveTimelockValue,\n serializeArkadeContractParams,\n witnessRefToBytes,\n type ArkadeContractParams,\n type CompiledProgramFunction,\n} from \"../../arkade/program\";\n\n/**\n * Extract the raw x-only pubkey hex the wallet signs with from the path\n * context, best-effort (mirrors the VHTLC handler's role resolution).\n */\nfunction walletKeyFrom(context: PathContext): string | undefined {\n const extract = (value: string): string | undefined => {\n if (!isDescriptor(value)) return value.toLowerCase();\n try {\n return extractPubKey(value).toLowerCase();\n } catch {\n return undefined;\n }\n };\n if (context.walletDescriptor) {\n const key = extract(context.walletDescriptor);\n if (key) return key;\n }\n if (context.walletPubKey) {\n return extract(context.walletPubKey);\n }\n return undefined;\n}\n\n/**\n * Resolve a pure-tapscript function's condition witness without call\n * arguments: literals and `$param` references resolve, function-input\n * references cannot (they only exist at call time) — those paths are not\n * generically spendable.\n */\nfunction staticWitness(\n fn: CompiledProgramFunction,\n script: ArkadeProgramScript,\n): Uint8Array[] | null {\n const refs = fn.def.tapscript.witness ?? [];\n try {\n return refs.map((w) => witnessRefToBytes(w, {}, script.args));\n } catch {\n return null;\n }\n}\n\n/**\n * Enumerate the spending paths of a compiled program for the given context.\n *\n * Covenant (`arkadeScript`) functions are excluded: they require the\n * co-signing service round-trip and call arguments, so they are spent through\n * `ArkadeContract.functions.<name>(...)`, never through generic wallet path\n * selection. Pure-tapscript functions follow the same conventions as the\n * built-in handlers:\n *\n * - collaborative context → non-timelocked paths (CLTV paths once satisfied);\n * - unilateral context → only paths that do not require the Arkade Service\n * signer, with CSV/CLTV gates applied (`checkTimelocks: false` skips the\n * gates, for `getAllSpendingPaths`).\n * - when the context identifies the wallet key and a path has non-server\n * signers, the wallet must be one of them.\n */\nfunction pathsFor(\n script: ArkadeProgramScript,\n context: PathContext,\n opts: { checkTimelocks: boolean },\n): PathSelection[] {\n const walletKey = walletKeyFrom(context);\n const serverHex = hex.encode(script.keys.serverKey);\n const paths: PathSelection[] = [];\n\n for (const fn of script.compiled) {\n if (fn.arkadeScript) continue;\n\n const witness = staticWitness(fn, script);\n if (witness === null) continue;\n\n const signerHexes = fn.signerKeys.map((s) => hex.encode(s));\n const requiresServer = signerHexes.includes(serverHex);\n const nonServer = signerHexes.filter((s) => s !== serverHex);\n\n // If we know who the wallet is and the path needs non-server\n // signatures, the wallet must be one of those signers.\n if (walletKey && nonServer.length > 0 && !nonServer.includes(walletKey)) {\n continue;\n }\n\n // `$param` timelock values resolved against the constructor args.\n const csvDef = fn.def.tapscript.csv;\n const csv = csvDef\n ? { type: csvDef.type, value: resolveTimelockValue(csvDef.value, script.args) }\n : undefined;\n const cltv =\n fn.def.tapscript.cltv !== undefined\n ? resolveTimelockValue(fn.def.tapscript.cltv, script.args)\n : undefined;\n\n if (context.collaborative) {\n // CSV leaves are unilateral-exit paths by convention.\n if (csv) continue;\n if (opts.checkTimelocks && cltv !== undefined && !isCltvSatisfied(context, cltv)) {\n continue;\n }\n paths.push({\n leaf: fn.tapLeafScript,\n ...(witness.length > 0 ? { extraWitness: witness } : {}),\n });\n continue;\n }\n\n // Unilateral: the Arkade Service will not co-sign.\n if (requiresServer) continue;\n const sequence = csv ? Number(timelockToSequence(csv)) : undefined;\n if (opts.checkTimelocks && csv && !isCsvSpendable(context, sequence)) continue;\n if (opts.checkTimelocks && cltv !== undefined && !isCltvSatisfied(context, cltv)) {\n continue;\n }\n paths.push({\n leaf: fn.tapLeafScript,\n ...(sequence !== undefined ? { sequence } : {}),\n ...(witness.length > 0 ? { extraWitness: witness } : {}),\n });\n }\n\n return paths;\n}\n\n/**\n * Generic handler for artifact/program-based Arkade contracts.\n *\n * Persists the full {@link ArkadeContractParams} (program artifact JSON, args,\n * signer keys) as string params, so any contract created via\n * `arkade.contract(program, args)` participates in the standard contract\n * pipeline: ContractManager persistence and validation, watcher events,\n * repository-backed balances, and offline script re-derivation. Rebuild a\n * callable contract from a stored row with `ArkadeContract.fromContract`.\n */\nexport const ArkadeContractHandler: ContractHandler<ArkadeContractParams, ArkadeProgramScript> &\n TapscriptDeriving<ArkadeProgramScript> = {\n type: \"arkade\",\n\n createScript(params: Record<string, string>): ArkadeProgramScript {\n const typed = this.deserializeParams(params);\n return new ArkadeProgramScript(typed.program, typed.args, {\n serverKey: typed.serverKey,\n userKey: typed.userKey,\n emulatorKey: typed.emulatorKey,\n });\n },\n\n serializeParams(params: ArkadeContractParams): Record<string, string> {\n return serializeArkadeContractParams(params);\n },\n\n deserializeParams(params: Record<string, string>): ArkadeContractParams {\n return deserializeArkadeContractParams(params);\n },\n\n selectPath(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection | null {\n const paths = pathsFor(script, context, { checkTimelocks: true });\n return paths.length > 0 ? paths[0] : null;\n },\n\n getAllSpendingPaths(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return pathsFor(script, context, { checkTimelocks: false });\n },\n\n getSpendablePaths(\n script: ArkadeProgramScript,\n _contract: Contract,\n context: PathContext,\n ): PathSelection[] {\n return pathsFor(script, context, { checkTimelocks: true });\n },\n\n /**\n * Opt-in, never opt-out. A program artifact cannot say whether its funds are\n * escrowed — an escrow's collaborative cancel leaf is indistinguishable from\n * an ordinary spend — so the answer is read from the row the registering code\n * wrote. Anything but an explicit `true` (absent, malformed, or a row written\n * before this gate existed) is not generically spendable: `createContract` is\n * first-writer-wins, so a fail-open marker would let one unmarked\n * registration permanently open the gate for every contract sharing the script.\n */\n isGenericallySpendable(contract: Contract): boolean {\n return contract.metadata?.genericallySpendable === true;\n },\n\n /**\n * Annotation tapscripts for VTXOs locked to this contract: prefer the\n * collaborative tapscript path (the multisig the Arkade Service co-signs,\n * mirroring `forfeit()` on the built-in script shapes); covenant-only\n * programs fall back to their first covenant leaf (its forfeit is\n * co-signed by the emulator during batch settlement); otherwise the first\n * declared leaf.\n */\n deriveTapscripts(script: ArkadeProgramScript, _contract: Contract): DerivedContractTapscripts {\n const collaborative = pathsFor(\n script,\n { collaborative: true, currentTime: 0 },\n { checkTimelocks: false },\n );\n const leaf =\n collaborative[0]?.leaf ??\n script.compiled.find((f) => f.arkadeScript)?.tapLeafScript ??\n script.compiled[0].tapLeafScript;\n return {\n forfeitTapLeafScript: leaf,\n intentTapLeafScript: leaf,\n tapTree: script.encode(),\n };\n },\n};\n","export { contractHandlers } from \"./registry\";\nexport { DefaultContractHandler } from \"./default\";\nexport type { DefaultContractParams } from \"./default\";\nexport { DelegateContractHandler } from \"./delegate\";\nexport type { DelegateContractParams } from \"./delegate\";\nexport { VHTLCContractHandler } from \"./vhtlc\";\nexport type { VHTLCContractParams } from \"./vhtlc\";\nexport { VHTLCV2ContractHandler } from \"./vhtlcV2\";\nexport type { VHTLCV2ContractParams } from \"./vhtlcV2\";\nexport { BoardingContractHandler } from \"./boarding\";\nexport type { BoardingContractParams } from \"./boarding\";\nexport { ArkadeContractHandler } from \"./arkade\";\n\n// Register built-in handlers\nimport { contractHandlers } from \"./registry\";\nimport { DefaultContractHandler } from \"./default\";\nimport { DelegateContractHandler } from \"./delegate\";\nimport { VHTLCContractHandler } from \"./vhtlc\";\nimport { VHTLCV2ContractHandler } from \"./vhtlcV2\";\nimport { BoardingContractHandler } from \"./boarding\";\nimport { ArkadeContractHandler } from \"./arkade\";\n\ncontractHandlers.register(DefaultContractHandler);\ncontractHandlers.register(DelegateContractHandler);\ncontractHandlers.register(VHTLCContractHandler);\ncontractHandlers.register(VHTLCV2ContractHandler);\ncontractHandlers.register(BoardingContractHandler);\ncontractHandlers.register(ArkadeContractHandler);\n"]}