@arkade-os/sdk 0.4.27 → 0.4.28

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 (531) hide show
  1. package/README.md +31 -100
  2. package/dist/adapters/asyncStorage.cjs +48 -0
  3. package/dist/adapters/asyncStorage.cjs.map +1 -0
  4. package/dist/adapters/asyncStorage.d.cts +16 -0
  5. package/dist/{types/storage → adapters}/asyncStorage.d.ts +5 -2
  6. package/dist/adapters/asyncStorage.js +46 -0
  7. package/dist/adapters/asyncStorage.js.map +1 -0
  8. package/dist/adapters/expo.cjs +19 -0
  9. package/dist/adapters/expo.cjs.map +1 -0
  10. package/dist/adapters/expo.d.cts +48 -0
  11. package/dist/adapters/expo.d.ts +48 -0
  12. package/dist/adapters/expo.js +6 -0
  13. package/dist/adapters/expo.js.map +1 -0
  14. package/dist/adapters/fileSystem.cjs +116 -0
  15. package/dist/adapters/fileSystem.cjs.map +1 -0
  16. package/dist/adapters/fileSystem.d.cts +17 -0
  17. package/dist/{types/storage → adapters}/fileSystem.d.ts +5 -2
  18. package/dist/adapters/fileSystem.js +93 -0
  19. package/dist/adapters/fileSystem.js.map +1 -0
  20. package/dist/adapters/indexedDB.cjs +103 -0
  21. package/dist/adapters/indexedDB.cjs.map +1 -0
  22. package/dist/adapters/indexedDB.d.cts +18 -0
  23. package/dist/{types/storage → adapters}/indexedDB.d.ts +5 -2
  24. package/dist/adapters/indexedDB.js +101 -0
  25. package/dist/adapters/indexedDB.js.map +1 -0
  26. package/dist/adapters/localStorage.cjs +50 -0
  27. package/dist/adapters/localStorage.cjs.map +1 -0
  28. package/dist/{types/storage/inMemory.d.ts → adapters/localStorage.d.cts} +6 -3
  29. package/dist/{types/storage → adapters}/localStorage.d.ts +5 -2
  30. package/dist/adapters/localStorage.js +48 -0
  31. package/dist/adapters/localStorage.js.map +1 -0
  32. package/dist/ark-TZ1gXAXU.d.cts +3880 -0
  33. package/dist/ark-TZ1gXAXU.d.ts +3880 -0
  34. package/dist/{types/worker/expo/asyncStorageTaskQueue.d.ts → asyncStorageTaskQueue-Cb1F_Z9s.d.ts} +6 -3
  35. package/dist/asyncStorageTaskQueue-EFqSmYTg.d.cts +49 -0
  36. package/dist/chunk-5BLDMQED.cjs +18 -0
  37. package/dist/chunk-5BLDMQED.cjs.map +1 -0
  38. package/dist/chunk-5PG7DV7A.cjs +805 -0
  39. package/dist/chunk-5PG7DV7A.cjs.map +1 -0
  40. package/dist/chunk-A3EMF7RN.js +95 -0
  41. package/dist/chunk-A3EMF7RN.js.map +1 -0
  42. package/dist/chunk-ADV27S4N.cjs +2701 -0
  43. package/dist/chunk-ADV27S4N.cjs.map +1 -0
  44. package/dist/chunk-BQLHADL7.js +13805 -0
  45. package/dist/chunk-BQLHADL7.js.map +1 -0
  46. package/dist/chunk-CFZMTDWI.js +209 -0
  47. package/dist/chunk-CFZMTDWI.js.map +1 -0
  48. package/dist/chunk-FG5ACJJW.cjs +212 -0
  49. package/dist/chunk-FG5ACJJW.cjs.map +1 -0
  50. package/dist/chunk-HW3JJ323.js +768 -0
  51. package/dist/chunk-HW3JJ323.js.map +1 -0
  52. package/dist/chunk-I3DGUUCT.cjs +838 -0
  53. package/dist/chunk-I3DGUUCT.cjs.map +1 -0
  54. package/dist/chunk-IPX2R7FR.cjs +100 -0
  55. package/dist/chunk-IPX2R7FR.cjs.map +1 -0
  56. package/dist/chunk-NSBPE2FW.js +15 -0
  57. package/dist/chunk-NSBPE2FW.js.map +1 -0
  58. package/dist/chunk-T64LAI7L.js +829 -0
  59. package/dist/chunk-T64LAI7L.js.map +1 -0
  60. package/dist/chunk-ZBUDLTBO.js +2671 -0
  61. package/dist/chunk-ZBUDLTBO.js.map +1 -0
  62. package/dist/chunk-ZLO6NETT.cjs +13910 -0
  63. package/dist/chunk-ZLO6NETT.cjs.map +1 -0
  64. package/dist/contracts/handlers/index.cjs +26 -0
  65. package/dist/contracts/handlers/index.cjs.map +1 -0
  66. package/dist/contracts/handlers/index.d.cts +7 -0
  67. package/dist/contracts/handlers/index.d.ts +7 -0
  68. package/dist/contracts/handlers/index.js +5 -0
  69. package/dist/contracts/handlers/index.js.map +1 -0
  70. package/dist/delegate-BFZs69hp.d.cts +84 -0
  71. package/dist/delegate-aaVGfWsV.d.ts +84 -0
  72. package/dist/index-B22cA64m.d.cts +199 -0
  73. package/dist/{types/storage/index.d.ts → index-C0IanN1m.d.cts} +3 -1
  74. package/dist/index-C0IanN1m.d.ts +11 -0
  75. package/dist/index-NDla_UoJ.d.ts +199 -0
  76. package/dist/index.cjs +480 -0
  77. package/dist/index.cjs.map +1 -0
  78. package/dist/index.d.cts +3343 -0
  79. package/dist/index.d.ts +3343 -0
  80. package/dist/index.js +7 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/repositories/realm/index.cjs +513 -0
  83. package/dist/repositories/realm/index.cjs.map +1 -0
  84. package/dist/repositories/realm/index.d.cts +217 -0
  85. package/dist/{types/repositories/realm/schemas.d.ts → repositories/realm/index.d.ts} +80 -112
  86. package/dist/repositories/realm/index.js +507 -0
  87. package/dist/repositories/realm/index.js.map +1 -0
  88. package/dist/repositories/sqlite/index.cjs +588 -0
  89. package/dist/repositories/sqlite/index.cjs.map +1 -0
  90. package/dist/repositories/sqlite/index.d.cts +118 -0
  91. package/dist/{types/repositories/sqlite/walletRepository.d.ts → repositories/sqlite/index.d.ts} +58 -5
  92. package/dist/repositories/sqlite/index.js +585 -0
  93. package/dist/repositories/sqlite/index.js.map +1 -0
  94. package/dist/taskRunner-C6Ff4OaU.d.cts +114 -0
  95. package/dist/taskRunner-yvPN8Z0K.d.ts +114 -0
  96. package/dist/wallet/expo/background.cjs +93 -0
  97. package/dist/wallet/expo/background.cjs.map +1 -0
  98. package/dist/wallet/expo/background.d.cts +84 -0
  99. package/dist/wallet/expo/background.d.ts +84 -0
  100. package/dist/wallet/expo/background.js +68 -0
  101. package/dist/wallet/expo/background.js.map +1 -0
  102. package/dist/wallet/expo/index.cjs +171 -0
  103. package/dist/wallet/expo/index.cjs.map +1 -0
  104. package/dist/wallet/expo/index.d.cts +122 -0
  105. package/dist/{types/wallet/expo/wallet.d.ts → wallet/expo/index.d.ts} +45 -22
  106. package/dist/wallet/expo/index.js +169 -0
  107. package/dist/wallet/expo/index.js.map +1 -0
  108. package/dist/wallet-AF-p-OWj.d.cts +774 -0
  109. package/dist/wallet-D9NBRqvC.d.ts +774 -0
  110. package/dist/worker/expo/index.cjs +140 -0
  111. package/dist/worker/expo/index.cjs.map +1 -0
  112. package/dist/worker/expo/index.d.cts +29 -0
  113. package/dist/worker/expo/index.d.ts +29 -0
  114. package/dist/worker/expo/index.js +121 -0
  115. package/dist/worker/expo/index.js.map +1 -0
  116. package/package.json +110 -76
  117. package/dist/cjs/adapters/asyncStorage.js +0 -5
  118. package/dist/cjs/adapters/expo.js +0 -8
  119. package/dist/cjs/adapters/fileSystem.js +0 -5
  120. package/dist/cjs/adapters/indexedDB.js +0 -5
  121. package/dist/cjs/adapters/localStorage.js +0 -5
  122. package/dist/cjs/arkfee/celenv.js +0 -43
  123. package/dist/cjs/arkfee/estimator.js +0 -143
  124. package/dist/cjs/arkfee/index.js +0 -5
  125. package/dist/cjs/arkfee/types.js +0 -26
  126. package/dist/cjs/arknote/index.js +0 -128
  127. package/dist/cjs/bip322/index.js +0 -270
  128. package/dist/cjs/contracts/arkcontract.js +0 -147
  129. package/dist/cjs/contracts/contractManager.js +0 -649
  130. package/dist/cjs/contracts/contractWatcher.js +0 -598
  131. package/dist/cjs/contracts/handlers/default.js +0 -93
  132. package/dist/cjs/contracts/handlers/delegate.js +0 -90
  133. package/dist/cjs/contracts/handlers/helpers.js +0 -115
  134. package/dist/cjs/contracts/handlers/index.js +0 -19
  135. package/dist/cjs/contracts/handlers/registry.js +0 -89
  136. package/dist/cjs/contracts/handlers/vhtlc.js +0 -194
  137. package/dist/cjs/contracts/index.js +0 -41
  138. package/dist/cjs/contracts/types.js +0 -2
  139. package/dist/cjs/contracts/vtxoOwnership.js +0 -78
  140. package/dist/cjs/extension/asset/assetGroup.js +0 -228
  141. package/dist/cjs/extension/asset/assetId.js +0 -152
  142. package/dist/cjs/extension/asset/assetInput.js +0 -222
  143. package/dist/cjs/extension/asset/assetOutput.js +0 -174
  144. package/dist/cjs/extension/asset/assetRef.js +0 -148
  145. package/dist/cjs/extension/asset/index.js +0 -23
  146. package/dist/cjs/extension/asset/metadata.js +0 -187
  147. package/dist/cjs/extension/asset/packet.js +0 -114
  148. package/dist/cjs/extension/asset/types.js +0 -22
  149. package/dist/cjs/extension/asset/utils.js +0 -105
  150. package/dist/cjs/extension/index.js +0 -254
  151. package/dist/cjs/extension/packet.js +0 -20
  152. package/dist/cjs/forfeit.js +0 -45
  153. package/dist/cjs/identity/descriptor.js +0 -169
  154. package/dist/cjs/identity/descriptorProvider.js +0 -2
  155. package/dist/cjs/identity/hdCapableIdentity.js +0 -20
  156. package/dist/cjs/identity/index.js +0 -40
  157. package/dist/cjs/identity/seedIdentity.js +0 -477
  158. package/dist/cjs/identity/serialize.js +0 -171
  159. package/dist/cjs/identity/singleKey.js +0 -126
  160. package/dist/cjs/identity/staticDescriptorProvider.js +0 -65
  161. package/dist/cjs/index.js +0 -202
  162. package/dist/cjs/intent/index.js +0 -259
  163. package/dist/cjs/musig2/index.js +0 -11
  164. package/dist/cjs/musig2/keys.js +0 -57
  165. package/dist/cjs/musig2/nonces.js +0 -48
  166. package/dist/cjs/musig2/sign.js +0 -102
  167. package/dist/cjs/networks.js +0 -26
  168. package/dist/cjs/package.json +0 -3
  169. package/dist/cjs/providers/ark.js +0 -577
  170. package/dist/cjs/providers/delegator.js +0 -85
  171. package/dist/cjs/providers/electrum.js +0 -869
  172. package/dist/cjs/providers/errors.js +0 -59
  173. package/dist/cjs/providers/expoArk.js +0 -82
  174. package/dist/cjs/providers/expoIndexer.js +0 -111
  175. package/dist/cjs/providers/expoUtils.js +0 -124
  176. package/dist/cjs/providers/indexer.js +0 -630
  177. package/dist/cjs/providers/onchain.js +0 -262
  178. package/dist/cjs/providers/utils.js +0 -121
  179. package/dist/cjs/repositories/contractRepository.js +0 -2
  180. package/dist/cjs/repositories/inMemory/contractRepository.js +0 -55
  181. package/dist/cjs/repositories/inMemory/walletRepository.js +0 -115
  182. package/dist/cjs/repositories/index.js +0 -34
  183. package/dist/cjs/repositories/indexedDB/contractRepository.js +0 -187
  184. package/dist/cjs/repositories/indexedDB/db.js +0 -19
  185. package/dist/cjs/repositories/indexedDB/manager.js +0 -100
  186. package/dist/cjs/repositories/indexedDB/schema.js +0 -204
  187. package/dist/cjs/repositories/indexedDB/walletRepository.js +0 -474
  188. package/dist/cjs/repositories/indexedDB/websqlAdapter.js +0 -144
  189. package/dist/cjs/repositories/migrations/contractRepositoryImpl.js +0 -127
  190. package/dist/cjs/repositories/migrations/fromStorageAdapter.js +0 -66
  191. package/dist/cjs/repositories/migrations/walletRepositoryImpl.js +0 -184
  192. package/dist/cjs/repositories/realm/contractRepository.js +0 -116
  193. package/dist/cjs/repositories/realm/index.js +0 -11
  194. package/dist/cjs/repositories/realm/schemas.js +0 -157
  195. package/dist/cjs/repositories/realm/types.js +0 -7
  196. package/dist/cjs/repositories/realm/walletRepository.js +0 -305
  197. package/dist/cjs/repositories/scriptFromAddress.js +0 -16
  198. package/dist/cjs/repositories/serialization.js +0 -82
  199. package/dist/cjs/repositories/sqlite/contractRepository.js +0 -135
  200. package/dist/cjs/repositories/sqlite/index.js +0 -7
  201. package/dist/cjs/repositories/sqlite/types.js +0 -2
  202. package/dist/cjs/repositories/sqlite/walletRepository.js +0 -441
  203. package/dist/cjs/repositories/walletRepository.js +0 -2
  204. package/dist/cjs/script/address.js +0 -108
  205. package/dist/cjs/script/base.js +0 -185
  206. package/dist/cjs/script/default.js +0 -57
  207. package/dist/cjs/script/delegate.js +0 -53
  208. package/dist/cjs/script/tapscript.js +0 -619
  209. package/dist/cjs/script/vhtlc.js +0 -170
  210. package/dist/cjs/storage/asyncStorage.js +0 -50
  211. package/dist/cjs/storage/fileSystem.js +0 -141
  212. package/dist/cjs/storage/inMemory.js +0 -24
  213. package/dist/cjs/storage/index.js +0 -2
  214. package/dist/cjs/storage/indexedDB.js +0 -101
  215. package/dist/cjs/storage/localStorage.js +0 -51
  216. package/dist/cjs/tree/signingSession.js +0 -229
  217. package/dist/cjs/tree/txTree.js +0 -192
  218. package/dist/cjs/tree/validation.js +0 -107
  219. package/dist/cjs/utils/anchor.js +0 -35
  220. package/dist/cjs/utils/arkTransaction.js +0 -271
  221. package/dist/cjs/utils/bip21.js +0 -127
  222. package/dist/cjs/utils/syncCursors.js +0 -128
  223. package/dist/cjs/utils/timelock.js +0 -59
  224. package/dist/cjs/utils/transaction.js +0 -28
  225. package/dist/cjs/utils/transactionHistory.js +0 -183
  226. package/dist/cjs/utils/txSizeEstimator.js +0 -132
  227. package/dist/cjs/utils/unknownFields.js +0 -174
  228. package/dist/cjs/wallet/asset-manager.js +0 -330
  229. package/dist/cjs/wallet/asset.js +0 -119
  230. package/dist/cjs/wallet/batch.js +0 -183
  231. package/dist/cjs/wallet/delegator.js +0 -308
  232. package/dist/cjs/wallet/expo/background.js +0 -116
  233. package/dist/cjs/wallet/expo/index.js +0 -9
  234. package/dist/cjs/wallet/expo/wallet.js +0 -230
  235. package/dist/cjs/wallet/hdDescriptorProvider.js +0 -188
  236. package/dist/cjs/wallet/index.js +0 -82
  237. package/dist/cjs/wallet/inputSignerRouter.js +0 -98
  238. package/dist/cjs/wallet/onchain.js +0 -290
  239. package/dist/cjs/wallet/ramps.js +0 -216
  240. package/dist/cjs/wallet/serviceWorker/wallet-message-handler.js +0 -953
  241. package/dist/cjs/wallet/serviceWorker/wallet.js +0 -1174
  242. package/dist/cjs/wallet/signingErrors.js +0 -32
  243. package/dist/cjs/wallet/unroll.js +0 -293
  244. package/dist/cjs/wallet/utils.js +0 -111
  245. package/dist/cjs/wallet/validation.js +0 -154
  246. package/dist/cjs/wallet/vtxo-manager.js +0 -1142
  247. package/dist/cjs/wallet/wallet.js +0 -2195
  248. package/dist/cjs/wallet/walletReceiveRotator.js +0 -547
  249. package/dist/cjs/worker/browser/service-worker-manager.js +0 -183
  250. package/dist/cjs/worker/browser/utils.js +0 -67
  251. package/dist/cjs/worker/errors.js +0 -16
  252. package/dist/cjs/worker/expo/asyncStorageTaskQueue.js +0 -78
  253. package/dist/cjs/worker/expo/index.js +0 -13
  254. package/dist/cjs/worker/expo/processors/contractPollProcessor.js +0 -62
  255. package/dist/cjs/worker/expo/processors/index.js +0 -6
  256. package/dist/cjs/worker/expo/taskQueue.js +0 -41
  257. package/dist/cjs/worker/expo/taskRunner.js +0 -73
  258. package/dist/cjs/worker/messageBus.js +0 -474
  259. package/dist/esm/adapters/asyncStorage.js +0 -1
  260. package/dist/esm/adapters/expo.js +0 -3
  261. package/dist/esm/adapters/fileSystem.js +0 -1
  262. package/dist/esm/adapters/indexedDB.js +0 -1
  263. package/dist/esm/adapters/localStorage.js +0 -1
  264. package/dist/esm/arkfee/celenv.js +0 -40
  265. package/dist/esm/arkfee/estimator.js +0 -139
  266. package/dist/esm/arkfee/index.js +0 -1
  267. package/dist/esm/arkfee/types.js +0 -22
  268. package/dist/esm/arknote/index.js +0 -124
  269. package/dist/esm/bip322/index.js +0 -267
  270. package/dist/esm/contracts/arkcontract.js +0 -140
  271. package/dist/esm/contracts/contractManager.js +0 -645
  272. package/dist/esm/contracts/contractWatcher.js +0 -594
  273. package/dist/esm/contracts/handlers/default.js +0 -90
  274. package/dist/esm/contracts/handlers/delegate.js +0 -87
  275. package/dist/esm/contracts/handlers/helpers.js +0 -110
  276. package/dist/esm/contracts/handlers/index.js +0 -12
  277. package/dist/esm/contracts/handlers/registry.js +0 -86
  278. package/dist/esm/contracts/handlers/vhtlc.js +0 -191
  279. package/dist/esm/contracts/index.js +0 -13
  280. package/dist/esm/contracts/types.js +0 -1
  281. package/dist/esm/contracts/vtxoOwnership.js +0 -69
  282. package/dist/esm/extension/asset/assetGroup.js +0 -224
  283. package/dist/esm/extension/asset/assetId.js +0 -148
  284. package/dist/esm/extension/asset/assetInput.js +0 -217
  285. package/dist/esm/extension/asset/assetOutput.js +0 -169
  286. package/dist/esm/extension/asset/assetRef.js +0 -144
  287. package/dist/esm/extension/asset/index.js +0 -8
  288. package/dist/esm/extension/asset/metadata.js +0 -182
  289. package/dist/esm/extension/asset/packet.js +0 -110
  290. package/dist/esm/extension/asset/types.js +0 -19
  291. package/dist/esm/extension/asset/utils.js +0 -99
  292. package/dist/esm/extension/index.js +0 -248
  293. package/dist/esm/extension/packet.js +0 -16
  294. package/dist/esm/forfeit.js +0 -41
  295. package/dist/esm/identity/descriptor.js +0 -161
  296. package/dist/esm/identity/descriptorProvider.js +0 -1
  297. package/dist/esm/identity/hdCapableIdentity.js +0 -17
  298. package/dist/esm/identity/index.js +0 -13
  299. package/dist/esm/identity/seedIdentity.js +0 -469
  300. package/dist/esm/identity/serialize.js +0 -164
  301. package/dist/esm/identity/singleKey.js +0 -121
  302. package/dist/esm/identity/staticDescriptorProvider.js +0 -61
  303. package/dist/esm/index.js +0 -87
  304. package/dist/esm/intent/index.js +0 -255
  305. package/dist/esm/musig2/index.js +0 -3
  306. package/dist/esm/musig2/keys.js +0 -21
  307. package/dist/esm/musig2/nonces.js +0 -11
  308. package/dist/esm/musig2/sign.js +0 -63
  309. package/dist/esm/networks.js +0 -22
  310. package/dist/esm/package.json +0 -3
  311. package/dist/esm/providers/ark.js +0 -572
  312. package/dist/esm/providers/delegator.js +0 -81
  313. package/dist/esm/providers/electrum.js +0 -864
  314. package/dist/esm/providers/errors.js +0 -54
  315. package/dist/esm/providers/expoArk.js +0 -78
  316. package/dist/esm/providers/expoIndexer.js +0 -107
  317. package/dist/esm/providers/expoUtils.js +0 -87
  318. package/dist/esm/providers/indexer.js +0 -626
  319. package/dist/esm/providers/onchain.js +0 -258
  320. package/dist/esm/providers/utils.js +0 -117
  321. package/dist/esm/repositories/contractRepository.js +0 -1
  322. package/dist/esm/repositories/inMemory/contractRepository.js +0 -51
  323. package/dist/esm/repositories/inMemory/walletRepository.js +0 -111
  324. package/dist/esm/repositories/index.js +0 -10
  325. package/dist/esm/repositories/indexedDB/contractRepository.js +0 -183
  326. package/dist/esm/repositories/indexedDB/db.js +0 -4
  327. package/dist/esm/repositories/indexedDB/manager.js +0 -95
  328. package/dist/esm/repositories/indexedDB/schema.js +0 -199
  329. package/dist/esm/repositories/indexedDB/walletRepository.js +0 -470
  330. package/dist/esm/repositories/indexedDB/websqlAdapter.js +0 -138
  331. package/dist/esm/repositories/migrations/contractRepositoryImpl.js +0 -121
  332. package/dist/esm/repositories/migrations/fromStorageAdapter.js +0 -58
  333. package/dist/esm/repositories/migrations/walletRepositoryImpl.js +0 -180
  334. package/dist/esm/repositories/realm/contractRepository.js +0 -112
  335. package/dist/esm/repositories/realm/index.js +0 -3
  336. package/dist/esm/repositories/realm/schemas.js +0 -153
  337. package/dist/esm/repositories/realm/types.js +0 -6
  338. package/dist/esm/repositories/realm/walletRepository.js +0 -301
  339. package/dist/esm/repositories/scriptFromAddress.js +0 -13
  340. package/dist/esm/repositories/serialization.js +0 -67
  341. package/dist/esm/repositories/sqlite/contractRepository.js +0 -131
  342. package/dist/esm/repositories/sqlite/index.js +0 -2
  343. package/dist/esm/repositories/sqlite/types.js +0 -1
  344. package/dist/esm/repositories/sqlite/walletRepository.js +0 -437
  345. package/dist/esm/repositories/walletRepository.js +0 -1
  346. package/dist/esm/script/address.js +0 -104
  347. package/dist/esm/script/base.js +0 -179
  348. package/dist/esm/script/default.js +0 -54
  349. package/dist/esm/script/delegate.js +0 -50
  350. package/dist/esm/script/tapscript.js +0 -615
  351. package/dist/esm/script/vhtlc.js +0 -167
  352. package/dist/esm/storage/asyncStorage.js +0 -46
  353. package/dist/esm/storage/fileSystem.js +0 -104
  354. package/dist/esm/storage/inMemory.js +0 -20
  355. package/dist/esm/storage/index.js +0 -1
  356. package/dist/esm/storage/indexedDB.js +0 -97
  357. package/dist/esm/storage/localStorage.js +0 -47
  358. package/dist/esm/tree/signingSession.js +0 -191
  359. package/dist/esm/tree/txTree.js +0 -188
  360. package/dist/esm/tree/validation.js +0 -101
  361. package/dist/esm/utils/anchor.js +0 -31
  362. package/dist/esm/utils/arkTransaction.js +0 -264
  363. package/dist/esm/utils/bip21.js +0 -123
  364. package/dist/esm/utils/syncCursors.js +0 -119
  365. package/dist/esm/utils/timelock.js +0 -22
  366. package/dist/esm/utils/transaction.js +0 -24
  367. package/dist/esm/utils/transactionHistory.js +0 -180
  368. package/dist/esm/utils/txSizeEstimator.js +0 -128
  369. package/dist/esm/utils/unknownFields.js +0 -169
  370. package/dist/esm/wallet/asset-manager.js +0 -325
  371. package/dist/esm/wallet/asset.js +0 -113
  372. package/dist/esm/wallet/batch.js +0 -180
  373. package/dist/esm/wallet/delegator.js +0 -303
  374. package/dist/esm/wallet/expo/background.js +0 -111
  375. package/dist/esm/wallet/expo/index.js +0 -2
  376. package/dist/esm/wallet/expo/wallet.js +0 -193
  377. package/dist/esm/wallet/hdDescriptorProvider.js +0 -184
  378. package/dist/esm/wallet/index.js +0 -75
  379. package/dist/esm/wallet/inputSignerRouter.js +0 -94
  380. package/dist/esm/wallet/onchain.js +0 -285
  381. package/dist/esm/wallet/ramps.js +0 -212
  382. package/dist/esm/wallet/serviceWorker/wallet-message-handler.js +0 -946
  383. package/dist/esm/wallet/serviceWorker/wallet.js +0 -1169
  384. package/dist/esm/wallet/signingErrors.js +0 -27
  385. package/dist/esm/wallet/unroll.js +0 -289
  386. package/dist/esm/wallet/utils.js +0 -103
  387. package/dist/esm/wallet/validation.js +0 -142
  388. package/dist/esm/wallet/vtxo-manager.js +0 -1136
  389. package/dist/esm/wallet/wallet.js +0 -2186
  390. package/dist/esm/wallet/walletReceiveRotator.js +0 -540
  391. package/dist/esm/worker/browser/service-worker-manager.js +0 -177
  392. package/dist/esm/worker/browser/utils.js +0 -63
  393. package/dist/esm/worker/errors.js +0 -11
  394. package/dist/esm/worker/expo/asyncStorageTaskQueue.js +0 -74
  395. package/dist/esm/worker/expo/index.js +0 -4
  396. package/dist/esm/worker/expo/processors/contractPollProcessor.js +0 -59
  397. package/dist/esm/worker/expo/processors/index.js +0 -1
  398. package/dist/esm/worker/expo/taskQueue.js +0 -37
  399. package/dist/esm/worker/expo/taskRunner.js +0 -69
  400. package/dist/esm/worker/messageBus.js +0 -470
  401. package/dist/types/adapters/asyncStorage.d.ts +0 -2
  402. package/dist/types/adapters/expo.d.ts +0 -4
  403. package/dist/types/adapters/fileSystem.d.ts +0 -2
  404. package/dist/types/adapters/indexedDB.d.ts +0 -2
  405. package/dist/types/adapters/localStorage.d.ts +0 -2
  406. package/dist/types/arkfee/celenv.d.ts +0 -25
  407. package/dist/types/arkfee/estimator.d.ts +0 -49
  408. package/dist/types/arkfee/index.d.ts +0 -2
  409. package/dist/types/arkfee/types.d.ts +0 -38
  410. package/dist/types/arknote/index.d.ts +0 -84
  411. package/dist/types/bip322/index.d.ts +0 -55
  412. package/dist/types/contracts/arkcontract.d.ts +0 -99
  413. package/dist/types/contracts/contractManager.d.ts +0 -411
  414. package/dist/types/contracts/contractWatcher.d.ts +0 -217
  415. package/dist/types/contracts/handlers/default.d.ts +0 -19
  416. package/dist/types/contracts/handlers/delegate.d.ts +0 -21
  417. package/dist/types/contracts/handlers/helpers.d.ts +0 -19
  418. package/dist/types/contracts/handlers/index.d.ts +0 -7
  419. package/dist/types/contracts/handlers/registry.d.ts +0 -65
  420. package/dist/types/contracts/handlers/vhtlc.d.ts +0 -32
  421. package/dist/types/contracts/index.d.ts +0 -14
  422. package/dist/types/contracts/types.d.ts +0 -250
  423. package/dist/types/contracts/vtxoOwnership.d.ts +0 -33
  424. package/dist/types/extension/asset/assetGroup.d.ts +0 -119
  425. package/dist/types/extension/asset/assetId.d.ts +0 -83
  426. package/dist/types/extension/asset/assetInput.d.ts +0 -64
  427. package/dist/types/extension/asset/assetOutput.d.ts +0 -54
  428. package/dist/types/extension/asset/assetRef.d.ts +0 -91
  429. package/dist/types/extension/asset/index.d.ts +0 -8
  430. package/dist/types/extension/asset/metadata.d.ts +0 -52
  431. package/dist/types/extension/asset/packet.d.ts +0 -41
  432. package/dist/types/extension/asset/types.d.ts +0 -16
  433. package/dist/types/extension/asset/utils.d.ts +0 -21
  434. package/dist/types/extension/index.d.ts +0 -56
  435. package/dist/types/extension/packet.d.ts +0 -21
  436. package/dist/types/forfeit.d.ts +0 -18
  437. package/dist/types/identity/descriptor.d.ts +0 -61
  438. package/dist/types/identity/descriptorProvider.d.ts +0 -42
  439. package/dist/types/identity/hdCapableIdentity.d.ts +0 -71
  440. package/dist/types/identity/index.d.ts +0 -57
  441. package/dist/types/identity/seedIdentity.d.ts +0 -270
  442. package/dist/types/identity/serialize.d.ts +0 -96
  443. package/dist/types/identity/singleKey.d.ts +0 -62
  444. package/dist/types/identity/staticDescriptorProvider.d.ts +0 -18
  445. package/dist/types/index.d.ts +0 -59
  446. package/dist/types/intent/index.d.ts +0 -86
  447. package/dist/types/musig2/index.d.ts +0 -4
  448. package/dist/types/musig2/keys.d.ts +0 -9
  449. package/dist/types/musig2/nonces.d.ts +0 -14
  450. package/dist/types/musig2/sign.d.ts +0 -27
  451. package/dist/types/networks.d.ts +0 -16
  452. package/dist/types/providers/ark.d.ts +0 -369
  453. package/dist/types/providers/delegator.d.ts +0 -82
  454. package/dist/types/providers/electrum.d.ts +0 -312
  455. package/dist/types/providers/errors.d.ts +0 -13
  456. package/dist/types/providers/expoArk.d.ts +0 -22
  457. package/dist/types/providers/expoIndexer.d.ts +0 -18
  458. package/dist/types/providers/expoUtils.d.ts +0 -18
  459. package/dist/types/providers/indexer.d.ts +0 -301
  460. package/dist/types/providers/onchain.d.ts +0 -148
  461. package/dist/types/providers/utils.d.ts +0 -12
  462. package/dist/types/repositories/contractRepository.d.ts +0 -32
  463. package/dist/types/repositories/inMemory/contractRepository.d.ts +0 -17
  464. package/dist/types/repositories/inMemory/walletRepository.d.ts +0 -29
  465. package/dist/types/repositories/index.d.ts +0 -9
  466. package/dist/types/repositories/indexedDB/contractRepository.d.ts +0 -21
  467. package/dist/types/repositories/indexedDB/db.d.ts +0 -4
  468. package/dist/types/repositories/indexedDB/manager.d.ts +0 -25
  469. package/dist/types/repositories/indexedDB/schema.d.ts +0 -9
  470. package/dist/types/repositories/indexedDB/walletRepository.d.ts +0 -28
  471. package/dist/types/repositories/indexedDB/websqlAdapter.d.ts +0 -49
  472. package/dist/types/repositories/migrations/contractRepositoryImpl.d.ts +0 -24
  473. package/dist/types/repositories/migrations/fromStorageAdapter.d.ts +0 -19
  474. package/dist/types/repositories/migrations/walletRepositoryImpl.d.ts +0 -27
  475. package/dist/types/repositories/realm/contractRepository.d.ts +0 -24
  476. package/dist/types/repositories/realm/index.d.ts +0 -4
  477. package/dist/types/repositories/realm/types.d.ts +0 -16
  478. package/dist/types/repositories/realm/walletRepository.d.ts +0 -34
  479. package/dist/types/repositories/scriptFromAddress.d.ts +0 -9
  480. package/dist/types/repositories/serialization.d.ts +0 -65
  481. package/dist/types/repositories/sqlite/contractRepository.d.ts +0 -33
  482. package/dist/types/repositories/sqlite/index.d.ts +0 -3
  483. package/dist/types/repositories/sqlite/types.d.ts +0 -18
  484. package/dist/types/repositories/walletRepository.d.ts +0 -72
  485. package/dist/types/script/address.d.ts +0 -67
  486. package/dist/types/script/base.d.ts +0 -105
  487. package/dist/types/script/default.d.ts +0 -44
  488. package/dist/types/script/delegate.d.ts +0 -40
  489. package/dist/types/script/tapscript.d.ts +0 -169
  490. package/dist/types/script/vhtlc.d.ts +0 -66
  491. package/dist/types/tree/signingSession.d.ts +0 -37
  492. package/dist/types/tree/txTree.d.ts +0 -28
  493. package/dist/types/tree/validation.d.ts +0 -15
  494. package/dist/types/utils/anchor.d.ts +0 -19
  495. package/dist/types/utils/arkTransaction.d.ts +0 -49
  496. package/dist/types/utils/bip21.d.ts +0 -38
  497. package/dist/types/utils/syncCursors.d.ts +0 -60
  498. package/dist/types/utils/timelock.d.ts +0 -9
  499. package/dist/types/utils/transaction.d.ts +0 -13
  500. package/dist/types/utils/transactionHistory.d.ts +0 -15
  501. package/dist/types/utils/txSizeEstimator.d.ts +0 -40
  502. package/dist/types/utils/unknownFields.d.ts +0 -83
  503. package/dist/types/wallet/asset-manager.d.ts +0 -69
  504. package/dist/types/wallet/asset.d.ts +0 -21
  505. package/dist/types/wallet/batch.d.ts +0 -107
  506. package/dist/types/wallet/delegator.d.ts +0 -48
  507. package/dist/types/wallet/expo/background.d.ts +0 -66
  508. package/dist/types/wallet/expo/index.d.ts +0 -4
  509. package/dist/types/wallet/hdDescriptorProvider.d.ts +0 -114
  510. package/dist/types/wallet/index.d.ts +0 -789
  511. package/dist/types/wallet/inputSignerRouter.d.ts +0 -35
  512. package/dist/types/wallet/onchain.d.ts +0 -109
  513. package/dist/types/wallet/ramps.d.ts +0 -64
  514. package/dist/types/wallet/serviceWorker/wallet-message-handler.d.ts +0 -543
  515. package/dist/types/wallet/serviceWorker/wallet.d.ts +0 -248
  516. package/dist/types/wallet/signingErrors.d.ts +0 -19
  517. package/dist/types/wallet/unroll.d.ts +0 -114
  518. package/dist/types/wallet/utils.d.ts +0 -36
  519. package/dist/types/wallet/validation.d.ts +0 -24
  520. package/dist/types/wallet/vtxo-manager.d.ts +0 -476
  521. package/dist/types/wallet/wallet.d.ts +0 -409
  522. package/dist/types/wallet/walletReceiveRotator.d.ts +0 -306
  523. package/dist/types/worker/browser/service-worker-manager.d.ts +0 -32
  524. package/dist/types/worker/browser/utils.d.ts +0 -17
  525. package/dist/types/worker/errors.d.ts +0 -7
  526. package/dist/types/worker/expo/index.d.ts +0 -7
  527. package/dist/types/worker/expo/processors/contractPollProcessor.d.ts +0 -19
  528. package/dist/types/worker/expo/processors/index.d.ts +0 -1
  529. package/dist/types/worker/expo/taskQueue.d.ts +0 -50
  530. package/dist/types/worker/expo/taskRunner.d.ts +0 -66
  531. package/dist/types/worker/messageBus.d.ts +0 -189
