@arkade-os/sdk 0.4.78 → 0.4.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/expo.cjs +5 -5
  3. package/dist/adapters/expo.d.cts +3 -3
  4. package/dist/adapters/expo.d.ts +3 -3
  5. package/dist/adapters/expo.js +3 -3
  6. package/dist/{asyncStorageTaskQueue-YW2t31_o.d.ts → asyncStorageTaskQueue-C5yQLJhm.d.ts} +1 -1
  7. package/dist/{asyncStorageTaskQueue-DiXxP-nQ.d.cts → asyncStorageTaskQueue-Shsih-1l.d.cts} +1 -1
  8. package/dist/{chunk-ZOCJ7E6M.js → chunk-4MXW2NDN.js} +10 -515
  9. package/dist/chunk-4MXW2NDN.js.map +1 -0
  10. package/dist/{chunk-KEEZSFLI.cjs → chunk-54FXLZ3T.cjs} +10 -10
  11. package/dist/{chunk-KEEZSFLI.cjs.map → chunk-54FXLZ3T.cjs.map} +1 -1
  12. package/dist/{chunk-PWIESIO6.cjs → chunk-DAYCCIRO.cjs} +372 -198
  13. package/dist/chunk-DAYCCIRO.cjs.map +1 -0
  14. package/dist/{chunk-Y7BVR6SQ.cjs → chunk-FUW3OM5X.cjs} +76 -561
  15. package/dist/chunk-FUW3OM5X.cjs.map +1 -0
  16. package/dist/{chunk-VJ7M6WKB.cjs → chunk-HAM3SHBV.cjs} +587 -532
  17. package/dist/chunk-HAM3SHBV.cjs.map +1 -0
  18. package/dist/{chunk-7KIGEOYT.js → chunk-JCPVP7TJ.js} +373 -201
  19. package/dist/chunk-JCPVP7TJ.js.map +1 -0
  20. package/dist/{chunk-DFWLP3MD.cjs → chunk-LASRYLMQ.cjs} +17 -17
  21. package/dist/{chunk-DFWLP3MD.cjs.map → chunk-LASRYLMQ.cjs.map} +1 -1
  22. package/dist/{chunk-CTFYT24G.js → chunk-QDXOTONI.js} +3 -3
  23. package/dist/{chunk-CTFYT24G.js.map → chunk-QDXOTONI.js.map} +1 -1
  24. package/dist/{chunk-IAM5IEVT.cjs → chunk-SJPPBR2V.cjs} +17 -17
  25. package/dist/{chunk-IAM5IEVT.cjs.map → chunk-SJPPBR2V.cjs.map} +1 -1
  26. package/dist/{chunk-P766MOPU.js → chunk-SK4OZRMB.js} +4 -4
  27. package/dist/{chunk-P766MOPU.js.map → chunk-SK4OZRMB.js.map} +1 -1
  28. package/dist/{chunk-OUHUC26M.js → chunk-VAFNWP3I.js} +4 -4
  29. package/dist/{chunk-OUHUC26M.js.map → chunk-VAFNWP3I.js.map} +1 -1
  30. package/dist/{chunk-LKAASQTL.js → chunk-YPQ37P3H.js} +128 -73
  31. package/dist/chunk-YPQ37P3H.js.map +1 -0
  32. package/dist/contracts/handlers/index.cjs +9 -9
  33. package/dist/contracts/handlers/index.d.cts +4 -4
  34. package/dist/contracts/handlers/index.d.ts +4 -4
  35. package/dist/contracts/handlers/index.js +2 -2
  36. package/dist/{delegate-DaNNUI_B.d.cts → delegate-B4bKASut.d.cts} +1 -1
  37. package/dist/{delegate-b2Wiymoj.d.ts → delegate-C9lpdrb0.d.ts} +1 -1
  38. package/dist/{hdWalletCapable-B2XVTOvu.d.ts → hdWalletCapable-CUJDKRKO.d.cts} +2 -3
  39. package/dist/{hdWalletCapable-D6PqWpuW.d.cts → hdWalletCapable-DJClhYMC.d.ts} +2 -3
  40. package/dist/{index-CAS4GyN-.d.ts → index-Ctul0N3Y.d.cts} +27 -6
  41. package/dist/{index-CAS4GyN-.d.cts → index-Ctul0N3Y.d.ts} +27 -6
  42. package/dist/{index-CYsKAXog.d.ts → index-D0qe2qVY.d.ts} +2 -2
  43. package/dist/{index-BlB97fYl.d.cts → index-YBFmScVS.d.cts} +2 -2
  44. package/dist/index.cjs +304 -304
  45. package/dist/index.d.cts +123 -123
  46. package/dist/index.d.ts +123 -123
  47. package/dist/index.js +4 -4
  48. package/dist/repositories/realm/index.cjs +20 -20
  49. package/dist/repositories/realm/index.d.cts +3 -3
  50. package/dist/repositories/realm/index.d.ts +3 -3
  51. package/dist/repositories/realm/index.js +5 -5
  52. package/dist/repositories/sqlite/index.cjs +19 -19
  53. package/dist/repositories/sqlite/index.d.cts +3 -3
  54. package/dist/repositories/sqlite/index.d.ts +3 -3
  55. package/dist/repositories/sqlite/index.js +5 -5
  56. package/dist/{taskRunner-BJj7xe35.d.ts → taskRunner-C08egG5a.d.ts} +1 -1
  57. package/dist/{taskRunner-HS2d2oda.d.cts → taskRunner-DB17db5n.d.cts} +1 -1
  58. package/dist/wallet/expo/background.cjs +14 -14
  59. package/dist/wallet/expo/background.d.cts +4 -4
  60. package/dist/wallet/expo/background.d.ts +4 -4
  61. package/dist/wallet/expo/background.js +6 -6
  62. package/dist/wallet/expo/index.cjs +14 -14
  63. package/dist/wallet/expo/index.d.cts +5 -5
  64. package/dist/wallet/expo/index.d.ts +5 -5
  65. package/dist/wallet/expo/index.js +5 -5
  66. package/dist/worker/expo/index.cjs +9 -9
  67. package/dist/worker/expo/index.d.cts +5 -5
  68. package/dist/worker/expo/index.d.ts +5 -5
  69. package/dist/worker/expo/index.js +5 -5
  70. package/package.json +6 -5
  71. package/dist/chunk-7KIGEOYT.js.map +0 -1
  72. package/dist/chunk-LKAASQTL.js.map +0 -1
  73. package/dist/chunk-PWIESIO6.cjs.map +0 -1
  74. package/dist/chunk-VJ7M6WKB.cjs.map +0 -1
  75. package/dist/chunk-Y7BVR6SQ.cjs.map +0 -1
  76. package/dist/chunk-ZOCJ7E6M.js.map +0 -1
