@arkade-os/sdk 0.4.33 → 0.4.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/adapters/expo.cjs +5 -5
- package/dist/adapters/expo.d.cts +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-DEsDMYGv.d.cts → ark-D6sau_6-.d.cts} +522 -9
- package/dist/{ark-DEsDMYGv.d.ts → ark-D6sau_6-.d.ts} +522 -9
- package/dist/{asyncStorageTaskQueue-D8T1VXEx.d.cts → asyncStorageTaskQueue-CpC027t_.d.cts} +2 -2
- package/dist/{asyncStorageTaskQueue-CMrTYlKG.d.ts → asyncStorageTaskQueue-GT8fmPUG.d.ts} +2 -2
- package/dist/{chunk-E22HEKLN.js → chunk-3JR77WQ4.js} +140 -42
- package/dist/chunk-3JR77WQ4.js.map +1 -0
- package/dist/{chunk-WMIPYZSB.cjs → chunk-CMPJR3HS.cjs} +42 -9
- package/dist/chunk-CMPJR3HS.cjs.map +1 -0
- package/dist/{chunk-AOJUURHM.js → chunk-CUSABEUQ.js} +141 -37
- package/dist/chunk-CUSABEUQ.js.map +1 -0
- package/dist/{chunk-HAVA4XB7.cjs → chunk-FM7T7JVL.cjs} +7 -7
- package/dist/{chunk-HAVA4XB7.cjs.map → chunk-FM7T7JVL.cjs.map} +1 -1
- package/dist/{chunk-GYSK5R57.cjs → chunk-GUTKJMSF.cjs} +164 -59
- package/dist/chunk-GUTKJMSF.cjs.map +1 -0
- package/dist/{chunk-7K3ROJF6.cjs → chunk-H2LX2KKY.cjs} +2161 -466
- package/dist/chunk-H2LX2KKY.cjs.map +1 -0
- package/dist/{chunk-DSS2GQUG.js → chunk-NOR7XOKN.js} +2021 -331
- package/dist/chunk-NOR7XOKN.js.map +1 -0
- package/dist/{chunk-BU3BU6XK.js → chunk-OURFR4UR.js} +3 -3
- package/dist/{chunk-BU3BU6XK.js.map → chunk-OURFR4UR.js.map} +1 -1
- package/dist/{chunk-TU3LVAPX.js → chunk-OUVTG72A.js} +43 -11
- package/dist/chunk-OUVTG72A.js.map +1 -0
- package/dist/{chunk-5CCRRL5S.cjs → chunk-VYS3KGRI.cjs} +19 -13
- package/dist/chunk-VYS3KGRI.cjs.map +1 -0
- package/dist/{chunk-SPDNHPM4.cjs → chunk-X2EQLK4O.cjs} +149 -46
- package/dist/chunk-X2EQLK4O.cjs.map +1 -0
- package/dist/{chunk-L6ZETTX3.js → chunk-XQS2HW4Q.js} +11 -5
- package/dist/chunk-XQS2HW4Q.js.map +1 -0
- package/dist/contracts/handlers/index.cjs +7 -7
- 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-BJeBNP5a.d.cts → delegate-C-L6gSZx.d.cts} +1 -1
- package/dist/{delegate-EXN2mfkb.d.ts → delegate-De5__fpZ.d.ts} +1 -1
- package/dist/{index-BG2ooYKO.d.ts → index-BETdjE_o.d.ts} +22 -16
- package/dist/{index-DHjEeHEp.d.cts → index-jwQfHP6D.d.cts} +22 -16
- package/dist/index.cjs +158 -130
- package/dist/index.d.cts +125 -16
- package/dist/index.d.ts +125 -16
- package/dist/index.js +4 -4
- package/dist/repositories/realm/index.cjs +14 -14
- package/dist/repositories/realm/index.cjs.map +1 -1
- 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/realm/index.js.map +1 -1
- package/dist/repositories/sqlite/index.cjs +13 -13
- package/dist/repositories/sqlite/index.d.cts +1 -1
- package/dist/repositories/sqlite/index.d.ts +1 -1
- package/dist/repositories/sqlite/index.js +4 -4
- package/dist/{taskRunner-pIGyarFG.d.cts → taskRunner-DCyp6Gea.d.cts} +2 -2
- package/dist/{taskRunner-B7lBU45X.d.ts → taskRunner-DnxtObeq.d.ts} +2 -2
- 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 +13 -13
- package/dist/wallet/expo/index.d.cts +5 -5
- package/dist/wallet/expo/index.d.ts +5 -5
- package/dist/wallet/expo/index.js +5 -5
- package/dist/{wallet-D4Dll5Gu.d.cts → wallet-BWHbd5b1.d.cts} +388 -10
- package/dist/{wallet-C4L_X0i6.d.ts → wallet-Bth5uucA.d.ts} +388 -10
- 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 +5 -5
- package/dist/chunk-5CCRRL5S.cjs.map +0 -1
- package/dist/chunk-7K3ROJF6.cjs.map +0 -1
- package/dist/chunk-AOJUURHM.js.map +0 -1
- package/dist/chunk-DSS2GQUG.js.map +0 -1
- package/dist/chunk-E22HEKLN.js.map +0 -1
- package/dist/chunk-GYSK5R57.cjs.map +0 -1
- package/dist/chunk-L6ZETTX3.js.map +0 -1
- package/dist/chunk-SPDNHPM4.cjs.map +0 -1
- package/dist/chunk-TU3LVAPX.js.map +0 -1
- package/dist/chunk-WMIPYZSB.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getRandomId, extendVirtualCoinForContract, warnAndFilterVtxosForScript, saveVtxosForContract } from './chunk-
|
|
1
|
+
import { getRandomId, extendVirtualCoinForContract, warnAndFilterVtxosForScript, saveVtxosForContract } from './chunk-NOR7XOKN.js';
|
|
2
2
|
|
|
3
3
|
// src/worker/expo/taskRunner.ts
|
|
4
4
|
async function runTasks(queue, processors, deps) {
|
|
@@ -91,5 +91,5 @@ var contractPollProcessor = {
|
|
|
91
91
|
};
|
|
92
92
|
|
|
93
93
|
export { CONTRACT_POLL_TASK_TYPE, contractPollProcessor, createTaskDependencies, runTasks };
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-OURFR4UR.js.map
|
|
95
|
+
//# sourceMappingURL=chunk-OURFR4UR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/worker/expo/taskRunner.ts","../src/worker/expo/processors/contractPollProcessor.ts"],"names":[],"mappings":";;;AAkDA,eAAsB,QAAA,CAClB,KAAA,EACA,UAAA,EACA,IAAA,EACqB;AACrB,EAAA,MAAM,KAAA,GAAQ,MAAM,KAAA,CAAM,QAAA,EAAS;AACnC,EAAA,MAAM,YAAA,GAAe,IAAI,GAAA,CAAI,UAAA,CAAW,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,QAAA,EAAU,CAAC,CAAC,CAAC,CAAA;AACnE,EAAA,MAAM,UAAwB,EAAC;AAE/B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,IAAA,MAAM,SAAA,GAAY,YAAA,CAAa,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA;AAE5C,IAAA,IAAI,OAAA;AAEJ,IAAA,IAAI,CAAC,SAAA,EAAW;AACZ,MAAA,OAAA,GAAU;AAAA,QACN,YAAY,IAAA,CAAK,EAAA;AAAA,QACjB,MAAM,IAAA,CAAK,IAAA;AAAA,QACX,MAAA,EAAQ;AAAA,OACZ;AAAA,IACJ,CAAA,MAAO;AACH,MAAA,IAAI;AACA,QAAA,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA;AAAA,MAChD,SAAS,KAAA,EAAO;AACZ,QAAA,OAAA,GAAU;AAAA,UACN,YAAY,IAAA,CAAK,EAAA;AAAA,UACjB,MAAM,IAAA,CAAK,IAAA;AAAA,UACX,MAAA,EAAQ,QAAA;AAAA,UACR,IAAA,EAAM;AAAA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,EAAO,IAAA,EAAK,GAAI,MAAM,gBAAgB,QAAA,CAAS;AAAA,UACnD,OAAA,EAAS,CAAC,QAAA,CAAS,MAAM,CAAA;AAAA,UACzB,SAAA;AAAA,UACA;AAAA,SACH,CAAA;AAED,QAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,UAAA,QAAA,CAAS,IAAA,CAAK,UAAA,CAAW,IAAA,EAAM,QAAQ,CAAC,CAAA;AAAA,QAC5C;AAEA,QAAA,OAAA,GAAU,IAAA,GAAO,KAAA,CAAM,MAAA,KAAW,QAAA,GAAW,KAAA;AAC7C,QAAA,SAAA,EAAA;AAAA,MACJ;AAKA,MAAA,MAAM,QAAA,GAAW,2BAAA;AAAA,QACb,QAAA;AAAA,QACA,QAAA,CAAS,MAAA;AAAA,QACT;AAAA,OACJ;AACA,MAAA,MAAM,oBAAA,CAAqB,gBAAA,EAAkB,QAAA,EAAU,QAAQ,CAAA;AAC/D,MAAA,UAAA,IAAc,QAAA,CAAS,MAAA;AACvB,MAAA,kBAAA,EAAA;AAAA,IACJ;AAEA,IAAA,OAAO;AAAA,MACH,YAAY,IAAA,CAAK,EAAA;AAAA,MACjB,IAAA,EAAM,uBAAA;AAAA,MACN,MAAA,EAAQ,SAAA;AAAA,MACR,IAAA,EAAM,EAAE,kBAAA,EAAoB,UAAA;AAAW,KAC3C;AAAA,EACJ;AACJ","file":"chunk-BU3BU6XK.js","sourcesContent":["import type { TaskItem, TaskResult, TaskQueue } from \"./taskQueue\";\nimport type { WalletRepository } from \"../../repositories/walletRepository\";\nimport type { ContractRepository } from \"../../repositories/contractRepository\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport type { ArkProvider } from \"../../providers/ark\";\nimport type { ExtendedVirtualCoin, VirtualCoin } from \"../../wallet\";\nimport type { Contract } from \"../../contracts/types\";\nimport { getRandomId, extendVirtualCoinForContract } from \"../../wallet/utils\";\n\n/**\n * Shared dependencies injected into every processor at runtime.\n *\n * `extendVtxo` requires the owning contract — processors must resolve each\n * vtxo's `script` to a known contract (via the contract repository) before\n * calling this. The strict signature prevents the footgun where a missing\n * contract silently falls back to the wallet's default tapscript.\n */\nexport interface TaskDependencies {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: ArkProvider;\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) => ExtendedVirtualCoin;\n}\n\n/**\n * A stateless unit that handles one type of task item.\n *\n * Processors must not keep in-memory state across invocations —\n * all coordination lives in the @see TaskQueue and repositories.\n *\n * The `TDeps` parameter defaults to @see TaskDependencies but\n * can be overridden for domain-specific processors (e.g. swap processing).\n */\nexport interface TaskProcessor<TDeps = TaskDependencies> {\n readonly taskType: string;\n execute(item: TaskItem, deps: TDeps): Promise<Omit<TaskResult, \"id\" | \"executedAt\">>;\n}\n\n/**\n * Run all pending tasks from the queue through matching processors.\n *\n * For each task in the inbox:\n * 1. Find the processor whose `taskType` matches `task.type`.\n * 2. Execute it, producing a @see TaskResult.\n * 3. Push the result to the outbox and remove the task from the inbox.\n *\n * Tasks with no matching processor produce a `\"noop\"` result.\n * Processor errors produce a `\"failed\"` result with the error message.\n */\nexport async function runTasks<TDeps = TaskDependencies>(\n queue: TaskQueue,\n processors: TaskProcessor<TDeps>[],\n deps: TDeps,\n): Promise<TaskResult[]> {\n const tasks = await queue.getTasks();\n const processorMap = new Map(processors.map((p) => [p.taskType, p]));\n const results: TaskResult[] = [];\n\n for (const task of tasks) {\n const processor = processorMap.get(task.type);\n\n let partial: Omit<TaskResult, \"id\" | \"executedAt\">;\n\n if (!processor) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"noop\",\n };\n } else {\n try {\n partial = await processor.execute(task, deps);\n } catch (error) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"failed\",\n data: {\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n const result: TaskResult = {\n ...partial,\n id: getRandomId(),\n executedAt: Date.now(),\n };\n\n await queue.pushResult(result);\n await queue.removeTask(task.id);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Options for @see createTaskDependencies.\n */\nexport interface CreateTaskDependenciesOptions {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: ArkProvider;\n}\n\n/**\n * Build the @see TaskDependencies needed by task processors\n * (e.g. `src/worker/expo/processors/contractPollProcessor.ts`)\n *\n * This is the same construction that `defineExpoBackgroundTask` does\n * internally, extracted so that consumers with custom schedulers\n * (e.g. bare React Native with `react-native-background-fetch`)\n * can build deps without depending on Expo.\n */\nexport function createTaskDependencies(options: CreateTaskDependenciesOptions): TaskDependencies {\n return {\n ...options,\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) =>\n extendVirtualCoinForContract(vtxo, contract),\n };\n}\n","import type { TaskItem, TaskResult } from \"../taskQueue\";\nimport type { TaskProcessor, TaskDependencies } from \"../taskRunner\";\nimport type { ExtendedVirtualCoin } from \"../../../wallet\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\n\nexport const CONTRACT_POLL_TASK_TYPE = \"contract-poll\";\n\n/**\n * Polls the indexer for the latest VTXO state of every contract and\n * persists the results to the wallet repository.\n *\n * Replicates the polling subset of @see ContractManager.initialize:\n * 1. Load all contracts from the contract repository.\n * 2. Paginated fetch of every VTXO (including spent) from the indexer.\n * 3. Extend each VTXO with tapscript data.\n * 4. Save to the wallet repository.\n *\n * NOTE: the indexer query deliberately omits `spendableOnly`. Every\n * repository implements `saveVtxos` as an upsert with no batch delete,\n * so filtering to spendable-only would leave VTXOs that became spent\n * between polls marked as spendable forever. Fetching the full set lets\n * the upsert overwrite stale records with their latest state.\n */\nexport const contractPollProcessor: TaskProcessor = {\n taskType: CONTRACT_POLL_TASK_TYPE,\n\n async execute(\n item: TaskItem,\n deps: TaskDependencies,\n ): Promise<Omit<TaskResult, \"id\" | \"executedAt\">> {\n const { contractRepository, walletRepository, indexerProvider, extendVtxo } = deps;\n\n const contracts = await contractRepository.getContracts();\n let contractsProcessed = 0;\n let vtxosSaved = 0;\n\n for (const contract of contracts) {\n // Paginated fetch of spendable virtual outputs\n const pageSize = 100;\n let pageIndex = 0;\n let hasMore = true;\n const allVtxos: ExtendedVirtualCoin[] = [];\n\n while (hasMore) {\n const { vtxos, page } = await indexerProvider.getVtxos({\n scripts: [contract.script],\n pageIndex,\n pageSize,\n });\n\n for (const vtxo of vtxos) {\n allVtxos.push(extendVtxo(vtxo, contract));\n }\n\n hasMore = page ? vtxos.length === pageSize : false;\n pageIndex++;\n }\n\n // Skip wrong-script rows (legacy duplicates or indexer drift)\n // before persisting; the loop must keep going for the remaining\n // contracts even when one row is rejected.\n const filtered = warnAndFilterVtxosForScript(\n allVtxos,\n contract.script,\n \"contractPollProcessor\",\n );\n await saveVtxosForContract(walletRepository, contract, filtered);\n vtxosSaved += filtered.length;\n contractsProcessed++;\n }\n\n return {\n taskItemId: item.id,\n type: CONTRACT_POLL_TASK_TYPE,\n status: \"success\",\n data: { contractsProcessed, vtxosSaved },\n };\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/worker/expo/taskRunner.ts","../src/worker/expo/processors/contractPollProcessor.ts"],"names":[],"mappings":";;;AAkDA,eAAsB,QAAA,CAClB,KAAA,EACA,UAAA,EACA,IAAA,EACqB;AACrB,EAAA,MAAM,KAAA,GAAQ,MAAM,KAAA,CAAM,QAAA,EAAS;AACnC,EAAA,MAAM,YAAA,GAAe,IAAI,GAAA,CAAI,UAAA,CAAW,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,QAAA,EAAU,CAAC,CAAC,CAAC,CAAA;AACnE,EAAA,MAAM,UAAwB,EAAC;AAE/B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,IAAA,MAAM,SAAA,GAAY,YAAA,CAAa,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA;AAE5C,IAAA,IAAI,OAAA;AAEJ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,SAAA;AAAA,MACR,IAAA,EAAM,EAAE,kBAAA,EAAoB,UAAA;AAAW,KAC3C;AAAA,EACJ;AACJ","file":"chunk-OURFR4UR.js","sourcesContent":["import type { TaskItem, TaskResult, TaskQueue } from \"./taskQueue\";\nimport type { WalletRepository } from \"../../repositories/walletRepository\";\nimport type { ContractRepository } from \"../../repositories/contractRepository\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport type { ArkProvider } from \"../../providers/ark\";\nimport type { ExtendedVirtualCoin, VirtualCoin } from \"../../wallet\";\nimport type { Contract } from \"../../contracts/types\";\nimport { getRandomId, extendVirtualCoinForContract } from \"../../wallet/utils\";\n\n/**\n * Shared dependencies injected into every processor at runtime.\n *\n * `extendVtxo` requires the owning contract — processors must resolve each\n * vtxo's `script` to a known contract (via the contract repository) before\n * calling this. The strict signature prevents the footgun where a missing\n * contract silently falls back to the wallet's default tapscript.\n */\nexport interface TaskDependencies {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: ArkProvider;\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) => ExtendedVirtualCoin;\n}\n\n/**\n * A stateless unit that handles one type of task item.\n *\n * Processors must not keep in-memory state across invocations —\n * all coordination lives in the @see TaskQueue and repositories.\n *\n * The `TDeps` parameter defaults to @see TaskDependencies but\n * can be overridden for domain-specific processors (e.g. swap processing).\n */\nexport interface TaskProcessor<TDeps = TaskDependencies> {\n readonly taskType: string;\n execute(item: TaskItem, deps: TDeps): Promise<Omit<TaskResult, \"id\" | \"executedAt\">>;\n}\n\n/**\n * Run all pending tasks from the queue through matching processors.\n *\n * For each task in the inbox:\n * 1. Find the processor whose `taskType` matches `task.type`.\n * 2. Execute it, producing a @see TaskResult.\n * 3. Push the result to the outbox and remove the task from the inbox.\n *\n * Tasks with no matching processor produce a `\"noop\"` result.\n * Processor errors produce a `\"failed\"` result with the error message.\n */\nexport async function runTasks<TDeps = TaskDependencies>(\n queue: TaskQueue,\n processors: TaskProcessor<TDeps>[],\n deps: TDeps,\n): Promise<TaskResult[]> {\n const tasks = await queue.getTasks();\n const processorMap = new Map(processors.map((p) => [p.taskType, p]));\n const results: TaskResult[] = [];\n\n for (const task of tasks) {\n const processor = processorMap.get(task.type);\n\n let partial: Omit<TaskResult, \"id\" | \"executedAt\">;\n\n if (!processor) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"noop\",\n };\n } else {\n try {\n partial = await processor.execute(task, deps);\n } catch (error) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"failed\",\n data: {\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n const result: TaskResult = {\n ...partial,\n id: getRandomId(),\n executedAt: Date.now(),\n };\n\n await queue.pushResult(result);\n await queue.removeTask(task.id);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Options for @see createTaskDependencies.\n */\nexport interface CreateTaskDependenciesOptions {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: ArkProvider;\n}\n\n/**\n * Build the @see TaskDependencies needed by task processors\n * (e.g. `src/worker/expo/processors/contractPollProcessor.ts`)\n *\n * This is the same construction that `defineExpoBackgroundTask` does\n * internally, extracted so that consumers with custom schedulers\n * (e.g. bare React Native with `react-native-background-fetch`)\n * can build deps without depending on Expo.\n */\nexport function createTaskDependencies(options: CreateTaskDependenciesOptions): TaskDependencies {\n return {\n ...options,\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) =>\n extendVirtualCoinForContract(vtxo, contract),\n };\n}\n","import type { TaskItem, TaskResult } from \"../taskQueue\";\nimport type { TaskProcessor, TaskDependencies } from \"../taskRunner\";\nimport type { ExtendedVirtualCoin } from \"../../../wallet\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\n\nexport const CONTRACT_POLL_TASK_TYPE = \"contract-poll\";\n\n/**\n * Polls the indexer for the latest VTXO state of every contract and\n * persists the results to the wallet repository.\n *\n * Replicates the polling subset of @see ContractManager.initialize:\n * 1. Load all contracts from the contract repository.\n * 2. Paginated fetch of every VTXO (including spent) from the indexer.\n * 3. Extend each VTXO with tapscript data.\n * 4. Save to the wallet repository.\n *\n * NOTE: the indexer query deliberately omits `spendableOnly`. Every\n * repository implements `saveVtxos` as an upsert with no batch delete,\n * so filtering to spendable-only would leave VTXOs that became spent\n * between polls marked as spendable forever. Fetching the full set lets\n * the upsert overwrite stale records with their latest state.\n */\nexport const contractPollProcessor: TaskProcessor = {\n taskType: CONTRACT_POLL_TASK_TYPE,\n\n async execute(\n item: TaskItem,\n deps: TaskDependencies,\n ): Promise<Omit<TaskResult, \"id\" | \"executedAt\">> {\n const { contractRepository, walletRepository, indexerProvider, extendVtxo } = deps;\n\n const contracts = await contractRepository.getContracts();\n let contractsProcessed = 0;\n let vtxosSaved = 0;\n\n for (const contract of contracts) {\n // Paginated fetch of spendable virtual outputs\n const pageSize = 100;\n let pageIndex = 0;\n let hasMore = true;\n const allVtxos: ExtendedVirtualCoin[] = [];\n\n while (hasMore) {\n const { vtxos, page } = await indexerProvider.getVtxos({\n scripts: [contract.script],\n pageIndex,\n pageSize,\n });\n\n for (const vtxo of vtxos) {\n allVtxos.push(extendVtxo(vtxo, contract));\n }\n\n hasMore = page ? vtxos.length === pageSize : false;\n pageIndex++;\n }\n\n // Skip wrong-script rows (legacy duplicates or indexer drift)\n // before persisting; the loop must keep going for the remaining\n // contracts even when one row is rejected.\n const filtered = warnAndFilterVtxosForScript(\n allVtxos,\n contract.script,\n \"contractPollProcessor\",\n );\n await saveVtxosForContract(walletRepository, contract, filtered);\n vtxosSaved += filtered.length;\n contractsProcessed++;\n }\n\n return {\n taskItemId: item.id,\n type: CONTRACT_POLL_TASK_TYPE,\n status: \"success\",\n data: { contractsProcessed, vtxosSaved },\n };\n },\n};\n"]}
|
|
@@ -2,7 +2,7 @@ import * as bip68 from 'bip68';
|
|
|
2
2
|
import { TEST_NETWORK, NETWORK } from '@scure/btc-signer/utils.js';
|
|
3
3
|
import { hex, bech32m } from '@scure/base';
|
|
4
4
|
import { Script as Script$1 } from '@scure/btc-signer/script.js';
|
|
5
|
-
import { ScriptNum, p2tr_ms, Script,
|
|
5
|
+
import { ScriptNum, p2tr_ms, Script, p2tr, TAPROOT_UNSPENDABLE_KEY, Address } from '@scure/btc-signer';
|
|
6
6
|
import { TAP_LEAF_VERSION } from '@scure/btc-signer/payment.js';
|
|
7
7
|
import { PSBTOutput } from '@scure/btc-signer/psbt.js';
|
|
8
8
|
|
|
@@ -621,6 +621,38 @@ var CLTVMultisigTapscript;
|
|
|
621
621
|
}
|
|
622
622
|
CLTVMultisigTapscript2.isScriptValid = isScriptValid;
|
|
623
623
|
})(CLTVMultisigTapscript || (CLTVMultisigTapscript = {}));
|
|
624
|
+
function assembleBtcdTaprootTree(scripts) {
|
|
625
|
+
if (scripts.length === 0) {
|
|
626
|
+
throw new Error("assembleBtcdTaprootTree: empty scripts list");
|
|
627
|
+
}
|
|
628
|
+
const leaves = scripts.map((script) => ({
|
|
629
|
+
script,
|
|
630
|
+
leafVersion: TAP_LEAF_VERSION
|
|
631
|
+
}));
|
|
632
|
+
if (leaves.length === 1) {
|
|
633
|
+
return leaves[0];
|
|
634
|
+
}
|
|
635
|
+
const branches = [];
|
|
636
|
+
for (let i = 0; i < leaves.length; i += 2) {
|
|
637
|
+
if (i === leaves.length - 1) {
|
|
638
|
+
const last = branches.pop();
|
|
639
|
+
if (last === void 0) {
|
|
640
|
+
throw new Error(
|
|
641
|
+
`assembleBtcdTaprootTree: unexpected odd leaf at i=${i} with no prior branch`
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
branches.push([last, leaves[i]]);
|
|
645
|
+
} else {
|
|
646
|
+
branches.push([leaves[i], leaves[i + 1]]);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
while (branches.length >= 2) {
|
|
650
|
+
const left = branches.shift();
|
|
651
|
+
const right = branches.shift();
|
|
652
|
+
branches.push([left, right]);
|
|
653
|
+
}
|
|
654
|
+
return branches[0];
|
|
655
|
+
}
|
|
624
656
|
var TapTreeCoder = PSBTOutput.tapTree[2];
|
|
625
657
|
function scriptFromTapLeafScript(leaf) {
|
|
626
658
|
return leaf[1].subarray(0, leaf[1].length - 1);
|
|
@@ -629,18 +661,18 @@ var VtxoScript = class _VtxoScript {
|
|
|
629
661
|
/**
|
|
630
662
|
* Create a virtual output script from its tapleaf scripts.
|
|
631
663
|
*
|
|
664
|
+
* The Taproot script tree is assembled using btcd's algorithm
|
|
665
|
+
* (`txscript.AssembleTaprootScriptTree`) so the derived taproot output
|
|
666
|
+
* key agrees with arkd for any leaf count. `@scure/btc-signer`'s
|
|
667
|
+
* default `taprootListToTree` is a Huffman builder that only agrees
|
|
668
|
+
* with arkd for power-of-2 leaf counts.
|
|
669
|
+
*
|
|
632
670
|
* @param scripts - Raw tapscript bytes for each leaf
|
|
633
671
|
* @throws Error if the provided leaves cannot produce a valid Taproot tree
|
|
634
672
|
*/
|
|
635
673
|
constructor(scripts) {
|
|
636
674
|
this.scripts = scripts;
|
|
637
|
-
const
|
|
638
|
-
const tapTree = taprootListToTree(
|
|
639
|
-
list.map((script) => ({
|
|
640
|
-
script,
|
|
641
|
-
leafVersion: TAP_LEAF_VERSION
|
|
642
|
-
}))
|
|
643
|
-
);
|
|
675
|
+
const tapTree = assembleBtcdTaprootTree(scripts);
|
|
644
676
|
const payment = p2tr(TAPROOT_UNSPENDABLE_KEY, tapTree, void 0, true);
|
|
645
677
|
if (!payment.tapLeafScript || payment.tapLeafScript.length !== scripts.length) {
|
|
646
678
|
throw new Error("invalid scripts");
|
|
@@ -764,6 +796,6 @@ function getSequence(tapLeafScript) {
|
|
|
764
796
|
return sequence;
|
|
765
797
|
}
|
|
766
798
|
|
|
767
|
-
export { ArkAddress, CLTVMultisigTapscript, CSVMultisigTapscript, ConditionCSVMultisigTapscript, ConditionMultisigTapscript, DEFAULT_ARKADE_SERVER_URL, DEFAULT_NETWORK, DEFAULT_NETWORK_NAME, MultisigTapscript, TapTreeCoder, VtxoScript, decodeTapscript, getNetwork, getSequence, networks, scriptFromTapLeafScript, sequenceToTimelock, timelockToSequence };
|
|
768
|
-
//# sourceMappingURL=chunk-
|
|
769
|
-
//# sourceMappingURL=chunk-
|
|
799
|
+
export { ArkAddress, CLTVMultisigTapscript, CSVMultisigTapscript, ConditionCSVMultisigTapscript, ConditionMultisigTapscript, DEFAULT_ARKADE_SERVER_URL, DEFAULT_NETWORK, DEFAULT_NETWORK_NAME, MultisigTapscript, TapTreeCoder, VtxoScript, assembleBtcdTaprootTree, decodeTapscript, getNetwork, getSequence, networks, scriptFromTapLeafScript, sequenceToTimelock, timelockToSequence };
|
|
800
|
+
//# sourceMappingURL=chunk-OUVTG72A.js.map
|
|
801
|
+
//# sourceMappingURL=chunk-OUVTG72A.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/timelock.ts","../src/networks.ts","../src/script/address.ts","../src/script/tapscript.ts","../src/script/taprootTree.ts","../src/script/base.ts"],"names":["Script","MultisigTapscript","MultisigType","encode","decode","CSVMultisigTapscript","ConditionCSVMultisigTapscript","ConditionMultisigTapscript","CLTVMultisigTapscript","TAP_LEAF_VERSION","leaf","hex"],"mappings":";;;;;;;;;AAMO,SAAS,mBAAmB,QAAA,EAAoC;AACnE,EAAA,OAAa,KAAA,CAAA,MAAA;AAAA,IACT,QAAA,CAAS,IAAA,KAAS,QAAA,GACZ,EAAE,QAAQ,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,KAC/B,EAAE,OAAA,EAAS,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA;AAAE,GAC5C;AACJ;AAKO,SAAS,mBAAmB,QAAA,EAAoC;AACnE,EAAA,MAAM,OAAA,GAAgB,aAAO,QAAQ,CAAA;AACrC,EAAA,IAAI,QAAA,IAAY,OAAA,IAAW,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAW;AACrD,IAA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nimport type { RelativeTimelock } from \"../script/tapscript\";\n\n/**\n * Convert RelativeTimelock to BIP68 sequence number.\n */\nexport function timelockToSequence(timelock: RelativeTimelock): number {\n return bip68.encode(\n timelock.type === \"blocks\"\n ? { blocks: Number(timelock.value) }\n : { seconds: Number(timelock.value) },\n );\n}\n\n/**\n * Convert BIP68 sequence number back to RelativeTimelock.\n */\nexport function sequenceToTimelock(sequence: number): RelativeTimelock {\n const decoded = bip68.decode(sequence);\n if (\"blocks\" in decoded && decoded.blocks !== undefined) {\n return { type: \"blocks\", value: BigInt(decoded.blocks) };\n }\n if (\"seconds\" in decoded && decoded.seconds !== undefined) {\n return { type: \"seconds\", value: BigInt(decoded.seconds) };\n }\n throw new Error(`Invalid BIP68 sequence: ${sequence}`);\n}\n","import { NETWORK, TEST_NETWORK } from \"@scure/btc-signer/utils.js\";\n\nexport type NetworkName = \"bitcoin\" | \"testnet\" | \"signet\" | \"mutinynet\" | \"regtest\";\n\nexport interface Network {\n hrp: string;\n bech32: string;\n pubKeyHash: number;\n scriptHash: number;\n wif: number;\n}\nexport const getNetwork = (network: NetworkName): Network => {\n return networks[network];\n};\n\nexport const networks = {\n bitcoin: withArkPrefix(NETWORK, \"ark\"),\n testnet: withArkPrefix(TEST_NETWORK, \"tark\"),\n signet: withArkPrefix(TEST_NETWORK, \"tark\"),\n mutinynet: withArkPrefix(TEST_NETWORK, \"tark\"),\n regtest: withArkPrefix(\n {\n ...TEST_NETWORK,\n bech32: \"bcrt\",\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n },\n \"tark\",\n ),\n};\n\nfunction withArkPrefix(network: Omit<Network, \"hrp\">, prefix: string): Network {\n return {\n ...network,\n hrp: prefix,\n };\n}\n\nexport const DEFAULT_ARKADE_SERVER_URL = \"https://arkade.computer\" as const;\nexport const DEFAULT_NETWORK = networks.bitcoin;\nexport const DEFAULT_NETWORK_NAME = \"bitcoin\" as const satisfies NetworkName;\n","import { bech32m } from \"@scure/base\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { Script } from \"@scure/btc-signer/script.js\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\n/**\n * ArkAddress allows creating and decoding bech32m-encoded Arkade addresses.\n *\n * An Arkade address is composed of:\n * - a human readable prefix (hrp)\n * - a version byte (1 byte)\n * - a server public key (32 bytes)\n * - a vtxo taproot public key (32 bytes)\n *\n * @remarks\n * This is an Arkade-specific address format.\n * It is distinct from the Taproot onchain address returned by `VtxoScript.onchainAddress`.\n *\n * @see VtxoScript\n *\n * @example\n * ```typescript\n * const address = new ArkAddress(\n * new Uint8Array(32), // server public key\n * new Uint8Array(32), // vtxo taproot public key\n * \"ark\"\n * );\n *\n * const encoded = address.encode();\n * console.log(\"address: \", encoded);\n *\n * const decoded = ArkAddress.decode(encoded);\n * ```\n */\nexport class ArkAddress {\n /**\n * Create an Arkade address from its server public key, Taproot output key, and prefix.\n *\n * @param serverPubKey - 32-byte Arkade server public key\n * @param vtxoTaprootKey - 32-byte Taproot output key (a.k.a. tweaked public key)\n * @param hrp - Bech32 human-readable prefix\n * @param version - Address version byte\n * @defaultValue `version = 0`\n * @throws Error if either public key is not 32 bytes long\n */\n constructor(\n readonly serverPubKey: Bytes,\n readonly vtxoTaprootKey: Bytes,\n readonly hrp: string = DEFAULT_NETWORK.hrp,\n readonly version: number = 0,\n ) {\n if (serverPubKey.length !== 32) {\n throw new Error(\n \"Invalid server public key length, expected 32 bytes, got \" + serverPubKey.length,\n );\n }\n if (vtxoTaprootKey.length !== 32) {\n throw new Error(\n \"Invalid vtxo taproot public key length, expected 32 bytes, got \" +\n vtxoTaprootKey.length,\n );\n }\n }\n\n /**\n * Decode an Arkade address from its bech32m string form.\n *\n * @param address - Bech32m-encoded Arkade address\n * @returns Decoded Arkade address\n * @throws Error if the address is malformed or has an invalid payload length\n * @see encode\n */\n static decode(address: string): ArkAddress {\n const decoded = bech32m.decodeUnsafe(address, 1023);\n if (!decoded) {\n throw new Error(\"Invalid address\");\n }\n const data = new Uint8Array(bech32m.fromWords(decoded.words));\n\n // First the version byte, then 32 bytes server pubkey, then 32 bytes vtxo taproot public key.\n if (data.length !== 1 + 32 + 32) {\n throw new Error(\"Invalid data length, expected 65 bytes, got \" + data.length);\n }\n\n const version = data[0];\n const serverPubKey = data.slice(1, 33);\n const vtxoTaprootPubKey = data.slice(33, 65);\n\n return new ArkAddress(serverPubKey, vtxoTaprootPubKey, decoded.prefix, version);\n }\n\n /**\n * Encode the address to its bech32m string form.\n *\n * @returns Bech32m-encoded Arkade address\n * @see decode\n */\n encode(): string {\n // Combine version byte, server pubkey, and vtxo taproot public key.\n const data = new Uint8Array(1 + 32 + 32);\n data[0] = this.version;\n data.set(this.serverPubKey, 1);\n data.set(this.vtxoTaprootKey, 33);\n\n const words = bech32m.toWords(data);\n return bech32m.encode(this.hrp, words, 1023);\n }\n\n /** ScriptPubKey used to send non-dust funds to the address. */\n get pkScript(): Bytes {\n return Script.encode([\"OP_1\", this.vtxoTaprootKey]);\n }\n\n /** ScriptPubKey used to send sub-dust funds to the address. */\n get subdustPkScript(): Bytes {\n return Script.encode([\"RETURN\", this.vtxoTaprootKey]);\n }\n}\n","import { Script, ScriptNum, ScriptType, p2tr_ms } from \"@scure/btc-signer\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\nimport { sequenceToTimelock, timelockToSequence } from \"../utils/timelock\";\n\nconst MinimalScriptNum = ScriptNum(undefined, true);\n\n/**\n * RelativeTimelock lets to create timelocked with CHECKSEQUENCEVERIFY script.\n *\n * @example\n * ```typescript\n * const timelock = { value: 144n, type: \"blocks\" }; // 1 day in blocks\n * const timelock = { value: 512n, type: \"seconds\" }; // 8 minutes in seconds\n * ```\n */\nexport type RelativeTimelock = {\n value: bigint;\n type: \"seconds\" | \"blocks\";\n};\n\nexport enum TapscriptType {\n Multisig = \"multisig\",\n CSVMultisig = \"csv-multisig\",\n ConditionCSVMultisig = \"condition-csv-multisig\",\n ConditionMultisig = \"condition-multisig\",\n CLTVMultisig = \"cltv-multisig\",\n}\n\n/**\n * ArkTapscript is the base element of vtxo scripts.\n * It is used to encode and decode the different types of vtxo scripts.\n */\nexport interface ArkTapscript<T extends TapscriptType, Params> {\n type: T;\n params: Params;\n script: Uint8Array;\n}\n\n/**\n * decodeTapscript is a function that decodes an Arkade tapscript from a raw script.\n *\n * @throws {Error} if the script is not a valid Arkade tapscript\n * @example\n * ```typescript\n * const arkTapscript = decodeTapscript(new Uint8Array(32));\n * console.log(\"type:\", arkTapscript.type);\n * ```\n */\nexport function decodeTapscript(script: Uint8Array): ArkTapscript<TapscriptType, any> {\n const types = [\n MultisigTapscript,\n CSVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n ConditionMultisigTapscript,\n CLTVMultisigTapscript,\n ];\n\n for (const type of types) {\n try {\n return type.decode(script);\n } catch (error) {\n continue;\n }\n }\n\n throw new Error(`Failed to decode: script ${hex.encode(script)} is not a valid tapscript`);\n}\n\n/**\n * Implements a multi-signature tapscript.\n *\n * <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const multisigTapscript = MultisigTapscript.encode({ pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace MultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.Multisig, Params>;\n\n export enum MultisigType {\n CHECKSIG,\n CHECKSIGADD,\n }\n\n export type Params = {\n pubkeys: Bytes[];\n type?: MultisigType;\n };\n\n /** Encode a plain multisig tapscript. */\n export function encode(params: Params): Type {\n if (params.pubkeys.length === 0) {\n throw new Error(\"At least 1 pubkey is required\");\n }\n\n for (const pubkey of params.pubkeys) {\n if (pubkey.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n }\n }\n\n if (!params.type) {\n params.type = MultisigType.CHECKSIG;\n }\n\n if (params.type === MultisigType.CHECKSIGADD) {\n return {\n type: TapscriptType.Multisig,\n params,\n script: p2tr_ms(params.pubkeys.length, params.pubkeys).script,\n };\n }\n\n const asm: ScriptType = [];\n for (let i = 0; i < params.pubkeys.length; i++) {\n asm.push(params.pubkeys[i]);\n\n // CHECKSIGVERIFY except the last pubkey\n if (i < params.pubkeys.length - 1) {\n asm.push(\"CHECKSIGVERIFY\");\n } else {\n asm.push(\"CHECKSIG\");\n }\n }\n\n return {\n type: TapscriptType.Multisig,\n params,\n script: Script.encode(asm),\n };\n }\n\n /** Decode a plain multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n try {\n // Try decoding as checksigAdd first\n return decodeChecksigAdd(script);\n } catch (error) {\n // If checksigAdd fails, try regular checksig\n try {\n return decodeChecksig(script);\n } catch (error2) {\n throw new Error(\n `Failed to decode script: ${error2 instanceof Error ? error2.message : String(error2)}`,\n );\n }\n }\n }\n\n // <pubkey> CHECKSIG <pubkey> CHECKSIGADD <len_keys> NUMEQUAL\n function decodeChecksigAdd(script: Uint8Array): Type {\n const asm = Script.decode(script);\n const pubkeys: Bytes[] = [];\n let foundNumEqual = false;\n\n // Parse through ASM operations\n for (let i = 0; i < asm.length; i++) {\n const op = asm[i];\n\n // If it's a data push, it should be a 32-byte pubkey\n if (typeof op !== \"string\" && typeof op !== \"number\") {\n if (op.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n }\n pubkeys.push(op);\n\n // Check next operation is CHECKSIGADD or CHECKSIG\n if (\n i + 1 >= asm.length ||\n (asm[i + 1] !== \"CHECKSIGADD\" && asm[i + 1] !== \"CHECKSIG\")\n ) {\n throw new Error(\"Expected CHECKSIGADD or CHECKSIG after pubkey\");\n }\n i++; // Skip the CHECKSIGADD op\n continue;\n }\n\n // Last operation should be NUMEQUAL\n if (i === asm.length - 1) {\n if (op !== \"NUMEQUAL\") {\n throw new Error(\"Expected NUMEQUAL at end of script\");\n }\n foundNumEqual = true;\n }\n }\n\n if (!foundNumEqual) {\n throw new Error(\"Missing NUMEQUAL operation\");\n }\n\n if (pubkeys.length === 0) {\n throw new Error(\"Invalid script: must have at least 1 pubkey\");\n }\n\n // Verify the script by re-encoding and comparing\n const reconstructed = encode({\n pubkeys,\n type: MultisigType.CHECKSIGADD,\n });\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.Multisig,\n params: { pubkeys, type: MultisigType.CHECKSIGADD },\n script,\n };\n }\n\n // <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n function decodeChecksig(script: Uint8Array): Type {\n const asm = Script.decode(script);\n const pubkeys: Bytes[] = [];\n\n // Parse through ASM operations\n for (let i = 0; i < asm.length; i++) {\n const op = asm[i];\n\n // If it's a data push, it should be a 32-byte pubkey\n if (typeof op !== \"string\" && typeof op !== \"number\") {\n if (op.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);\n }\n pubkeys.push(op);\n\n // Check next operation\n if (i + 1 >= asm.length) {\n throw new Error(\"Unexpected end of script\");\n }\n\n const nextOp = asm[i + 1];\n if (nextOp !== \"CHECKSIGVERIFY\" && nextOp !== \"CHECKSIG\") {\n throw new Error(\"Expected CHECKSIGVERIFY or CHECKSIG after pubkey\");\n }\n\n // Last operation must be CHECKSIG, not CHECKSIGVERIFY\n if (i === asm.length - 2 && nextOp !== \"CHECKSIG\") {\n throw new Error(\"Last operation must be CHECKSIG\");\n }\n\n i++; // Skip the CHECKSIG/CHECKSIGVERIFY op\n continue;\n }\n }\n\n if (pubkeys.length === 0) {\n throw new Error(\"Invalid script: must have at least 1 pubkey\");\n }\n\n // Verify the script by re-encoding and comparing\n const reconstructed = encode({ pubkeys, type: MultisigType.CHECKSIG });\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.Multisig,\n params: { pubkeys, type: MultisigType.CHECKSIG },\n script,\n };\n }\n\n /** Return true when the tapscript is a plain multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.Multisig;\n }\n}\n\n/**\n * Implements a relative timelock script that requires all specified pubkeys to sign\n * after the relative timelock has expired. The timelock can be specified in blocks or seconds.\n *\n * This is the standard exit closure and it is also used for the sweep closure in vtxo trees.\n *\n * <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const csvMultisigTapscript = CSVMultisigTapscript.encode({ timelock: { type: \"blocks\", value: 144 }, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CSVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.CSVMultisig, Params>;\n\n export type Params = {\n timelock: RelativeTimelock;\n } & MultisigTapscript.Params;\n\n /** Encode a CSV multisig tapscript. */\n export function encode(params: Params): Type {\n for (const pubkey of params.pubkeys) {\n if (pubkey.length !== 32) {\n throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);\n }\n }\n\n const sequence = MinimalScriptNum.encode(BigInt(timelockToSequence(params.timelock)));\n\n const asm: ScriptType = [\n sequence.length === 1 ? sequence[0] : sequence,\n \"CHECKSEQUENCEVERIFY\",\n \"DROP\",\n ];\n const multisigScript = MultisigTapscript.encode(params);\n const script = new Uint8Array([...Script.encode(asm), ...multisigScript.script]);\n\n return {\n type: TapscriptType.CSVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a CSV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const sequence = asm[0];\n const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n let multisig: MultisigTapscript.Type;\n\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n let sequenceNum: number;\n if (typeof sequence === \"number\") {\n sequenceNum = sequence;\n } else {\n sequenceNum = Number(MinimalScriptNum.decode(sequence as Uint8Array));\n }\n const timelock = sequenceToTimelock(sequenceNum);\n\n const reconstructed = encode({\n timelock,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.CSVMultisig,\n params: {\n timelock,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a CSV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.CSVMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 3) {\n return new Error(`Invalid script: too short (expected at least 3)`);\n }\n\n const sequence = asm[0];\n if (typeof sequence === \"string\") {\n return new Error(\"Invalid script: expected sequence number\");\n }\n\n if (asm[1] !== \"CHECKSEQUENCEVERIFY\" || asm[2] !== \"DROP\") {\n return new Error(\"Invalid script: expected CHECKSEQUENCEVERIFY DROP\");\n }\n\n return true;\n }\n}\n\n/**\n * Combines a condition script with an exit closure. The resulting script requires\n * the condition to be met, followed by the standard exit closure requirements\n * (timelock and signatures).\n *\n * <conditionScript> VERIFY <sequence> CHECKSEQUENCEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionCSVMultisigTapscript = ConditionCSVMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionCSVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.ConditionCSVMultisig, Params>;\n\n export type Params = {\n conditionScript: Bytes;\n } & CSVMultisigTapscript.Params;\n\n /** Encode a condition + CSV multisig tapscript. */\n export function encode(params: Params): Type {\n const script = new Uint8Array([\n ...params.conditionScript,\n ...Script.encode([\"VERIFY\"]),\n ...CSVMultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.ConditionCSVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a condition + CSV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n let verifyIndex = getVerifyIndex(asm);\n\n if (verifyIndex === -1) {\n throw Error(\"Invalid script: missing VERIFY operation\");\n }\n\n const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n const csvMultisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n let csvMultisig: CSVMultisigTapscript.Type;\n try {\n csvMultisig = CSVMultisigTapscript.decode(csvMultisigScript);\n } catch (error) {\n throw new Error(\n `Invalid CSV multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const reconstructed = encode({\n conditionScript,\n ...csvMultisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.ConditionCSVMultisig,\n params: {\n conditionScript,\n ...csvMultisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a condition + CSV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.ConditionCSVMultisig;\n }\n\n function getVerifyIndex(asm: ScriptType) {\n let verifyIndex = -1;\n for (let i = asm.length - 1; i >= 0; i--) {\n if (asm[i] === \"VERIFY\") {\n verifyIndex = i;\n return verifyIndex;\n }\n }\n return verifyIndex;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 1) {\n return new Error(`Invalid script: too short (expected at least 1)`);\n }\n\n let verifyIndex = getVerifyIndex(asm);\n\n if (verifyIndex === -1) {\n return new Error(\"Invalid script: missing VERIFY operation\");\n }\n\n return true;\n }\n}\n\n/**\n * Combines a condition script with a forfeit closure. The resulting script requires\n * the condition to be met, followed by the standard forfeit closure requirements\n * (multi-signature).\n *\n * <conditionScript> VERIFY <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const conditionMultisigTapscript = ConditionMultisigTapscript.encode({ conditionScript: new Uint8Array(32), pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace ConditionMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.ConditionMultisig, Params>;\n\n export type Params = {\n conditionScript: Bytes;\n } & MultisigTapscript.Params;\n\n /** Encode a condition + multisig tapscript. */\n export function encode(params: Params): Type {\n const script = new Uint8Array([\n ...params.conditionScript,\n ...Script.encode([\"VERIFY\"]),\n ...MultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.ConditionMultisig,\n params,\n script,\n };\n }\n\n /** Decode a condition + multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n let verifyIndex = getVerifyIndex(asm);\n\n if (verifyIndex === -1) {\n throw Error(\"Invalid script: missing VERIFY operation\");\n }\n\n const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));\n const multisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));\n\n let multisig: MultisigTapscript.Type;\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n const reconstructed = encode({\n conditionScript,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.ConditionMultisig,\n params: {\n conditionScript,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a condition + multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.ConditionMultisig;\n }\n\n function getVerifyIndex(asm: ScriptType) {\n let verifyIndex = -1;\n for (let i = asm.length - 1; i >= 0; i--) {\n if (asm[i] === \"VERIFY\") {\n verifyIndex = i;\n return verifyIndex;\n }\n }\n return verifyIndex;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 1) {\n return new Error(`Invalid script: too short (expected at least 1)`);\n }\n\n let verifyIndex = getVerifyIndex(asm);\n\n if (verifyIndex === -1) {\n return new Error(\"Invalid script: missing VERIFY operation\");\n }\n\n return true;\n }\n}\n\n/**\n * Implements an absolute timelock (CLTV) script combined with a forfeit closure.\n * The script requires waiting until a specific block height/timestamp before the\n * forfeit closure conditions can be met.\n *\n * <locktime> CHECKLOCKTIMEVERIFY DROP <pubkey> CHECKSIGVERIFY <pubkey> CHECKSIG\n *\n * @example\n * ```typescript\n * const cltvMultisigTapscript = CLTVMultisigTapscript.encode({ absoluteTimelock: 144, pubkeys: [new Uint8Array(32), new Uint8Array(32)] });\n * ```\n */\nexport namespace CLTVMultisigTapscript {\n export type Type = ArkTapscript<TapscriptType.CLTVMultisig, Params>;\n\n export type Params = {\n absoluteTimelock: bigint;\n } & MultisigTapscript.Params;\n\n /** Encode a CLTV multisig tapscript. */\n export function encode(params: Params): Type {\n const locktime = MinimalScriptNum.encode(params.absoluteTimelock);\n const asm: ScriptType = [\n locktime.length === 1 ? locktime[0] : locktime,\n \"CHECKLOCKTIMEVERIFY\",\n \"DROP\",\n ];\n const timelockedScript = Script.encode(asm);\n\n const script = new Uint8Array([\n ...timelockedScript,\n ...MultisigTapscript.encode(params).script,\n ]);\n\n return {\n type: TapscriptType.CLTVMultisig,\n params,\n script,\n };\n }\n\n /** Decode a CLTV multisig tapscript from raw script bytes. */\n export function decode(script: Uint8Array): Type {\n if (script.length === 0) {\n throw new Error(\"Failed to decode: script is empty\");\n }\n\n const isValid = isScriptValid(script);\n if (isValid instanceof Error) {\n throw isValid;\n }\n\n const asm = Script.decode(script);\n\n const locktime = asm[0];\n if (typeof locktime === \"string\") {\n throw new Error(\"Invalid script: expected locktime number\");\n }\n\n if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n throw new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n }\n\n const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));\n let multisig: MultisigTapscript.Type;\n\n try {\n multisig = MultisigTapscript.decode(multisigScript);\n } catch (error) {\n throw new Error(\n `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n let absoluteTimelock: bigint;\n if (typeof locktime === \"number\") {\n absoluteTimelock = BigInt(locktime);\n } else {\n absoluteTimelock = MinimalScriptNum.decode(locktime as Bytes);\n }\n\n const reconstructed = encode({\n absoluteTimelock,\n ...multisig.params,\n });\n\n if (hex.encode(reconstructed.script) !== hex.encode(script)) {\n throw new Error(\"Invalid script format: script reconstruction mismatch\");\n }\n\n return {\n type: TapscriptType.CLTVMultisig,\n params: {\n absoluteTimelock,\n ...multisig.params,\n },\n script,\n };\n }\n\n /** Return true when the tapscript is a CLTV multisig tapscript. */\n export function is(tapscript: ArkTapscript<any, any>): tapscript is Type {\n return tapscript.type === TapscriptType.CLTVMultisig;\n }\n\n export function isScriptValid(script: Uint8Array): true | Error {\n const asm = Script.decode(script);\n\n if (asm.length < 3) {\n return new Error(`Invalid script: too short (expected at least 3)`);\n }\n\n const locktime = asm[0];\n if (typeof locktime === \"string\") {\n return new Error(\"Invalid script: expected locktime as number or bytes\");\n }\n\n if (asm[1] !== \"CHECKLOCKTIMEVERIFY\" || asm[2] !== \"DROP\") {\n return new Error(\"Invalid script: expected CHECKLOCKTIMEVERIFY DROP\");\n }\n\n return true;\n }\n}\n","import { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\n\n/**\n * A leaf node in the Taproot script tree, as consumed by\n * `@scure/btc-signer`'s `p2tr(internalKey, tree, ...)`.\n */\nexport interface TaprootLeaf {\n script: Bytes;\n leafVersion: number;\n}\n\n/**\n * Internal tree node shape consumed by `@scure/btc-signer`'s `p2tr`:\n * - A leaf is `{ script, leafVersion }`\n * - A branch is a 2-element tuple `[leftNode, rightNode]` of nodes\n */\nexport type TaprootTreeNode = TaprootLeaf | [TaprootTreeNode, TaprootTreeNode];\n\n/**\n * Assemble a Taproot script tree from a flat list of scripts using the\n * exact algorithm arkd's btcd dependency uses\n * (`txscript.AssembleTaprootScriptTree`, see\n * https://github.com/btcsuite/btcd/blob/master/txscript/taproot.go).\n *\n * The algorithm:\n *\n * Phase 1 — pair leaves left-to-right:\n * for i := 0; i < len(leaves); i += 2:\n * if i is the last index (odd leaf at end):\n * merge with the LAST branch built so far (do NOT pair as a fresh leaf)\n * else:\n * create a new branch from (leaves[i], leaves[i+1])\n *\n * Phase 2 — FIFO-queue merge branches:\n * while branches has ≥ 2 items:\n * take front two, combine into a new branch, push to back of queue\n *\n * This matters because `@scure/btc-signer`'s `taprootListToTree` builds a\n * Huffman tree (weight-1 leaves combine by smallest-weight pairs). For\n * power-of-2 leaf counts both algorithms happen to produce the same\n * perfectly-balanced binary tree and agree. For any other count they\n * produce DIFFERENT shapes → different merkle roots → different taproot\n * output keys → arkd rejects spends with `INVALID_PSBT_INPUT`.\n *\n * Reproducing btcd's algorithm here lets the SDK construct taptrees that\n * arkd accepts for arbitrary leaf counts.\n *\n * @param scripts - Raw tapscript bytes for each leaf, in the order they\n * should be encoded in the TapTree PSBT field.\n * @returns The nested-tuple form `p2tr` accepts.\n */\nexport function assembleBtcdTaprootTree(scripts: Bytes[]): TaprootTreeNode {\n if (scripts.length === 0) {\n throw new Error(\"assembleBtcdTaprootTree: empty scripts list\");\n }\n\n const leaves: TaprootLeaf[] = scripts.map((script) => ({\n script,\n leafVersion: TAP_LEAF_VERSION,\n }));\n\n if (leaves.length === 1) {\n return leaves[0];\n }\n\n // ── Phase 1: pair leaves left-to-right ─────────────────────────────\n const branches: TaprootTreeNode[] = [];\n for (let i = 0; i < leaves.length; i += 2) {\n if (i === leaves.length - 1) {\n // Odd leaf at end: merge into the LAST branch built so far.\n // Mirrors btcd's\n // branches[len(branches)-1] = NewTapBranch(branchToMerge, leaf)\n const last = branches.pop();\n if (last === undefined) {\n // Defensive — caller should have provided ≥ 2 leaves.\n throw new Error(\n `assembleBtcdTaprootTree: unexpected odd leaf at i=${i} with no prior branch`,\n );\n }\n branches.push([last, leaves[i]]);\n } else {\n // Pair two consecutive leaves into a new branch.\n branches.push([leaves[i], leaves[i + 1]]);\n }\n }\n\n // ── Phase 2: FIFO-queue merge branches ─────────────────────────────\n // Take front two, combine, push to back. Stops when one branch remains.\n while (branches.length >= 2) {\n const left = branches.shift()!;\n const right = branches.shift()!;\n branches.push([left, right]);\n }\n\n return branches[0];\n}\n","import { Script, Address, p2tr, TAPROOT_UNSPENDABLE_KEY, NETWORK } from \"@scure/btc-signer\";\nimport { TAP_LEAF_VERSION } from \"@scure/btc-signer/payment.js\";\nimport { PSBTOutput } from \"@scure/btc-signer/psbt.js\";\nimport { Bytes } from \"@scure/btc-signer/utils.js\";\nimport { hex } from \"@scure/base\";\nimport { ArkAddress } from \"./address\";\nimport { timelockToSequence } from \"../utils/timelock\";\nimport {\n CLTVMultisigTapscript,\n ConditionCSVMultisigTapscript,\n CSVMultisigTapscript,\n} from \"./tapscript\";\nimport { assembleBtcdTaprootTree } from \"./taprootTree\";\nimport { DEFAULT_NETWORK } from \"../networks\";\n\nexport type TapLeafScript = [\n {\n version: number;\n internalKey: Bytes;\n merklePath: Bytes[];\n },\n Bytes,\n];\n\nexport const TapTreeCoder: (typeof PSBTOutput.tapTree)[2] = PSBTOutput.tapTree[2];\n\nexport function scriptFromTapLeafScript(leaf: TapLeafScript): Bytes {\n return leaf[1].subarray(0, leaf[1].length - 1); // remove the version byte\n}\n\n/**\n * VtxoScript is a script that contains a list of tapleaf scripts.\n * It is used to create virtual output scripts.\n *\n * @see ArkAddress\n *\n * @example\n * ```typescript\n * const vtxoScript = new VtxoScript([new Uint8Array(32), new Uint8Array(32)]);\n * ```\n */\nexport class VtxoScript {\n readonly leaves: TapLeafScript[];\n readonly tweakedPublicKey: Bytes;\n\n /**\n * Decode a virtual output script from an encoded TapTree.\n *\n * @param tapTree - Encoded TapTree bytes\n * @returns Decoded virtual output script\n * @throws Error if the TapTree cannot be decoded into a valid script set\n * @see encode\n */\n static decode(tapTree: Bytes): VtxoScript {\n const leaves = TapTreeCoder.decode(tapTree);\n const scripts = leaves.map((leaf) => leaf.script);\n return new VtxoScript(scripts);\n }\n\n /**\n * Create a virtual output script from its tapleaf scripts.\n *\n * The Taproot script tree is assembled using btcd's algorithm\n * (`txscript.AssembleTaprootScriptTree`) so the derived taproot output\n * key agrees with arkd for any leaf count. `@scure/btc-signer`'s\n * default `taprootListToTree` is a Huffman builder that only agrees\n * with arkd for power-of-2 leaf counts.\n *\n * @param scripts - Raw tapscript bytes for each leaf\n * @throws Error if the provided leaves cannot produce a valid Taproot tree\n */\n constructor(readonly scripts: Bytes[]) {\n const tapTree = assembleBtcdTaprootTree(scripts);\n\n const payment = p2tr(TAPROOT_UNSPENDABLE_KEY, tapTree, undefined, true);\n\n if (!payment.tapLeafScript || payment.tapLeafScript.length !== scripts.length) {\n throw new Error(\"invalid scripts\");\n }\n\n this.leaves = payment.tapLeafScript;\n this.tweakedPublicKey = payment.tweakedPubkey;\n }\n\n /**\n * Encode the virtual output script to a TapTree byte representation.\n *\n * @returns Encoded TapTree bytes\n * @see decode\n */\n encode(): Bytes {\n const tapTree = TapTreeCoder.encode(\n this.scripts.map((script) => ({\n depth: 1,\n version: TAP_LEAF_VERSION,\n script,\n })),\n );\n return tapTree;\n }\n\n /**\n * Build the Arkade address corresponding to this virtual output script.\n *\n * @param prefix - Bech32 human-readable prefix\n * @param serverPubKey - 32-byte Arkade server public key\n * @returns Arkade address for this script\n * @see ArkAddress\n */\n address(prefix: string = DEFAULT_NETWORK.hrp, serverPubKey: Bytes): ArkAddress {\n return new ArkAddress(serverPubKey, this.tweakedPublicKey, prefix);\n }\n\n get pkScript(): Bytes {\n return Script.encode([\"OP_1\", this.tweakedPublicKey]);\n }\n\n /**\n * Build the Taproot onchain address corresponding to this virtual output script.\n *\n * @param network - Bitcoin network descriptor\n * @returns Taproot onchain address\n * @see address\n */\n onchainAddress(network: typeof NETWORK = DEFAULT_NETWORK): string {\n return Address(network).encode({\n type: \"tr\",\n pubkey: this.tweakedPublicKey,\n });\n }\n\n /**\n * Look up a tapleaf script by its hex-encoded tapscript body.\n *\n * @param scriptHex - Hex-encoded tapscript body without the leaf version byte\n * @returns Matching tapleaf script\n * @throws Error if no matching leaf exists\n */\n findLeaf(scriptHex: string): TapLeafScript {\n const leaf = this.leaves.find(\n (leaf) => hex.encode(scriptFromTapLeafScript(leaf)) === scriptHex,\n )!;\n if (!leaf) {\n throw new Error(`leaf '${scriptHex}' not found`);\n }\n return leaf;\n }\n\n /**\n * Return all unilateral exit paths embedded in the virtual output script.\n *\n * @returns CSV-based exit paths found in the leaves\n * @see getSequence\n */\n exitPaths(): Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> {\n const paths: Array<CSVMultisigTapscript.Type | ConditionCSVMultisigTapscript.Type> = [];\n for (const leaf of this.leaves) {\n try {\n const script = scriptFromTapLeafScript(leaf);\n if (CSVMultisigTapscript.isScriptValid(script) === true) {\n const tapScript = CSVMultisigTapscript.decode(script);\n paths.push(tapScript);\n } else if (ConditionCSVMultisigTapscript.isScriptValid(script) === true) {\n const tapScript = ConditionCSVMultisigTapscript.decode(script);\n paths.push(tapScript);\n }\n } catch (e) {\n console.debug(\"Failed to decode script\", e);\n }\n }\n return paths;\n }\n}\n\nexport type EncodedVtxoScript = { tapTree: Bytes };\n\n/**\n * Extract the timelock value encoded in a timelocked tapleaf, if any.\n *\n * The return value is unit-ambiguous: for a CSV leaf it is a BIP-68\n * nSequence (relative timelock); for a CLTV leaf it is an absolute\n * nLockTime. Callers must know which leaf shape they are inspecting to\n * interpret the number correctly, and must not copy a CSV result into\n * `Transaction.lockTime` (or vice versa).\n *\n * @param tapLeafScript - Tapleaf script to inspect\n * @returns The encoded timelock value, or `undefined` when neither a CSV\n * nor CLTV path is present\n * @see VtxoScript.exitPaths\n */\n// TODO(next-major): return a discriminated union\n// (`{ kind: \"relative\", nSequence } | { kind: \"absolute\", lockTime }`)\n// so callers can't conflate the two. Deferred because changing the\n// return type is a breaking change.\nexport function getSequence(tapLeafScript: TapLeafScript): number | undefined {\n let sequence: number | undefined = undefined;\n\n try {\n const scriptWithLeafVersion = tapLeafScript[1];\n const script = scriptWithLeafVersion.subarray(0, scriptWithLeafVersion.length - 1);\n try {\n const params = CSVMultisigTapscript.decode(script).params;\n sequence = timelockToSequence(params.timelock);\n } catch {\n const params = CLTVMultisigTapscript.decode(script).params;\n sequence = Number(params.absoluteTimelock);\n }\n } catch {}\n\n return sequence;\n}\n"]}
|
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkX2EQLK4O_cjs = require('./chunk-X2EQLK4O.cjs');
|
|
4
|
+
var chunkCMPJR3HS_cjs = require('./chunk-CMPJR3HS.cjs');
|
|
5
5
|
|
|
6
6
|
// src/providers/expoUtils.ts
|
|
7
7
|
async function getExpoFetch(options) {
|
|
8
8
|
try {
|
|
9
9
|
const expoFetchModule = await import('expo/fetch');
|
|
10
10
|
console.debug("Using expo/fetch for streaming");
|
|
11
|
-
|
|
11
|
+
const expoFetchWithHeader = (input, init) => {
|
|
12
|
+
const headers = new Headers(init?.headers);
|
|
13
|
+
headers.set("X-Build-Version", chunkX2EQLK4O_cjs.buildVersion);
|
|
14
|
+
headers.set("X-SDK-VERSION", chunkX2EQLK4O_cjs.sdkVersion);
|
|
15
|
+
return expoFetchModule.fetch(input, { ...init, headers });
|
|
16
|
+
};
|
|
17
|
+
return expoFetchWithHeader;
|
|
12
18
|
} catch (error) {
|
|
13
19
|
console.warn(
|
|
14
20
|
"Using standard fetch instead of expo/fetch. Streaming may not be fully supported in some environments.",
|
|
15
21
|
error
|
|
16
22
|
);
|
|
17
|
-
return fetch;
|
|
23
|
+
return chunkX2EQLK4O_cjs.fetch;
|
|
18
24
|
}
|
|
19
25
|
}
|
|
20
26
|
async function* sseStreamIterator(url, abortSignal, fetchFn, headers, parseData) {
|
|
@@ -71,8 +77,8 @@ async function* sseStreamIterator(url, abortSignal, fetchFn, headers, parseData)
|
|
|
71
77
|
}
|
|
72
78
|
|
|
73
79
|
// src/providers/expoArk.ts
|
|
74
|
-
var ExpoArkProvider = class extends
|
|
75
|
-
constructor(serverUrl =
|
|
80
|
+
var ExpoArkProvider = class extends chunkX2EQLK4O_cjs.RestArkProvider {
|
|
81
|
+
constructor(serverUrl = chunkCMPJR3HS_cjs.DEFAULT_ARKADE_SERVER_URL) {
|
|
76
82
|
super(serverUrl);
|
|
77
83
|
}
|
|
78
84
|
async *getEventStream(signal, topics) {
|
|
@@ -92,7 +98,7 @@ var ExpoArkProvider = class extends chunkSPDNHPM4_cjs.RestArkProvider {
|
|
|
92
98
|
if (error instanceof Error && error.name === "AbortError") {
|
|
93
99
|
break;
|
|
94
100
|
}
|
|
95
|
-
if (
|
|
101
|
+
if (chunkX2EQLK4O_cjs.isFetchTimeoutError(error)) {
|
|
96
102
|
console.debug("Timeout error ignored");
|
|
97
103
|
continue;
|
|
98
104
|
}
|
|
@@ -113,7 +119,7 @@ var ExpoArkProvider = class extends chunkSPDNHPM4_cjs.RestArkProvider {
|
|
|
113
119
|
if (error instanceof Error && error.name === "AbortError") {
|
|
114
120
|
break;
|
|
115
121
|
}
|
|
116
|
-
if (
|
|
122
|
+
if (chunkX2EQLK4O_cjs.isFetchTimeoutError(error)) {
|
|
117
123
|
console.debug("Timeout error ignored");
|
|
118
124
|
continue;
|
|
119
125
|
}
|
|
@@ -152,8 +158,8 @@ function convertVtxo(vtxo) {
|
|
|
152
158
|
}))
|
|
153
159
|
};
|
|
154
160
|
}
|
|
155
|
-
var ExpoIndexerProvider = class extends
|
|
156
|
-
constructor(serverUrl =
|
|
161
|
+
var ExpoIndexerProvider = class extends chunkX2EQLK4O_cjs.RestIndexerProvider {
|
|
162
|
+
constructor(serverUrl = chunkCMPJR3HS_cjs.DEFAULT_ARKADE_SERVER_URL) {
|
|
157
163
|
super(serverUrl);
|
|
158
164
|
}
|
|
159
165
|
async *getSubscription(subscriptionId, abortSignal) {
|
|
@@ -196,7 +202,7 @@ var ExpoIndexerProvider = class extends chunkSPDNHPM4_cjs.RestIndexerProvider {
|
|
|
196
202
|
if (error instanceof Error && error.name === "AbortError") {
|
|
197
203
|
break;
|
|
198
204
|
}
|
|
199
|
-
if (
|
|
205
|
+
if (chunkX2EQLK4O_cjs.isFetchTimeoutError(error)) {
|
|
200
206
|
console.debug("Timeout error ignored");
|
|
201
207
|
continue;
|
|
202
208
|
}
|
|
@@ -209,5 +215,5 @@ var ExpoIndexerProvider = class extends chunkSPDNHPM4_cjs.RestIndexerProvider {
|
|
|
209
215
|
|
|
210
216
|
exports.ExpoArkProvider = ExpoArkProvider;
|
|
211
217
|
exports.ExpoIndexerProvider = ExpoIndexerProvider;
|
|
212
|
-
//# sourceMappingURL=chunk-
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
218
|
+
//# sourceMappingURL=chunk-VYS3KGRI.cjs.map
|
|
219
|
+
//# sourceMappingURL=chunk-VYS3KGRI.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/providers/expoUtils.ts","../src/providers/expoArk.ts","../src/providers/expoIndexer.ts"],"names":["buildVersion","sdkVersion","fetch","RestArkProvider","DEF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AI,WAAW,CAAA;AAAA,gBACzD,EAAA,EAAI,KAAK,KAAA,CAAM,EAAA;AAAA,gBACf,aAAA,EAAe,KAAK,KAAA,CAAM;AAAA,eAC9B;AAAA,YACJ;AACA,YAAA,OAAO,IAAA;AAAA,UACX;AAAA,SACJ;AAAA,MACJ,SAAS,KAAA,EAAO;AACZ,QAAA,IAAI,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,YAAA,EAAc;AACvD,UAAA;AAAA,QACJ;AAIA,QAAA,IAAIC,qCAAA,CAAoB,KAAK,CAAA,EAAG;AAC5B,UAAA,OAAA,CAAQ,MAAM,uBAAuB,CAAA;AACrC,UAAA;AAAA,QACJ;AAEA,QAAA,OAAA,CAAQ,KAAA,CAAM,uBAAuB,KAAK,CAAA;AAC1C,QAAA,MAAM,KAAA;AAAA,MACV;AAAA,IACJ;AAAA,EACJ;AACJ","file":"chunk-VYS3KGRI.cjs","sourcesContent":["import { fetch, buildVersion, sdkVersion } from \"../utils/fetch\";\n\n/**\n * Dynamically imports expo/fetch with fallback to standard fetch.\n * @returns A fetch function suitable for SSE streaming\n */\nexport async function getExpoFetch(options?: { requireExpo?: boolean }): Promise<typeof fetch> {\n const requireExpo = options?.requireExpo ?? false;\n\n try {\n const expoFetchModule = await import(\"expo/fetch\");\n console.debug(\"Using expo/fetch for streaming\");\n const expoFetchWithHeader = (input: RequestInfo, init?: RequestInit) => {\n const headers = new Headers(init?.headers);\n headers.set(\"X-Build-Version\", buildVersion);\n headers.set(\"X-SDK-VERSION\", sdkVersion);\n return expoFetchModule.fetch(input, { ...init, headers });\n };\n return expoFetchWithHeader as unknown as typeof fetch;\n } catch (error) {\n if (requireExpo) {\n throw new Error(\n \"expo/fetch is unavailable in this environment. \" +\n \"Please ensure expo/fetch is installed and properly configured.\",\n );\n }\n\n console.warn(\n \"Using standard fetch instead of expo/fetch. \" +\n \"Streaming may not be fully supported in some environments.\",\n error,\n );\n return fetch;\n }\n}\n\n/**\n * Generic SSE stream processor using fetch API with ReadableStream.\n * Handles SSE format parsing, buffer management, and abort signals.\n *\n * @param url - The SSE endpoint URL\n * @param abortSignal - Signal to abort the stream\n * @param fetchFn - Fetch function to use (defaults to standard fetch)\n * @param headers - Additional headers to send\n * @param parseData - Function to parse and yield data from SSE events\n */\nexport async function* sseStreamIterator<T>(\n url: string,\n abortSignal: AbortSignal,\n fetchFn: typeof fetch,\n headers: Record<string, string>,\n parseData: (data: any) => T | null,\n): AsyncGenerator<T, void, unknown> {\n const fetchController = new AbortController();\n const cleanup = () => fetchController.abort();\n abortSignal?.addEventListener(\"abort\", cleanup, { once: true });\n\n try {\n const response = await fetchFn(url, {\n headers: {\n Accept: \"text/event-stream\",\n ...headers,\n },\n signal: fetchController.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Unexpected status ${response.status} when fetching SSE stream`);\n }\n\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (!abortSignal?.aborted) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n for (let i = 0; i < lines.length - 1; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n if (line.startsWith(\"data:\")) {\n const jsonStr = line.substring(5).trim();\n if (!jsonStr) continue;\n\n try {\n const data = JSON.parse(jsonStr);\n const parsed = parseData(data);\n if (parsed !== null) {\n yield parsed;\n }\n } catch (parseError) {\n console.error(\"Failed to parse SSE data:\", parseError);\n throw parseError;\n }\n }\n }\n\n buffer = lines[lines.length - 1];\n }\n } finally {\n abortSignal?.removeEventListener(\"abort\", cleanup);\n }\n}\n","import { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\nimport { RestArkProvider, SettlementEvent, TxNotification, isFetchTimeoutError } from \"./ark\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\n\n/**\n * Expo-compatible Arkade provider implementation using expo/fetch for SSE support.\n * This provider works specifically in React Native/Expo environments where\n * standard EventSource is not available but expo/fetch provides SSE capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoArkProvider } from '@arkade-os/sdk/providers/expo';\n *\n * const provider = new ExpoArkProvider('https://arkade.computer');\n * const info = await provider.getInfo();\n * ```\n */\nexport class ExpoArkProvider extends RestArkProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getEventStream(\n signal: AbortSignal,\n topics: string[],\n ): AsyncIterableIterator<SettlementEvent> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/batch/events`;\n const queryParams =\n topics.length > 0\n ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join(\"&\")}`\n : \"\";\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url + queryParams, signal, expoFetch, {}, (data) => {\n // Handle different response structures\n // v8 mesh API might wrap in {result: ...} or send directly\n const eventData = data.result || data;\n\n // Skip heartbeat messages\n if (eventData.heartbeat !== undefined) {\n return null;\n }\n\n return this.parseSettlementEvent(eventData);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Event stream error:\", error);\n throw error;\n }\n }\n }\n\n override async *getTransactionsStream(signal: AbortSignal): AsyncIterableIterator<{\n commitmentTx?: TxNotification;\n arkTx?: TxNotification;\n }> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/txs`;\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url, signal, expoFetch, {}, (data) => {\n return this.parseTransactionNotification(data.result);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Transaction stream error:\", error);\n throw error;\n }\n }\n }\n}\n","import { RestIndexerProvider, SubscriptionResponse, Vtxo } from \"./indexer\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { VirtualCoin } from \"../wallet\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\n\n// Helper function to convert Vtxo to VirtualCoin (same as in indexer.ts)\nfunction convertVtxo(vtxo: Vtxo): VirtualCoin {\n return {\n txid: vtxo.outpoint.txid,\n vout: vtxo.outpoint.vout,\n value: Number(vtxo.amount),\n status: {\n confirmed: !vtxo.isSwept && !vtxo.isPreconfirmed,\n isLeaf: !vtxo.isPreconfirmed,\n },\n virtualStatus: {\n state: vtxo.isSwept ? \"swept\" : vtxo.isPreconfirmed ? \"preconfirmed\" : \"settled\",\n commitmentTxIds: vtxo.commitmentTxids,\n batchExpiry: vtxo.expiresAt ? Number(vtxo.expiresAt) * 1000 : undefined,\n },\n spentBy: vtxo.spentBy ?? \"\",\n settledBy: vtxo.settledBy,\n arkTxId: vtxo.arkTxid,\n createdAt: new Date(Number(vtxo.createdAt) * 1000),\n isUnrolled: vtxo.isUnrolled,\n isSpent: vtxo.isSpent,\n script: vtxo.script,\n assets: vtxo.assets?.map((a) => ({\n assetId: a.assetId,\n amount: BigInt(a.amount),\n })),\n };\n}\n\n/**\n * Expo-compatible Indexer provider implementation using expo/fetch for streaming support.\n * This provider works specifically in React Native/Expo environments where\n * standard fetch streaming may not work properly but expo/fetch provides streaming capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoIndexerProvider } from '@arkade-os/sdk/adapters/expo';\n *\n * const provider = new ExpoIndexerProvider('https://indexer.example.com');\n * const vtxos = await provider.getVtxos({ scripts: ['script1'] });\n * ```\n */\nexport class ExpoIndexerProvider extends RestIndexerProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getSubscription(\n subscriptionId: string,\n abortSignal: AbortSignal,\n ): AsyncIterableIterator<SubscriptionResponse> {\n // Detect if we're running in React Native/Expo environment\n const isReactNative =\n typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\";\n\n const expoFetch = await getExpoFetch().catch((error) => {\n // In React Native/Expo, expo/fetch is required for proper streaming support\n if (isReactNative) {\n throw new Error(\n \"expo/fetch is unavailable in React Native environment. \" +\n \"Please ensure expo/fetch is installed and properly configured. \" +\n \"Streaming support may not work with standard fetch in React Native.\",\n );\n }\n throw error;\n });\n\n const url = `${this.serverUrl}/v1/indexer/script/subscription/${subscriptionId}`;\n\n while (!abortSignal.aborted) {\n try {\n yield* sseStreamIterator(\n url,\n abortSignal,\n expoFetch,\n { \"Content-Type\": \"application/json\" },\n (data): SubscriptionResponse | null => {\n // Handle new v8 proto format with heartbeat or event\n if (data.heartbeat !== undefined) {\n // Skip heartbeat messages\n return null;\n }\n // Process event messages\n if (data.event) {\n return {\n txid: data.event.txid,\n scripts: data.event.scripts || [],\n newVtxos: (data.event.newVtxos || []).map(convertVtxo),\n spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),\n sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),\n tx: data.event.tx,\n checkpointTxs: data.event.checkpointTxs,\n };\n }\n return null;\n },\n );\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Subscription error:\", error);\n throw error;\n }\n }\n }\n}\n"]}
|