@arkade-os/sdk 0.4.48 → 0.4.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/expo.cjs +5 -5
- package/dist/adapters/expo.d.cts +2 -2
- package/dist/adapters/expo.d.ts +2 -2
- package/dist/adapters/expo.js +3 -3
- package/dist/adapters/indexedDB.cjs +5 -5
- package/dist/adapters/indexedDB.js +4 -4
- package/dist/{ark-CjE0KkGp.d.cts → ark-nkSiPYNf.d.cts} +86 -24
- package/dist/{ark-CjE0KkGp.d.ts → ark-nkSiPYNf.d.ts} +86 -24
- package/dist/{asyncStorageTaskQueue-D9SOPMPC.d.ts → asyncStorageTaskQueue-DCaEE83p.d.ts} +1 -1
- package/dist/{asyncStorageTaskQueue-CeLZhZFU.d.cts → asyncStorageTaskQueue-DdxhsEz6.d.cts} +1 -1
- package/dist/{chunk-ENZ4YPR2.cjs → chunk-2LAJ3RTH.cjs} +491 -418
- package/dist/chunk-2LAJ3RTH.cjs.map +1 -0
- package/dist/{chunk-NYR5H6GR.js → chunk-5QVBJUOG.js} +154 -81
- package/dist/chunk-5QVBJUOG.js.map +1 -0
- package/dist/{chunk-SYDANBJI.cjs → chunk-6UI5BFE7.cjs} +9 -9
- package/dist/{chunk-SYDANBJI.cjs.map → chunk-6UI5BFE7.cjs.map} +1 -1
- package/dist/{chunk-G6J6AEMH.js → chunk-BLJQV3N4.js} +4 -4
- package/dist/{chunk-G6J6AEMH.js.map → chunk-BLJQV3N4.js.map} +1 -1
- package/dist/{chunk-BHHLRZCS.js → chunk-CPO2UB7L.js} +4 -4
- package/dist/{chunk-BHHLRZCS.js.map → chunk-CPO2UB7L.js.map} +1 -1
- package/dist/{chunk-7TXSPRN5.cjs → chunk-E7HB3GKK.cjs} +31 -2
- package/dist/chunk-E7HB3GKK.cjs.map +1 -0
- package/dist/{chunk-ZDDBTFVO.js → chunk-EFNLTS6Q.js} +29 -3
- package/dist/chunk-EFNLTS6Q.js.map +1 -0
- package/dist/{chunk-XFMGIFBL.js → chunk-HN25T276.js} +4 -4
- package/dist/{chunk-XFMGIFBL.js.map → chunk-HN25T276.js.map} +1 -1
- package/dist/{chunk-5XMVTK5S.cjs → chunk-LJQ2VQBE.cjs} +211 -230
- package/dist/chunk-LJQ2VQBE.cjs.map +1 -0
- package/dist/{chunk-4VVTRPH3.js → chunk-MBSYQ3WX.js} +183 -201
- package/dist/chunk-MBSYQ3WX.js.map +1 -0
- package/dist/{chunk-EB3ALGTM.cjs → chunk-QDXQULVM.cjs} +13 -13
- package/dist/{chunk-EB3ALGTM.cjs.map → chunk-QDXQULVM.cjs.map} +1 -1
- package/dist/{chunk-ENDNQPZA.cjs → chunk-XOLH3LFO.cjs} +17 -17
- package/dist/{chunk-ENDNQPZA.cjs.map → chunk-XOLH3LFO.cjs.map} +1 -1
- package/dist/contracts/handlers/index.cjs +8 -8
- package/dist/contracts/handlers/index.d.cts +3 -3
- package/dist/contracts/handlers/index.d.ts +3 -3
- package/dist/contracts/handlers/index.js +2 -2
- package/dist/{delegate-D3dY-2vS.d.cts → delegate-Cqqw1T1J.d.cts} +1 -1
- package/dist/{delegate-DhGZk1r2.d.ts → delegate-D6Orvyq7.d.ts} +1 -1
- package/dist/{index-DK4_iWYy.d.ts → index-CWoogah0.d.ts} +2 -2
- package/dist/{index-D6RQROds.d.cts → index-Yd4hecbM.d.cts} +2 -2
- package/dist/index.cjs +181 -181
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +4 -4
- package/dist/repositories/realm/index.cjs +19 -19
- package/dist/repositories/realm/index.d.cts +2 -2
- package/dist/repositories/realm/index.d.ts +2 -2
- package/dist/repositories/realm/index.js +5 -5
- package/dist/repositories/sqlite/index.cjs +18 -18
- package/dist/repositories/sqlite/index.d.cts +2 -2
- package/dist/repositories/sqlite/index.d.ts +2 -2
- package/dist/repositories/sqlite/index.js +5 -5
- package/dist/{taskRunner-Brnak0Rc.d.cts → taskRunner-BjB5QINR.d.cts} +1 -1
- package/dist/{taskRunner-B-2MHCYG.d.ts → taskRunner-Dw7xs60Q.d.ts} +1 -1
- package/dist/wallet/expo/background.cjs +14 -14
- package/dist/wallet/expo/background.d.cts +3 -3
- package/dist/wallet/expo/background.d.ts +3 -3
- package/dist/wallet/expo/background.js +6 -6
- package/dist/wallet/expo/index.cjs +14 -14
- package/dist/wallet/expo/index.d.cts +4 -4
- package/dist/wallet/expo/index.d.ts +4 -4
- package/dist/wallet/expo/index.js +5 -5
- package/dist/{wallet-B5bwixQa.d.ts → wallet-CGkWu3xV.d.cts} +2 -2
- package/dist/{wallet-DiOrtYic.d.cts → wallet-DyUHrPyN.d.ts} +2 -2
- package/dist/worker/expo/index.cjs +9 -9
- package/dist/worker/expo/index.d.cts +4 -4
- package/dist/worker/expo/index.d.ts +4 -4
- package/dist/worker/expo/index.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-4VVTRPH3.js.map +0 -1
- package/dist/chunk-5XMVTK5S.cjs.map +0 -1
- package/dist/chunk-7TXSPRN5.cjs.map +0 -1
- package/dist/chunk-ENZ4YPR2.cjs.map +0 -1
- package/dist/chunk-NYR5H6GR.js.map +0 -1
- package/dist/chunk-ZDDBTFVO.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/contracts/handlers/registry.ts","../src/script/default.ts","../src/identity/descriptor.ts","../src/contracts/metadata.ts","../src/contracts/handlers/helpers.ts","../src/contracts/handlers/default.ts","../src/script/delegate.ts","../src/contracts/handlers/delegate.ts","../src/script/vhtlc.ts","../src/contracts/handlers/vhtlc.ts","../src/contracts/handlers/boarding.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/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","VHTLC","ConditionMultisigTapscript","CLTVMultisigTapscript","ConditionCSVMultisigTapscript","i","baseHex","view","OP","__export","ScriptNum","schnorr","bytesToNumberBE","secp256k1"],"mappings":";;;;;;;;;;;AAkBA,IAAM,0BAAN,MAA8B;AAAA,EAClB,QAAA,uBAAe,GAAA,EAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ7D,SAAS,OAAA,EAAyC;AAC9C,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA,EAAG;AACjC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAA,CAAQ,IAAI,CAAA,uBAAA,CAAyB,CAAA;AAAA,IACvF;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,IAAA,EAAoD;AACpD,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,WAAW,IAAA,EAAwC;AAC/C,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,GAAA,CAAI,IAAI,CAAA;AAC7B,IAAA,IAAI,CAAC,OAAA,EAAS;AACV,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,yCAAA,EAA4C,IAAI,CAAA,CAAA,CAAG,CAAA;AAAA,IACvE;AACA,IAAA,OAAO,OAAA;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,IAAA,EAAuB;AACvB,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,GAAA,CAA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;AAAA,MACH,oBAAA,EAAsB,IAAA;AAAA,MACtB,mBAAA,EAAqB,IAAA;AAAA,MACrB,OAAA,EAAS,OAAO,MAAA;AAAO,KAC3B;AAAA,EACJ;AACJ;;;AC7MA,gBAAA,CAAiB,SAAS,sBAAsB,CAAA;AAChD,gBAAA,CAAiB,SAAS,uBAAuB,CAAA;AACjD,gBAAA,CAAiB,SAAS,oBAAoB,CAAA;AAC9C,gBAAA,CAAiB,SAAS,uBAAuB,CAAA;AACjD,gBAAA,CAAiB,SAAS,qBAAqB,CAAA","file":"chunk-LJQ2VQBE.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/** 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 * 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 { 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 if (locktime < CLTV_HEIGHT_THRESHOLD) {\n if (context.blockHeight === undefined) return false;\n return BigInt(context.blockHeight) >= locktime;\n }\n const currentTimeSec = BigInt(Math.floor(context.currentTime / 1000));\n return currentTimeSec >= locktime;\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 const blockTime = context.vtxo.status.block_time;\n if (blockTime === undefined) return false;\n return context.currentTime / 1000 - 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 { scriptHex: 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.scriptHex)),\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.scriptHex)).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: DiscoveryDeps,\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 * 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 { 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 discoverAt: discoverAtViaRange(discoverDefaultRange),\n\n discoverRange: discoverDefaultRange,\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) =>\n buildSignerTimelockCandidates(descriptor, deps, (opts) => new DefaultVtxo.Script(opts)),\n // The matched signer is threaded through the script (already built),\n // the persisted params, and the encoded address so signing/forfeit\n // later resolves the right key.\n (c, index, descriptor) => ({\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 ...rotatedReceiveMetadata(index, descriptor),\n }),\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 { 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 discoverAt: discoverAtViaRange(discoverDelegateRange),\n\n discoverRange: discoverDelegateRange,\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 const delegatePubKey = deps.delegatePubKey;\n if (!delegatePubKey) {\n return Promise.resolve(new Map(entries.map((e) => [e.index, []])));\n }\n\n return discoverIndexerCandidates(\n deps.indexerProvider,\n entries,\n // The delegate key is constant across the cross-product, so it rides\n // the closure rather than being repeated on every candidate.\n (_index, descriptor) =>\n buildSignerTimelockCandidates(\n descriptor,\n deps,\n (opts) => new DelegateVtxo.Script({ ...opts, delegatePubKey }),\n ),\n // The matched signer is threaded through script, params, and address so\n // signing/forfeit later resolves the right key.\n (c, index, descriptor) => ({\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 ...rotatedReceiveMetadata(index, descriptor),\n }),\n );\n}\n","import { Script } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport {\n CLTVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n ConditionMultisigTapscript,\n CSVMultisigTapscript,\n MultisigTapscript,\n RelativeTimelock,\n} from \"./tapscript\";\nimport { hex } from \"@scure/base\";\nimport { TapLeafScript, VtxoScript } from \"./base\";\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\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 *\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 VtxoScript {\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\n /** Create a VHTLC script from the supplied participant keys, hash, and timelocks. */\n constructor(readonly options: Options) {\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 const conditionScript = preimageConditionScript(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 super([\n claimScript,\n refundScript,\n refundWithoutReceiverScript,\n unilateralClaimScript,\n unilateralRefundScript,\n unilateralRefundWithoutReceiverScript,\n ]);\n\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 }\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\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 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","import { hex } from \"@scure/base\";\nimport { VHTLC } from \"../../script/vhtlc\";\nimport { RelativeTimelock } from \"../../script/tapscript\";\nimport { Contract, ContractHandler, PathContext, PathSelection } from \"../types\";\nimport { 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 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","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 /**\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","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 // Arkade VM enforces MINIMALDATA: values 0, 1..16 and -1 must\n // use OP_0 / OP_1..OP_16 / OP_1NEGATE, not data pushes.\n if (o === 0 || o === 0n) {\n w.byte(0x00);\n continue;\n } else if (o >= 1 && o <= 16) {\n w.byte(OP.OP_1 - 1 + Number(o));\n continue;\n } else if (o === -1 || o === -1n) {\n w.byte(OP[\"1NEGATE\"]);\n continue;\n }\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 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","/**\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 * 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 { 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 { BoardingContractHandler } from \"./boarding\";\nimport { ArkadeContractHandler } from \"./arkade\";\n\ncontractHandlers.register(DefaultContractHandler);\ncontractHandlers.register(DelegateContractHandler);\ncontractHandlers.register(VHTLCContractHandler);\ncontractHandlers.register(BoardingContractHandler);\ncontractHandlers.register(ArkadeContractHandler);\n"]}
|