@@ -0,0 +1,2671 @@
1
+ import { VtxoScript, getSequence, sequenceToTimelock } from './chunk-HW3JJ323.js';
2
+ import { __export } from './chunk-NSBPE2FW.js';
3
+ import { OP, Script, SigHash, RawWitness, Transaction as Transaction$1, ScriptNum } from '@scure/btc-signer';
4
+ import { hex } from '@scure/base';
5
+ import { schnorr } from '@noble/curves/secp256k1.js';
6
+ import { compareBytes } from '@scure/btc-signer/utils.js';
7
+
8
+ var Transaction = class extends Transaction$1 {
9
+ static ARK_TX_OPTS = {
10
+ allowUnknown: true,
11
+ allowUnknownOutputs: true,
12
+ allowUnknownInputs: true
13
+ };
14
+ constructor(opts) {
15
+ super(withArkOpts(opts));
16
+ }
17
+ static fromPSBT(psbt_, opts) {
18
+ return Transaction$1.fromPSBT(psbt_, withArkOpts(opts));
19
+ }
20
+ static fromRaw(raw, opts) {
21
+ return Transaction$1.fromRaw(raw, withArkOpts(opts));
22
+ }
23
+ };
24
+ function withArkOpts(opts) {
25
+ return { ...Transaction.ARK_TX_OPTS, ...opts };
26
+ }
27
+ var ArkPsbtFieldKey = /* @__PURE__ */ ((ArkPsbtFieldKey2) => {
28
+ ArkPsbtFieldKey2["VtxoTaprootTree"] = "taptree";
29
+ ArkPsbtFieldKey2["VtxoTreeExpiry"] = "expiry";
30
+ ArkPsbtFieldKey2["Cosigner"] = "cosigner";
31
+ ArkPsbtFieldKey2["ConditionWitness"] = "condition";
32
+ return ArkPsbtFieldKey2;
33
+ })(ArkPsbtFieldKey || {});
34
+ var ArkPsbtFieldKeyType = 222;
35
+ function setArkPsbtField(tx, inputIndex, coder, value) {
36
+ tx.updateInput(inputIndex, {
37
+ unknown: [...tx.getInput(inputIndex)?.unknown ?? [], coder.encode(value)]
38
+ });
39
+ }
40
+ function getArkPsbtFields(tx, inputIndex, coder) {
41
+ const unknown = tx.getInput(inputIndex)?.unknown ?? [];
42
+ const fields = [];
43
+ for (const u of unknown) {
44
+ const v = coder.decode(u);
45
+ if (v) fields.push(v);
46
+ }
47
+ return fields;
48
+ }
49
+ var VtxoTaprootTree = {
50
+ key: "taptree" /* VtxoTaprootTree */,
51
+ encode: (value) => [
52
+ {
53
+ type: ArkPsbtFieldKeyType,
54
+ key: encodedPsbtFieldKey["taptree" /* VtxoTaprootTree */]
55
+ },
56
+ value
57
+ ],
58
+ decode: (value) => nullIfCatch(() => {
59
+ if (!checkKeyIncludes(value[0], "taptree" /* VtxoTaprootTree */)) return null;
60
+ return value[1];
61
+ })
62
+ };
63
+ var ConditionWitness = {
64
+ key: "condition" /* ConditionWitness */,
65
+ encode: (value) => [
66
+ {
67
+ type: ArkPsbtFieldKeyType,
68
+ key: encodedPsbtFieldKey["condition" /* ConditionWitness */]
69
+ },
70
+ RawWitness.encode(value)
71
+ ],
72
+ decode: (value) => nullIfCatch(() => {
73
+ if (!checkKeyIncludes(value[0], "condition" /* ConditionWitness */)) return null;
74
+ return RawWitness.decode(value[1]);
75
+ })
76
+ };
77
+ var CosignerPublicKey = {
78
+ key: "cosigner" /* Cosigner */,
79
+ encode: (value) => [
80
+ {
81
+ type: ArkPsbtFieldKeyType,
82
+ key: new Uint8Array([...encodedPsbtFieldKey["cosigner" /* Cosigner */], value.index])
83
+ },
84
+ value.key
85
+ ],
86
+ decode: (unknown) => nullIfCatch(() => {
87
+ if (!checkKeyIncludes(unknown[0], "cosigner" /* Cosigner */)) return null;
88
+ return {
89
+ index: unknown[0].key[unknown[0].key.length - 1],
90
+ key: unknown[1]
91
+ };
92
+ })
93
+ };
94
+ var VtxoTreeExpiry = {
95
+ key: "expiry" /* VtxoTreeExpiry */,
96
+ encode: (value) => [
97
+ {
98
+ type: ArkPsbtFieldKeyType,
99
+ key: encodedPsbtFieldKey["expiry" /* VtxoTreeExpiry */]
100
+ },
101
+ ScriptNum(6, true).encode(value.value === 0n ? 0n : value.value)
102
+ ],
103
+ decode: (unknown) => nullIfCatch(() => {
104
+ if (!checkKeyIncludes(unknown[0], "expiry" /* VtxoTreeExpiry */)) return null;
105
+ const v = ScriptNum(6, true).decode(unknown[1]);
106
+ if (!v) return null;
107
+ return sequenceToTimelock(Number(v));
108
+ })
109
+ };
110
+ var encodedPsbtFieldKey = Object.fromEntries(
111
+ Object.values(ArkPsbtFieldKey).map((key) => [key, new TextEncoder().encode(key)])
112
+ );
113
+ var nullIfCatch = (fn) => {
114
+ try {
115
+ return fn();
116
+ } catch (err) {
117
+ return null;
118
+ }
119
+ };
120
+ function checkKeyIncludes(key, arkPsbtFieldKey) {
121
+ const expected = hex.encode(encodedPsbtFieldKey[arkPsbtFieldKey]);
122
+ return hex.encode(new Uint8Array([key.type, ...key.key])).includes(expected);
123
+ }
124
+
125
+ // src/providers/errors.ts
126
+ var ArkError = class extends Error {
127
+ constructor(code, message, name, metadata) {
128
+ super(message);
129
+ this.code = code;
130
+ this.message = message;
131
+ this.name = name;
132
+ this.metadata = metadata;
133
+ }
134
+ };
135
+ function maybeArkError(error) {
136
+ try {
137
+ if (!(error instanceof Error)) return void 0;
138
+ const decoded = JSON.parse(error.message);
139
+ if (!("details" in decoded)) return void 0;
140
+ if (!Array.isArray(decoded.details)) return void 0;
141
+ for (const details of decoded.details) {
142
+ if (!("@type" in details)) continue;
143
+ const type = details["@type"];
144
+ if (type !== "type.googleapis.com/ark.v1.ErrorDetails") continue;
145
+ if (!("code" in details)) continue;
146
+ const code = details.code;
147
+ if (!("message" in details)) continue;
148
+ const message = details.message;
149
+ if (!("name" in details)) continue;
150
+ const name = details.name;
151
+ let metadata;
152
+ if ("metadata" in details && isMetadata(details.metadata)) {
153
+ metadata = details.metadata;
154
+ }
155
+ return new ArkError(code, message, name, metadata);
156
+ }
157
+ return void 0;
158
+ } catch (e) {
159
+ return void 0;
160
+ }
161
+ }
162
+ function isMetadata(value) {
163
+ return typeof value === "object" && value !== null && !Array.isArray(value);
164
+ }
165
+ var Intent;
166
+ ((Intent2) => {
167
+ function create(message, ins, outputs = []) {
168
+ if (typeof message !== "string") {
169
+ message = encodeMessage(message);
170
+ }
171
+ if (ins.length == 0) throw new Error("intent proof requires at least one input");
172
+ const inputs = ins.map(prepareCoinAsIntentProofInput);
173
+ if (!validateInputs(inputs)) ;
174
+ if (!validateOutputs(outputs)) ;
175
+ const toSpend = craftToSpendTx(message, inputs[0].witnessUtxo.script);
176
+ return craftToSignTx(toSpend, inputs, outputs);
177
+ }
178
+ Intent2.create = create;
179
+ function fee(proof) {
180
+ let sumOfInputs = 0n;
181
+ for (let i = 0; i < proof.inputsLength; i++) {
182
+ const input = proof.getInput(i);
183
+ if (input.witnessUtxo === void 0)
184
+ throw new Error("intent proof input requires witness utxo");
185
+ sumOfInputs += input.witnessUtxo.amount;
186
+ }
187
+ let sumOfOutputs = 0n;
188
+ for (let i = 0; i < proof.outputsLength; i++) {
189
+ const output = proof.getOutput(i);
190
+ if (output.amount === void 0) throw new Error("intent proof output requires amount");
191
+ sumOfOutputs += output.amount;
192
+ }
193
+ if (sumOfOutputs > sumOfInputs) {
194
+ throw new Error(
195
+ `intent proof output amount is greater than input amount: ${sumOfOutputs} > ${sumOfInputs}`
196
+ );
197
+ }
198
+ return Number(sumOfInputs - sumOfOutputs);
199
+ }
200
+ Intent2.fee = fee;
201
+ function encodeMessage(message) {
202
+ switch (message.type) {
203
+ case "register":
204
+ return JSON.stringify({
205
+ type: "register",
206
+ onchain_output_indexes: message.onchain_output_indexes,
207
+ valid_at: message.valid_at,
208
+ expire_at: message.expire_at,
209
+ cosigners_public_keys: message.cosigners_public_keys
210
+ });
211
+ case "delete":
212
+ return JSON.stringify({
213
+ type: "delete",
214
+ expire_at: message.expire_at
215
+ });
216
+ case "get-pending-tx":
217
+ return JSON.stringify({
218
+ type: "get-pending-tx",
219
+ expire_at: message.expire_at
220
+ });
221
+ }
222
+ }
223
+ Intent2.encodeMessage = encodeMessage;
224
+ })(Intent || (Intent = {}));
225
+ var OP_RETURN_EMPTY_PKSCRIPT = new Uint8Array([OP.RETURN]);
226
+ var ZERO_32 = new Uint8Array(32).fill(0);
227
+ var MAX_INDEX = 4294967295;
228
+ var TAG_INTENT_PROOF = "ark-intent-proof-message";
229
+ function validateInput(input) {
230
+ if (input.index === void 0) throw new Error("intent proof input requires index");
231
+ if (input.txid === void 0) throw new Error("intent proof input requires txid");
232
+ if (input.witnessUtxo === void 0)
233
+ throw new Error("intent proof input requires witness utxo");
234
+ return true;
235
+ }
236
+ function validateInputs(inputs) {
237
+ inputs.forEach(validateInput);
238
+ return true;
239
+ }
240
+ function validateOutput(output) {
241
+ if (output.amount === void 0) throw new Error("intent proof output requires amount");
242
+ if (output.script === void 0) throw new Error("intent proof output requires script");
243
+ return true;
244
+ }
245
+ function validateOutputs(outputs) {
246
+ outputs.forEach(validateOutput);
247
+ return true;
248
+ }
249
+ function craftToSpendTx(message, pkScript, tag = TAG_INTENT_PROOF) {
250
+ const messageHash = hashMessage(message, tag);
251
+ const tx = new Transaction({
252
+ version: 0
253
+ });
254
+ tx.addInput({
255
+ txid: ZERO_32,
256
+ // zero hash
257
+ index: MAX_INDEX,
258
+ sequence: 0
259
+ });
260
+ tx.addOutput({
261
+ amount: 0n,
262
+ script: pkScript
263
+ });
264
+ tx.updateInput(0, {
265
+ finalScriptSig: Script.encode(["OP_0", messageHash])
266
+ });
267
+ return tx;
268
+ }
269
+ function craftToSignTx(toSpend, inputs, outputs) {
270
+ const firstInput = inputs[0];
271
+ const tx = new Transaction({
272
+ version: 2,
273
+ lockTime: 0
274
+ });
275
+ tx.addInput({
276
+ ...firstInput,
277
+ txid: toSpend.id,
278
+ index: 0,
279
+ witnessUtxo: {
280
+ script: firstInput.witnessUtxo.script,
281
+ amount: 0n
282
+ },
283
+ sighashType: SigHash.ALL
284
+ });
285
+ for (const [i, input] of inputs.entries()) {
286
+ tx.addInput({
287
+ ...input,
288
+ sighashType: SigHash.ALL
289
+ });
290
+ if (input.unknown?.length) {
291
+ tx.updateInput(i + 1, {
292
+ unknown: input.unknown
293
+ });
294
+ }
295
+ }
296
+ if (outputs.length === 0) {
297
+ outputs = [
298
+ {
299
+ amount: 0n,
300
+ script: OP_RETURN_EMPTY_PKSCRIPT
301
+ }
302
+ ];
303
+ }
304
+ for (const output of outputs) {
305
+ tx.addOutput({
306
+ amount: output.amount,
307
+ script: output.script
308
+ });
309
+ }
310
+ return tx;
311
+ }
312
+ function hashMessage(message, tag = TAG_INTENT_PROOF) {
313
+ return schnorr.utils.taggedHash(tag, new TextEncoder().encode(message));
314
+ }
315
+ function prepareCoinAsIntentProofInput(coin) {
316
+ if (!("tapTree" in coin)) {
317
+ return coin;
318
+ }
319
+ const vtxoScript = VtxoScript.decode(coin.tapTree);
320
+ const sequence = getSequence(coin.intentTapLeafScript);
321
+ const unknown = [VtxoTaprootTree.encode(coin.tapTree)];
322
+ if (coin.extraWitness) {
323
+ unknown.push(ConditionWitness.encode(coin.extraWitness));
324
+ }
325
+ return {
326
+ txid: hex.decode(coin.txid),
327
+ index: coin.vout,
328
+ witnessUtxo: {
329
+ amount: BigInt(coin.value),
330
+ script: vtxoScript.pkScript
331
+ },
332
+ sequence,
333
+ tapLeafScript: [coin.intentTapLeafScript],
334
+ unknown
335
+ };
336
+ }
337
+
338
+ // src/providers/utils.ts
339
+ function createAbortError() {
340
+ const error = new Error("EventSource closed");
341
+ error.name = "AbortError";
342
+ return error;
343
+ }
344
+ function eventSourceIterator(eventSource) {
345
+ const messageQueue = [];
346
+ const errorQueue = [];
347
+ let messageResolve = null;
348
+ let errorResolve = null;
349
+ let closed = false;
350
+ let cleanedUp = false;
351
+ const cleanup = () => {
352
+ if (cleanedUp) return;
353
+ cleanedUp = true;
354
+ eventSource.removeEventListener("message", messageHandler);
355
+ eventSource.removeEventListener("error", errorHandler);
356
+ };
357
+ const close = () => {
358
+ if (closed) return;
359
+ closed = true;
360
+ messageQueue.length = 0;
361
+ errorQueue.length = 0;
362
+ eventSource.close();
363
+ cleanup();
364
+ if (errorResolve) {
365
+ const reject = errorResolve;
366
+ messageResolve = null;
367
+ errorResolve = null;
368
+ reject(createAbortError());
369
+ }
370
+ };
371
+ const messageHandler = (event) => {
372
+ if (closed) return;
373
+ if (messageResolve) {
374
+ const resolve = messageResolve;
375
+ messageResolve = null;
376
+ errorResolve = null;
377
+ resolve(event);
378
+ } else {
379
+ messageQueue.push(event);
380
+ }
381
+ };
382
+ const errorHandler = () => {
383
+ if (closed) return;
384
+ const error = new Error("EventSource error");
385
+ error.name = "EventSourceError";
386
+ if (errorResolve) {
387
+ const reject = errorResolve;
388
+ messageResolve = null;
389
+ errorResolve = null;
390
+ reject(error);
391
+ } else {
392
+ errorQueue.push(error);
393
+ }
394
+ };
395
+ eventSource.addEventListener("message", messageHandler);
396
+ eventSource.addEventListener("error", errorHandler);
397
+ const gen = (async function* () {
398
+ try {
399
+ while (!closed) {
400
+ if (messageQueue.length > 0) {
401
+ yield messageQueue.shift();
402
+ continue;
403
+ }
404
+ if (errorQueue.length > 0) {
405
+ const error = errorQueue.shift();
406
+ throw error;
407
+ }
408
+ const result = await new Promise((resolve, reject) => {
409
+ messageResolve = resolve;
410
+ errorResolve = reject;
411
+ }).finally(() => {
412
+ messageResolve = null;
413
+ errorResolve = null;
414
+ });
415
+ if (!closed && result) {
416
+ yield result;
417
+ }
418
+ }
419
+ } finally {
420
+ closed = true;
421
+ cleanup();
422
+ eventSource.close();
423
+ }
424
+ })();
425
+ const origReturn = gen.return.bind(gen);
426
+ const managed = gen;
427
+ managed.close = close;
428
+ managed.return = (value) => {
429
+ close();
430
+ return origReturn(value);
431
+ };
432
+ return managed;
433
+ }
434
+ function isEventSourceError(error) {
435
+ return error instanceof Error && error.name === "EventSourceError";
436
+ }
437
+
438
+ // src/providers/ark.ts
439
+ var SettlementEventType = /* @__PURE__ */ ((SettlementEventType2) => {
440
+ SettlementEventType2["BatchStarted"] = "batch_started";
441
+ SettlementEventType2["BatchFinalization"] = "batch_finalization";
442
+ SettlementEventType2["BatchFinalized"] = "batch_finalized";
443
+ SettlementEventType2["BatchFailed"] = "batch_failed";
444
+ SettlementEventType2["TreeSigningStarted"] = "tree_signing_started";
445
+ SettlementEventType2["TreeNonces"] = "tree_nonces";
446
+ SettlementEventType2["TreeTx"] = "tree_tx";
447
+ SettlementEventType2["TreeSignature"] = "tree_signature";
448
+ SettlementEventType2["StreamStarted"] = "stream_started";
449
+ return SettlementEventType2;
450
+ })(SettlementEventType || {});
451
+ var RestArkProvider = class {
452
+ constructor(serverUrl) {
453
+ this.serverUrl = serverUrl;
454
+ }
455
+ async getInfo() {
456
+ const url = `${this.serverUrl}/v1/info`;
457
+ const response = await fetch(url);
458
+ if (!response.ok) {
459
+ const errorText = await response.text();
460
+ handleError(errorText, `Failed to get server info: ${response.statusText}`);
461
+ }
462
+ const fromServer = await response.json();
463
+ return {
464
+ boardingExitDelay: BigInt(fromServer.boardingExitDelay ?? 0),
465
+ checkpointTapscript: fromServer.checkpointTapscript ?? "",
466
+ deprecatedSigners: fromServer.deprecatedSigners?.map((signer) => ({
467
+ cutoffDate: BigInt(signer.cutoffDate ?? 0),
468
+ pubkey: signer.pubkey ?? ""
469
+ })) ?? [],
470
+ digest: fromServer.digest ?? "",
471
+ dust: BigInt(fromServer.dust ?? 0),
472
+ fees: {
473
+ intentFee: fromServer.fees?.intentFee ?? {},
474
+ txFeeRate: fromServer?.fees?.txFeeRate ?? ""
475
+ },
476
+ forfeitAddress: fromServer.forfeitAddress ?? "",
477
+ forfeitPubkey: fromServer.forfeitPubkey ?? "",
478
+ network: fromServer.network ?? "",
479
+ scheduledSession: "scheduledSession" in fromServer && fromServer.scheduledSession != null ? {
480
+ duration: BigInt(fromServer.scheduledSession.duration ?? 0),
481
+ nextStartTime: BigInt(fromServer.scheduledSession.nextStartTime ?? 0),
482
+ nextEndTime: BigInt(fromServer.scheduledSession.nextEndTime ?? 0),
483
+ period: BigInt(fromServer.scheduledSession.period ?? 0),
484
+ fees: fromServer.scheduledSession.fees ?? {}
485
+ } : void 0,
486
+ serviceStatus: fromServer.serviceStatus ?? {},
487
+ sessionDuration: BigInt(fromServer.sessionDuration ?? 0),
488
+ signerPubkey: fromServer.signerPubkey ?? "",
489
+ unilateralExitDelay: BigInt(fromServer.unilateralExitDelay ?? 0),
490
+ utxoMaxAmount: BigInt(fromServer.utxoMaxAmount ?? -1),
491
+ utxoMinAmount: BigInt(fromServer.utxoMinAmount ?? 0),
492
+ version: fromServer.version ?? "",
493
+ vtxoMaxAmount: BigInt(fromServer.vtxoMaxAmount ?? -1),
494
+ vtxoMinAmount: BigInt(fromServer.vtxoMinAmount ?? 0)
495
+ };
496
+ }
497
+ async submitTx(signedArkTx, checkpointTxs) {
498
+ const url = `${this.serverUrl}/v1/tx/submit`;
499
+ const response = await fetch(url, {
500
+ method: "POST",
501
+ headers: {
502
+ "Content-Type": "application/json"
503
+ },
504
+ body: JSON.stringify({
505
+ signedArkTx,
506
+ checkpointTxs
507
+ })
508
+ });
509
+ if (!response.ok) {
510
+ const errorText = await response.text();
511
+ handleError(errorText, `Failed to submit virtual transaction: ${errorText}`);
512
+ }
513
+ const data = await response.json();
514
+ return {
515
+ arkTxid: data.arkTxid,
516
+ finalArkTx: data.finalArkTx,
517
+ signedCheckpointTxs: data.signedCheckpointTxs
518
+ };
519
+ }
520
+ async finalizeTx(arkTxid, finalCheckpointTxs) {
521
+ const url = `${this.serverUrl}/v1/tx/finalize`;
522
+ const response = await fetch(url, {
523
+ method: "POST",
524
+ headers: {
525
+ "Content-Type": "application/json"
526
+ },
527
+ body: JSON.stringify({
528
+ arkTxid,
529
+ finalCheckpointTxs
530
+ })
531
+ });
532
+ if (!response.ok) {
533
+ const errorText = await response.text();
534
+ handleError(errorText, `Failed to finalize offchain transaction: ${errorText}`);
535
+ }
536
+ }
537
+ async registerIntent(intent) {
538
+ const url = `${this.serverUrl}/v1/batch/registerIntent`;
539
+ const response = await fetch(url, {
540
+ method: "POST",
541
+ headers: {
542
+ "Content-Type": "application/json"
543
+ },
544
+ body: JSON.stringify({
545
+ intent: {
546
+ proof: intent.proof,
547
+ message: Intent.encodeMessage(intent.message)
548
+ }
549
+ })
550
+ });
551
+ if (!response.ok) {
552
+ const errorText = await response.text();
553
+ handleError(errorText, `Failed to register intent: ${errorText}`);
554
+ }
555
+ const data = await response.json();
556
+ return data.intentId;
557
+ }
558
+ async deleteIntent(intent) {
559
+ const url = `${this.serverUrl}/v1/batch/deleteIntent`;
560
+ const response = await fetch(url, {
561
+ method: "POST",
562
+ headers: {
563
+ "Content-Type": "application/json"
564
+ },
565
+ body: JSON.stringify({
566
+ intent: {
567
+ proof: intent.proof,
568
+ message: Intent.encodeMessage(intent.message)
569
+ }
570
+ })
571
+ });
572
+ if (!response.ok) {
573
+ const errorText = await response.text();
574
+ handleError(errorText, `Failed to delete intent: ${errorText}`);
575
+ }
576
+ }
577
+ async confirmRegistration(intentId) {
578
+ const url = `${this.serverUrl}/v1/batch/ack`;
579
+ const response = await fetch(url, {
580
+ method: "POST",
581
+ headers: {
582
+ "Content-Type": "application/json"
583
+ },
584
+ body: JSON.stringify({
585
+ intentId
586
+ })
587
+ });
588
+ if (!response.ok) {
589
+ const errorText = await response.text();
590
+ handleError(errorText, `Failed to confirm registration: ${errorText}`);
591
+ }
592
+ }
593
+ async submitTreeNonces(batchId, pubkey, nonces) {
594
+ const url = `${this.serverUrl}/v1/batch/tree/submitNonces`;
595
+ const response = await fetch(url, {
596
+ method: "POST",
597
+ headers: {
598
+ "Content-Type": "application/json"
599
+ },
600
+ body: JSON.stringify({
601
+ batchId,
602
+ pubkey,
603
+ treeNonces: encodeMusig2Nonces(nonces)
604
+ })
605
+ });
606
+ if (!response.ok) {
607
+ const errorText = await response.text();
608
+ handleError(errorText, `Failed to submit tree nonces: ${errorText}`);
609
+ }
610
+ }
611
+ async submitTreeSignatures(batchId, pubkey, signatures) {
612
+ const url = `${this.serverUrl}/v1/batch/tree/submitSignatures`;
613
+ const response = await fetch(url, {
614
+ method: "POST",
615
+ headers: {
616
+ "Content-Type": "application/json"
617
+ },
618
+ body: JSON.stringify({
619
+ batchId,
620
+ pubkey,
621
+ treeSignatures: encodeMusig2Signatures(signatures)
622
+ })
623
+ });
624
+ if (!response.ok) {
625
+ const errorText = await response.text();
626
+ handleError(errorText, `Failed to submit tree signatures: ${errorText}`);
627
+ }
628
+ }
629
+ async submitSignedForfeitTxs(signedForfeitTxs, signedCommitmentTx) {
630
+ const url = `${this.serverUrl}/v1/batch/submitForfeitTxs`;
631
+ const response = await fetch(url, {
632
+ method: "POST",
633
+ headers: {
634
+ "Content-Type": "application/json"
635
+ },
636
+ body: JSON.stringify({
637
+ signedForfeitTxs,
638
+ signedCommitmentTx
639
+ })
640
+ });
641
+ if (!response.ok) {
642
+ const errorText = await response.text();
643
+ handleError(errorText, `Failed to submit forfeit transactions: ${response.statusText}`);
644
+ }
645
+ }
646
+ getEventStream(signal, topics) {
647
+ const url = `${this.serverUrl}/v1/batch/events`;
648
+ const queryParams = topics.length > 0 ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join("&")}` : "";
649
+ let iterator = null;
650
+ const closeIterator = () => iterator?.close();
651
+ const self = this;
652
+ const gen = (async function* () {
653
+ const abortHandler = closeIterator;
654
+ signal?.addEventListener("abort", abortHandler);
655
+ try {
656
+ while (!signal?.aborted) {
657
+ const currentIterator = eventSourceIterator(new EventSource(url + queryParams));
658
+ iterator = currentIterator;
659
+ try {
660
+ for await (const event of currentIterator) {
661
+ if (signal?.aborted) break;
662
+ try {
663
+ const data = JSON.parse(event.data);
664
+ const settlementEvent = self.parseSettlementEvent(data);
665
+ if (settlementEvent) {
666
+ yield settlementEvent;
667
+ }
668
+ } catch (err) {
669
+ console.error("Failed to parse event:", err);
670
+ throw err;
671
+ }
672
+ }
673
+ } catch (error) {
674
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
675
+ break;
676
+ }
677
+ if (isFetchTimeoutError(error)) {
678
+ console.debug("Timeout error ignored");
679
+ continue;
680
+ }
681
+ if (isEventSourceError(error)) {
682
+ throw error;
683
+ }
684
+ console.error("Event stream error:", error);
685
+ throw error;
686
+ } finally {
687
+ currentIterator.close();
688
+ iterator = null;
689
+ }
690
+ }
691
+ } finally {
692
+ signal?.removeEventListener("abort", abortHandler);
693
+ closeIterator();
694
+ }
695
+ })();
696
+ const origReturn = gen.return.bind(gen);
697
+ gen.return = (value) => {
698
+ closeIterator();
699
+ return origReturn(value);
700
+ };
701
+ return gen;
702
+ }
703
+ getTransactionsStream(signal) {
704
+ const url = `${this.serverUrl}/v1/txs`;
705
+ let iterator = null;
706
+ const closeIterator = () => iterator?.close();
707
+ const self = this;
708
+ const gen = (async function* () {
709
+ const abortHandler = closeIterator;
710
+ signal?.addEventListener("abort", abortHandler);
711
+ try {
712
+ while (!signal?.aborted) {
713
+ try {
714
+ const currentIterator = eventSourceIterator(new EventSource(url));
715
+ iterator = currentIterator;
716
+ for await (const event of currentIterator) {
717
+ if (signal?.aborted) break;
718
+ try {
719
+ const data = JSON.parse(event.data);
720
+ const txNotification = self.parseTransactionNotification(data);
721
+ if (txNotification) {
722
+ yield txNotification;
723
+ }
724
+ } catch (err) {
725
+ console.error("Failed to parse transaction notification:", err);
726
+ throw err;
727
+ }
728
+ }
729
+ } catch (error) {
730
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
731
+ break;
732
+ }
733
+ if (isFetchTimeoutError(error)) {
734
+ console.debug("Timeout error ignored");
735
+ continue;
736
+ }
737
+ if (isEventSourceError(error)) {
738
+ throw error;
739
+ }
740
+ console.error("Transaction stream error:", error);
741
+ throw error;
742
+ } finally {
743
+ closeIterator();
744
+ iterator = null;
745
+ }
746
+ }
747
+ } finally {
748
+ signal?.removeEventListener("abort", abortHandler);
749
+ closeIterator();
750
+ }
751
+ })();
752
+ const origReturn = gen.return.bind(gen);
753
+ gen.return = (value) => {
754
+ closeIterator();
755
+ return origReturn(value);
756
+ };
757
+ return gen;
758
+ }
759
+ async getPendingTxs(intent) {
760
+ const url = `${this.serverUrl}/v1/tx/pending`;
761
+ const response = await fetch(url, {
762
+ method: "POST",
763
+ headers: {
764
+ "Content-Type": "application/json"
765
+ },
766
+ body: JSON.stringify({
767
+ intent: {
768
+ proof: intent.proof,
769
+ message: Intent.encodeMessage(intent.message)
770
+ }
771
+ })
772
+ });
773
+ if (!response.ok) {
774
+ const errorText = await response.text();
775
+ handleError(errorText, `Failed to get pending transactions: ${errorText}`);
776
+ }
777
+ const data = await response.json();
778
+ return data.pendingTxs;
779
+ }
780
+ parseSettlementEvent(data) {
781
+ if (data.batchStarted) {
782
+ return {
783
+ type: "batch_started" /* BatchStarted */,
784
+ id: data.batchStarted.id,
785
+ intentIdHashes: data.batchStarted.intentIdHashes,
786
+ batchExpiry: BigInt(data.batchStarted.batchExpiry)
787
+ };
788
+ }
789
+ if (data.batchFinalization) {
790
+ return {
791
+ type: "batch_finalization" /* BatchFinalization */,
792
+ id: data.batchFinalization.id,
793
+ commitmentTx: data.batchFinalization.commitmentTx
794
+ };
795
+ }
796
+ if (data.batchFinalized) {
797
+ return {
798
+ type: "batch_finalized" /* BatchFinalized */,
799
+ id: data.batchFinalized.id,
800
+ commitmentTxid: data.batchFinalized.commitmentTxid
801
+ };
802
+ }
803
+ if (data.batchFailed) {
804
+ return {
805
+ type: "batch_failed" /* BatchFailed */,
806
+ id: data.batchFailed.id,
807
+ reason: data.batchFailed.reason
808
+ };
809
+ }
810
+ if (data.treeSigningStarted) {
811
+ return {
812
+ type: "tree_signing_started" /* TreeSigningStarted */,
813
+ id: data.treeSigningStarted.id,
814
+ cosignersPublicKeys: data.treeSigningStarted.cosignersPubkeys,
815
+ unsignedCommitmentTx: data.treeSigningStarted.unsignedCommitmentTx
816
+ };
817
+ }
818
+ if (data.treeNoncesAggregated) {
819
+ return null;
820
+ }
821
+ if (data.treeNonces) {
822
+ return {
823
+ type: "tree_nonces" /* TreeNonces */,
824
+ id: data.treeNonces.id,
825
+ topic: data.treeNonces.topic,
826
+ txid: data.treeNonces.txid,
827
+ nonces: decodeMusig2Nonces(data.treeNonces.nonces)
828
+ // pubkey -> public nonce
829
+ };
830
+ }
831
+ if (data.treeTx) {
832
+ const children = Object.fromEntries(
833
+ Object.entries(data.treeTx.children).map(([outputIndex, txid]) => {
834
+ return [parseInt(outputIndex), txid];
835
+ })
836
+ );
837
+ return {
838
+ type: "tree_tx" /* TreeTx */,
839
+ id: data.treeTx.id,
840
+ topic: data.treeTx.topic,
841
+ batchIndex: data.treeTx.batchIndex,
842
+ chunk: {
843
+ txid: data.treeTx.txid,
844
+ tx: data.treeTx.tx,
845
+ children
846
+ }
847
+ };
848
+ }
849
+ if (data.treeSignature) {
850
+ return {
851
+ type: "tree_signature" /* TreeSignature */,
852
+ id: data.treeSignature.id,
853
+ topic: data.treeSignature.topic,
854
+ batchIndex: data.treeSignature.batchIndex,
855
+ txid: data.treeSignature.txid,
856
+ signature: data.treeSignature.signature
857
+ };
858
+ }
859
+ if (data.streamStarted) {
860
+ return {
861
+ type: "stream_started" /* StreamStarted */,
862
+ id: data.streamStarted.id
863
+ };
864
+ }
865
+ if (data.heartbeat) {
866
+ return null;
867
+ }
868
+ console.warn("Unknown event type:", data);
869
+ return null;
870
+ }
871
+ parseTransactionNotification(data) {
872
+ if (data.commitmentTx) {
873
+ return {
874
+ commitmentTx: {
875
+ txid: data.commitmentTx.txid,
876
+ tx: data.commitmentTx.tx,
877
+ spentVtxos: data.commitmentTx.spentVtxos.map(mapVtxo),
878
+ spendableVtxos: data.commitmentTx.spendableVtxos.map(mapVtxo),
879
+ checkpointTxs: data.commitmentTx.checkpointTxs
880
+ }
881
+ };
882
+ }
883
+ if (data.arkTx) {
884
+ return {
885
+ arkTx: {
886
+ txid: data.arkTx.txid,
887
+ tx: data.arkTx.tx,
888
+ spentVtxos: data.arkTx.spentVtxos.map(mapVtxo),
889
+ spendableVtxos: data.arkTx.spendableVtxos.map(mapVtxo),
890
+ checkpointTxs: data.arkTx.checkpointTxs
891
+ }
892
+ };
893
+ }
894
+ if (data.heartbeat) {
895
+ return null;
896
+ }
897
+ console.warn("Unknown transaction notification type:", data);
898
+ return null;
899
+ }
900
+ };
901
+ function encodeMusig2Nonces(nonces) {
902
+ const noncesObject = {};
903
+ for (const [txid, nonce] of nonces) {
904
+ noncesObject[txid] = hex.encode(nonce.pubNonce);
905
+ }
906
+ return noncesObject;
907
+ }
908
+ function encodeMusig2Signatures(signatures) {
909
+ const sigObject = {};
910
+ for (const [txid, sig] of signatures) {
911
+ sigObject[txid] = hex.encode(sig.encode());
912
+ }
913
+ return sigObject;
914
+ }
915
+ function decodeMusig2Nonces(noncesObject) {
916
+ return new Map(
917
+ Object.entries(noncesObject).map(([txid, nonce]) => {
918
+ if (typeof nonce !== "string") {
919
+ throw new Error("invalid nonce");
920
+ }
921
+ return [txid, { pubNonce: hex.decode(nonce) }];
922
+ })
923
+ );
924
+ }
925
+ function isFetchTimeoutError(err) {
926
+ const checkError = (error) => {
927
+ if (!(error instanceof Error)) return false;
928
+ const isCloudflare524 = error.name === "TypeError" && error.message === "Failed to fetch";
929
+ return isCloudflare524 || error.name === "HeadersTimeoutError" || error.name === "BodyTimeoutError" || error.code === "UND_ERR_HEADERS_TIMEOUT" || error.code === "UND_ERR_BODY_TIMEOUT";
930
+ };
931
+ return checkError(err) || checkError(err.cause);
932
+ }
933
+ function mapVtxo(vtxo) {
934
+ return {
935
+ outpoint: {
936
+ txid: vtxo.outpoint.txid,
937
+ vout: vtxo.outpoint.vout
938
+ },
939
+ amount: vtxo.amount,
940
+ script: vtxo.script,
941
+ createdAt: vtxo.createdAt,
942
+ expiresAt: vtxo.expiresAt,
943
+ commitmentTxids: vtxo.commitmentTxids,
944
+ isPreconfirmed: vtxo.isPreconfirmed,
945
+ isSwept: vtxo.isSwept,
946
+ isUnrolled: vtxo.isUnrolled,
947
+ isSpent: vtxo.isSpent,
948
+ spentBy: vtxo.spentBy,
949
+ settledBy: vtxo.settledBy,
950
+ arkTxid: vtxo.arkTxid
951
+ };
952
+ }
953
+ function handleError(errorText, defaultMessage) {
954
+ const error = new Error(errorText);
955
+ const arkError = maybeArkError(error);
956
+ throw arkError ?? new Error(defaultMessage);
957
+ }
958
+
959
+ // src/extension/asset/index.ts
960
+ var asset_exports = {};
961
+ __export(asset_exports, {
962
+ AssetGroup: () => AssetGroup,
963
+ AssetId: () => AssetId,
964
+ AssetInput: () => AssetInput,
965
+ AssetInputType: () => AssetInputType,
966
+ AssetInputs: () => AssetInputs,
967
+ AssetOutput: () => AssetOutput,
968
+ AssetOutputs: () => AssetOutputs,
969
+ AssetRef: () => AssetRef,
970
+ AssetRefType: () => AssetRefType,
971
+ Metadata: () => Metadata,
972
+ MetadataList: () => MetadataList,
973
+ Packet: () => Packet
974
+ });
975
+
976
+ // src/extension/asset/types.ts
977
+ var TX_HASH_SIZE = 32;
978
+ var ASSET_ID_SIZE = 34;
979
+ var AssetInputType = /* @__PURE__ */ ((AssetInputType2) => {
980
+ AssetInputType2[AssetInputType2["Unspecified"] = 0] = "Unspecified";
981
+ AssetInputType2[AssetInputType2["Local"] = 1] = "Local";
982
+ AssetInputType2[AssetInputType2["Intent"] = 2] = "Intent";
983
+ return AssetInputType2;
984
+ })(AssetInputType || {});
985
+ var AssetRefType = /* @__PURE__ */ ((AssetRefType2) => {
986
+ AssetRefType2[AssetRefType2["Unspecified"] = 0] = "Unspecified";
987
+ AssetRefType2[AssetRefType2["ByID"] = 1] = "ByID";
988
+ AssetRefType2[AssetRefType2["ByGroup"] = 2] = "ByGroup";
989
+ return AssetRefType2;
990
+ })(AssetRefType || {});
991
+ var MASK_ASSET_ID = 1;
992
+ var MASK_CONTROL_ASSET = 2;
993
+ var MASK_METADATA = 4;
994
+
995
+ // src/extension/asset/utils.ts
996
+ var BufferWriter = class {
997
+ buffer = [];
998
+ write(data) {
999
+ for (const byte of data) {
1000
+ this.buffer.push(byte);
1001
+ }
1002
+ }
1003
+ writeByte(byte) {
1004
+ this.buffer.push(byte & 255);
1005
+ }
1006
+ writeUint16LE(value) {
1007
+ const buf = new Uint8Array(2);
1008
+ new DataView(buf.buffer).setUint16(0, value, true);
1009
+ this.write(buf);
1010
+ }
1011
+ writeVarUint(value) {
1012
+ if (typeof value === "number") {
1013
+ if (!Number.isInteger(value) || value < 0) {
1014
+ throw new RangeError("writeVarUint: value must be a non-negative integer");
1015
+ }
1016
+ } else if (value < 0n) {
1017
+ throw new RangeError("writeVarUint: value must be a non-negative integer");
1018
+ }
1019
+ const val = typeof value === "number" ? BigInt(value) : value;
1020
+ const bytes = [];
1021
+ let remaining = val;
1022
+ do {
1023
+ let byte = Number(remaining & 0x7fn);
1024
+ remaining >>= 7n;
1025
+ if (remaining > 0n) {
1026
+ byte |= 128;
1027
+ }
1028
+ bytes.push(byte);
1029
+ } while (remaining > 0n);
1030
+ this.write(new Uint8Array(bytes));
1031
+ }
1032
+ writeVarSlice(data) {
1033
+ this.writeVarUint(data.length);
1034
+ this.write(data);
1035
+ }
1036
+ toBytes() {
1037
+ return new Uint8Array(this.buffer);
1038
+ }
1039
+ };
1040
+ var BufferReader = class {
1041
+ view;
1042
+ offset = 0;
1043
+ constructor(data) {
1044
+ this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
1045
+ }
1046
+ remaining() {
1047
+ return this.view.byteLength - this.offset;
1048
+ }
1049
+ readByte() {
1050
+ if (this.offset >= this.view.byteLength) {
1051
+ throw new Error("unexpected end of buffer");
1052
+ }
1053
+ return this.view.getUint8(this.offset++);
1054
+ }
1055
+ readSlice(size) {
1056
+ if (this.offset + size > this.view.byteLength) {
1057
+ throw new Error("unexpected end of buffer");
1058
+ }
1059
+ const result = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, size);
1060
+ this.offset += size;
1061
+ return result;
1062
+ }
1063
+ readUint16LE() {
1064
+ if (this.offset + 2 > this.view.byteLength) {
1065
+ throw new Error("unexpected end of buffer");
1066
+ }
1067
+ const value = this.view.getUint16(this.offset, true);
1068
+ this.offset += 2;
1069
+ return value;
1070
+ }
1071
+ readVarUint() {
1072
+ let result = 0n;
1073
+ let shift = 0n;
1074
+ let byte;
1075
+ do {
1076
+ if (this.offset >= this.view.byteLength) {
1077
+ throw new Error("unexpected end of buffer");
1078
+ }
1079
+ byte = this.view.getUint8(this.offset++);
1080
+ result |= BigInt(byte & 127) << shift;
1081
+ shift += 7n;
1082
+ } while (byte & 128);
1083
+ return result;
1084
+ }
1085
+ readVarSlice() {
1086
+ const length = Number(this.readVarUint());
1087
+ return this.readSlice(length);
1088
+ }
1089
+ };
1090
+ function isZeroBytes(bytes) {
1091
+ return bytes.every((byte) => byte === 0);
1092
+ }
1093
+
1094
+ // src/extension/asset/assetId.ts
1095
+ var AssetId = class _AssetId {
1096
+ constructor(txid, groupIndex) {
1097
+ this.txid = txid;
1098
+ this.groupIndex = groupIndex;
1099
+ }
1100
+ /**
1101
+ * Create an asset id from a genesis transaction id and group index.
1102
+ *
1103
+ * @param txid - Hex-encoded genesis transaction id
1104
+ * @param groupIndex - Asset group index within the genesis transaction
1105
+ * @returns A validated asset id
1106
+ * @throws Error if the txid is missing, malformed, or not 32 bytes long
1107
+ * @see fromString
1108
+ */
1109
+ static create(txid, groupIndex) {
1110
+ if (!txid) {
1111
+ throw new Error("missing txid");
1112
+ }
1113
+ let buf;
1114
+ try {
1115
+ buf = hex.decode(txid);
1116
+ } catch {
1117
+ throw new Error("invalid txid format, must be hex");
1118
+ }
1119
+ if (buf.length !== TX_HASH_SIZE) {
1120
+ throw new Error(
1121
+ `invalid txid length: got ${buf.length} bytes, want ${TX_HASH_SIZE} bytes`
1122
+ );
1123
+ }
1124
+ const assetId = new _AssetId(buf, groupIndex);
1125
+ assetId.validate();
1126
+ return assetId;
1127
+ }
1128
+ /**
1129
+ * Decode an asset id from its hex string representation.
1130
+ *
1131
+ * @param s - Hex-encoded asset id
1132
+ * @returns Decoded asset id
1133
+ * @throws Error if the string is not valid hex or does not encode a valid asset id
1134
+ * @see toString
1135
+ */
1136
+ static fromString(s) {
1137
+ let buf;
1138
+ try {
1139
+ buf = hex.decode(s);
1140
+ } catch {
1141
+ throw new Error("invalid asset id format, must be hex");
1142
+ }
1143
+ return _AssetId.fromBytes(buf);
1144
+ }
1145
+ /**
1146
+ * Decode an asset id from its serialized bytes.
1147
+ *
1148
+ * @param buf - Serialized asset id bytes
1149
+ * @returns Decoded asset id
1150
+ * @throws Error if the buffer length is invalid
1151
+ */
1152
+ static fromBytes(buf) {
1153
+ if (!buf || buf.length === 0) {
1154
+ throw new Error("missing asset id");
1155
+ }
1156
+ if (buf.length !== ASSET_ID_SIZE) {
1157
+ throw new Error(
1158
+ `invalid asset id length: got ${buf.length} bytes, want ${ASSET_ID_SIZE} bytes`
1159
+ );
1160
+ }
1161
+ const reader = new BufferReader(buf);
1162
+ return _AssetId.fromReader(reader);
1163
+ }
1164
+ /**
1165
+ * Serialize the asset id to raw bytes.
1166
+ *
1167
+ * @returns Serialized asset id bytes
1168
+ * @see fromBytes
1169
+ */
1170
+ serialize() {
1171
+ const writer = new BufferWriter();
1172
+ this.serializeTo(writer);
1173
+ return writer.toBytes();
1174
+ }
1175
+ /**
1176
+ * Encode the asset id to a hex string.
1177
+ *
1178
+ * @returns Hex-encoded asset id
1179
+ * @see fromString
1180
+ */
1181
+ toString() {
1182
+ return hex.encode(this.serialize());
1183
+ }
1184
+ /**
1185
+ * Validate the asset id fields.
1186
+ *
1187
+ * @throws Error if the txid is empty or the group index is out of range
1188
+ */
1189
+ validate() {
1190
+ if (isZeroBytes(this.txid)) {
1191
+ throw new Error("empty txid");
1192
+ }
1193
+ if (!Number.isInteger(this.groupIndex) || this.groupIndex < 0 || this.groupIndex > 65535) {
1194
+ throw new Error(`invalid group index: ${this.groupIndex}, must be in range [0, 65535]`);
1195
+ }
1196
+ }
1197
+ /**
1198
+ * Decode an asset id from a binary reader.
1199
+ *
1200
+ * @param reader - Reader positioned at an asset id
1201
+ * @returns Decoded asset id
1202
+ * @throws Error if the reader does not contain enough bytes
1203
+ */
1204
+ static fromReader(reader) {
1205
+ if (reader.remaining() < ASSET_ID_SIZE) {
1206
+ throw new Error(
1207
+ `invalid asset id length: got ${reader.remaining()}, want ${ASSET_ID_SIZE}`
1208
+ );
1209
+ }
1210
+ const txid = reader.readSlice(TX_HASH_SIZE);
1211
+ const index = reader.readUint16LE();
1212
+ const assetId = new _AssetId(txid, index);
1213
+ assetId.validate();
1214
+ return assetId;
1215
+ }
1216
+ /**
1217
+ * Serialize the asset id into an existing binary writer.
1218
+ *
1219
+ * @param writer - Writer to append the asset id to
1220
+ * @see serialize
1221
+ */
1222
+ serializeTo(writer) {
1223
+ writer.write(this.txid);
1224
+ writer.writeUint16LE(this.groupIndex);
1225
+ }
1226
+ };
1227
+ var AssetRef = class _AssetRef {
1228
+ constructor(ref) {
1229
+ this.ref = ref;
1230
+ }
1231
+ /** Reference type discriminator. */
1232
+ get type() {
1233
+ return this.ref.type;
1234
+ }
1235
+ /**
1236
+ * Create an asset reference that points to a specific asset id.
1237
+ *
1238
+ * @param assetId - Asset id referenced by this pointer
1239
+ * @returns Asset reference by id
1240
+ * @see fromGroupIndex
1241
+ */
1242
+ static fromId(assetId) {
1243
+ return new _AssetRef({ type: 1 /* ByID */, assetId });
1244
+ }
1245
+ /**
1246
+ * Create an asset reference that points to another asset group by index.
1247
+ *
1248
+ * @param groupIndex - Zero-based asset group index in the packet
1249
+ * @returns Asset reference by group index
1250
+ * @see fromId
1251
+ */
1252
+ static fromGroupIndex(groupIndex) {
1253
+ return new _AssetRef({ type: 2 /* ByGroup */, groupIndex });
1254
+ }
1255
+ /**
1256
+ * Decode an asset reference from its hex string form.
1257
+ *
1258
+ * @param s - Hex-encoded asset reference
1259
+ * @returns Decoded asset reference
1260
+ * @throws Error if the string is not valid hex or does not encode a valid asset reference
1261
+ * @see toString
1262
+ */
1263
+ static fromString(s) {
1264
+ let buf;
1265
+ try {
1266
+ buf = hex.decode(s);
1267
+ } catch {
1268
+ throw new Error("invalid asset ref format, must be hex");
1269
+ }
1270
+ return _AssetRef.fromBytes(buf);
1271
+ }
1272
+ /**
1273
+ * Decode an asset reference from its serialized bytes.
1274
+ *
1275
+ * @param buf - Serialized asset reference bytes
1276
+ * @returns Decoded asset reference
1277
+ * @throws Error if the buffer is empty or malformed
1278
+ */
1279
+ static fromBytes(buf) {
1280
+ if (!buf || buf.length === 0) {
1281
+ throw new Error("missing asset ref");
1282
+ }
1283
+ const reader = new BufferReader(buf);
1284
+ return _AssetRef.fromReader(reader);
1285
+ }
1286
+ /**
1287
+ * Serialize the asset reference to raw bytes.
1288
+ *
1289
+ * @returns Serialized asset reference bytes
1290
+ * @see fromBytes
1291
+ */
1292
+ serialize() {
1293
+ const writer = new BufferWriter();
1294
+ this.serializeTo(writer);
1295
+ return writer.toBytes();
1296
+ }
1297
+ /**
1298
+ * Encode the asset reference to a hex string.
1299
+ *
1300
+ * @returns Hex-encoded asset reference
1301
+ * @see fromString
1302
+ */
1303
+ toString() {
1304
+ return hex.encode(this.serialize());
1305
+ }
1306
+ /**
1307
+ * Decode an asset reference from a binary reader.
1308
+ *
1309
+ * @param reader - Reader positioned at an asset reference
1310
+ * @returns Decoded asset reference
1311
+ * @throws Error if the type is unknown or the reader does not contain enough bytes
1312
+ */
1313
+ static fromReader(reader) {
1314
+ const type = reader.readByte();
1315
+ let ref;
1316
+ switch (type) {
1317
+ case 1 /* ByID */: {
1318
+ const assetId = AssetId.fromReader(reader);
1319
+ ref = new _AssetRef({ type: 1 /* ByID */, assetId });
1320
+ break;
1321
+ }
1322
+ case 2 /* ByGroup */: {
1323
+ if (reader.remaining() < 2) {
1324
+ throw new Error("invalid asset ref length");
1325
+ }
1326
+ const groupIndex = reader.readUint16LE();
1327
+ ref = new _AssetRef({ type: 2 /* ByGroup */, groupIndex });
1328
+ break;
1329
+ }
1330
+ case 0 /* Unspecified */:
1331
+ throw new Error("asset ref type unspecified");
1332
+ default:
1333
+ throw new Error(`asset ref type unknown ${type}`);
1334
+ }
1335
+ return ref;
1336
+ }
1337
+ /**
1338
+ * Serialize the asset reference into an existing binary writer.
1339
+ *
1340
+ * @param writer - Writer to append the asset reference to
1341
+ * @see serialize
1342
+ */
1343
+ serializeTo(writer) {
1344
+ writer.writeByte(this.ref.type);
1345
+ switch (this.ref.type) {
1346
+ case 1 /* ByID */:
1347
+ this.ref.assetId.serializeTo(writer);
1348
+ break;
1349
+ case 2 /* ByGroup */:
1350
+ writer.writeUint16LE(this.ref.groupIndex);
1351
+ break;
1352
+ }
1353
+ }
1354
+ };
1355
+ var AssetInput = class _AssetInput {
1356
+ constructor(input) {
1357
+ this.input = input;
1358
+ }
1359
+ /** Gets the transaction input index for an asset input, e.g. 0 */
1360
+ get vin() {
1361
+ return this.input.vin;
1362
+ }
1363
+ /** Gets the amount for an input (in most cases, 330 sats) */
1364
+ get amount() {
1365
+ return this.input.amount;
1366
+ }
1367
+ /** Create a local asset input that points at a transaction input index. */
1368
+ static create(vin, amount) {
1369
+ const input = new _AssetInput({
1370
+ type: 1 /* Local */,
1371
+ vin,
1372
+ amount: typeof amount === "number" ? BigInt(amount) : amount
1373
+ });
1374
+ input.validate();
1375
+ return input;
1376
+ }
1377
+ /** Create an intent-backed asset input referencing an external intent transaction. */
1378
+ static createIntent(txid, vin, amount) {
1379
+ if (!txid || txid.length === 0) {
1380
+ throw new Error("missing input intent txid");
1381
+ }
1382
+ let buf;
1383
+ try {
1384
+ buf = hex.decode(txid);
1385
+ } catch {
1386
+ throw new Error("invalid input intent txid format, must be hex");
1387
+ }
1388
+ if (buf.length !== TX_HASH_SIZE) {
1389
+ throw new Error("invalid input intent txid length");
1390
+ }
1391
+ const input = new _AssetInput({
1392
+ type: 2 /* Intent */,
1393
+ txid: buf,
1394
+ vin,
1395
+ amount: typeof amount === "number" ? BigInt(amount) : amount
1396
+ });
1397
+ input.validate();
1398
+ return input;
1399
+ }
1400
+ /** Decode an asset input from its hex string form. */
1401
+ static fromString(s) {
1402
+ let buf;
1403
+ try {
1404
+ buf = hex.decode(s);
1405
+ } catch {
1406
+ throw new Error("invalid format, must be hex");
1407
+ }
1408
+ return _AssetInput.fromBytes(buf);
1409
+ }
1410
+ /** Decode an asset input from its serialized bytes. */
1411
+ static fromBytes(buf) {
1412
+ const reader = new BufferReader(buf);
1413
+ return _AssetInput.fromReader(reader);
1414
+ }
1415
+ /** Serialize the asset input to raw bytes. */
1416
+ serialize() {
1417
+ const writer = new BufferWriter();
1418
+ this.serializeTo(writer);
1419
+ return writer.toBytes();
1420
+ }
1421
+ /** Encode the asset input to a hex string. */
1422
+ toString() {
1423
+ return hex.encode(this.serialize());
1424
+ }
1425
+ /** Validate the asset input fields. */
1426
+ validate() {
1427
+ switch (this.input.type) {
1428
+ case 1 /* Local */:
1429
+ break;
1430
+ case 2 /* Intent */:
1431
+ if (isZeroBytes(this.input.txid)) {
1432
+ throw new Error("missing input intent txid");
1433
+ }
1434
+ break;
1435
+ }
1436
+ }
1437
+ /** Decode an asset input from a buffer reader. */
1438
+ static fromReader(reader) {
1439
+ const type = reader.readByte();
1440
+ let input;
1441
+ switch (type) {
1442
+ case 1 /* Local */: {
1443
+ const vin = reader.readUint16LE();
1444
+ const amount = reader.readVarUint();
1445
+ input = new _AssetInput({
1446
+ type: 1 /* Local */,
1447
+ vin,
1448
+ amount
1449
+ });
1450
+ break;
1451
+ }
1452
+ case 2 /* Intent */: {
1453
+ if (reader.remaining() < TX_HASH_SIZE) {
1454
+ throw new Error("invalid input intent txid length");
1455
+ }
1456
+ const txid = reader.readSlice(TX_HASH_SIZE);
1457
+ const vin = reader.readUint16LE();
1458
+ const amount = reader.readVarUint();
1459
+ input = new _AssetInput({
1460
+ type: 2 /* Intent */,
1461
+ txid: new Uint8Array(txid),
1462
+ vin,
1463
+ amount
1464
+ });
1465
+ break;
1466
+ }
1467
+ case 0 /* Unspecified */:
1468
+ throw new Error("asset input type unspecified");
1469
+ default:
1470
+ throw new Error(`asset input type ${type} unknown`);
1471
+ }
1472
+ input.validate();
1473
+ return input;
1474
+ }
1475
+ /** Serialize the asset input into an existing buffer writer. */
1476
+ serializeTo(writer) {
1477
+ writer.writeByte(this.input.type);
1478
+ if (this.input.type === 2 /* Intent */) {
1479
+ writer.write(this.input.txid);
1480
+ }
1481
+ writer.writeUint16LE(this.input.vin);
1482
+ writer.writeVarUint(this.input.amount);
1483
+ }
1484
+ };
1485
+ var AssetInputs = class _AssetInputs {
1486
+ constructor(inputs) {
1487
+ this.inputs = inputs;
1488
+ }
1489
+ /** Create a validated list of asset inputs. */
1490
+ static create(inputs) {
1491
+ const list = new _AssetInputs(inputs);
1492
+ list.validate();
1493
+ return list;
1494
+ }
1495
+ /** Decode an asset input list from its hex string form. */
1496
+ static fromString(s) {
1497
+ if (!s || s.length === 0) {
1498
+ throw new Error("missing asset inputs");
1499
+ }
1500
+ let buf;
1501
+ try {
1502
+ buf = hex.decode(s);
1503
+ } catch {
1504
+ throw new Error("invalid asset inputs format, must be hex");
1505
+ }
1506
+ const reader = new BufferReader(buf);
1507
+ return _AssetInputs.fromReader(reader);
1508
+ }
1509
+ /** Serialize the asset input list to raw bytes. */
1510
+ serialize() {
1511
+ const writer = new BufferWriter();
1512
+ this.serializeTo(writer);
1513
+ return writer.toBytes();
1514
+ }
1515
+ /** Encode the asset input list to a hex string. */
1516
+ toString() {
1517
+ return hex.encode(this.serialize());
1518
+ }
1519
+ /** Validate the asset input list. */
1520
+ validate() {
1521
+ const seen = /* @__PURE__ */ new Set();
1522
+ let listType = 0 /* Unspecified */;
1523
+ for (const assetInput of this.inputs) {
1524
+ assetInput.validate();
1525
+ if (listType === 0 /* Unspecified */) {
1526
+ listType = assetInput.input.type;
1527
+ } else if (listType !== assetInput.input.type) {
1528
+ throw new Error("all inputs must be of the same type");
1529
+ }
1530
+ if (assetInput.input.type === 1 /* Local */) {
1531
+ if (seen.has(assetInput.input.vin)) {
1532
+ throw new Error(`duplicated input vin ${assetInput.input.vin}`);
1533
+ }
1534
+ seen.add(assetInput.input.vin);
1535
+ continue;
1536
+ }
1537
+ }
1538
+ }
1539
+ /** Decode an asset input list from a buffer reader. */
1540
+ static fromReader(reader) {
1541
+ const count = Number(reader.readVarUint());
1542
+ const inputs = [];
1543
+ for (let i = 0; i < count; i++) {
1544
+ inputs.push(AssetInput.fromReader(reader));
1545
+ }
1546
+ return _AssetInputs.create(inputs);
1547
+ }
1548
+ /** Serialize the asset input list into an existing buffer writer. */
1549
+ serializeTo(writer) {
1550
+ writer.writeVarUint(this.inputs.length);
1551
+ for (const input of this.inputs) {
1552
+ input.serializeTo(writer);
1553
+ }
1554
+ }
1555
+ };
1556
+ var AssetOutput = class _AssetOutput {
1557
+ constructor(vout, amount) {
1558
+ this.vout = vout;
1559
+ this.amount = amount;
1560
+ }
1561
+ // 0x01 means local output, there is only 1 local output type currently
1562
+ // however we serialize it for future upgrades
1563
+ static TYPE_LOCAL = 1;
1564
+ /** Create a local asset output referencing a transaction output index. */
1565
+ static create(vout, amount) {
1566
+ const output = new _AssetOutput(vout, typeof amount === "number" ? BigInt(amount) : amount);
1567
+ output.validate();
1568
+ return output;
1569
+ }
1570
+ /** Decode an asset output from its hex string form. */
1571
+ static fromString(s) {
1572
+ let buf;
1573
+ try {
1574
+ buf = hex.decode(s);
1575
+ } catch {
1576
+ throw new Error("invalid asset output format, must be hex");
1577
+ }
1578
+ return _AssetOutput.fromBytes(buf);
1579
+ }
1580
+ /** Decode an asset output from its serialized bytes. */
1581
+ static fromBytes(buf) {
1582
+ if (!buf || buf.length === 0) {
1583
+ throw new Error("missing asset output");
1584
+ }
1585
+ const reader = new BufferReader(buf);
1586
+ const output = _AssetOutput.fromReader(reader);
1587
+ output.validate();
1588
+ return output;
1589
+ }
1590
+ /** Serialize the asset output to raw bytes. */
1591
+ serialize() {
1592
+ const writer = new BufferWriter();
1593
+ this.serializeTo(writer);
1594
+ return writer.toBytes();
1595
+ }
1596
+ /** Encode the asset output to a hex string. */
1597
+ toString() {
1598
+ return hex.encode(this.serialize());
1599
+ }
1600
+ /** Validate the asset output fields. */
1601
+ validate() {
1602
+ if (!Number.isInteger(this.vout) || this.vout < 0 || this.vout > 65535) {
1603
+ throw new Error("asset output vout must be an integer in range [0, 65535]");
1604
+ }
1605
+ if (this.amount <= 0n) {
1606
+ throw new Error("asset output amount must be greater than 0");
1607
+ }
1608
+ }
1609
+ /** Decode an asset output from a buffer reader. */
1610
+ static fromReader(reader) {
1611
+ if (reader.remaining() < 2) {
1612
+ throw new Error("invalid asset output vout length");
1613
+ }
1614
+ const type = reader.readByte();
1615
+ if (type !== _AssetOutput.TYPE_LOCAL) {
1616
+ if (type === 0) {
1617
+ throw new Error("output type unspecified");
1618
+ }
1619
+ throw new Error("unknown asset output type");
1620
+ }
1621
+ let vout;
1622
+ try {
1623
+ vout = reader.readUint16LE();
1624
+ } catch {
1625
+ throw new Error("invalid asset output vout length");
1626
+ }
1627
+ const amount = reader.readVarUint();
1628
+ return new _AssetOutput(vout, amount);
1629
+ }
1630
+ /** Serialize the asset output into an existing buffer writer. */
1631
+ serializeTo(writer) {
1632
+ writer.writeByte(1);
1633
+ writer.writeUint16LE(this.vout);
1634
+ writer.writeVarUint(this.amount);
1635
+ }
1636
+ };
1637
+ var AssetOutputs = class _AssetOutputs {
1638
+ constructor(outputs) {
1639
+ this.outputs = outputs;
1640
+ }
1641
+ /** Create a validated list of asset outputs. */
1642
+ static create(outputs) {
1643
+ const list = new _AssetOutputs(outputs);
1644
+ list.validate();
1645
+ return list;
1646
+ }
1647
+ /** Decode an asset output list from its hex string form. */
1648
+ static fromString(s) {
1649
+ if (!s || s.length === 0) {
1650
+ throw new Error("missing asset outputs");
1651
+ }
1652
+ let buf;
1653
+ try {
1654
+ buf = hex.decode(s);
1655
+ } catch {
1656
+ throw new Error("invalid asset outputs format, must be hex");
1657
+ }
1658
+ const reader = new BufferReader(buf);
1659
+ return _AssetOutputs.fromReader(reader);
1660
+ }
1661
+ /** Serialize the asset output list to raw bytes. */
1662
+ serialize() {
1663
+ const writer = new BufferWriter();
1664
+ this.serializeTo(writer);
1665
+ return writer.toBytes();
1666
+ }
1667
+ /** Encode the asset output list to a hex string. */
1668
+ toString() {
1669
+ return hex.encode(this.serialize());
1670
+ }
1671
+ /** Validate the asset output list. */
1672
+ validate() {
1673
+ const seen = /* @__PURE__ */ new Set();
1674
+ for (const output of this.outputs) {
1675
+ output.validate();
1676
+ if (seen.has(output.vout)) {
1677
+ throw new Error(`duplicated output vout ${output.vout}`);
1678
+ }
1679
+ seen.add(output.vout);
1680
+ }
1681
+ }
1682
+ /** Decode an asset output list from a buffer reader. */
1683
+ static fromReader(reader) {
1684
+ const count = Number(reader.readVarUint());
1685
+ if (count === 0) {
1686
+ return new _AssetOutputs([]);
1687
+ }
1688
+ const outputs = [];
1689
+ for (let i = 0; i < count; i++) {
1690
+ outputs.push(AssetOutput.fromReader(reader));
1691
+ }
1692
+ const result = new _AssetOutputs(outputs);
1693
+ result.validate();
1694
+ return result;
1695
+ }
1696
+ /** Serialize the asset output list into an existing buffer writer. */
1697
+ serializeTo(writer) {
1698
+ this.validate();
1699
+ writer.writeVarUint(this.outputs.length);
1700
+ for (const output of this.outputs) {
1701
+ output.serializeTo(writer);
1702
+ }
1703
+ }
1704
+ };
1705
+ var Metadata = class _Metadata {
1706
+ constructor(key, value) {
1707
+ this.key = key;
1708
+ this.value = value;
1709
+ }
1710
+ /** Create a metadata entry from raw key and value bytes. */
1711
+ static create(key, value) {
1712
+ const md = new _Metadata(key, value);
1713
+ md.validate();
1714
+ return md;
1715
+ }
1716
+ /** Decode metadata from its hex string form. */
1717
+ static fromString(s) {
1718
+ let buf;
1719
+ try {
1720
+ buf = hex.decode(s);
1721
+ } catch {
1722
+ throw new Error("invalid metadata format, must be hex");
1723
+ }
1724
+ return _Metadata.fromBytes(buf);
1725
+ }
1726
+ /** Decode metadata from its serialized bytes. */
1727
+ static fromBytes(buf) {
1728
+ if (!buf || buf.length === 0) {
1729
+ throw new Error("missing metadata");
1730
+ }
1731
+ const reader = new BufferReader(buf);
1732
+ return _Metadata.fromReader(reader);
1733
+ }
1734
+ /** Serialize metadata to raw bytes. */
1735
+ serialize() {
1736
+ const writer = new BufferWriter();
1737
+ this.serializeTo(writer);
1738
+ return writer.toBytes();
1739
+ }
1740
+ /** Encode metadata to a hex string. */
1741
+ toString() {
1742
+ return hex.encode(this.serialize());
1743
+ }
1744
+ get keyString() {
1745
+ return new TextDecoder().decode(this.key);
1746
+ }
1747
+ get valueString() {
1748
+ return new TextDecoder().decode(this.value);
1749
+ }
1750
+ /** Validate the metadata key and value. */
1751
+ validate() {
1752
+ if (this.key.length === 0) {
1753
+ throw new Error("missing metadata key");
1754
+ }
1755
+ if (this.value.length === 0) {
1756
+ throw new Error("missing metadata value");
1757
+ }
1758
+ }
1759
+ /** Decode metadata from a buffer reader. */
1760
+ static fromReader(reader) {
1761
+ let key;
1762
+ let value;
1763
+ try {
1764
+ key = reader.readVarSlice();
1765
+ } catch {
1766
+ throw new Error("invalid metadata length");
1767
+ }
1768
+ try {
1769
+ value = reader.readVarSlice();
1770
+ } catch {
1771
+ throw new Error("invalid metadata length");
1772
+ }
1773
+ const md = new _Metadata(key, value);
1774
+ md.validate();
1775
+ return md;
1776
+ }
1777
+ /** Serialize metadata into an existing buffer writer. */
1778
+ serializeTo(writer) {
1779
+ writer.writeVarSlice(this.key);
1780
+ writer.writeVarSlice(this.value);
1781
+ }
1782
+ };
1783
+ var MetadataList = class _MetadataList {
1784
+ constructor(items) {
1785
+ this.items = items;
1786
+ }
1787
+ static ARK_LEAF_TAG = "ArkadeAssetLeaf";
1788
+ static ARK_BRANCH_TAG = "ArkadeAssetBranch";
1789
+ static ARK_LEAF_VERSION = 0;
1790
+ /** Create a metadata list from its hex string form. */
1791
+ static fromString(s) {
1792
+ let buf;
1793
+ try {
1794
+ buf = hex.decode(s);
1795
+ } catch {
1796
+ throw new Error("invalid metadata list format");
1797
+ }
1798
+ return _MetadataList.fromBytes(buf);
1799
+ }
1800
+ /** Decode a metadata list from its serialized bytes. */
1801
+ static fromBytes(buf) {
1802
+ if (!buf || buf.length === 0) {
1803
+ throw new Error("missing metadata list");
1804
+ }
1805
+ const reader = new BufferReader(buf);
1806
+ return _MetadataList.fromReader(reader);
1807
+ }
1808
+ /** Decode a metadata list from a buffer reader. */
1809
+ static fromReader(reader) {
1810
+ const count = Number(reader.readVarUint());
1811
+ const items = Array.from({ length: count }, () => Metadata.fromReader(reader));
1812
+ return new _MetadataList(items);
1813
+ }
1814
+ /** Serialize the metadata list into an existing buffer writer. */
1815
+ serializeTo(writer) {
1816
+ writer.writeVarUint(this.items.length);
1817
+ for (const item of this) {
1818
+ item.serializeTo(writer);
1819
+ }
1820
+ }
1821
+ /** Serialize the metadata list to raw bytes. */
1822
+ serialize() {
1823
+ const writer = new BufferWriter();
1824
+ this.serializeTo(writer);
1825
+ return writer.toBytes();
1826
+ }
1827
+ /** Iterate through metadata entries in insertion order. */
1828
+ [Symbol.iterator]() {
1829
+ return this.items[Symbol.iterator]();
1830
+ }
1831
+ get length() {
1832
+ return this.items.length;
1833
+ }
1834
+ /** Compute the tagged Merkle root for the metadata list. */
1835
+ hash() {
1836
+ if (this.items.length === 0) throw new Error("missing metadata list");
1837
+ const levels = buildMetadataMerkleTree(this.items);
1838
+ return levels[levels.length - 1][0];
1839
+ }
1840
+ };
1841
+ function computeMetadataLeafHash(md) {
1842
+ const writer = new BufferWriter();
1843
+ writer.writeByte(MetadataList.ARK_LEAF_VERSION);
1844
+ writer.writeVarSlice(md.key);
1845
+ writer.writeVarSlice(md.value);
1846
+ return schnorr.utils.taggedHash(MetadataList.ARK_LEAF_TAG, writer.toBytes());
1847
+ }
1848
+ function computeMetadataBranchHash(a, b) {
1849
+ const [smaller, larger] = compareBytes(a, b) === -1 ? [a, b] : [b, a];
1850
+ return schnorr.utils.taggedHash(MetadataList.ARK_BRANCH_TAG, smaller, larger);
1851
+ }
1852
+ function buildMetadataMerkleTree(leaves) {
1853
+ if (leaves.length === 0) return [];
1854
+ const leafHashes = leaves.map(computeMetadataLeafHash);
1855
+ const levels = [leafHashes];
1856
+ let current = leafHashes;
1857
+ while (current.length > 1) {
1858
+ const next = [];
1859
+ for (let i = 0; i < current.length; i += 2) {
1860
+ if (i + 1 < current.length) {
1861
+ next.push(computeMetadataBranchHash(current[i], current[i + 1]));
1862
+ } else {
1863
+ next.push(current[i]);
1864
+ }
1865
+ }
1866
+ levels.push(next);
1867
+ current = next;
1868
+ }
1869
+ return levels;
1870
+ }
1871
+ var AssetGroup = class _AssetGroup {
1872
+ /** @see create */
1873
+ constructor(assetId, controlAsset, inputs, outputs, metadata) {
1874
+ this.assetId = assetId;
1875
+ this.controlAsset = controlAsset;
1876
+ this.inputs = inputs;
1877
+ this.outputs = outputs;
1878
+ this.metadataList = new MetadataList(metadata);
1879
+ }
1880
+ metadataList;
1881
+ /**
1882
+ * Create and validate an asset group.
1883
+ *
1884
+ * @param assetId - Asset id for this group, or `null` for fresh issuance
1885
+ * @param controlAsset - Optional control asset reference for (re) issuance
1886
+ * @param inputs - Asset inputs in the group
1887
+ * @param outputs - Asset outputs in the group
1888
+ * @param metadata - Metadata entries associated with the group
1889
+ * @returns A validated asset group
1890
+ * @throws Error if the group fails validation
1891
+ * @see validate
1892
+ */
1893
+ static create(assetId, controlAsset, inputs, outputs, metadata) {
1894
+ const ag = new _AssetGroup(assetId, controlAsset, inputs, outputs, metadata);
1895
+ ag.validate();
1896
+ return ag;
1897
+ }
1898
+ /**
1899
+ * Decode an asset group from its hex string form.
1900
+ *
1901
+ * @param s - Hex-encoded asset group
1902
+ * @returns Decoded asset group
1903
+ * @throws Error if the string is not valid hex or does not encode a valid asset group
1904
+ * @see toString
1905
+ */
1906
+ static fromString(s) {
1907
+ let buf;
1908
+ try {
1909
+ buf = hex.decode(s);
1910
+ } catch {
1911
+ throw new Error("invalid format, must be hex");
1912
+ }
1913
+ return _AssetGroup.fromBytes(buf);
1914
+ }
1915
+ /**
1916
+ * Decode an asset group from its serialized bytes.
1917
+ *
1918
+ * @param buf - Serialized asset group bytes
1919
+ * @returns Decoded asset group
1920
+ * @throws Error if the buffer is empty or malformed
1921
+ */
1922
+ static fromBytes(buf) {
1923
+ if (!buf || buf.length === 0) {
1924
+ throw new Error("missing asset group");
1925
+ }
1926
+ const reader = new BufferReader(buf);
1927
+ return _AssetGroup.fromReader(reader);
1928
+ }
1929
+ /**
1930
+ * Return true when the group represents an issuance.
1931
+ *
1932
+ * @returns `true` when the group has no asset id
1933
+ */
1934
+ isIssuance() {
1935
+ return this.assetId === null;
1936
+ }
1937
+ /**
1938
+ * Return true when the group represents a reissuance.
1939
+ *
1940
+ * @returns `true` when the group has an asset id and outputs exceed local inputs
1941
+ * @remarks
1942
+ * Only local inputs contribute to the comparison; intent-backed inputs contribute `0` here.
1943
+ */
1944
+ isReissuance() {
1945
+ const sumReducer = (s, { amount }) => s + amount;
1946
+ const sumOutputs = this.outputs.reduce(sumReducer, 0n);
1947
+ const sumInputs = this.inputs.map((i) => ({
1948
+ amount: i.input.type === 1 /* Local */ ? i.input.amount : 0n
1949
+ })).reduce(sumReducer, 0n);
1950
+ return !this.isIssuance() && sumInputs < sumOutputs;
1951
+ }
1952
+ /**
1953
+ * Serialize the asset group to raw bytes.
1954
+ *
1955
+ * @returns Serialized asset group bytes
1956
+ * @see fromBytes
1957
+ */
1958
+ serialize() {
1959
+ this.validate();
1960
+ const writer = new BufferWriter();
1961
+ this.serializeTo(writer);
1962
+ return writer.toBytes();
1963
+ }
1964
+ /**
1965
+ * Validate the asset group and its child structures.
1966
+ *
1967
+ * @throws Error if the group is empty or violates issuance invariants
1968
+ */
1969
+ validate() {
1970
+ if (this.inputs.length === 0 && this.outputs.length === 0) {
1971
+ throw new Error("empty asset group");
1972
+ }
1973
+ if (this.isIssuance()) {
1974
+ if (this.inputs.length !== 0) {
1975
+ throw new Error("issuance must have no inputs");
1976
+ }
1977
+ } else {
1978
+ if (this.controlAsset !== null) {
1979
+ throw new Error("only issuance can have a control asset");
1980
+ }
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Convert the group into its batch-leaf representation for the given intent txid.
1985
+ *
1986
+ * @param intentTxid - Intent transaction id used to build the leaf input reference
1987
+ * @returns Batch-leaf asset group
1988
+ * @see AssetInput.createIntent
1989
+ */
1990
+ toBatchLeafAssetGroup(intentTxid) {
1991
+ const leafInput = AssetInput.createIntent(hex.encode(intentTxid), 0, 0);
1992
+ return new _AssetGroup(
1993
+ this.assetId,
1994
+ this.controlAsset,
1995
+ [leafInput],
1996
+ this.outputs,
1997
+ this.metadataList.items
1998
+ );
1999
+ }
2000
+ /**
2001
+ * Encode the asset group to a hex string.
2002
+ *
2003
+ * @returns Hex-encoded asset group
2004
+ * @see fromString
2005
+ */
2006
+ toString() {
2007
+ return hex.encode(this.serialize());
2008
+ }
2009
+ /**
2010
+ * Decode an asset group from a binary reader.
2011
+ *
2012
+ * @param reader - Reader positioned at an asset group
2013
+ * @returns Decoded asset group
2014
+ * @throws Error if the encoded group is malformed
2015
+ */
2016
+ static fromReader(reader) {
2017
+ const presence = reader.readByte();
2018
+ let assetId = null;
2019
+ let controlAsset = null;
2020
+ let metadata = [];
2021
+ if (presence & MASK_ASSET_ID) {
2022
+ assetId = AssetId.fromReader(reader);
2023
+ }
2024
+ if (presence & MASK_CONTROL_ASSET) {
2025
+ controlAsset = AssetRef.fromReader(reader);
2026
+ }
2027
+ if (presence & MASK_METADATA) {
2028
+ metadata = MetadataList.fromReader(reader).items;
2029
+ }
2030
+ const inputs = AssetInputs.fromReader(reader);
2031
+ const outputs = AssetOutputs.fromReader(reader);
2032
+ const ag = new _AssetGroup(assetId, controlAsset, inputs.inputs, outputs.outputs, metadata);
2033
+ ag.validate();
2034
+ return ag;
2035
+ }
2036
+ /**
2037
+ * Serialize the asset group into an existing binary writer.
2038
+ *
2039
+ * @param writer - Writer to append the asset group to
2040
+ */
2041
+ serializeTo(writer) {
2042
+ let presence = 0;
2043
+ if (this.assetId !== null) {
2044
+ presence |= MASK_ASSET_ID;
2045
+ }
2046
+ if (this.controlAsset !== null) {
2047
+ presence |= MASK_CONTROL_ASSET;
2048
+ }
2049
+ if (this.metadataList.length > 0) {
2050
+ presence |= MASK_METADATA;
2051
+ }
2052
+ writer.writeByte(presence);
2053
+ if (presence & MASK_ASSET_ID) {
2054
+ this.assetId.serializeTo(writer);
2055
+ }
2056
+ if (presence & MASK_CONTROL_ASSET) {
2057
+ this.controlAsset.serializeTo(writer);
2058
+ }
2059
+ if (presence & MASK_METADATA) {
2060
+ this.metadataList.serializeTo(writer);
2061
+ }
2062
+ writer.writeVarUint(this.inputs.length);
2063
+ for (const input of this.inputs) {
2064
+ input.serializeTo(writer);
2065
+ }
2066
+ writer.writeVarUint(this.outputs.length);
2067
+ for (const output of this.outputs) {
2068
+ output.serializeTo(writer);
2069
+ }
2070
+ }
2071
+ };
2072
+ var Packet = class _Packet {
2073
+ constructor(groups) {
2074
+ this.groups = groups;
2075
+ }
2076
+ /** PACKET_TYPE is the 1-byte TLV type tag used in the Extension envelope. */
2077
+ static PACKET_TYPE = 0;
2078
+ /** Create a validated asset packet from a list of asset groups. */
2079
+ static create(groups) {
2080
+ const p = new _Packet(groups);
2081
+ p.validate();
2082
+ return p;
2083
+ }
2084
+ /**
2085
+ * fromBytes parses a Packet from raw bytes.
2086
+ */
2087
+ static fromBytes(buf) {
2088
+ return _Packet.fromReader(new BufferReader(buf));
2089
+ }
2090
+ /**
2091
+ * fromString parses a Packet from a raw hex string (not an OP_RETURN script).
2092
+ */
2093
+ static fromString(s) {
2094
+ if (!s) {
2095
+ throw new Error("missing packet data");
2096
+ }
2097
+ let buf;
2098
+ try {
2099
+ buf = hex.decode(s);
2100
+ } catch {
2101
+ throw new Error("invalid packet format, must be hex");
2102
+ }
2103
+ return _Packet.fromBytes(buf);
2104
+ }
2105
+ /**
2106
+ * type returns the TLV packet type tag. Implements ExtensionPacket interface.
2107
+ */
2108
+ type() {
2109
+ return _Packet.PACKET_TYPE;
2110
+ }
2111
+ /** Convert the packet into the batch-leaf form for a specific intent transaction id. */
2112
+ leafTxPacket(intentTxid) {
2113
+ const leafGroups = this.groups.map((group) => group.toBatchLeafAssetGroup(intentTxid));
2114
+ return new _Packet(leafGroups);
2115
+ }
2116
+ /**
2117
+ * serialize encodes the packet as raw bytes (varint group count + group data).
2118
+ * Does NOT include OP_RETURN, Arkade magic bytes (`ARK`), or TLV type/length; those are
2119
+ * added by the Extension module.
2120
+ */
2121
+ serialize() {
2122
+ if (this.groups.length === 0) {
2123
+ return new Uint8Array(0);
2124
+ }
2125
+ const writer = new BufferWriter();
2126
+ writer.writeVarUint(this.groups.length);
2127
+ for (const group of this.groups) {
2128
+ group.serializeTo(writer);
2129
+ }
2130
+ return writer.toBytes();
2131
+ }
2132
+ /**
2133
+ * toString returns the hex-encoded raw packet bytes.
2134
+ */
2135
+ toString() {
2136
+ return hex.encode(this.serialize());
2137
+ }
2138
+ /** Validate packet structure and cross-group references. */
2139
+ validate() {
2140
+ if (this.groups.length === 0) {
2141
+ throw new Error("missing assets");
2142
+ }
2143
+ const seenAssetIds = /* @__PURE__ */ new Set();
2144
+ for (const group of this.groups) {
2145
+ if (group.assetId !== null) {
2146
+ const key = group.assetId.toString();
2147
+ if (seenAssetIds.has(key)) {
2148
+ throw new Error(`duplicate asset group for asset ${key}`);
2149
+ }
2150
+ seenAssetIds.add(key);
2151
+ }
2152
+ if (group.controlAsset !== null && group.controlAsset.ref.type === 2 /* ByGroup */ && group.controlAsset.ref.groupIndex >= this.groups.length) {
2153
+ throw new Error(
2154
+ `invalid control asset group index, ${group.controlAsset.ref.groupIndex} out of range [0, ${this.groups.length - 1}]`
2155
+ );
2156
+ }
2157
+ }
2158
+ }
2159
+ static fromReader(reader) {
2160
+ const count = Number(reader.readVarUint());
2161
+ const groups = [];
2162
+ for (let i = 0; i < count; i++) {
2163
+ groups.push(AssetGroup.fromReader(reader));
2164
+ }
2165
+ if (reader.remaining() > 0) {
2166
+ throw new Error(
2167
+ `invalid packet length, left ${reader.remaining()} unknown bytes to read`
2168
+ );
2169
+ }
2170
+ const packet = new _Packet(groups);
2171
+ packet.validate();
2172
+ return packet;
2173
+ }
2174
+ };
2175
+ var IndexerTxType = /* @__PURE__ */ ((IndexerTxType2) => {
2176
+ IndexerTxType2[IndexerTxType2["INDEXER_TX_TYPE_UNSPECIFIED"] = 0] = "INDEXER_TX_TYPE_UNSPECIFIED";
2177
+ IndexerTxType2[IndexerTxType2["INDEXER_TX_TYPE_RECEIVED"] = 1] = "INDEXER_TX_TYPE_RECEIVED";
2178
+ IndexerTxType2[IndexerTxType2["INDEXER_TX_TYPE_SENT"] = 2] = "INDEXER_TX_TYPE_SENT";
2179
+ return IndexerTxType2;
2180
+ })(IndexerTxType || {});
2181
+ var ChainTxType = /* @__PURE__ */ ((ChainTxType2) => {
2182
+ ChainTxType2["UNSPECIFIED"] = "INDEXER_CHAINED_TX_TYPE_UNSPECIFIED";
2183
+ ChainTxType2["COMMITMENT"] = "INDEXER_CHAINED_TX_TYPE_COMMITMENT";
2184
+ ChainTxType2["ARK"] = "INDEXER_CHAINED_TX_TYPE_ARK";
2185
+ ChainTxType2["TREE"] = "INDEXER_CHAINED_TX_TYPE_TREE";
2186
+ ChainTxType2["CHECKPOINT"] = "INDEXER_CHAINED_TX_TYPE_CHECKPOINT";
2187
+ return ChainTxType2;
2188
+ })(ChainTxType || {});
2189
+ var RestIndexerProvider = class {
2190
+ constructor(serverUrl) {
2191
+ this.serverUrl = serverUrl;
2192
+ }
2193
+ async getVtxoTree(batchOutpoint, opts) {
2194
+ let url = `${this.serverUrl}/v1/indexer/batch/${batchOutpoint.txid}/${batchOutpoint.vout}/tree`;
2195
+ const params = new URLSearchParams();
2196
+ if (opts) {
2197
+ if (opts.pageIndex !== void 0)
2198
+ params.append("page.index", opts.pageIndex.toString());
2199
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2200
+ }
2201
+ if (params.toString()) {
2202
+ url += "?" + params.toString();
2203
+ }
2204
+ const res = await fetch(url);
2205
+ if (!res.ok) {
2206
+ throw new Error(`Failed to fetch vtxo tree: ${res.statusText}`);
2207
+ }
2208
+ const data = await res.json();
2209
+ if (!Response.isVtxoTreeResponse(data)) {
2210
+ throw new Error("Invalid vtxo tree data received");
2211
+ }
2212
+ data.vtxoTree.forEach((tx) => {
2213
+ tx.children = Object.fromEntries(
2214
+ Object.entries(tx.children).map(([key, value]) => [Number(key), value])
2215
+ );
2216
+ });
2217
+ return data;
2218
+ }
2219
+ async getVtxoTreeLeaves(batchOutpoint, opts) {
2220
+ let url = `${this.serverUrl}/v1/indexer/batch/${batchOutpoint.txid}/${batchOutpoint.vout}/tree/leaves`;
2221
+ const params = new URLSearchParams();
2222
+ if (opts) {
2223
+ if (opts.pageIndex !== void 0)
2224
+ params.append("page.index", opts.pageIndex.toString());
2225
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2226
+ }
2227
+ if (params.toString()) {
2228
+ url += "?" + params.toString();
2229
+ }
2230
+ const res = await fetch(url);
2231
+ if (!res.ok) {
2232
+ throw new Error(`Failed to fetch vtxo tree leaves: ${res.statusText}`);
2233
+ }
2234
+ const data = await res.json();
2235
+ if (!Response.isVtxoTreeLeavesResponse(data)) {
2236
+ throw new Error("Invalid vtxos tree leaves data received");
2237
+ }
2238
+ return data;
2239
+ }
2240
+ async getBatchSweepTransactions(batchOutpoint) {
2241
+ const url = `${this.serverUrl}/v1/indexer/batch/${batchOutpoint.txid}/${batchOutpoint.vout}/sweepTxs`;
2242
+ const res = await fetch(url);
2243
+ if (!res.ok) {
2244
+ throw new Error(`Failed to fetch batch sweep transactions: ${res.statusText}`);
2245
+ }
2246
+ const data = await res.json();
2247
+ if (!Response.isBatchSweepTransactionsResponse(data)) {
2248
+ throw new Error("Invalid batch sweep transactions data received");
2249
+ }
2250
+ return data;
2251
+ }
2252
+ async getCommitmentTx(txid) {
2253
+ const url = `${this.serverUrl}/v1/indexer/commitmentTx/${txid}`;
2254
+ const res = await fetch(url);
2255
+ if (!res.ok) {
2256
+ throw new Error(`Failed to fetch commitment tx: ${res.statusText}`);
2257
+ }
2258
+ const data = await res.json();
2259
+ if (!Response.isCommitmentTx(data)) {
2260
+ throw new Error("Invalid commitment tx data received");
2261
+ }
2262
+ return data;
2263
+ }
2264
+ async getCommitmentTxConnectors(txid, opts) {
2265
+ let url = `${this.serverUrl}/v1/indexer/commitmentTx/${txid}/connectors`;
2266
+ const params = new URLSearchParams();
2267
+ if (opts) {
2268
+ if (opts.pageIndex !== void 0)
2269
+ params.append("page.index", opts.pageIndex.toString());
2270
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2271
+ }
2272
+ if (params.toString()) {
2273
+ url += "?" + params.toString();
2274
+ }
2275
+ const res = await fetch(url);
2276
+ if (!res.ok) {
2277
+ throw new Error(`Failed to fetch commitment tx connectors: ${res.statusText}`);
2278
+ }
2279
+ const data = await res.json();
2280
+ if (!Response.isConnectorsResponse(data)) {
2281
+ throw new Error("Invalid commitment tx connectors data received");
2282
+ }
2283
+ data.connectors.forEach((tx) => {
2284
+ tx.children = Object.fromEntries(
2285
+ Object.entries(tx.children).map(([key, value]) => [Number(key), value])
2286
+ );
2287
+ });
2288
+ return data;
2289
+ }
2290
+ async getCommitmentTxForfeitTxs(txid, opts) {
2291
+ let url = `${this.serverUrl}/v1/indexer/commitmentTx/${txid}/forfeitTxs`;
2292
+ const params = new URLSearchParams();
2293
+ if (opts) {
2294
+ if (opts.pageIndex !== void 0)
2295
+ params.append("page.index", opts.pageIndex.toString());
2296
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2297
+ }
2298
+ if (params.toString()) {
2299
+ url += "?" + params.toString();
2300
+ }
2301
+ const res = await fetch(url);
2302
+ if (!res.ok) {
2303
+ throw new Error(`Failed to fetch commitment tx forfeitTxs: ${res.statusText}`);
2304
+ }
2305
+ const data = await res.json();
2306
+ if (!Response.isForfeitTxsResponse(data)) {
2307
+ throw new Error("Invalid commitment tx forfeitTxs data received");
2308
+ }
2309
+ return data;
2310
+ }
2311
+ getSubscription(subscriptionId, abortSignal) {
2312
+ const url = `${this.serverUrl}/v1/indexer/script/subscription/${subscriptionId}`;
2313
+ let iterator = null;
2314
+ const closeIterator = () => iterator?.close();
2315
+ const gen = (async function* () {
2316
+ const abortHandler = closeIterator;
2317
+ abortSignal?.addEventListener("abort", abortHandler);
2318
+ try {
2319
+ while (!abortSignal?.aborted) {
2320
+ try {
2321
+ const currentIterator = eventSourceIterator(new EventSource(url));
2322
+ iterator = currentIterator;
2323
+ for await (const event of currentIterator) {
2324
+ if (abortSignal?.aborted) break;
2325
+ try {
2326
+ const data = JSON.parse(event.data);
2327
+ if (data.event) {
2328
+ yield {
2329
+ txid: data.event.txid,
2330
+ scripts: data.event.scripts || [],
2331
+ newVtxos: (data.event.newVtxos || []).map(convertVtxo),
2332
+ spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),
2333
+ sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),
2334
+ tx: data.event.tx,
2335
+ checkpointTxs: data.event.checkpointTxs
2336
+ };
2337
+ }
2338
+ } catch (err) {
2339
+ console.error("Failed to parse subscription event:", err);
2340
+ throw err;
2341
+ }
2342
+ }
2343
+ } catch (error) {
2344
+ if (abortSignal?.aborted || error instanceof Error && error.name === "AbortError") {
2345
+ break;
2346
+ }
2347
+ if (isFetchTimeoutError(error)) {
2348
+ console.debug("Timeout error ignored");
2349
+ continue;
2350
+ }
2351
+ if (isEventSourceError(error)) {
2352
+ throw error;
2353
+ }
2354
+ console.error("Subscription error:", error);
2355
+ throw error;
2356
+ } finally {
2357
+ closeIterator();
2358
+ iterator = null;
2359
+ }
2360
+ }
2361
+ } finally {
2362
+ abortSignal?.removeEventListener("abort", abortHandler);
2363
+ closeIterator();
2364
+ }
2365
+ })();
2366
+ const origReturn = gen.return.bind(gen);
2367
+ gen.return = (value) => {
2368
+ closeIterator();
2369
+ return origReturn(value);
2370
+ };
2371
+ return gen;
2372
+ }
2373
+ async getVirtualTxs(txids, opts) {
2374
+ let url = `${this.serverUrl}/v1/indexer/virtualTx/${txids.join(",")}`;
2375
+ const params = new URLSearchParams();
2376
+ if (opts) {
2377
+ if (opts.pageIndex !== void 0)
2378
+ params.append("page.index", opts.pageIndex.toString());
2379
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2380
+ }
2381
+ if (params.toString()) {
2382
+ url += "?" + params.toString();
2383
+ }
2384
+ const res = await fetch(url);
2385
+ if (!res.ok) {
2386
+ throw new Error(`Failed to fetch virtual txs: ${res.statusText}`);
2387
+ }
2388
+ const data = await res.json();
2389
+ if (!Response.isVirtualTxsResponse(data)) {
2390
+ throw new Error("Invalid virtual txs data received");
2391
+ }
2392
+ return data;
2393
+ }
2394
+ async getVtxoChain(vtxoOutpoint, opts) {
2395
+ let url = `${this.serverUrl}/v1/indexer/vtxo/${vtxoOutpoint.txid}/${vtxoOutpoint.vout}/chain`;
2396
+ const params = new URLSearchParams();
2397
+ if (opts) {
2398
+ if (opts.pageIndex !== void 0)
2399
+ params.append("page.index", opts.pageIndex.toString());
2400
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2401
+ }
2402
+ if (params.toString()) {
2403
+ url += "?" + params.toString();
2404
+ }
2405
+ const res = await fetch(url);
2406
+ if (!res.ok) {
2407
+ throw new Error(`Failed to fetch vtxo chain: ${res.statusText}`);
2408
+ }
2409
+ const data = await res.json();
2410
+ if (!Response.isVtxoChainResponse(data)) {
2411
+ throw new Error("Invalid vtxo chain data received");
2412
+ }
2413
+ return data;
2414
+ }
2415
+ async getVtxos(opts) {
2416
+ const hasScripts = (opts?.scripts?.length ?? 0) > 0;
2417
+ const hasOutpoints = (opts?.outpoints?.length ?? 0) > 0;
2418
+ if (hasScripts && hasOutpoints) {
2419
+ throw new Error("scripts and outpoints are mutually exclusive options");
2420
+ }
2421
+ if (!hasScripts && !hasOutpoints) {
2422
+ throw new Error("Either scripts or outpoints must be provided");
2423
+ }
2424
+ const filterCount = [opts?.spendableOnly, opts?.spentOnly, opts?.recoverableOnly].filter(
2425
+ Boolean
2426
+ ).length;
2427
+ if (filterCount > 1) {
2428
+ throw new Error(
2429
+ "spendableOnly, spentOnly, and recoverableOnly are mutually exclusive options"
2430
+ );
2431
+ }
2432
+ if (opts?.after !== void 0 && opts?.before !== void 0 && opts.after !== 0 && opts.before !== 0 && opts.before <= opts.after) {
2433
+ throw new Error("before must be greater than after");
2434
+ }
2435
+ let url = `${this.serverUrl}/v1/indexer/vtxos`;
2436
+ const params = new URLSearchParams();
2437
+ if (hasScripts) {
2438
+ opts.scripts.forEach((script) => {
2439
+ params.append("scripts", script);
2440
+ });
2441
+ }
2442
+ if (hasOutpoints) {
2443
+ opts.outpoints.forEach((outpoint) => {
2444
+ params.append("outpoints", `${outpoint.txid}:${outpoint.vout}`);
2445
+ });
2446
+ }
2447
+ if (opts) {
2448
+ if (opts.spendableOnly !== void 0)
2449
+ params.append("spendableOnly", opts.spendableOnly.toString());
2450
+ if (opts.spentOnly !== void 0) params.append("spentOnly", opts.spentOnly.toString());
2451
+ if (opts.recoverableOnly !== void 0)
2452
+ params.append("recoverableOnly", opts.recoverableOnly.toString());
2453
+ if (opts.pendingOnly !== void 0)
2454
+ params.append("pendingOnly", opts.pendingOnly.toString());
2455
+ if (opts.after !== void 0) params.append("after", opts.after.toString());
2456
+ if (opts.before !== void 0) params.append("before", opts.before.toString());
2457
+ if (opts.pageIndex !== void 0)
2458
+ params.append("page.index", opts.pageIndex.toString());
2459
+ if (opts.pageSize !== void 0) params.append("page.size", opts.pageSize.toString());
2460
+ }
2461
+ if (params.toString()) {
2462
+ url += "?" + params.toString();
2463
+ }
2464
+ const res = await fetch(url);
2465
+ if (!res.ok) {
2466
+ throw new Error(`Failed to fetch vtxos: ${res.statusText}`);
2467
+ }
2468
+ const data = await res.json();
2469
+ if (!Response.isVtxosResponse(data)) {
2470
+ throw new Error("Invalid vtxos data received");
2471
+ }
2472
+ return {
2473
+ vtxos: data.vtxos.map(convertVtxo),
2474
+ page: data.page
2475
+ };
2476
+ }
2477
+ async getAssetDetails(assetId) {
2478
+ const url = `${this.serverUrl}/v1/indexer/asset/${encodeURIComponent(assetId)}`;
2479
+ const res = await fetch(url);
2480
+ if (!res.ok) {
2481
+ throw new Error(`Failed to fetch asset details: ${res.statusText}`);
2482
+ }
2483
+ const data = await res.json();
2484
+ if (!Response.isGetAssetResponse(data)) {
2485
+ throw new Error("Invalid get asset response");
2486
+ }
2487
+ const metadata = data.metadata?.length ? parseAssetMetadata(data.metadata) : void 0;
2488
+ return {
2489
+ assetId: data.assetId ?? assetId,
2490
+ supply: BigInt(data.supply ?? 0),
2491
+ metadata,
2492
+ controlAssetId: data.controlAsset || void 0
2493
+ };
2494
+ }
2495
+ async subscribeForScripts(scripts, subscriptionId) {
2496
+ const url = `${this.serverUrl}/v1/indexer/script/subscribe`;
2497
+ const res = await fetch(url, {
2498
+ headers: {
2499
+ "Content-Type": "application/json"
2500
+ },
2501
+ method: "POST",
2502
+ body: JSON.stringify({ scripts, subscriptionId })
2503
+ });
2504
+ if (!res.ok) {
2505
+ const errorText = await res.text();
2506
+ throw new Error(`Failed to subscribe to scripts: ${errorText}`);
2507
+ }
2508
+ const data = await res.json();
2509
+ if (!data.subscriptionId) throw new Error(`Subscription ID not found`);
2510
+ return data.subscriptionId;
2511
+ }
2512
+ async unsubscribeForScripts(subscriptionId, scripts) {
2513
+ const url = `${this.serverUrl}/v1/indexer/script/unsubscribe`;
2514
+ const res = await fetch(url, {
2515
+ headers: {
2516
+ "Content-Type": "application/json"
2517
+ },
2518
+ method: "POST",
2519
+ body: JSON.stringify({ subscriptionId, scripts })
2520
+ });
2521
+ if (!res.ok) {
2522
+ const errorText = await res.text();
2523
+ console.warn(`Failed to unsubscribe to scripts: ${errorText}`);
2524
+ }
2525
+ }
2526
+ };
2527
+ function parseAssetMetadata(metadata) {
2528
+ const metadataList = MetadataList.fromString(metadata);
2529
+ const out = {};
2530
+ const decoder = new TextDecoder();
2531
+ for (const { key, value } of metadataList.items) {
2532
+ const keyString = decoder.decode(key);
2533
+ switch (keyString) {
2534
+ case "decimals":
2535
+ const n = Number(decoder.decode(value));
2536
+ out[keyString] = Number.isFinite(n) ? n : hex.encode(value);
2537
+ break;
2538
+ case "name":
2539
+ case "ticker":
2540
+ case "icon":
2541
+ out[keyString] = decoder.decode(value);
2542
+ break;
2543
+ default:
2544
+ out[keyString] = hex.encode(value);
2545
+ break;
2546
+ }
2547
+ }
2548
+ return out;
2549
+ }
2550
+ function convertVtxo(vtxo) {
2551
+ return {
2552
+ txid: vtxo.outpoint.txid,
2553
+ vout: vtxo.outpoint.vout,
2554
+ value: Number(vtxo.amount),
2555
+ status: {
2556
+ confirmed: !vtxo.isSwept && !vtxo.isPreconfirmed,
2557
+ isLeaf: !vtxo.isPreconfirmed
2558
+ },
2559
+ virtualStatus: {
2560
+ state: vtxo.isSwept ? "swept" : vtxo.isPreconfirmed ? "preconfirmed" : "settled",
2561
+ commitmentTxIds: vtxo.commitmentTxids,
2562
+ batchExpiry: vtxo.expiresAt ? Number(vtxo.expiresAt) * 1e3 : void 0
2563
+ },
2564
+ spentBy: vtxo.spentBy ?? "",
2565
+ settledBy: vtxo.settledBy,
2566
+ arkTxId: vtxo.arkTxid,
2567
+ createdAt: new Date(Number(vtxo.createdAt) * 1e3),
2568
+ isUnrolled: vtxo.isUnrolled,
2569
+ isSpent: vtxo.isSpent,
2570
+ script: vtxo.script,
2571
+ assets: vtxo.assets?.map((a) => ({
2572
+ assetId: a.assetId,
2573
+ amount: BigInt(a.amount)
2574
+ }))
2575
+ };
2576
+ }
2577
+ var Response;
2578
+ ((Response2) => {
2579
+ function isBatchInfo(data) {
2580
+ return typeof data === "object" && typeof data.totalOutputAmount === "string" && typeof data.totalOutputVtxos === "number" && typeof data.expiresAt === "string" && typeof data.swept === "boolean";
2581
+ }
2582
+ function isChain(data) {
2583
+ return typeof data === "object" && typeof data.txid === "string" && typeof data.expiresAt === "string" && Object.values(ChainTxType).includes(data.type) && Array.isArray(data.spends) && data.spends.every((spend) => typeof spend === "string");
2584
+ }
2585
+ function isCommitmentTx(data) {
2586
+ return typeof data === "object" && typeof data.startedAt === "string" && typeof data.endedAt === "string" && typeof data.totalInputAmount === "string" && typeof data.totalInputVtxos === "number" && typeof data.totalOutputAmount === "string" && typeof data.totalOutputVtxos === "number" && typeof data.batches === "object" && Object.values(data.batches).every(isBatchInfo);
2587
+ }
2588
+ Response2.isCommitmentTx = isCommitmentTx;
2589
+ function isOutpoint(data) {
2590
+ return typeof data === "object" && typeof data.txid === "string" && typeof data.vout === "number";
2591
+ }
2592
+ Response2.isOutpoint = isOutpoint;
2593
+ function isOutpointArray(data) {
2594
+ return Array.isArray(data) && data.every(isOutpoint);
2595
+ }
2596
+ Response2.isOutpointArray = isOutpointArray;
2597
+ function isTx(data) {
2598
+ return typeof data === "object" && typeof data.txid === "string" && typeof data.children === "object" && Object.values(data.children).every(isTxid) && Object.keys(data.children).every((k) => Number.isInteger(Number(k)));
2599
+ }
2600
+ function isTxsArray(data) {
2601
+ return Array.isArray(data) && data.every(isTx);
2602
+ }
2603
+ Response2.isTxsArray = isTxsArray;
2604
+ function isTxHistoryRecord(data) {
2605
+ return typeof data === "object" && typeof data.amount === "string" && typeof data.createdAt === "string" && typeof data.isSettled === "boolean" && typeof data.settledBy === "string" && Object.values(IndexerTxType).includes(data.type) && (!data.commitmentTxid && typeof data.virtualTxid === "string" || typeof data.commitmentTxid === "string" && !data.virtualTxid);
2606
+ }
2607
+ function isTxHistoryRecordArray(data) {
2608
+ return Array.isArray(data) && data.every(isTxHistoryRecord);
2609
+ }
2610
+ Response2.isTxHistoryRecordArray = isTxHistoryRecordArray;
2611
+ function isTxid(data) {
2612
+ return typeof data === "string" && data.length === 64;
2613
+ }
2614
+ function isTxidArray(data) {
2615
+ return Array.isArray(data) && data.every(isTxid);
2616
+ }
2617
+ Response2.isTxidArray = isTxidArray;
2618
+ function isVtxoAsset(data) {
2619
+ return typeof data === "object" && data !== null && typeof data.assetId === "string" && typeof data.amount === "string";
2620
+ }
2621
+ function isVtxo(data) {
2622
+ return typeof data === "object" && isOutpoint(data.outpoint) && typeof data.createdAt === "string" && (data.expiresAt === null || typeof data.expiresAt === "string") && typeof data.amount === "string" && typeof data.script === "string" && typeof data.isPreconfirmed === "boolean" && typeof data.isSwept === "boolean" && typeof data.isUnrolled === "boolean" && typeof data.isSpent === "boolean" && (!data.spentBy || typeof data.spentBy === "string") && (!data.settledBy || typeof data.settledBy === "string") && (!data.arkTxid || typeof data.arkTxid === "string") && Array.isArray(data.commitmentTxids) && data.commitmentTxids.every(isTxid) && (data.assets === void 0 || Array.isArray(data.assets) && data.assets.every(isVtxoAsset));
2623
+ }
2624
+ function isPageResponse(data) {
2625
+ return typeof data === "object" && typeof data.current === "number" && typeof data.next === "number" && typeof data.total === "number";
2626
+ }
2627
+ function isVtxoTreeResponse(data) {
2628
+ return typeof data === "object" && Array.isArray(data.vtxoTree) && data.vtxoTree.every(isTx) && (!data.page || isPageResponse(data.page));
2629
+ }
2630
+ Response2.isVtxoTreeResponse = isVtxoTreeResponse;
2631
+ function isVtxoTreeLeavesResponse(data) {
2632
+ return typeof data === "object" && Array.isArray(data.leaves) && data.leaves.every(isOutpoint) && (!data.page || isPageResponse(data.page));
2633
+ }
2634
+ Response2.isVtxoTreeLeavesResponse = isVtxoTreeLeavesResponse;
2635
+ function isConnectorsResponse(data) {
2636
+ return typeof data === "object" && Array.isArray(data.connectors) && data.connectors.every(isTx) && (!data.page || isPageResponse(data.page));
2637
+ }
2638
+ Response2.isConnectorsResponse = isConnectorsResponse;
2639
+ function isForfeitTxsResponse(data) {
2640
+ return typeof data === "object" && Array.isArray(data.txids) && data.txids.every(isTxid) && (!data.page || isPageResponse(data.page));
2641
+ }
2642
+ Response2.isForfeitTxsResponse = isForfeitTxsResponse;
2643
+ function isSweptCommitmentTxResponse(data) {
2644
+ return typeof data === "object" && Array.isArray(data.sweptBy) && data.sweptBy.every(isTxid);
2645
+ }
2646
+ Response2.isSweptCommitmentTxResponse = isSweptCommitmentTxResponse;
2647
+ function isBatchSweepTransactionsResponse(data) {
2648
+ return typeof data === "object" && Array.isArray(data.sweptBy) && data.sweptBy.every(isTxid);
2649
+ }
2650
+ Response2.isBatchSweepTransactionsResponse = isBatchSweepTransactionsResponse;
2651
+ function isVirtualTxsResponse(data) {
2652
+ return typeof data === "object" && Array.isArray(data.txs) && data.txs.every((tx) => typeof tx === "string") && (!data.page || isPageResponse(data.page));
2653
+ }
2654
+ Response2.isVirtualTxsResponse = isVirtualTxsResponse;
2655
+ function isVtxoChainResponse(data) {
2656
+ return typeof data === "object" && Array.isArray(data.chain) && data.chain.every(isChain) && (!data.page || isPageResponse(data.page));
2657
+ }
2658
+ Response2.isVtxoChainResponse = isVtxoChainResponse;
2659
+ function isVtxosResponse(data) {
2660
+ return typeof data === "object" && Array.isArray(data.vtxos) && data.vtxos.every(isVtxo) && (!data.page || isPageResponse(data.page));
2661
+ }
2662
+ Response2.isVtxosResponse = isVtxosResponse;
2663
+ function isGetAssetResponse(data) {
2664
+ return typeof data === "object" && data !== null && typeof data.assetId === "string" && typeof data.supply === "string" && (data.controlAsset === void 0 || typeof data.controlAsset === "string") && (data.metadata === void 0 || typeof data.metadata === "string");
2665
+ }
2666
+ Response2.isGetAssetResponse = isGetAssetResponse;
2667
+ })(Response || (Response = {}));
2668
+
2669
+ export { ArkError, ArkPsbtFieldKey, ArkPsbtFieldKeyType, AssetGroup, AssetId, AssetInput, AssetOutput, AssetRef, BufferReader, ChainTxType, ConditionWitness, CosignerPublicKey, IndexerTxType, Intent, Metadata, OP_RETURN_EMPTY_PKSCRIPT, Packet, RestArkProvider, RestIndexerProvider, SettlementEventType, Transaction, VtxoTaprootTree, VtxoTreeExpiry, asset_exports, craftToSpendTx, getArkPsbtFields, isEventSourceError, isFetchTimeoutError, maybeArkError, setArkPsbtField };
2670
+ //# sourceMappingURL=chunk-ZBUDLTBO.js.map
2671
+ //# sourceMappingURL=chunk-ZBUDLTBO.js.map