@@ -1,5 +1,5 @@
1
- import { getRandomId, extendVirtualCoinForContract, isWatchedContract, warnAndFilterVtxosForScript, saveVtxosForContract } from './chunk-LKAASQTL.js';
2
- import { getNormalizedVtxos } from './chunk-7KIGEOYT.js';
1
+ import { getRandomId, extendVirtualCoinForContract, isWatchedContract, warnAndFilterVtxosForScript, saveVtxosForContract } from './chunk-YPQ37P3H.js';
2
+ import { getNormalizedVtxos } from './chunk-JCPVP7TJ.js';
3
3
 
4
4
  // src/worker/expo/taskRunner.ts
5
5
  async function runTasks(queue, processors, deps) {
@@ -92,5 +92,5 @@ var contractPollProcessor = {
92
92
  };
93
93
 
94
94
  export { CONTRACT_POLL_TASK_TYPE, contractPollProcessor, createTaskDependencies, runTasks };
95
- //# sourceMappingURL=chunk-P766MOPU.js.map
96
- //# sourceMappingURL=chunk-P766MOPU.js.map
95
+ //# sourceMappingURL=chunk-SK4OZRMB.js.map
96
+ //# sourceMappingURL=chunk-SK4OZRMB.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;AA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I,OAAA,GAAU,IAAA;AACd,MAAA,MAAM,WAAkC,EAAC;AAEzC,MAAA,OAAO,OAAA,EAAS;AACZ,QAAA,MAAM,EAAE,KAAA,EAAO,IAAA,EAAK,GAAI,MAAM,mBAAmB,eAAA,EAAiB;AAAA,UAC9D,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-P766MOPU.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 { getNormalizedVtxos } from \"../../../wallet/vtxo\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\nimport { isWatchedContract } from \"../../../contracts/types\";\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 every watched contract 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 // Background channel, so it covers exactly what the watcher's\n // subscription covers: `retained` rows are kept for reads only.\n const contracts = (await contractRepository.getContracts()).filter(isWatchedContract);\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 getNormalizedVtxos(indexerProvider, {\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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T;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-SK4OZRMB.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 { getNormalizedVtxos } from \"../../../wallet/vtxo\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\nimport { isWatchedContract } from \"../../../contracts/types\";\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 every watched contract 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 // Background channel, so it covers exactly what the watcher's\n // subscription covers: `retained` rows are kept for reads only.\n const contracts = (await contractRepository.getContracts()).filter(isWatchedContract);\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 getNormalizedVtxos(indexerProvider, {\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,5 +1,5 @@
1
- import { RestIndexerProvider } from './chunk-CTFYT24G.js';
2
- import { RestArkProvider, DEFAULT_ARKADE_SERVER_URL, ARKADE_VERSION_HEADERS, isFetchTimeoutError, convertVtxo, baseFetch } from './chunk-7KIGEOYT.js';
1
+ import { RestIndexerProvider } from './chunk-QDXOTONI.js';
2
+ import { RestArkProvider, DEFAULT_ARKADE_SERVER_URL, ARKADE_VERSION_HEADERS, isFetchTimeoutError, convertVtxo, baseFetch } from './chunk-JCPVP7TJ.js';
3
3
 
4
4
  // src/providers/expoUtils.ts
5
5
  async function getExpoFetch(options) {
@@ -188,5 +188,5 @@ var ExpoIndexerProvider = class extends RestIndexerProvider {
188
188
  };
189
189
 
190
190
  export { ExpoArkProvider, ExpoIndexerProvider };
191
- //# sourceMappingURL=chunk-OUHUC26M.js.map
192
- //# sourceMappingURL=chunk-OUHUC26M.js.map
191
+ //# sourceMappingURL=chunk-VAFNWP3I.js.map
192
+ //# sourceMappingURL=chunk-VAFNWP3I.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/providers/expoUtils.ts","../src/providers/expoArk.ts","../src/providers/expoIndexer.ts"],"names":[],"mappings":";;;;AAUA,eAAsB,aAAa,OAAA,EAA4D;AAG3F,EAAA,IAAI;AACA,IAAA,MAAM,eAAA,GAAkB,MAAM,OAAO,YAAY,CAAA;AACjD,IAAA,OAAA,CAAQ,MAAM,gCAAgC,CAAA;AAC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;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-OUHUC26M.js","sourcesContent":["import { baseFetch, fetch } from \"../utils/fetch\";\n\n/**\n * Dynamically imports expo/fetch, falling back to {@link baseFetch}.\n *\n * Adds no headers of its own: both Expo providers share this function but reach\n * different origins, so each passes its own per request.\n *\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 return expoFetchModule.fetch 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 baseFetch;\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 // Required, not just for cancellation: `getExpoFetch` falls back to\n // `baseFetch`, which bounds any read that brings no signal of its\n // own. Drop this and the stream is truncated at READ_TIMEOUT_MS.\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, TxNotificationEvent, isFetchTimeoutError } from \"./ark\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { ARKADE_VERSION_HEADERS } from \"../utils/fetch\";\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(\n url + queryParams,\n signal,\n expoFetch,\n ARKADE_VERSION_HEADERS,\n (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 );\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(\n signal: AbortSignal,\n ): AsyncIterableIterator<TxNotificationEvent> {\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, ARKADE_VERSION_HEADERS, (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 } from \"./indexer\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { convertVtxo } from \"../wallet/vtxo\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\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"]}
1
+ {"version":3,"sources":["../src/providers/expoUtils.ts","../src/providers/expoArk.ts","../src/providers/expoIndexer.ts"],"names":[],"mappings":";;;;AAUA,eAAsB,aAAa,OAAA,EAA4D;AAG3F,EAAA,IAAI;AACA,IAAA,MAAM,eAAA,GAAkB,MAAM,OAAO,YAAY,CAAA;AACjD,IAAA,OAAA,CAAQ,MAAM,gCAAgC,CAAA;AAC9C,IAAA,OAAO,eAAA,CAAgB,KAAA;AAAA,EAC3B,SAAS,KAAA,EAAO;AAQZ,IAAA,OAAA,CAAQ,IAAA;AAAA,MACJ,wGAAA;AAAA,MAEA;AAAA,KACJ;AACA,IAAA,OAAO,SAAA;AAAA,EACX;AACJ;AAYA,gBAAuB,iBAAA,CACnB,GAAA,EACA,WAAA,EACA,OAAA,EACA,SACA,SAAA,EACgC;AAChC,EAAA,MAAM,eAAA,GAAkB,IAAI,eAAA,EAAgB;AAC5C,EAAA,MAAM,OAAA,GAAU,MAAM,eAAA,CAAgB,KAAA,EAAM;AAC5C,EAAA,WAAA,EAAa,iBAAiB,OAAA,EAAS,OAAA,EAAS,EAAE,IAAA,EAAM,MAAM,CAAA;AAE9D,EAAA,IAAI;AACA,IAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,GAAA,EAAK;AAAA,MAChC,OAAA,EAAS;AAAA,QACL,MAAA,EAAQ,mBAAA;AAAA,QACR,GAAG;AAAA,OACP;AAAA;AAAA;AAAA;AAAA,MAIA,QAAQ,eAAA,CAAgB;AAAA,KAC3B,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAqB,QAAA,CAAS,MAAM,CAAA,yBAAA,CAA2B,CAAA;AAAA,IACnF;AAEA,IAAA,IAAI,CAAC,SAAS,IA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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,IAAI,mBAAA,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-VAFNWP3I.js","sourcesContent":["import { baseFetch, fetch } from \"../utils/fetch\";\n\n/**\n * Dynamically imports expo/fetch, falling back to {@link baseFetch}.\n *\n * Adds no headers of its own: both Expo providers share this function but reach\n * different origins, so each passes its own per request.\n *\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 return expoFetchModule.fetch 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 baseFetch;\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 // Required, not just for cancellation: `getExpoFetch` falls back to\n // `baseFetch`, which bounds any read that brings no signal of its\n // own. Drop this and the stream is truncated at READ_TIMEOUT_MS.\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, TxNotificationEvent, isFetchTimeoutError } from \"./ark\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { ARKADE_VERSION_HEADERS } from \"../utils/fetch\";\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(\n url + queryParams,\n signal,\n expoFetch,\n ARKADE_VERSION_HEADERS,\n (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 );\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(\n signal: AbortSignal,\n ): AsyncIterableIterator<TxNotificationEvent> {\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, ARKADE_VERSION_HEADERS, (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 } from \"./indexer\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { convertVtxo } from \"../wallet/vtxo\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\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"]}
@@ -1,16 +1,16 @@
1
- import { AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, Packet, BufferReader, BufferWriter, AssetRef, RestIndexerProvider } from './chunk-CTFYT24G.js';
2
- import { witnessRefToBytes, validateProgram, toASM, stringifyArtifact, serializeArkadeContractParams, resolveAsm, parseArtifact, getOpcodeValue, getOpcodeName, fromASM, deserializeArkadeContractParams, computeArkadeScriptPublicKey, bytesToASM, asmToBytes, arkadeWitnessHash, arkadeScriptHash, SUPPORTED_PROGRAM_VERSION, OPCODE_VALUES, OPCODE_NAMES, bignum_exports, ArkadeScript, ArkadeProgramScript, ARKADE_OPS, ARKADE_OPCODE_VALUES, ARKADE_OPCODE_NAMES, ARKADE_OPCODES, ARKADE_OP, toXOnly, inputName, contractHandlers, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, parseHDDescriptor, identityDescriptor, DefaultVtxo, speculativeReceiveMetadata, DelegateVtxo, WALLET_RECEIVE_SOURCE, BoardingContractHandler } from './chunk-ZOCJ7E6M.js';
3
- import { VtxoScript, Transaction, requiresForfeit, CSVMultisigTapscript, networks, getNetwork, DEFAULT_NETWORK, resolveEmulatorPubkey, isVtxoSpent, getNormalizedVtxos, setArkPsbtField, PrevArkTxField, ConditionWitness, craftToSpendTx, ArkAddress, isVirtualCoin, getArkPsbtFields, CosignerPublicKey, ServerResponseMismatchError, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, sequenceToTimelock, timelockToSequence, decodeTapscript, scriptFromTapLeafScript, CLTVMultisigTapscript, VtxoTaprootTree, assertAllowedSighashTypes, baseFetch, Intent, rateGate, DEFAULT_NETWORK_NAME, formatSighash, normalizeVtxo, getSequence, toBatchExpiry, maybeArkError, isArkError, ArkErrorName, toOffchainInputFeeParams, canRecoverOnchain, MultisigTapscript, isEventSourceError, isEventSourceUnavailableError, getAllNormalizedVtxos, isPastExpiry, isRetryableProviderError, DEFAULT_PAGE_SIZE, RestArkProvider, toVirtualStatus, ArkError, TapTreeCoder, resolveTimeHeight, canSpendOffchain, parseLegacyExpiry, isRecoverable, isExpired, PrevoutTxField, fetchVtxoCreatedAtByTxid, DEFAULT_ARKADE_SERVER_URL, ProviderUnavailableError } from './chunk-7KIGEOYT.js';
1
+ import { AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, Packet, BufferReader, BufferWriter, AssetRef, RestIndexerProvider } from './chunk-QDXOTONI.js';
2
+ import { witnessRefToBytes, validateProgram, toASM, stringifyArtifact, serializeArkadeContractParams, resolveAsm, parseArtifact, getOpcodeValue, getOpcodeName, fromASM, deserializeArkadeContractParams, computeArkadeScriptPublicKey, bytesToASM, asmToBytes, arkadeWitnessHash, arkadeScriptHash, SUPPORTED_PROGRAM_VERSION, OPCODE_VALUES, OPCODE_NAMES, bignum_exports, ArkadeScript, ArkadeProgramScript, ARKADE_OPS, ARKADE_OPCODE_VALUES, ARKADE_OPCODE_NAMES, ARKADE_OPCODES, ARKADE_OP, toXOnly, inputName, contractHandlers, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, parseHDDescriptor, identityDescriptor, DefaultVtxo, speculativeReceiveMetadata, DelegateVtxo, WALLET_RECEIVE_SOURCE, BoardingContractHandler } from './chunk-4MXW2NDN.js';
3
+ import { VtxoScript, Transaction, requiresForfeit, CSVMultisigTapscript, networks, getNetwork, DEFAULT_NETWORK, resolveEmulatorPubkey, isVtxoSpent, getNormalizedVtxos, setArkPsbtField, PrevArkTxField, ConditionWitness, craftToSpendTx, ArkAddress, isVirtualCoin, getArkPsbtFields, CosignerPublicKey, ServerResponseMismatchError, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, sequenceToTimelock, timelockToSequence, decodeTapscript, scriptFromTapLeafScript, CLTVMultisigTapscript, VtxoTaprootTree, assertAllowedSighashTypes, baseFetch, Intent, rateGate, DEFAULT_NETWORK_NAME, formatSighash, normalizeVtxo, getSequence, toBatchExpiry, maybeArkError, isArkError, ArkErrorName, toOffchainInputFeeParams, canRecoverOnchain, MultisigTapscript, isEventSourceError, isEventSourceUnavailableError, getAllNormalizedVtxos, isPastExpiry, isRetryableProviderError, DEFAULT_PAGE_SIZE, RestArkProvider, toVirtualStatus, ArkError, toBIP371TapTree, resolveTimeHeight, canSpendOffchain, parseLegacyExpiry, isRecoverable, isExpired, PrevoutTxField, fetchVtxoCreatedAtByTxid, DEFAULT_ARKADE_SERVER_URL, ProviderUnavailableError } from './chunk-JCPVP7TJ.js';
4
4
  import { __export } from './chunk-NSBPE2FW.js';
5
5
  import { sha256 as sha256$1, equalBytes, hash160, sha256x2, concatBytes, randomPrivateKeyBytes, pubECDSA, pubSchnorr } from '@scure/btc-signer/utils.js';
6
- import { SigHash, Script, OP, OutScript, Address, RawWitness, p2tr, p2wpkh, TaprootControlBlock, DEFAULT_SEQUENCE, Transaction as Transaction$2 } from '@scure/btc-signer';
6
+ import { SigHash, Script, OP, OutScript, Address, RawWitness, p2tr, p2wpkh, TaprootControlBlock, DEFAULT_SEQUENCE, Transaction as Transaction$1 } from '@scure/btc-signer';
7
7
  import { hex, base58, base64, bech32m } from '@scure/base';
8
8
  import * as musig2 from '@scure/btc-signer/musig2.js';
9
9
  import { equalBytes as equalBytes$1, bytesToNumberBE } from '@noble/curves/utils.js';
10
10
  import { signAsync, schnorr as schnorr$1, Point } from '@noble/secp256k1';
11
11
  import { secp256k1, schnorr } from '@noble/curves/secp256k1.js';
12
12
  import { Script as Script$1 } from '@scure/btc-signer/script.js';
13
- import { Transaction as Transaction$1, SigHash as SigHash$1 } from '@scure/btc-signer/transaction.js';
13
+ import { SigHash as SigHash$1 } from '@scure/btc-signer/transaction.js';
14
14
  import { mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
15
15
  import { wordlist } from '@scure/bip39/wordlists/english.js';
16
16
  import { networks as networks$1, scriptExpressions, HDKey, expand } from '@bitcoinerlab/descriptors-scure';
@@ -954,33 +954,62 @@ function isAddressAllocationCapable(value) {
954
954
  return typeof value.getNewAddresses === "function";
955
955
  }
956
956
 
957
+ // ../../node_modules/@noble/hashes/_u64.js
958
+ var fromNumH = (n) => n / 2 ** 32 | 0;
959
+ var fromNumL = (n) => n >>> 0;
960
+ function setU64FromNum(view, byteOffset, n, isLE) {
961
+ const h = fromNumH(n);
962
+ const l = fromNumL(n);
963
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
964
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
965
+ }
966
+
957
967
  // ../../node_modules/@noble/hashes/utils.js
958
968
  function isBytes(a) {
959
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
969
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
970
+ }
971
+ var atitle = (title) => title ? `"${title}" ` : "";
972
+ function anumber(n, title = "") {
973
+ if (typeof n !== "number")
974
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
975
+ if (!Number.isSafeInteger(n) || n < 0)
976
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
977
+ return n;
960
978
  }
961
979
  function abytes(value, length, title = "") {
980
+ if (isBytes(value) && (length === void 0))
981
+ return value;
962
982
  const bytes = isBytes(value);
963
- const len = value?.length;
964
- const needsLen = length !== void 0;
965
- if (!bytes || needsLen) {
966
- const prefix = title && `"${title}" `;
967
- const ofLen = "";
968
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
969
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
970
- }
971
- return value;
972
- }
983
+ const ofLen = "";
984
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
985
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
986
+ if (!bytes)
987
+ throw new TypeError(message);
988
+ throw new RangeError(message);
989
+ }
990
+ var aobject = (value, label) => {
991
+ if (value === null || typeof value !== "object" || Array.isArray(value))
992
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
993
+ };
994
+ var aopts = (value, label) => {
995
+ aobject(value, label);
996
+ const proto = Object.getPrototypeOf(value);
997
+ if (proto !== Object.prototype && proto !== null)
998
+ throw new TypeError(`"${label}" expected plain object`);
999
+ if (Object.hasOwn(value, "__proto__"))
1000
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
1001
+ };
973
1002
  function aexists(instance, checkFinished = true) {
974
1003
  if (instance.destroyed)
975
- throw new Error("Hash instance has been destroyed");
1004
+ throw new Error("hash was destroyed");
976
1005
  if (checkFinished && instance.finished)
977
- throw new Error("Hash#digest() has already been called");
1006
+ throw new Error("digest() was already called");
978
1007
  }
979
1008
  function aoutput(out, instance) {
980
- abytes(out, void 0, "digestInto() output");
1009
+ abytes(out, void 0, "output");
981
1010
  const min = instance.outputLen;
982
- if (out.length < min) {
983
- throw new Error('"digestInto() output" expected to be of length >=' + min);
1011
+ if (!(out.length >= min)) {
1012
+ throw new RangeError('"output" expected length >= ' + min);
984
1013
  }
985
1014
  }
986
1015
  function clean(...arrays) {
@@ -994,22 +1023,38 @@ function createView(arr) {
994
1023
  function rotr(word, shift) {
995
1024
  return word << 32 - shift | word >>> shift;
996
1025
  }
1026
+ function checkOpts(defaults, opts, title = "opts") {
1027
+ aopts(defaults, "defaults");
1028
+ if (opts !== void 0)
1029
+ aopts(opts, title);
1030
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
1031
+ return merged;
1032
+ }
997
1033
  function createHasher(hashCons, info = {}) {
1034
+ if (typeof hashCons !== "function")
1035
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
1036
+ info = checkOpts({}, info, "info");
998
1037
  const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
999
1038
  const tmp = hashCons(void 0);
1000
1039
  hashC.outputLen = tmp.outputLen;
1001
1040
  hashC.blockLen = tmp.blockLen;
1041
+ hashC.canXOF = tmp.canXOF;
1002
1042
  hashC.create = (opts) => hashCons(opts);
1003
1043
  Object.assign(hashC, info);
1004
1044
  return Object.freeze(hashC);
1005
1045
  }
1006
1046
  function randomBytes(bytesLength = 32) {
1047
+ anumber(bytesLength, "bytesLength");
1007
1048
  const cr = typeof globalThis === "object" ? globalThis.crypto : null;
1008
1049
  if (typeof cr?.getRandomValues !== "function")
1009
1050
  throw new Error("crypto.getRandomValues must be defined");
1051
+ if (bytesLength > 65536)
1052
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
1010
1053
  return cr.getRandomValues(new Uint8Array(bytesLength));
1011
1054
  }
1012
1055
  var oidNist = (suffix) => ({
1056
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
1057
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
1013
1058
  oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
1014
1059
  });
1015
1060
 
@@ -1023,6 +1068,7 @@ function Maj(a, b, c) {
1023
1068
  var HashMD = class {
1024
1069
  blockLen;
1025
1070
  outputLen;
1071
+ canXOF = false;
1026
1072
  padOffset;
1027
1073
  isLE;
1028
1074
  // For partial updates less than block size
@@ -1045,24 +1091,28 @@ var HashMD = class {
1045
1091
  abytes(data);
1046
1092
  const { view, buffer, blockLen } = this;
1047
1093
  const len = data.length;
1094
+ let processed = false;
1048
1095
  for (let pos = 0; pos < len; ) {
1049
1096
  const take = Math.min(blockLen - this.pos, len - pos);
1050
1097
  if (take === blockLen) {
1051
1098
  const dataView = createView(data);
1052
1099
  for (; blockLen <= len - pos; pos += blockLen)
1053
1100
  this.process(dataView, pos);
1101
+ processed = true;
1054
1102
  continue;
1055
1103
  }
1056
- buffer.set(data.subarray(pos, pos + take), this.pos);
1104
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
1057
1105
  this.pos += take;
1058
1106
  pos += take;
1059
1107
  if (this.pos === blockLen) {
1060
1108
  this.process(view, 0);
1061
1109
  this.pos = 0;
1110
+ processed = true;
1062
1111
  }
1063
1112
  }
1064
1113
  this.length += data.length;
1065
- this.roundClean();
1114
+ if (processed)
1115
+ this.roundClean();
1066
1116
  return this;
1067
1117
  }
1068
1118
  digestInto(out) {
@@ -1072,23 +1122,20 @@ var HashMD = class {
1072
1122
  const { buffer, view, blockLen, isLE } = this;
1073
1123
  let { pos } = this;
1074
1124
  buffer[pos++] = 128;
1075
- clean(this.buffer.subarray(pos));
1125
+ buffer.fill(0, pos);
1076
1126
  if (this.padOffset > blockLen - pos) {
1077
1127
  this.process(view, 0);
1078
- pos = 0;
1128
+ buffer.fill(0);
1079
1129
  }
1080
- for (let i = pos; i < blockLen; i++)
1081
- buffer[i] = 0;
1082
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
1130
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
1083
1131
  this.process(view, 0);
1084
- const oview = createView(out);
1132
+ this.roundClean();
1133
+ const oview = out === buffer ? view : createView(out);
1085
1134
  const len = this.outputLen;
1086
- if (len % 4)
1087
- throw new Error("_sha2: outputLen must be aligned to 32bit");
1088
1135
  const outLen = len / 4;
1089
1136
  const state = this.get();
1090
- if (outLen > state.length)
1091
- throw new Error("_sha2: outputLen bigger than state");
1137
+ if (len % 4 || outLen > state.length)
1138
+ throw new Error("invalid outputLen");
1092
1139
  for (let i = 0; i < outLen; i++)
1093
1140
  oview.setUint32(4 * i, state[i], isLE);
1094
1141
  }
@@ -1099,15 +1146,13 @@ var HashMD = class {
1099
1146
  this.destroy();
1100
1147
  return res;
1101
1148
  }
1102
- _cloneInto(to) {
1103
- to ||= new this.constructor();
1104
- to.set(...this.get());
1105
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
1149
+ _cloneIntoMeta(to) {
1150
+ const { buffer, length, finished, destroyed, pos } = this;
1106
1151
  to.destroyed = destroyed;
1107
1152
  to.finished = finished;
1108
1153
  to.length = length;
1109
1154
  to.pos = pos;
1110
- if (length % blockLen)
1155
+ if (pos)
1111
1156
  to.buffer.set(buffer);
1112
1157
  return to;
1113
1158
  }
@@ -1195,8 +1240,28 @@ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
1195
1240
  ]);
1196
1241
  var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1197
1242
  var SHA2_32B = class extends HashMD {
1198
- constructor(outputLen) {
1243
+ // We cannot use array here since array allows indexing by variable
1244
+ // which means optimizer/compiler cannot use registers.
1245
+ // Numeric initializers matter: starting the fields as `undefined` changes
1246
+ // V8's field representation and makes sha256 3x slower (measured).
1247
+ A = 0;
1248
+ B = 0;
1249
+ C = 0;
1250
+ D = 0;
1251
+ E = 0;
1252
+ F = 0;
1253
+ G = 0;
1254
+ H = 0;
1255
+ constructor(outputLen, IV) {
1199
1256
  super(64, outputLen, 8, false);
1257
+ this.A = IV[0] | 0;
1258
+ this.B = IV[1] | 0;
1259
+ this.C = IV[2] | 0;
1260
+ this.D = IV[3] | 0;
1261
+ this.E = IV[4] | 0;
1262
+ this.F = IV[5] | 0;
1263
+ this.G = IV[6] | 0;
1264
+ this.H = IV[7] | 0;
1200
1265
  }
1201
1266
  get() {
1202
1267
  const { A, B, C, D, E, F, G, H } = this;
@@ -1213,6 +1278,10 @@ var SHA2_32B = class extends HashMD {
1213
1278
  this.G = G | 0;
1214
1279
  this.H = H | 0;
1215
1280
  }
1281
+ _cloneInto(to) {
1282
+ (to ||= new this.constructor()).set(...this.get());
1283
+ return this._cloneIntoMeta(to);
1284
+ }
1216
1285
  process(view, offset) {
1217
1286
  for (let i = 0; i < 16; i++, offset += 4)
1218
1287
  SHA256_W[i] = view.getUint32(offset, false);
@@ -1252,23 +1321,14 @@ var SHA2_32B = class extends HashMD {
1252
1321
  clean(SHA256_W);
1253
1322
  }
1254
1323
  destroy() {
1324
+ this.destroyed = true;
1255
1325
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
1256
1326
  clean(this.buffer);
1257
1327
  }
1258
1328
  };
1259
1329
  var _SHA256 = class extends SHA2_32B {
1260
- // We cannot use array here since array allows indexing by variable
1261
- // which means optimizer/compiler cannot use registers.
1262
- A = SHA256_IV[0] | 0;
1263
- B = SHA256_IV[1] | 0;
1264
- C = SHA256_IV[2] | 0;
1265
- D = SHA256_IV[3] | 0;
1266
- E = SHA256_IV[4] | 0;
1267
- F = SHA256_IV[5] | 0;
1268
- G = SHA256_IV[6] | 0;
1269
- H = SHA256_IV[7] | 0;
1270
1330
  constructor() {
1271
- super(32);
1331
+ super(32, SHA256_IV);
1272
1332
  }
1273
1333
  };
1274
1334
  var sha256 = /* @__PURE__ */ createHasher(
@@ -2314,7 +2374,7 @@ function validateConnectorsTxGraph(settlementTxB64, connectorsGraph) {
2314
2374
  connectorsGraph.validate();
2315
2375
  if (connectorsGraph.root.inputsLength !== 1) throw ErrNumberOfInputs;
2316
2376
  const rootInput = connectorsGraph.root.getInput(0);
2317
- const settlementTx = Transaction$1.fromPSBT(base64.decode(settlementTxB64));
2377
+ const settlementTx = Transaction.fromPSBT(base64.decode(settlementTxB64));
2318
2378
  if (settlementTx.outputsLength <= BATCH_OUTPUT_CONNECTORS_INDEX)
2319
2379
  throw ErrInvalidSettlementTxOutputs;
2320
2380
  const expectedRootTxid = settlementTx.id;
@@ -6935,7 +6995,7 @@ function buildGraph(rootTxid, chunksByTxid) {
6935
6995
  return new TxTree(rootTx, children);
6936
6996
  }
6937
6997
  function decodeNode(chunk) {
6938
- const tx = Transaction$1.fromPSBT(base64.decode(chunk.tx));
6998
+ const tx = Transaction.fromPSBT(base64.decode(chunk.tx));
6939
6999
  return { tx, children: chunk.children };
6940
7000
  }
6941
7001
  var Batch;
@@ -15571,7 +15631,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15571
15631
  ]);
15572
15632
  let intentTxId;
15573
15633
  try {
15574
- intentTxId = Transaction$2.fromPSBT(base64.decode(intent.proof)).id;
15634
+ intentTxId = Transaction.fromPSBT(base64.decode(intent.proof)).id;
15575
15635
  } catch {
15576
15636
  intentTxId = params.inputs.map((i) => `${i.txid}:${i.vout}`).sort().join("|");
15577
15637
  }
@@ -15712,7 +15772,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15712
15772
  }
15713
15773
  async handleSettlementFinalizationEvent(event, inputs, forfeitOutputScript, expectedRecipients, connectorsGraph, validatedCommitmentTxid) {
15714
15774
  const signedForfeits = [];
15715
- let settlementPsbt = Transaction$2.fromPSBT(base64.decode(event.commitmentTx));
15775
+ let settlementPsbt = Transaction.fromPSBT(base64.decode(event.commitmentTx));
15716
15776
  assertFinalCommitmentMatchesValidated(
15717
15777
  settlementPsbt,
15718
15778
  validatedCommitmentTxid,
@@ -15890,7 +15950,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
15890
15950
  if (!xOnlyPublicKeys.includes(hex.encode(xonlySignerPublicKey))) {
15891
15951
  return { skip: true };
15892
15952
  }
15893
- const commitmentTx = Transaction$2.fromPSBT(
15953
+ const commitmentTx = Transaction.fromPSBT(
15894
15954
  base64.decode(event.unsignedCommitmentTx)
15895
15955
  );
15896
15956
  validateVtxoTxGraph(vtxoTree, commitmentTx, sweepTapTreeRoot);
@@ -16115,7 +16175,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16115
16175
  batchPending.push(pendingTx.arkTxid);
16116
16176
  try {
16117
16177
  const checkpointTxs = pendingTx.signedCheckpointTxs.map((c) => {
16118
- const tx = Transaction$2.fromPSBT(base64.decode(c));
16178
+ const tx = Transaction.fromPSBT(base64.decode(c));
16119
16179
  assertAllowedSighashTypes(tx);
16120
16180
  return tx;
16121
16181
  });
@@ -16449,7 +16509,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16449
16509
  for (const pendingTx of pendingTxs) {
16450
16510
  try {
16451
16511
  const checkpointTxs = pendingTx.signedCheckpointTxs.map((checkpoint) => {
16452
- const tx = Transaction$2.fromPSBT(base64.decode(checkpoint));
16512
+ const tx = Transaction.fromPSBT(base64.decode(checkpoint));
16453
16513
  assertAllowedSighashTypes(tx);
16454
16514
  return tx;
16455
16515
  });
@@ -16490,7 +16550,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16490
16550
  }
16491
16551
  /** Sum the outputs of an ark tx PSBT that pay the given scriptPubKey. */
16492
16552
  arkTxAmountPaidTo(arkTxPsbt, pkScriptHex) {
16493
- const arkTx = Transaction$2.fromPSBT(base64.decode(arkTxPsbt));
16553
+ const arkTx = Transaction.fromPSBT(base64.decode(arkTxPsbt));
16494
16554
  let total = 0;
16495
16555
  for (let i = 0; i < arkTx.outputsLength; i++) {
16496
16556
  const output = arkTx.getOutput(i);
@@ -16661,7 +16721,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
16661
16721
  script: recipient.script,
16662
16722
  amount: BigInt(recipient.amount),
16663
16723
  // Already checked against the recipient address in `validateRecipients`.
16664
- ...recipient.tapTree ? { tapTree: TapTreeCoder.decode(recipient.tapTree) } : {}
16724
+ ...recipient.tapTree ? { tapTree: toBIP371TapTree(recipient.tapTree) } : {}
16665
16725
  }));
16666
16726
  const totalBtcOutput = outputs.reduce((sum, o) => sum + Number(o.amount), 0);
16667
16727
  let changeAmount = totalBtcSelected - totalBtcOutput;
@@ -17002,7 +17062,7 @@ var Wallet2 = class _Wallet extends ReadonlyWallet {
17002
17062
  }
17003
17063
  const checkpointIdByOutpoint = /* @__PURE__ */ new Map();
17004
17064
  for (const encoded of signedCheckpointTxs) {
17005
- const checkpoint = Transaction$2.fromPSBT(base64.decode(encoded));
17065
+ const checkpoint = Transaction.fromPSBT(base64.decode(encoded));
17006
17066
  for (let i = 0; i < checkpoint.inputsLength; i++) {
17007
17067
  const input = checkpoint.getInput(i);
17008
17068
  if (!input.txid) continue;
@@ -21610,7 +21670,7 @@ var WsElectrumChainSource = class {
21610
21670
  );
21611
21671
  const txs = await this.fetchTransactions(unspentsFromElectrum.map((u) => u.tx_hash));
21612
21672
  return unspentsFromElectrum.map((u, index) => {
21613
- const tx = Transaction$2.fromRaw(hex.decode(txs[index].hex), {
21673
+ const tx = Transaction$1.fromRaw(hex.decode(txs[index].hex), {
21614
21674
  allowUnknownOutputs: true
21615
21675
  });
21616
21676
  const output = tx.getOutput(u.tx_pos);
@@ -21705,7 +21765,7 @@ var ElectrumOnchainProvider = class {
21705
21765
  }
21706
21766
  async getTxOutspends(txid) {
21707
21767
  const [txResult] = await this.chain.fetchTransactions([txid]);
21708
- const tx = Transaction$2.fromRaw(hex.decode(txResult.hex), {
21768
+ const tx = Transaction$1.fromRaw(hex.decode(txResult.hex), {
21709
21769
  allowUnknownOutputs: true
21710
21770
  });
21711
21771
  const outputCount = tx.outputsLength;
@@ -21773,7 +21833,7 @@ var ElectrumOnchainProvider = class {
21773
21833
  for (const candidateTxid of ambiguousCandidates[j]) {
21774
21834
  const rawHex = txMap.get(candidateTxid);
21775
21835
  if (!rawHex) continue;
21776
- const candidateTx = Transaction$2.fromRaw(hex.decode(rawHex), {
21836
+ const candidateTx = Transaction$1.fromRaw(hex.decode(rawHex), {
21777
21837
  allowUnknownOutputs: true,
21778
21838
  allowUnknownInputs: true
21779
21839
  });
@@ -21849,7 +21909,7 @@ var ElectrumOnchainProvider = class {
21849
21909
  if (rawHex) {
21850
21910
  let tx;
21851
21911
  try {
21852
- tx = Transaction$2.fromRaw(hex.decode(rawHex), {
21912
+ tx = Transaction$1.fromRaw(hex.decode(rawHex), {
21853
21913
  allowUnknownOutputs: true,
21854
21914
  allowUnknownInputs: true
21855
21915
  });
@@ -22045,7 +22105,7 @@ function isTxNotInBlockError(err) {
22045
22105
  return normalized.includes("notyetinablock") || normalized.includes("notinablock") || normalized.includes("notinblock") || normalized.includes("noconfirmedtransaction");
22046
22106
  }
22047
22107
  function childTxidFromHex(txHex) {
22048
- const tx = Transaction$2.fromRaw(hex.decode(txHex), {
22108
+ const tx = Transaction$1.fromRaw(hex.decode(txHex), {
22049
22109
  allowUnknownOutputs: true,
22050
22110
  allowUnknownInputs: true
22051
22111
  });
@@ -22293,7 +22353,7 @@ function verifyP2TR(message, witnessItems, pkScript, pubkey) {
22293
22353
  return false;
22294
22354
  }
22295
22355
  const toSpend = craftToSpendTx(message, pkScript, TAG_BIP322);
22296
- const toSign = craftBIP322ToSignP2TR(toSpend, pkScript, pubkey);
22356
+ const toSign = craftBIP322ToSignP2TR(toSpend, pkScript);
22297
22357
  const sighash = toSign.preimageWitnessV1(0, [pkScript], sighashType, [0n]);
22298
22358
  const rawSig = sig.length === 65 ? sig.subarray(0, 64) : sig;
22299
22359
  return schnorr.verify(rawSig, sighash, pubkey);
@@ -25154,12 +25214,7 @@ function createDefaultPaymentRouter(wallet) {
25154
25214
  prefs: { priority: ["ark", "ark-asset", "lightning", "onchain"] }
25155
25215
  }).use(arkRail()).use(arkAssetRail()).use(onchainRail({ feeInfo: walletFeeSource(wallet) }));
25156
25216
  }
25157
- /*! Bundled license information:
25158
-
25159
- @noble/hashes/utils.js:
25160
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
25161
- */
25162
25217
 
25163
25218
  export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, ASSET_CARRIER_SATS, AbortError, ActivityRegistry, AmbiguousRouteError, ArkNote, ArkadeCash, ArkadeCashCreateError, AssetManager, BIP21, BIP21Error, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, CachingArkProvider, ChainedTxType, ConnectionDisposedError, ContractManager, ContractRepositoryImpl, ContractWatcher, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_MIN_BATCH_EXPIRY_SECONDS, DEFAULT_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, DatabaseUpgradeBlockedError, DelegateManagerImpl, DelegateNotConfiguredError, DelegatorManagerImpl, DelegatorNotConfiguredError, DescriptorIdentity, DescriptorSigningProviderMissingError, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, ESPLORA_URL, ElectrumOnchainProvider, EmulatorPacket, EsploraProvider, Estimator, Extension, ExtensionNotFoundError, ForeignDescriptorError, HDDescriptorProvider, INTENT_TERMINAL_STATES, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexedDBWalletRepository, MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, MIGRATION_KEY, MUTINYNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, MissingSigningDescriptorError, MnemonicIdentity, OnchainWallet, OversizedChangeError, P2A, PaymentRouter, PrevTxUnavailableError, REGTEST_MIN_BATCH_EXPIRY_SECONDS, REGTEST_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlySingleKey, ReadonlyWallet, ReadonlyWalletError, RestDelegateProvider, RestDelegatorProvider, RestEmulatorProvider, SIGNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, SeedIdentity, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, SingleKey, TxTree, TxType, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, VtxoManager, Wallet2 as Wallet, WalletCannotAllocateAddressError, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WalletRepositoryImpl, WsElectrumChainSource, adoptContractDescriptor, arkAssetRail, arkRail, arkTarget, arkade_exports, assertFinalCommitmentMatchesValidated, assertIntentIdUnique, assertNoAssets, assertNoSelection, assertSendableAmount, assertSubmittedArkTxid, assertValidBatchExpiry, assertValidServerUnrollScript, assetMintResolver, assetsOf, attachPrevArkTxs, attachPrevoutTxs, awaitTransaction, boardingResolver, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, claimWithPreimageIdentity, classifyAgainstSignerSet, classifyContractSigner, closeDatabase, collabExitResolver, combineTapscriptSigs, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createAssetPacket, createDefaultActivityRegistry, createDefaultPaymentRouter, createExitChainResolver, createManagedConnection, decodeArkContract, defaultBatchExpiryPolicy, defaultCheckpointExitDelayPolicy, deleteByIndex, deserializeAssets, deserializeExitPackage, deserializeUtxo, deserializeVtxo, encodeArkContract, exitObserverFor, extendVirtualCoinForContract, extractArkProviderUrl, gateExclusion, gatedContracts, getAllByIndexValues, getMigrationStatus, getRandomId, hasBoardingTxExpired, hasCandidates, intentMatchesFilter, intentPageBounds, invoiceTarget, isAddressAllocationCapable, isArkContract, isBatchSignable, isBtcAddress, isContractGenericallySpendable, isContractVtxoEvent, isCooperativelyMigratable, isDeterministicSigner, isDiscoverable, isHDAllocationCapable, isHDDeterministicSignCapable, isHDWalletCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isSigningIdentity, isSubdust, isTerminalIntentState, isValidArkAddress, isVtxoExpiringSoon, isVtxoForScript, isWatchedContract, logExcludedVtxos, makeHandle, matchServerCheckpoints, mergeChainedTxType, migrateWalletRepository, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, promisifyRequest, provisionClaimSecret, provisionRefundKey, registerWalletRestoreHook, requiresMigration, resolveAssetAmount, resolveBatchExpiryPolicy, resolveCheckpointExitDelayPolicy, resolveDescriptorSigner, resolvePrevTxs, resolveSendAmount, rollbackMigration, saveVtxosForContract, scriptFromArkAddress, selectCoinsWithAsset, selectVirtualCoins, selectionOf, serializeAssets, serializeExitPackage, serializeUtxo, serializeVtxo, setupServiceWorker, signAndSubmitOffchainTx, signerSetFromInfo, signingDescriptorIndex, strictSigningDescriptorIndex, toXOnlySignerHex, tryResolveSendAmount, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, waitForIncomingFunds, walletFeeSource, warnAndFilterVtxosForScript, withPrevTxs };
25164
- //# sourceMappingURL=chunk-LKAASQTL.js.map
25165
- //# sourceMappingURL=chunk-LKAASQTL.js.map
25219
+ //# sourceMappingURL=chunk-YPQ37P3H.js.map
25220
+ //# sourceMappingURL=chunk-YPQ37P3H.js.map