@laceio/sdk 0.1.1-canary.2 → 0.1.1

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 (386) hide show
  1. package/dist/{TransactionBuilder-CCjOn7NA.cjs → TransactionBuilder-DrB3NVTi.cjs} +0 -42
  2. package/dist/{TransactionBuilder-CIzdw18M.js → TransactionBuilder-V6aLx4SV.js} +1 -1
  3. package/dist/{_polyfill-buffer-patch-CM8X7JiY.cjs → _polyfill-buffer-patch-BnPVerlG.cjs} +2 -21
  4. package/dist/account-guards.stable-B1DSSh9D.cjs +10 -0
  5. package/dist/account-guards.stable-JRQ5qx2V.js +5 -0
  6. package/dist/{activity-type-Ch6ljxBy.cjs → activity-type.stable-BJEfeLxL.cjs} +1 -2
  7. package/dist/{activity-type-GsJGWs-3.js → activity-type.stable-C76_hWd7.js} +1 -2
  8. package/dist/{address-book-address-validator-ByIZOdO-.js → address-book-address-validator-DIUolI-s.js} +2 -2
  9. package/dist/{address-book-address-validator-BjOWerRE.cjs → address-book-address-validator-DNwQGlOB.cjs} +2 -2
  10. package/dist/bitcoin.cjs +0 -45
  11. package/dist/bitcoin.d.ts +1 -29782
  12. package/dist/bitcoin.js +0 -20
  13. package/dist/{blockfrost-tx-submit-provider-CLNQ5ycR.cjs → blockfrost-tx-submit-provider-BAIzV5o3.cjs} +167 -3
  14. package/dist/{blockfrost-tx-submit-provider-CBWQ0wK9.js → blockfrost-tx-submit-provider-DPTrapz-.js} +157 -5
  15. package/dist/{secret-box-DrjLZuS1.cjs → bytes.vo-Ck5u40RA.cjs} +35 -1
  16. package/dist/{secret-box-DUR0ACYz.js → bytes.vo-TgiwogWF.js} +25 -3
  17. package/dist/{cardano-network-id.vo-wfLiAxpY.js → cardano-network-id.vo-CK1tNQDg.js} +1 -1
  18. package/dist/{cardano-network-id.vo-BEvFd_74.cjs → cardano-network-id.vo-DSxrFk9S.cjs} +1 -1
  19. package/dist/cardano.cjs +18 -22
  20. package/dist/cardano.d.ts +3982 -18409
  21. package/dist/cardano.js +11 -16
  22. package/dist/codecs-B7X9pAsK.cjs +1945 -0
  23. package/dist/codecs-CC1Xjntz.js +1882 -0
  24. package/dist/{const-oMF-TLow.cjs → const-BDEg2Trq.cjs} +4 -4
  25. package/dist/{const-iwzZEE_w.cjs → const-BY8B3_0_.cjs} +1 -1
  26. package/dist/{const-CBGn60yu.js → const-C84qHkjp.js} +4 -4
  27. package/dist/{const-CjmfjBP3.js → const-DXk2tFyv.js} +1 -1
  28. package/dist/{delegation-tx-builder-BR6bt1fE.js → delegation-tx-builder-CGVqlaFE.js} +5 -5
  29. package/dist/{delegation-tx-builder-DVwGfiV0.cjs → delegation-tx-builder-CRpLP6jH.cjs} +6 -6
  30. package/dist/{deregistration-tx-builder-BhJRGj1M.js → deregistration-tx-builder-B-CrUyX6.js} +5 -5
  31. package/dist/{deregistration-tx-builder-Cv_09HGf.cjs → deregistration-tx-builder-DZGwB4cz.cjs} +6 -6
  32. package/dist/{earn-rewards-tx-builder-RYzKsZ6-.js → earn-rewards-tx-builder-BDbTDZmD.js} +5 -5
  33. package/dist/{earn-rewards-tx-builder-52gJiJYa.cjs → earn-rewards-tx-builder-D5sUT5v8.cjs} +6 -6
  34. package/dist/{group-cardano-addresses-by-account-D06r7daZ.cjs → group-cardano-addresses-by-account-B533oVXR.cjs} +35 -19
  35. package/dist/{group-cardano-addresses-by-account-CxCqFDrX.js → group-cardano-addresses-by-account-RHKoEskR.js} +35 -19
  36. package/dist/{guarded-transaction-signer-BhnTBjf6.cjs → guarded-transaction-signer-Bxl6_XNd.cjs} +18 -17
  37. package/dist/{guarded-transaction-signer-BSEx83R-.js → guarded-transaction-signer-CpKLj8Kp.js} +15 -8
  38. package/dist/{in-memory-wallet-integration-CH4rcg92.cjs → in-memory-wallet-integration-CnLYeX4-.cjs} +108 -17
  39. package/dist/{in-memory-wallet-integration-BKu985Jz.js → in-memory-wallet-integration-Croiuopx.js} +104 -7
  40. package/dist/{in-memory-wallet-integration-B0blZBxM.js → in-memory-wallet-integration-D-qn65Kx.js} +2 -5
  41. package/dist/{in-memory-wallet-integration-CwPCDMIe.cjs → in-memory-wallet-integration-DVh9sRXa.cjs} +2 -3
  42. package/dist/index.cjs +47 -84
  43. package/dist/index.d.ts +13618 -40268
  44. package/dist/index.js +24 -52
  45. package/dist/{init-DUF4ar8P.cjs → init-B64zCLxG.cjs} +4 -4
  46. package/dist/{init-Y3mkB4XS.js → init-BAJJzBza.js} +2 -2
  47. package/dist/{init-BTzOjA8x.cjs → init-BJVU54pI.cjs} +1 -1
  48. package/dist/{init-D6BxBs7e.cjs → init-BKhH6mVR.cjs} +1 -1
  49. package/dist/{init-EP0CUWNK.cjs → init-BsCBAGWf.cjs} +2 -2
  50. package/dist/{init-Dy-05ktr.cjs → init-BtzMZ7Pk.cjs} +1 -1
  51. package/dist/init-Bv53hpLM.js +19 -0
  52. package/dist/{init-BopV9ed4.cjs → init-C-jErzp5.cjs} +2 -2
  53. package/dist/{init-CjT-WZcW.cjs → init-C4Bkib9u.cjs} +59 -49
  54. package/dist/{init-BEjCRHxU.cjs → init-C7IeJwQR.cjs} +61 -258
  55. package/dist/{init-C-G32J12.cjs → init-CB__aLD7.cjs} +2 -2
  56. package/dist/{init-CyAY4Lzl.js → init-CFYsq82V.js} +1 -1
  57. package/dist/{init-0zzs9aqU.js → init-CLHuAMB-.js} +4 -4
  58. package/dist/{init-DA7zmptx.js → init-CNLGJJRx.js} +1 -1
  59. package/dist/{init-B-YE57gg.js → init-CR6tpw1B.js} +33 -25
  60. package/dist/init-CRbjI7p1.js +3494 -0
  61. package/dist/{init-CSDpdu0Q.cjs → init-CSHwHnfg.cjs} +2 -2
  62. package/dist/{init-CNM5m7M2.js → init-Cg9XdAru.js} +4 -4
  63. package/dist/{init-B3-1ghyx.js → init-CigestoM.js} +2 -2
  64. package/dist/{init-Dv3zKj0r.cjs → init-D6DBUsD3.cjs} +4 -4
  65. package/dist/init-DAna1KCg.cjs +3495 -0
  66. package/dist/{init-D74mn8nH2.js → init-DDdhguVC.js} +2 -2
  67. package/dist/init-DGe47B22.cjs +364 -0
  68. package/dist/init-DMtyvYfC.cjs +21 -0
  69. package/dist/{init-BrdVzxei.cjs → init-DX4WyB0R.cjs} +3 -3
  70. package/dist/{init-C8URA2OX.js → init-DcYY6zMD.js} +1 -1
  71. package/dist/{init-DFMiP2ZH.cjs → init-DkIc5nqF.cjs} +1 -1
  72. package/dist/{init-vqxOQNZi.js → init-Dku4b2lG.js} +1 -1
  73. package/dist/{init-NdhG_VrF.cjs → init-DxUHsN53.cjs} +6 -6
  74. package/dist/{init-COMH3Hfo.js → init-FMGDET-9.js} +60 -259
  75. package/dist/{init-DrkOb-wd.cjs → init-LfyMo-sS.cjs} +2 -2
  76. package/dist/{init-NCjgwCZy.js → init-Rxohwpmu.js} +2 -2
  77. package/dist/init-TkPDD750.js +363 -0
  78. package/dist/{init-C2RgrfZe.js → init-TkPq_Ny_.js} +1 -1
  79. package/dist/{init-5KcGcBb5.cjs → init-U8c9yHYx.cjs} +1 -1
  80. package/dist/{init-CX0AMQUn.js → init-aJHl-7AO.js} +2 -2
  81. package/dist/{init-rmt7-fQE.cjs → init-anYu6XB7.cjs} +2 -2
  82. package/dist/{init-Fw89ZmrR.js → init-w9GEs73W.js} +2 -2
  83. package/dist/{init-Dnsv155v.js → init-y2Ra0vZP.js} +3 -3
  84. package/dist/{init-DFjT8YvT.js → init-zSzCjoor.js} +4 -4
  85. package/dist/{is-retriable-error-BUiVJDwH.js → is-retriable-error-BU0e3hVI.js} +1 -1
  86. package/dist/{is-retriable-error-Dpt860if.cjs → is-retriable-error-CeeuHqDa.cjs} +1 -1
  87. package/dist/{lace-context-BZciB9c7.js → lace-context-CZcNHr4M.js} +4 -4
  88. package/dist/{lace-context-DgR6vLli.cjs → lace-context-fJTDghdp.cjs} +4 -4
  89. package/dist/{libsodium-wrappers-BhbOA8dQ.js → libsodium-wrappers-UH0LaOUE.js} +1647 -3
  90. package/dist/modules-cardano-BDvuL4Xx.js +5248 -0
  91. package/dist/modules-cardano-D2G3De2P.cjs +5432 -0
  92. package/dist/{retry-config-Dmgt28wM.js → retry-config-BcUmMS--.js} +1 -1
  93. package/dist/{retry-config-BaCfVC1H.cjs → retry-config-DC5IMaH7.cjs} +1 -1
  94. package/dist/{seam-cardano-B_etH4F4.js → seam-cardano-CATqBEyK.js} +1 -1
  95. package/dist/{signer-factory-B7PMe3lQ.js → signer-factory-9URFliA5.js} +3 -6
  96. package/dist/{signer-factory-DduwpsQj.cjs → signer-factory-BWGUmnvm.cjs} +3 -4
  97. package/dist/{slice-CqVNnz-j.js → slice-B2PhoWAg.js} +125 -316
  98. package/dist/{slice-DyNs7oWp.js → slice-BNu73oBa.js} +2 -2
  99. package/dist/{slice-GwiiJRoq.js → slice-CB4SnzMm.js} +3 -3
  100. package/dist/slice-CGVHXHDt.cjs +125 -0
  101. package/dist/{slice-CU80pbiu.js → slice-CnyWevM9.js} +3 -3
  102. package/dist/{slice-CwyYrh1H.js → slice-CobanYgn.js} +2 -2
  103. package/dist/{slice-7G2xxYKJ.cjs → slice-CuHUaPZx.cjs} +3 -3
  104. package/dist/{slice-DayJvMRD.cjs → slice-D11m2EKl.cjs} +1 -1
  105. package/dist/{slice-Bg6HEr3K.cjs → slice-DGcNrbPR.cjs} +4 -4
  106. package/dist/{slice-B4CdYoPu.cjs → slice-DZmQJNV8.cjs} +2 -2
  107. package/dist/slice-DhvF7L6X.js +107 -0
  108. package/dist/{slice-C9TT5KhY.cjs → slice-Do2R2CYW.cjs} +6 -6
  109. package/dist/{slice-Bs2aMERu.cjs → slice-DtaO72qY.cjs} +3 -3
  110. package/dist/{slice-C34iOOUH.cjs → slice-HeHCv3bl.cjs} +7 -7
  111. package/dist/{slice-D-9aPKG-.js → slice-d0p6-xj5.js} +6 -6
  112. package/dist/{slice-CK07EBCo.js → slice-eIwcwKHI.js} +4 -4
  113. package/dist/{slice-DBpJ2QGf.js → slice-maaskdUn.js} +6 -6
  114. package/dist/{slice-6sP0Qs5V.cjs → slice-mxLQ_FeY.cjs} +127 -343
  115. package/dist/{slice-DnG-yvpI.cjs → slice-oqm_r1cS.cjs} +2 -2
  116. package/dist/{slice-Da426sf9.js → slice-zJ9XVYjZ.js} +1 -1
  117. package/dist/{sync-operation-utils-KT5Y9yFK.js → sync-operation-utils-BYXLO80m.js} +52 -1
  118. package/dist/{sync-operation-utils-C9kcmjKH.cjs → sync-operation-utils-SdPbwFoD.cjs} +87 -0
  119. package/dist/{token-id-mapper-qx7XfH0b.js → token-id-mapper-B2ivlLv3.js} +2 -2
  120. package/dist/{token-id-mapper-IApjwuJb.cjs → token-id-mapper-DsPAL6Nh.cjs} +2 -2
  121. package/dist/{util-D1e0skzp.js → util-BaLzwa32.js} +1 -1
  122. package/dist/{util-BeG7WXzM.cjs → util-CGzqQ8IV.cjs} +1 -1
  123. package/dist/{utils-DsElZgCI.cjs → utils-5JvjbqH3.cjs} +1 -7
  124. package/dist/{utils-BfBEUvWA.js → utils-o8aMjfln.js} +2 -2
  125. package/dist/{vote-delegation-tx-builder-CtdIgaIt.cjs → vote-delegation-tx-builder-BpEMSti4.cjs} +6 -6
  126. package/dist/{vote-delegation-tx-builder-CQjGvVNZ.js → vote-delegation-tx-builder-CmKv6GoG.js} +5 -5
  127. package/package.json +4 -96
  128. package/dist/_polyfill-buffer-patch-yNxN4d5E.js +0 -1467
  129. package/dist/_web-crypto-random-bytes-Bo-GTcRS.js +0 -197
  130. package/dist/acc-module-4iIUv6My.cjs +0 -27654
  131. package/dist/acc-module-Cmj8EsIb.js +0 -27624
  132. package/dist/account-BlYkEmcs.cjs +0 -11
  133. package/dist/account-DVX0F5_M.js +0 -6
  134. package/dist/account-call-D68oF6bh.js +0 -267
  135. package/dist/account-call-DIIa2rK_.cjs +0 -314
  136. package/dist/account-call-NgLhYein.cjs +0 -4
  137. package/dist/account-call-n-Nkp35e.js +0 -3
  138. package/dist/account-guards-BtjTGxDZ.cjs +0 -42
  139. package/dist/account-guards-D9Lu5T3W.js +0 -36
  140. package/dist/account-tokens-CtN2BaFy.js +0 -16
  141. package/dist/account-tokens-DXr8DlpW.cjs +0 -21
  142. package/dist/address-B9ntKL8K.js +0 -13761
  143. package/dist/address-BXp-mY8H.cjs +0 -11270
  144. package/dist/address-book-address-validator-DK0dnsRS.cjs +0 -41
  145. package/dist/address-book-address-validator-Di_ywo8M.js +0 -39
  146. package/dist/artefact-loader-54uK5RAa.js +0 -160
  147. package/dist/artefact-loader-DZPYrq-6.cjs +0 -183
  148. package/dist/auto-dismiss-failure-on-success-C-qoJuid.cjs +0 -37
  149. package/dist/auto-dismiss-failure-on-success-s8MGDEIu.js +0 -31
  150. package/dist/bip32-D6wd_QMn.cjs +0 -3851
  151. package/dist/bitcoin-data-provider-BYPSmuZS.js +0 -21
  152. package/dist/bitcoin-data-provider-w1oEDSU3.cjs +0 -26
  153. package/dist/bn-d3nSOIf7.cjs +0 -2553
  154. package/dist/browser-B1eMbDwh.js +0 -7468
  155. package/dist/bytes.vo-BB7_4JK6.js +0 -23
  156. package/dist/bytes.vo-BNRquqaO.cjs +0 -34
  157. package/dist/cardano-DfPwhwm-.js +0 -3
  158. package/dist/client-DXBLHk7K.cjs +0 -808
  159. package/dist/codecs-Cswkg7Tm.cjs +0 -4051
  160. package/dist/codecs-Dc1Krpbt.js +0 -3903
  161. package/dist/const-BfEnY8fg.js +0 -153
  162. package/dist/const-BhYOdznB.cjs +0 -42
  163. package/dist/const-CUnCl5U0.js +0 -13
  164. package/dist/const-DLrX5SD9.cjs +0 -31995
  165. package/dist/contract-C_CBwwiC.cjs +0 -189
  166. package/dist/contract-s_x-9-lz.js +0 -171
  167. package/dist/create-add-accounts-Brqk84vF.js +0 -102
  168. package/dist/create-add-accounts-DzXIh7Ot.cjs +0 -114
  169. package/dist/device-commitment-hex.vo-5wFtQvDS.js +0 -26
  170. package/dist/device-commitment-hex.vo-CT3RmAug.cjs +0 -31
  171. package/dist/device-readers-70i7tQqU.cjs +0 -8
  172. package/dist/device-readers-B7--ezKM.js +0 -4
  173. package/dist/device-readers-BWOmz9eD.js +0 -145
  174. package/dist/device-readers-CIgYZN7f.cjs +0 -168
  175. package/dist/dist-BMi5ZjEq.cjs +0 -43175
  176. package/dist/dist-BtIq4XFn.cjs +0 -535
  177. package/dist/dist-C3SHC_Ho.cjs +0 -1394
  178. package/dist/dist-CykEjYEX.cjs +0 -3814
  179. package/dist/dist-Dcsxh3be.cjs +0 -3452
  180. package/dist/dist-DqJfSlTd.cjs +0 -4413
  181. package/dist/dist-nTZ70qj7.cjs +0 -1306
  182. package/dist/enc-key-circuits-C8fGAMEF.cjs +0 -24
  183. package/dist/enc-key-circuits-DA2Xs3vZ.js +0 -13
  184. package/dist/english-Byb9M0E_.cjs +0 -2057
  185. package/dist/envelopes-BkH1Qdxk.js +0 -1620
  186. package/dist/envelopes-ETZEJS_O.cjs +0 -1721
  187. package/dist/errors-BZ8hnhCM.cjs +0 -584
  188. package/dist/errors-DIJTAsLa.js +0 -392
  189. package/dist/esm-HBSUQw3w.js +0 -384
  190. package/dist/esm-LZuaZjMf.cjs +0 -389
  191. package/dist/experimental.cjs +0 -7073
  192. package/dist/experimental.d.ts +0 -84347
  193. package/dist/experimental.js +0 -6915
  194. package/dist/gated-call-Boy6rXdC.js +0 -3
  195. package/dist/gated-call-DJWY299W.cjs +0 -736
  196. package/dist/gated-call-DjoRPqn1.js +0 -695
  197. package/dist/gated-call-SomdJ5nj.cjs +0 -4
  198. package/dist/grant-circuits-_1x--moV.cjs +0 -49
  199. package/dist/grant-circuits-swuzEdUl.js +0 -26
  200. package/dist/grant-rules-7Zqi_3BN.cjs +0 -7114
  201. package/dist/grant-rules-_xJHAT2M.js +0 -6833
  202. package/dist/grant-status-B2y49iIu.js +0 -2688
  203. package/dist/grant-status-DOr3t_u8.cjs +0 -2820
  204. package/dist/grants--b0LQQzZ.cjs +0 -266
  205. package/dist/grants-BIs6qm3b.js +0 -213
  206. package/dist/grants-CSgfYlOO.js +0 -5
  207. package/dist/grants-D61131nK.cjs +0 -17
  208. package/dist/hex-D9ITYbwt.cjs +0 -263
  209. package/dist/hex-mkXcV3pN.js +0 -191
  210. package/dist/http-client-B3N-TMxu.cjs +0 -167
  211. package/dist/http-client-TRlhDZGh.js +0 -155
  212. package/dist/identity-BMLuufva.cjs +0 -263
  213. package/dist/identity-DII6f-h7.js +0 -233
  214. package/dist/in-memory-wallet-integration-B2xzxORj.cjs +0 -20741
  215. package/dist/in-memory-wallet-integration-CUKesGG1.js +0 -130
  216. package/dist/in-memory-wallet-integration-CoPx69lQ.cjs +0 -240
  217. package/dist/in-memory-wallet-integration-TM9bBphA.js +0 -20738
  218. package/dist/init-B5X_sGj9.cjs +0 -6
  219. package/dist/init-BJn-8_hf.js +0 -141
  220. package/dist/init-Bp6yJk31.js +0 -1142
  221. package/dist/init-Bu4iXcTH.cjs +0 -34
  222. package/dist/init-C00gw1zi.js +0 -422
  223. package/dist/init-CIjZaQvL.js +0 -3584
  224. package/dist/init-CR7BfztQ.cjs +0 -18
  225. package/dist/init-Cp8EJGbm.js +0 -5
  226. package/dist/init-CpIadSUb.js +0 -33
  227. package/dist/init-D5UiYI12.cjs +0 -106
  228. package/dist/init-DAikR9qU.js +0 -1177
  229. package/dist/init-DGjXwWs2.cjs +0 -143
  230. package/dist/init-DHrCbpkW.cjs +0 -121
  231. package/dist/init-DU5yYX5u.js +0 -2374
  232. package/dist/init-DWvkFDkc.cjs +0 -1176
  233. package/dist/init-DY1unoGb.cjs +0 -1141
  234. package/dist/init-DlqJuHhl.js +0 -119
  235. package/dist/init-DuYENxci.js +0 -17
  236. package/dist/init-E7c40ddW.cjs +0 -3585
  237. package/dist/init-GsT2AEa4.cjs +0 -424
  238. package/dist/init-KQnIdm39.js +0 -104
  239. package/dist/init-ZjNDDC-T.cjs +0 -2375
  240. package/dist/jubjub-authoriser-BxE3oN2y.js +0 -86
  241. package/dist/jubjub-authoriser-C6SDEP9I.cjs +0 -87
  242. package/dist/key-source-5oUBFiC7.cjs +0 -583
  243. package/dist/key-source-B08HukZg.js +0 -2550
  244. package/dist/keyDerivation-D3k9XyHg.js +0 -4077
  245. package/dist/keyDerivation-u0nBA93T.cjs +0 -274
  246. package/dist/lib--iqvW4O_.js +0 -2354
  247. package/dist/lib-Yk6Upl5D.cjs +0 -2359
  248. package/dist/midnight-account-id.vo-0x9X-r3l.cjs +0 -10
  249. package/dist/midnight-account-id.vo-DjCAGcqc.js +0 -5
  250. package/dist/midnight-engine-DpemplKO.js +0 -5
  251. package/dist/midnight-engine-xU1wotne.cjs +0 -6
  252. package/dist/midnight-wallet-DIsAlSn6.js +0 -18
  253. package/dist/midnight-wallet-XTZc2li7.cjs +0 -24
  254. package/dist/midnight.cjs +0 -1406
  255. package/dist/midnight.d.ts +0 -28586
  256. package/dist/midnight.js +0 -1350
  257. package/dist/modules-cardano-CtWLntet.cjs +0 -1108
  258. package/dist/modules-cardano-D2dkeKHY.js +0 -995
  259. package/dist/node-relay-Cv0cNknM.js +0 -48
  260. package/dist/node-relay-DblH5fKv.cjs +0 -49
  261. package/dist/outputs-Bd2yZVjx.js +0 -720
  262. package/dist/outputs-CJoQBIA2.cjs +0 -990
  263. package/dist/pbkdf2-CIW-oWrm.cjs +0 -1337
  264. package/dist/pending-operation-B0_P78Jo.cjs +0 -26
  265. package/dist/pending-operation-BIS6mpjB.js +0 -21
  266. package/dist/providers-BLgJ0uQs.cjs +0 -366
  267. package/dist/providers-CwnT4vEE.js +0 -343
  268. package/dist/redacted-BmE2aXqr.js +0 -81
  269. package/dist/redacted-CRZJLS3w.cjs +0 -86
  270. package/dist/safe-buffer-B_vMqJWU.js +0 -43
  271. package/dist/safe-buffer-DYOwEfHB.cjs +0 -48
  272. package/dist/sdk-DIcjlgLF.js +0 -1241
  273. package/dist/sdk-Dgal10kG.cjs +0 -1439
  274. package/dist/sdk-init-BKkqFtWZ.cjs +0 -3791
  275. package/dist/sdk-init-DNd-oQXp.js +0 -1044
  276. package/dist/send-proof-progress-DTK3ZuYB.js +0 -22
  277. package/dist/send-proof-progress-dDoqIohG.cjs +0 -33
  278. package/dist/side-effects-BnqYz7Nl.js +0 -768
  279. package/dist/side-effects-CngaeXi0.cjs +0 -804
  280. package/dist/sign-bitcoin-transaction-with-seed-D4z62-jV.js +0 -147
  281. package/dist/sign-bitcoin-transaction-with-seed-DsLYXnCY.cjs +0 -158
  282. package/dist/signer-3fk8lZtE.cjs +0 -7
  283. package/dist/signer-CsL28DrK.cjs +0 -121
  284. package/dist/signer-DGluibtn.js +0 -92
  285. package/dist/signer-RqB5pu3K.js +0 -2
  286. package/dist/signer-factory-BA7WFJVZ.js +0 -282
  287. package/dist/signer-factory-CORIG4Yl.cjs +0 -130
  288. package/dist/signer-factory-Cd2TwD50.js +0 -129
  289. package/dist/signer-factory-Cwd6o-lG.cjs +0 -281
  290. package/dist/slice-BOyAAaj0.cjs +0 -378
  291. package/dist/slice-BnTJeMOb.js +0 -354
  292. package/dist/slice-C4uXUT7S.js +0 -9013
  293. package/dist/slice-CxKWDuBP.js +0 -87
  294. package/dist/slice-DQv_RhsI.cjs +0 -9031
  295. package/dist/slice-HjLXJyQG2.cjs +0 -105
  296. package/dist/src-BDzYIksE.cjs +0 -20637
  297. package/dist/src-BFoefPv_.js +0 -20755
  298. package/dist/store-B1Lq3cEf.cjs +0 -66
  299. package/dist/store-DuBG8qh5.js +0 -37
  300. package/dist/submit-BBYjnZu8.cjs +0 -87
  301. package/dist/submit-D_yxYM_T.js +0 -70
  302. package/dist/submit-bitcoin-tx-BkZIeF4b.js +0 -983
  303. package/dist/submit-bitcoin-tx-DZNQgihl.cjs +0 -1049
  304. package/dist/token-id-mapper-Bnds3xKH.cjs +0 -18
  305. package/dist/token-id-mapper-CnKHQ8DV.js +0 -16
  306. package/dist/tokens-Cevp7rdU.cjs +0 -62
  307. package/dist/tokens-Diw4MLRM.js +0 -44
  308. package/dist/types-B8uiJn-X.js +0 -12
  309. package/dist/types-CJT6XF2c.js +0 -10
  310. package/dist/types-CLRUYpfe.cjs +0 -23
  311. package/dist/types-DWbVZpnF.cjs +0 -15
  312. package/dist/types-T0cjaR75.js +0 -33
  313. package/dist/types-Zj78LtYu.cjs +0 -50
  314. package/dist/unwrap-provider-result-BZSiwabU.js +0 -32
  315. package/dist/unwrap-provider-result-ZqfBsTkk.cjs +0 -39
  316. package/dist/utils-BfMdr_1w.cjs +0 -112
  317. package/dist/utils-CvAW5Yw7.js +0 -65
  318. package/dist/v8Signatures-CO_Uloy7.cjs +0 -71
  319. package/dist/watch-Cz1J42um.cjs +0 -52205
  320. package/dist/watch-Z53L4yoK.js +0 -13054
  321. /package/dist/{account-id.vo-DwqFjK5u.cjs → account-id.vo-LvCBVn5r.cjs} +0 -0
  322. /package/dist/{account-id.vo-OPz2v-JZ.js → account-id.vo-MYSI7YFm.js} +0 -0
  323. /package/dist/{actions-iLXdgL5Y.js → actions-9QSQR-GB.js} +0 -0
  324. /package/dist/{actions-B2BJ4RTy.cjs → actions-DdGbj7c7.cjs} +0 -0
  325. /package/dist/{apply-vkey-witnesses-ZnFS0jnJ.cjs → apply-vkey-witnesses-CLzVSWxl.cjs} +0 -0
  326. /package/dist/{apply-vkey-witnesses-BKx3lcs0.js → apply-vkey-witnesses-ClZbpk5w.js} +0 -0
  327. /package/dist/{asyncoption-CruEYOBI.js → asyncoption-Cw07zPH7.js} +0 -0
  328. /package/dist/{asyncoption-i0VbqVTq.cjs → asyncoption-DYoGuQfP.cjs} +0 -0
  329. /package/dist/{bignum.vo-CEXOIew0.js → bignum.vo-B0rK_PQ1.js} +0 -0
  330. /package/dist/{bignum.vo-hx2kuqlA.cjs → bignum.vo-DsG3kNiZ.cjs} +0 -0
  331. /package/dist/{bip32ed25519-B7Yat217.cjs → bip32ed25519-1ApqeAZk.cjs} +0 -0
  332. /package/dist/{bip32ed25519-FQ8qvdcq.js → bip32ed25519-DetAdGwD.js} +0 -0
  333. /package/dist/{blake2b-DEeVUdKR.cjs → blake2b-B9tftbvG.cjs} +0 -0
  334. /package/dist/{blake2b-BiQTw3GC.js → blake2b-DOEVc57D.js} +0 -0
  335. /package/dist/{blockchain-network-id.vo-BAKEwGjG.cjs → blockchain-network-id.vo-BXpZhvvQ.cjs} +0 -0
  336. /package/dist/{blockchain-network-id.vo-CiVykuqG.js → blockchain-network-id.vo-DNRkuT5B.js} +0 -0
  337. /package/dist/{blockingWithLatestFrom-Cd8c8EPG.js → blockingWithLatestFrom-C5wp_uA-.js} +0 -0
  338. /package/dist/{blockingWithLatestFrom-D8kBPBMX.cjs → blockingWithLatestFrom-DY8OPg0w.cjs} +0 -0
  339. /package/dist/{cardano-network-id-to-network-type-C0ufJOyE.cjs → cardano-network-id-to-network-type-BDTF-HmK.cjs} +0 -0
  340. /package/dist/{cardano-network-id-to-network-type-BWwzeEtM.js → cardano-network-id-to-network-type-CrZfUcyP.js} +0 -0
  341. /package/dist/{cardano-tx-id.vo-D3ASTIMd.cjs → cardano-tx-id.vo-BPhV-AmZ.cjs} +0 -0
  342. /package/dist/{cardano-tx-id.vo-BXLo1b7Q.js → cardano-tx-id.vo-DF9NzZXk.js} +0 -0
  343. /package/dist/{composite-signer-factory-m5cVs9h_.cjs → composite-signer-factory-BpF1mIYA.cjs} +0 -0
  344. /package/dist/{composite-signer-factory-CR8YHA1y.js → composite-signer-factory-_46QsNBz.js} +0 -0
  345. /package/dist/{error-DIZOY2Lw.js → error-BCp9NkPi.js} +0 -0
  346. /package/dist/{error-Cb3EnD0u.cjs → error-CNIquqT5.cjs} +0 -0
  347. /package/dist/{esm-browser-MG97cre9.js → esm-browser-C93Q-EOI.js} +0 -0
  348. /package/dist/{esm-browser-bweqfBlL.cjs → esm-browser-DTc9IK3D.cjs} +0 -0
  349. /package/dist/{feature-flag-key.vo-RlfHL3hq.cjs → feature-flag-key.vo-BPz-ZAp6.cjs} +0 -0
  350. /package/dist/{feature-flag-key.vo-DN_-4-sG.js → feature-flag-key.vo-ofrB6ZVQ.js} +0 -0
  351. /package/dist/{first-state-of-status-unPynOuM.js → first-state-of-status-DQnMT3ya.js} +0 -0
  352. /package/dist/{first-state-of-status-CbT7hPa4.cjs → first-state-of-status-OROkXcRv.cjs} +0 -0
  353. /package/dist/{init-zUoRG_EC2.cjs → init-C5CEZ1m0.cjs} +0 -0
  354. /package/dist/{init-DHaMxHM1.js → init-CKipPE_c.js} +0 -0
  355. /package/dist/{init-Atisw4x2.cjs → init-DFQQ9dTW.cjs} +0 -0
  356. /package/dist/{init-829HRYcz.js → init-Es3wHW7D.js} +0 -0
  357. /package/dist/{init-BgNobbNq.cjs → init-IAk_CkGa.cjs} +0 -0
  358. /package/dist/{init-atCFur0v.js → init-cqN3uX2j.js} +0 -0
  359. /package/dist/{is-redux-persist-state-BCFnSm36.cjs → is-redux-persist-state-CTn3WZVh.cjs} +0 -0
  360. /package/dist/{is-redux-persist-state-yBfq0h_E.js → is-redux-persist-state-Cxcd0_bM.js} +0 -0
  361. /package/dist/{key-value-store--W3SrMaw.js → key-value-store-8cMzeNyG.js} +0 -0
  362. /package/dist/{key-value-store-C2Xt5Emp.cjs → key-value-store-DUAepXQf.cjs} +0 -0
  363. /package/dist/{repo-slice-RxFm0zDZ.js → repo-slice-DwyMhCR1.js} +0 -0
  364. /package/dist/{repo-slice-7X4AYYVm.cjs → repo-slice-WxetRhMY.cjs} +0 -0
  365. /package/dist/{reselect-CGoLzEPv.js → reselect-C06X06oX.js} +0 -0
  366. /package/dist/{reselect-Bd94u0K-.cjs → reselect-CRDqmQY9.cjs} +0 -0
  367. /package/dist/{serializable-BHdKIgk3.js → serializable-B8GahgE1.js} +0 -0
  368. /package/dist/{serializable-BxHkoPdk.cjs → serializable-CRdnFaLZ.cjs} +0 -0
  369. /package/dist/{slice-obCSLm1x.js → slice-B87b52iM.js} +0 -0
  370. /package/dist/{slice-Bk0Sv05J.js → slice-Be7hj4Iy.js} +0 -0
  371. /package/dist/{slice-BiRsDKOK.cjs → slice-D11FHQuQ.cjs} +0 -0
  372. /package/dist/{slice-Dqw1ecum.cjs → slice-FioKeHtA.cjs} +0 -0
  373. /package/dist/{src-Cqp0B2M_.cjs → src-BTPIvlDI.cjs} +0 -0
  374. /package/dist/{src-BlxEp6Mm.js → src-vq1wS9sZ.js} +0 -0
  375. /package/dist/{time.vo-D3wWRw9L.cjs → time.vo-CQ8pSXz2.cjs} +0 -0
  376. /package/dist/{time.vo-tNheinXm.js → time.vo-DkYYGYp6.js} +0 -0
  377. /package/dist/{toEmpty-8Zax1MPd.js → toEmpty-CgAl3097.js} +0 -0
  378. /package/dist/{toEmpty-CYAbupM4.cjs → toEmpty-DAMmNB5r.cjs} +0 -0
  379. /package/dist/{token-id.vo-DXv5uS9n.cjs → token-id.vo-BxG9TG0O.cjs} +0 -0
  380. /package/dist/{token-id.vo-Bvwhr3ZE.js → token-id.vo-ClsroxHO.js} +0 -0
  381. /package/dist/{util-CzeB3hfa.cjs → util-CmdAhheh.cjs} +0 -0
  382. /package/dist/{util-C8a4fA9p.js → util-DxzlYNS5.js} +0 -0
  383. /package/dist/{util-selector-BWPH68_l.cjs → util-selector-BcAncU4L.cjs} +0 -0
  384. /package/dist/{util-selector-BSTsxgne.js → util-selector-CcK-GAdE.js} +0 -0
  385. /package/dist/{while-active-B0lWy_6l.js → while-active-BpppWuCs.js} +0 -0
  386. /package/dist/{while-active-Dsowp0Fi.cjs → while-active-Dhc2LwOm.cjs} +0 -0
package/dist/midnight.js DELETED
@@ -1,1350 +0,0 @@
1
- import { r as __exportAll } from "./rolldown-runtime-OvD0k9op.js";
2
- import "./_web-crypto-random-bytes-Bo-GTcRS.js";
3
- import { n as import_buffer, r as init__polyfill_buffer_patch } from "./_polyfill-buffer-patch-yNxN4d5E.js";
4
- import "./libsodium-wrappers-BhbOA8dQ.js";
5
- import "./codecs-Dc1Krpbt.js";
6
- import "./util-D1e0skzp.js";
7
- import { t as ByteArray } from "./bytes.vo-BB7_4JK6.js";
8
- import { A as ContractName, C as walletRepoStoreContract, E as featureStoreContract, M as WalletId, O as combineStore, S as WalletType, T as failuresStoreContract, _ as walletActiveStateDependencyContract, a as createInMemoryWalletEntity, b as addressesStoreContract, c as createLaceWallet, i as createBlockchainWalletEntity, j as ModuleName, k as createMixin, l as signerFactoryAddonContract, n as sdk_default$1, o as inMemoryIntegrationAddonContract, r as sdk_default, s as AuthSecret, t as sdk_default$2, v as tokensStoreContract, w as networkStoreContract, x as activitiesStoreContract, y as syncStoreContract } from "./sdk-DIcjlgLF.js";
9
- import { s as Timestamp } from "./time.vo-tNheinXm.js";
10
- import { t as BigNumber } from "./bignum.vo-CEXOIew0.js";
11
- import { n as Ok, t as Err } from "./asyncoption-CruEYOBI.js";
12
- import { t as createPasskeyKeySource } from "./key-source-B08HukZg.js";
13
- import { a as inferStoreContext, i as inferModuleContext, n as combineContracts, r as inferContractContext } from "./store-DuBG8qh5.js";
14
- import { t as FEATURE_FLAG_NETWORK_TYPE } from "./const-CjmfjBP3.js";
15
- import { t as AccountId } from "./account-id.vo-OPz2v-JZ.js";
16
- import "./slice-DBpJ2QGf.js";
17
- import "./retry-config-Dmgt28wM.js";
18
- import { t as ActivityType } from "./activity-type-GsJGWs-3.js";
19
- import { t as TokenId } from "./token-id.vo-Bvwhr3ZE.js";
20
- import { c as MidnightSDKNetworkIds, d as NIGHT_TOKEN_ID, g as MidnightNetworkId, m as defaultTxTtlLength, s as MidnightSDKNetworkId, v as TEMENOS_PROOF_SERVER_MODES, y as assertProofServerRouting } from "./const-BfEnY8fg.js";
21
- import { t as MidnightAccountId } from "./midnight-account-id.vo-DjCAGcqc.js";
22
- import { i as midnightContextSelectors, n as midnightContextActions } from "./slice-BnTJeMOb.js";
23
- import { c as toUnshieldedTokenType, i as fromUnshieldedTokenType, s as isInMemoryMidnightAccount } from "./utils-CvAW5Yw7.js";
24
- import { a as AttestationError, d as FEATURE_FLAG_MIDNIGHT, l as createProvingProviderFromTransport, p as FEATURE_FLAG_MIDNIGHT_UNSHIELDED, t as midnightDustBalances } from "./watch-Z53L4yoK.js";
25
- import { ReplaySubject, catchError, combineLatest, concat, defaultIfEmpty, defer, distinctUntilChanged, filter, finalize, firstValueFrom, from, ignoreElements, map, of, scan, share, skipWhile, startWith, switchMap, take, tap, throwError, timeout, timer, withLatestFrom } from "rxjs";
26
- import { createAction } from "@reduxjs/toolkit";
27
- import { dummyLogger } from "ts-log";
28
- import { DustAddress, MidnightBech32m, ShieldedAddress, UnshieldedAddress } from "@midnightntwrk/wallet-sdk-address-format";
29
- import inRange from "lodash/inRange.js";
30
- import toLower from "lodash/toLower.js";
31
- import * as ledger from "@midnight-ntwrk/ledger-v8";
32
- import { addressFromKey } from "@midnight-ntwrk/ledger-v8";
33
- //#region src/create-midnight-accounts.ts
34
- /**
35
- * Derives a Midnight account index using the entity's encrypted recovery material.
36
- * Indexes must be integers in `[0, 2³¹)`. Omitted networks use the integration's
37
- * defaults. Rejects duplicate accounts, an entity with neither a Midnight
38
- * seed nor a recovery phrase (a passkey entity), unavailable integration and
39
- * decryption or derivation errors. Other blockchain accounts are preserved.
40
- *
41
- * Returns an updated entity without dispatching. For a new entity, dispatch
42
- * `wallets.addWallet`; for an existing one, dispatch `wallets.updateWallet`
43
- * with its updated `accounts` and `blockchainSpecific`.
44
- */
45
- const createMidnightAccounts = async (wallet, props) => {
46
- if (!Number.isInteger(props.accountIndex) || props.accountIndex < 0 || props.accountIndex >= 2 ** 31) throw new RangeError("Midnight account index must be an integer in [0, 2³¹)");
47
- if (!props.wallet.blockchainSpecific.Midnight?.encryptedSeed && !props.wallet.encryptedRecoveryPhrase) throw new Error("The entity holds no Midnight seed and no recovery phrase: derive the accounts of a passkey entity with createMidnightPasskeyWalletEntity({ accounts })");
48
- const integration = (await wallet._loadModules("addons.loadInMemoryWalletIntegration")).find((candidate) => candidate.blockchainName === "Midnight");
49
- if (!integration) throw new Error("Midnight integration is not loaded");
50
- const { wallet: updated } = await integration.addAccounts(props, { logger: dummyLogger });
51
- const accountIds = updated.accounts.map((account) => account.accountId);
52
- if (new Set(accountIds).size !== accountIds.length) throw new Error("Midnight account already exists");
53
- return updated;
54
- };
55
- //#endregion
56
- //#region ../../packages/contract/midnight-context/src/store/index.ts
57
- var store_default = inferStoreContext({
58
- load: async () => import("./init-KQnIdm39.js"),
59
- context: {
60
- actions: midnightContextActions,
61
- selectors: midnightContextSelectors
62
- }
63
- });
64
- //#endregion
65
- //#region ../../packages/contract/midnight-context/src/contract.ts
66
- const midnightContextStoreContract = inferContractContext({
67
- name: ContractName("midnight-context-store"),
68
- instance: "exactly-one",
69
- contractType: "store",
70
- dependsOn: combineContracts([networkStoreContract, featureStoreContract]),
71
- mixin: createMixin((laceModule) => ({ store: combineStore(laceModule, store_default) }))
72
- });
73
- const midnightDependencyContract = inferContractContext({
74
- contractType: "sideEffectDependency",
75
- name: ContractName("midnight-dependency"),
76
- instance: "exactly-one"
77
- });
78
- //#endregion
79
- //#region ../../packages/contract/midnight-context/src/midnight-engine-addon.ts
80
- /**
81
- * Engine access for code outside the store, such as the SDK's Midnight
82
- * helpers. Implemented by the headless Midnight engine module only.
83
- */
84
- const midnightEngineAddonContract = inferContractContext({
85
- name: ContractName("midnight-engine-addon"),
86
- instance: "exactly-one",
87
- contractType: "addon",
88
- provides: { addons: ["loadMidnightEngine"] }
89
- });
90
- //#endregion
91
- //#region ../../packages/contract/midnight-context/src/dust-utils.ts
92
- /**
93
- * Determines the designation target type based on NIGHT coin registration and dust balance.
94
- *
95
- * TODO: Update when SDK supports distinguishing self vs external designation.
96
- * Currently, the SDK's `registeredForDustGeneration` flag only indicates that NIGHT is
97
- * participating in dust generation, but does not specify the target dust address.
98
- * Until SDK provides this information, we treat all designation as 'self'.
99
- *
100
- * @returns 'self' when user has designation (registered NIGHT or dust balance), 'none' otherwise.
101
- * Note: 'external' is not returned until SDK supports proper detection.
102
- */
103
- const getDesignationTargetType = (coins, currentDustValue) => {
104
- return coins.some((coin) => coin.registeredForDustGeneration === true) || currentDustValue > 0n ? "self" : "none";
105
- };
106
- const TOKEN_FORBIDDEN_NAMES = [
107
- "dust",
108
- "lace",
109
- "midnight",
110
- "tdust",
111
- "night",
112
- "tnight"
113
- ];
114
- /** Checks reserved and additional excluded names case-insensitively; trim input first. */
115
- const isForbiddenTokenName = (name, extraExcludedTokenNames = []) => [...TOKEN_FORBIDDEN_NAMES, ...extraExcludedTokenNames.map(toLower)].includes(toLower(name));
116
- /** Checks case-insensitive display-name collisions; omit the current token from the list. */
117
- const isTakenTokenName = (name, takenTokenNames = []) => takenTokenNames.map(toLower).includes(toLower(name));
118
- const createTokenNameValidator = (minLength, maxLength) => (name, excludedNames = []) => {
119
- const isInvalidNameLength = !inRange(name.trim().length, minLength, maxLength + 1);
120
- return !(isForbiddenTokenName(name, excludedNames) || isInvalidNameLength);
121
- };
122
- /** Validates display-name length and reserved names; trim before validating and saving. */
123
- const isTokenFullNameValid = createTokenNameValidator(1, 30);
124
- /** Validates ticker length and reserved names; trim before validating and saving. */
125
- const isTokenShortNameValid = createTokenNameValidator(1, 4);
126
- /** Direct import of this is an anti-pattern. OK for tests. */
127
- const midnightSyncActions = { midnightSync: {
128
- requestResync: createAction("midnight/requestResync"),
129
- resync: createAction("midnight/resync"),
130
- restartWalletWatch: createAction("midnight/restartWalletWatch"),
131
- restartAccountWatch: createAction("midnight/restartAccountWatch")
132
- } };
133
- //#endregion
134
- //#region ../../packages/module/midnight-sync/src/store/prepare-midnight-tx.ts
135
- const constructDustDesignationTransaction = ({ address, networkId, nightUtxos, nightVerifyingKey, ttl = new Date(Date.now() + defaultTxTtlLength), allowFeePayment }) => {
136
- const parsedAddress = MidnightBech32m.parse(address);
137
- const receiverData = DustAddress.codec.decode(networkId, parsedAddress).data;
138
- const currentTime = /* @__PURE__ */ new Date();
139
- const intent = ledger.Intent.new(ttl);
140
- const totalNightValue = nightUtxos.map(({ utxo: { value } }) => BigNumber.valueOf(value)).reduce((total, value) => total + value, 0n);
141
- const inputs = nightUtxos.map(({ utxo }) => ({
142
- ...utxo,
143
- owner: nightVerifyingKey
144
- }));
145
- const outputs = inputs.map((input) => ({
146
- owner: ledger.addressFromKey(nightVerifyingKey),
147
- type: input.type,
148
- value: input.value
149
- }));
150
- intent.guaranteedUnshieldedOffer = ledger.UnshieldedOffer.new(inputs, outputs, []);
151
- const dustRegistration = new ledger.DustRegistration("signature", nightVerifyingKey, receiverData, allowFeePayment ?? totalNightValue);
152
- intent.dustActions = new ledger.DustActions("signature", "pre-proof", currentTime, [], [dustRegistration]);
153
- return ledger.Transaction.fromParts(networkId, void 0, void 0, intent);
154
- };
155
- const constructUnshieldedTransaction = ({ networkId, transfers, ttl = new Date(Date.now() + defaultTxTtlLength) }) => {
156
- const intent = ledger.Intent.new(ttl);
157
- const outputs = transfers.map(({ address, amount, tokenId }) => ({
158
- value: amount,
159
- owner: UnshieldedAddress.codec.decode(networkId, MidnightBech32m.parse(address)).data.toString("hex"),
160
- type: tokenId
161
- }));
162
- intent.guaranteedUnshieldedOffer = ledger.UnshieldedOffer.new([], outputs, []);
163
- return ledger.Transaction.fromParts(networkId, void 0, void 0, intent);
164
- };
165
- const constructShieldedTransaction = ({ networkId, transfers }) => {
166
- const toOffer = ({ address, amount, tokenId }) => {
167
- const decodedAddress = ShieldedAddress.codec.decode(networkId, MidnightBech32m.parse(address));
168
- const output = ledger.ZswapOutput.new(ledger.createShieldedCoinInfo(tokenId, amount), 0, decodedAddress.coinPublicKey.toHexString(), decodedAddress.encryptionPublicKey.toHexString());
169
- return ledger.ZswapOffer.fromOutput(output, tokenId, amount);
170
- };
171
- const [firstTransfer, ...remainingTransfers] = transfers;
172
- if (!firstTransfer) throw new Error("At least one token transfer is required");
173
- const offer = remainingTransfers.map(toOffer).reduce((merged, singleton) => merged.merge(singleton), toOffer(firstTransfer));
174
- return ledger.Transaction.fromParts(networkId, offer);
175
- };
176
- /** Normalize token-state IDs and reject a batch before any engine operation. */
177
- const normalizeMidnightTransfers = (networkId, kind, outputs) => {
178
- if (kind !== "shielded" && kind !== "unshielded") throw new Error("Unsupported Midnight transfer kind");
179
- if (outputs.length === 0) throw new Error("At least one token transfer is required");
180
- return outputs.map(({ to, tokenId, amount }) => {
181
- if (typeof amount !== "bigint" || amount <= 0n) throw new Error("Transfer amount must be a positive bigint");
182
- const prefix = `unshielded-${networkId}`;
183
- if (kind === "unshielded" && !tokenId.startsWith(prefix)) throw new Error("Unshielded token ID must match the transfer kind and network");
184
- const raw = kind === "unshielded" ? fromUnshieldedTokenType(tokenId, networkId) : tokenId;
185
- if (!/^[0-9a-f]{64}$/.test(raw)) throw new Error("Invalid token ID or token-kind mismatch");
186
- const parsed = MidnightBech32m.parse(to);
187
- if (kind === "shielded") ShieldedAddress.codec.decode(networkId, parsed);
188
- else UnshieldedAddress.codec.decode(networkId, parsed);
189
- return {
190
- address: to,
191
- tokenId: TokenId(raw),
192
- amount
193
- };
194
- });
195
- };
196
- /** Keep designation's zero-fee exception identical in headless and UI preparation. */
197
- const estimatePreparedMidnightFee = (wallet, tx, { isDustDesignation, dustBalance, areKeysAvailable }) => {
198
- if (isDustDesignation && dustBalance === 0n) return of(0n);
199
- return areKeysAvailable ? wallet.estimateTransactionFee(tx, { currentTime: /* @__PURE__ */ new Date() }) : wallet.calculateTransactionFee(tx);
200
- };
201
- //#endregion
202
- //#region ../../packages/lib/vendor/src/temenos-attested-prover.ts
203
- var TemenosAttestationError = class extends AttestationError {
204
- constructor(phase, checkId) {
205
- super("temenos", phase === "obtain-evidence" ? "evidence" : phase === "fetch-expected-values" ? "policy" : phase === "bind-channel" ? "channel" : "appraisal", checkId ? `Temenos attestation failed: check "${checkId}" of phase "${phase}"` : `Temenos attestation failed at phase "${phase}"`);
206
- this.phase = phase;
207
- this.checkId = checkId;
208
- this.name = "TemenosAttestationError";
209
- }
210
- };
211
- /**
212
- * `pointerContractAddress` is the one on-chain constant: the pointer's
213
- * `current` cell names the attestation ledger, so a ledger redeploy is a
214
- * pointer update, not a Lace release. All Temenos deployments register on the
215
- * single preprod pointer, whatever network the proof server serves, so this
216
- * stays on preprod on every network. The caller resolves the ledger
217
- * indexer from Lace configuration at the start of each attestation run.
218
- *
219
- * `wardenTlsCertificate` is empty by design: a browser context cannot pin
220
- * the transport certificate, so the Warden is reached over public WebPKI
221
- * TLS — its verdict is defense-in-depth on top of the local checks, not a
222
- * trust root.
223
- */
224
- const SHARED_TEMENOS_DEPLOYMENT = {
225
- pointerContractAddress: "a58974f1cacda177edfea3bdc76c1cd48d5e3107b9a543b9d65cee6b454c9122",
226
- wardenUrl: "https://warden.wastedp.io",
227
- wardenTlsCertificate: ""
228
- };
229
- const TEMENOS_PREPROD_DEPLOYMENT = {
230
- ...SHARED_TEMENOS_DEPLOYMENT,
231
- proofServerApiUrl: "https://api.proofserver.wastedp.io",
232
- attestationHost: "attestation.proofserver.wastedp.io",
233
- akxServerUrl: "https://attestation.proofserver.wastedp.io/tee_attestation",
234
- applicationId: "afe48970b7083e1b2855acce95a488e93a7c257a34f6275e77ac26f79ac7ad05"
235
- };
236
- /**
237
- * Attestation parameters per network, matching `TEMENOS_PROOF_SERVER_MODES`
238
- * entry for entry. Values are build-baked and reviewed like code; the
239
- * persisted mode carries only the URL, so nothing here can be injected via
240
- * feature-flag payloads.
241
- */
242
- const TEMENOS_ATTESTATION_CONFIGS = {
243
- mainnet: {
244
- ...SHARED_TEMENOS_DEPLOYMENT,
245
- proofServerApiUrl: "https://api.proofserver.mainnet.wastedp.io",
246
- attestationHost: "attestation.proofserver.mainnet.wastedp.io",
247
- akxServerUrl: "https://attestation.proofserver.mainnet.wastedp.io/tee_attestation",
248
- applicationId: "70402462424c122c65e2d3d2312757face3974940c9ac5d09249b61028350427"
249
- },
250
- preprod: TEMENOS_PREPROD_DEPLOYMENT,
251
- preview: {
252
- ...SHARED_TEMENOS_DEPLOYMENT,
253
- proofServerApiUrl: "https://api.proofserver.preview.wastedp.io",
254
- attestationHost: "attestation.proofserver.preview.wastedp.io",
255
- akxServerUrl: "https://attestation.proofserver.preview.wastedp.io/tee_attestation",
256
- applicationId: "b294b8879607f7d0f5cca3808a4b64aab7992de2a73d1e55dbafb091efca25f2"
257
- }
258
- };
259
- for (const [networkId, mode] of Object.entries(TEMENOS_PROOF_SERVER_MODES)) {
260
- if (!mode) continue;
261
- if (TEMENOS_ATTESTATION_CONFIGS[networkId]?.proofServerApiUrl !== mode.url) throw new Error(`TEMENOS_PROOF_SERVER_MODES[${networkId}] ("${mode.url}") has no matching entry in TEMENOS_ATTESTATION_CONFIGS`);
262
- }
263
- /** temenos-spec phases 1–5 of the AKX flow, in execution order. */
264
- const TEMENOS_ATTESTATION_PHASES = [
265
- "obtain-evidence",
266
- "fetch-expected-values",
267
- "verify-locally",
268
- "warden-verify",
269
- "bind-channel"
270
- ];
271
- const PHASE_MAP = {
272
- "obtain-evidence": "obtain-evidence",
273
- "fetch-expected-values": "fetch-expected-values",
274
- "verify-locally": "verify-locally",
275
- "warden-verify": "warden-verify",
276
- "bind-channel": "bind-channel"
277
- };
278
- /**
279
- * `nonce-freshness` belongs to the library's SPKI-pin flow, which Lace never
280
- * runs (the AKX evidence provider always yields epoch-key evidence) — it has
281
- * no contract ID, so its events are dropped rather than mislabeled.
282
- */
283
- const mapCheckId = (id) => id === "nonce-freshness" ? void 0 : id;
284
- const mapPhaseEvent = (event) => {
285
- if (event.status === "check") {
286
- const id = mapCheckId(event.check.id);
287
- if (!id) return void 0;
288
- return {
289
- type: "check",
290
- check: {
291
- id,
292
- status: event.check.status,
293
- detail: event.check.detail
294
- }
295
- };
296
- }
297
- if (event.phase === "prove") return void 0;
298
- const phase = PHASE_MAP[event.phase];
299
- switch (event.status) {
300
- case "started": return {
301
- type: "phase",
302
- phase,
303
- status: "started"
304
- };
305
- case "completed": return {
306
- type: "phase",
307
- phase,
308
- status: "completed",
309
- ...event.detail === void 0 ? {} : { detail: event.detail }
310
- };
311
- case "failed": return {
312
- type: "phase",
313
- phase,
314
- status: "failed",
315
- detail: event.error.message
316
- };
317
- }
318
- };
319
- const toTemenosAttestationError = (error, fallbackPhase, { LocalCheckFailedError, AttestationVerificationError }) => {
320
- const mapped = error instanceof LocalCheckFailedError ? new TemenosAttestationError("verify-locally", mapCheckId(error.checkId)) : error instanceof AttestationVerificationError ? new TemenosAttestationError(error.phase === "prove" ? fallbackPhase : PHASE_MAP[error.phase]) : new TemenosAttestationError(fallbackPhase);
321
- mapped.cause = error;
322
- return mapped;
323
- };
324
- /**
325
- * `/prove` payloads travel as AEAD records tunneled through the AKX channel.
326
- * The enclave proxy forwards to `/prove` only, so the session offers nothing
327
- * else: the public API endpoint is never contacted from this flow.
328
- */
329
- const createTunneledSession = (session) => ({
330
- prove: async (payload) => {
331
- const response = await session.prove({ body: payload });
332
- if (response.status !== 200) throw new Error(`Proof server returned ${response.status} through the attested channel`);
333
- return response.body;
334
- },
335
- close: async () => session.close()
336
- });
337
- /**
338
- * {@link createTemenosAttestedProver} with a deployment override that replaces
339
- * the baked deployment and skips its proof-server URL match. No public entry
340
- * re-exports it; only tests driving the verifier library's mock fixtures pass
341
- * the override.
342
- *
343
- * @internal
344
- */
345
- const createTemenosAttestedProverWith = ({ networkId, proofServerApiUrl, trustRoots, getLedgerIndexerUrl, verifier }, testSeam) => {
346
- const baked = TEMENOS_ATTESTATION_CONFIGS[networkId];
347
- const deployment = testSeam?.config ?? (baked?.proofServerApiUrl === proofServerApiUrl ? baked : void 0);
348
- if (!deployment) throw new Error(`No baked Temenos attestation config on ${networkId} for proof server "${proofServerApiUrl}"`);
349
- if (!trustRoots?.amdRootCertificates?.length || trustRoots.amdRootCertificates.some((root) => root.trim().length === 0)) throw new AttestationError("temenos", "policy", "Temenos requires explicit AMD trust roots");
350
- const amdRootCertificates = [...trustRoots.amdRootCertificates];
351
- return {
352
- id: "temenos",
353
- operations: ["prove"],
354
- phases: TEMENOS_ATTESTATION_PHASES,
355
- establishAttestedSession: async (onEvent) => {
356
- const config = {
357
- ...deployment,
358
- amdRootCertificates,
359
- indexerUrl: await getLedgerIndexerUrl()
360
- };
361
- const operationVerifier = verifier.createVerifier(config);
362
- let currentPhase = "obtain-evidence";
363
- try {
364
- return createTunneledSession(await operationVerifier.establishVerifiedSession((event) => {
365
- if (event.status === "started" && event.phase !== "prove") currentPhase = PHASE_MAP[event.phase];
366
- const mapped = mapPhaseEvent(event);
367
- if (mapped) onEvent(mapped);
368
- }));
369
- } catch (error) {
370
- throw toTemenosAttestationError(error, currentPhase, verifier);
371
- }
372
- }
373
- };
374
- };
375
- /**
376
- * The real Temenos attestation driver: runs the verifier library's full
377
- * pipeline — evidence from `GET /enclave-key`, expected values from the
378
- * on-chain registration via the indexer, the nine local checks against
379
- * explicitly supplied AMD roots, Warden verification, and the AKX
380
- * attested-channel handshake — then hands back a session that tunnels
381
- * through that channel. Trust-root sourcing is separate from this adapter.
382
- * Only the deployment baked for `networkId` is accepted, and only
383
- * when `proofServerApiUrl` names its proof server.
384
- */
385
- const createTemenosAttestedProver = (props) => createTemenosAttestedProverWith(props);
386
- //#endregion
387
- //#region ../../packages/module/midnight-sync/src/sdk.ts
388
- const createMidnightSyncModule = (options) => inferModuleContext({
389
- moduleName: ModuleName("midnight-sync"),
390
- implements: combineContracts([
391
- inMemoryIntegrationAddonContract,
392
- tokensStoreContract,
393
- syncStoreContract,
394
- addressesStoreContract,
395
- midnightContextStoreContract,
396
- midnightDependencyContract,
397
- midnightEngineAddonContract,
398
- signerFactoryAddonContract
399
- ]),
400
- dependsOn: combineContracts([
401
- activitiesStoreContract,
402
- failuresStoreContract,
403
- featureStoreContract,
404
- networkStoreContract,
405
- walletActiveStateDependencyContract,
406
- walletRepoStoreContract
407
- ]),
408
- feature: {
409
- willLoad: (featureFlags) => featureFlags.some((flag) => flag.key === FEATURE_FLAG_MIDNIGHT),
410
- metadata: {
411
- name: "MidnightSync",
412
- description: "Midnight engine, wallet lifecycle and signer"
413
- }
414
- },
415
- store: inferStoreContext({
416
- load: async () => {
417
- const { createSdkStoreInit } = await import("./sdk-init-DNd-oQXp.js");
418
- return { default: createSdkStoreInit(options) };
419
- },
420
- context: {
421
- actions: midnightSyncActions,
422
- selectors: {}
423
- }
424
- }),
425
- addons: {
426
- loadSignerFactory: async () => import("./signer-factory-Cd2TwD50.js"),
427
- loadMidnightEngine: async () => import("./midnight-engine-DpemplKO.js"),
428
- loadInMemoryWalletIntegration: async () => import("./in-memory-wallet-integration-CUKesGG1.js").then((module) => ({ default: module.inMemoryWalletIntegrationReactNative }))
429
- }
430
- });
431
- //#endregion
432
- //#region src/midnight-module.ts
433
- const publicEndpoints = (networkId) => ({
434
- nodeAddress: `https://rpc.${networkId}.midnight.network`,
435
- indexerAddress: `https://indexer.${networkId}.midnight.network/api/v4/graphql`
436
- });
437
- /**
438
- * The public Midnight endpoints the SDK syncs through by default. Every other
439
- * network needs its endpoints from `networks` before `selectMidnightNetwork`
440
- * accepts it.
441
- */
442
- const MIDNIGHT_PUBLIC_ENDPOINTS = {
443
- [MidnightSDKNetworkIds.MainNet]: publicEndpoints(MidnightSDKNetworkIds.MainNet),
444
- [MidnightSDKNetworkIds.PreProd]: publicEndpoints(MidnightSDKNetworkIds.PreProd),
445
- [MidnightSDKNetworkIds.Preview]: publicEndpoints(MidnightSDKNetworkIds.Preview),
446
- [MidnightSDKNetworkIds.QaNet]: publicEndpoints(MidnightSDKNetworkIds.QaNet)
447
- };
448
- /** The public node of Midnight Preview. */
449
- const MIDNIGHT_PREVIEW_NODE_URL = MIDNIGHT_PUBLIC_ENDPOINTS[MidnightSDKNetworkIds.Preview].nodeAddress;
450
- /** The public indexer of Midnight Preview. */
451
- const MIDNIGHT_PREVIEW_INDEXER_URL = MIDNIGHT_PUBLIC_ENDPOINTS[MidnightSDKNetworkIds.Preview].indexerAddress;
452
- /** A proof server on the consumer's own machine, the default prover. */
453
- const MIDNIGHT_LOCAL_PROOF_SERVER_URL = "http://localhost:6300";
454
- const isPublicNetworkId = (networkId) => networkId in MIDNIGHT_PUBLIC_ENDPOINTS;
455
- const passwordAuth = (password) => {
456
- const owned = ByteArray.clone(ByteArray(password));
457
- return {
458
- authenticate: () => of(true),
459
- accessAuthSecret: (callback) => {
460
- const clone = AuthSecret(ByteArray.clone(owned));
461
- return callback(clone).pipe(tap(() => clone.fill(0)), finalize(() => clone.fill(0)));
462
- }
463
- };
464
- };
465
- const proofServerMode = (url) => {
466
- const { hostname } = new URL(url);
467
- return hostname === "localhost" || hostname === "127.0.0.1" ? {
468
- kind: "local-host",
469
- url
470
- } : {
471
- kind: "delegated",
472
- url,
473
- label: hostname
474
- };
475
- };
476
- const defaultProofServers = (proofServerUrl, networks, createAttestedProver) => Object.fromEntries(MidnightSDKNetworkId.map((networkId) => {
477
- const mode = networks[networkId]?.proofServer ?? proofServerMode(proofServerUrl);
478
- assertProofServerRouting(mode, !!createAttestedProver);
479
- return [networkId, mode];
480
- }));
481
- const networkOverrides = (networks) => Object.fromEntries(MidnightSDKNetworkId.map((networkId) => {
482
- const { proofServer: _, ...endpoints } = networks[networkId] ?? {};
483
- return [networkId, {
484
- ...isPublicNetworkId(networkId) && MIDNIGHT_PUBLIC_ENDPOINTS[networkId],
485
- ...endpoints
486
- }];
487
- }));
488
- /** The networks whose overrides carry both endpoints; the contract defaults are not served. */
489
- const supportedNetworkIds = (overrides) => MidnightSDKNetworkId.filter((networkId) => overrides[networkId]?.nodeAddress !== void 0 && overrides[networkId]?.indexerAddress !== void 0);
490
- /**
491
- * The Midnight engine for `createLaceWallet`: syncs every in-memory Midnight
492
- * account on the active network, persists its state through the loaded
493
- * storage module and signs with the password instead of a prompt. Loads
494
- * behind `FEATURE_FLAG_MIDNIGHT`. The password is copied here, but the
495
- * caller's buffer must stay intact until its last entity helper call that
496
- * takes the same bytes.
497
- *
498
- * The `config` of `createLaceWallet` must then set
499
- * `defaultMidnightTestnetNetworkId`, the testnet a wallet starts on, as
500
- * Cardano needs `defaultTestnetChainId`; without a testnet there,
501
- * `createLaceWallet` rejects.
502
- */
503
- const createMidnightModule = ({ password, proofServerUrl = MIDNIGHT_LOCAL_PROOF_SERVER_URL, networks = {}, batchUpdates, createAttestedProver }) => {
504
- const overrides = networkOverrides(networks);
505
- return createMidnightSyncModule({
506
- auth: passwordAuth(password),
507
- networks: overrides,
508
- supportedNetworkIds: supportedNetworkIds(overrides),
509
- defaultProofServers: defaultProofServers(proofServerUrl, networks, createAttestedProver),
510
- batchUpdates,
511
- createAttestedProver
512
- });
513
- };
514
- //#endregion
515
- //#region src/midnight-passkey-wallet-entity.ts
516
- /**
517
- * Derives the Midnight accounts of the passkey's words inside one assertion.
518
- * Unlike the Cardano passkey entity, the result is an `InMemory` wallet: the
519
- * Midnight engine needs the account keys while it syncs, so each account
520
- * holds its keys sealed under `password`. The entity holds no recovery
521
- * phrase and no seed, and no account of another blockchain.
522
- */
523
- const createMidnightPasskeyWalletEntity = async (wallet, { keySource, password, walletName, accounts = [] }) => keySource.withPasskeyMnemonic(async (words) => {
524
- let entity = await createBlockchainWalletEntity(wallet, "Midnight", {
525
- mnemonicWords: [...words],
526
- password,
527
- walletName
528
- });
529
- if (entity.accounts.length === 0) throw new Error("No Midnight account derived: load createMidnightModule behind FEATURE_FLAG_MIDNIGHT");
530
- for (const account of accounts) entity = await createMidnightAccounts(wallet, {
531
- ...account,
532
- wallet: entity,
533
- password
534
- });
535
- return withoutSeedMaterial(entity);
536
- });
537
- const withoutSeedMaterial = ({ encryptedRecoveryPhrase: _phrase, blockchainSpecific: { Midnight: _seed, ...blockchainSpecific }, ...entity }) => ({
538
- ...entity,
539
- blockchainSpecific
540
- });
541
- //#endregion
542
- //#region src/midnight-errors.ts
543
- /** The loadout has no endpoints for the network: none public, none from `networks`. */
544
- var MidnightNetworkNotConfiguredError = class extends Error {
545
- code = "midnight-network-not-configured";
546
- constructor(networkId) {
547
- super(`Midnight network "${networkId}" has no endpoints in this loadout: pass networks.${networkId} with nodeAddress and indexerAddress to createMidnightModule`);
548
- this.name = "MidnightNetworkNotConfiguredError";
549
- }
550
- };
551
- /** No single in-memory Midnight account on the active network answers the request. */
552
- var MidnightAccountNotFoundError = class extends Error {
553
- code = "midnight-account-not-found";
554
- constructor(message) {
555
- super(message);
556
- this.name = "MidnightAccountNotFoundError";
557
- }
558
- };
559
- /** The engine did not start the account's wallets within the wait. */
560
- var MidnightWalletNotReadyError = class extends Error {
561
- code = "midnight-wallet-not-ready";
562
- constructor(accountId, timeoutMs) {
563
- super(`Midnight wallet for account "${accountId}" did not start within ${timeoutMs}ms`);
564
- this.name = "MidnightWalletNotReadyError";
565
- }
566
- };
567
- /** The account holds no available NIGHT to register for DUST generation. */
568
- var MidnightNothingToRegisterError = class extends Error {
569
- code = "midnight-nothing-to-register";
570
- constructor(accountId) {
571
- super(`Account "${accountId}" has no available NIGHT to register`);
572
- this.name = "MidnightNothingToRegisterError";
573
- }
574
- };
575
- /**
576
- * `submitMidnightTx` stopped waiting for the node to report the transaction final. The engine had already been
577
- * given the transaction, so it may be on chain or reach it later: look for `activityHash` in the account's
578
- * activities before submitting again.
579
- */
580
- var MidnightSubmitTimeoutError = class extends Error {
581
- code = "midnight-submit-timeout";
582
- /** The transaction's hash, which is the `activityId` of its activity. */
583
- activityHash;
584
- constructor(activityHash, timeoutMs) {
585
- super(`Midnight transaction ${activityHash} was not reported final within ${timeoutMs}ms and may still reach the chain`);
586
- this.name = "MidnightSubmitTimeoutError";
587
- this.activityHash = activityHash;
588
- }
589
- };
590
- //#endregion
591
- //#region src/select-midnight-network.ts
592
- /**
593
- * Makes `networkId` the active Midnight network. A testnet also becomes the
594
- * selected testnet, so the wallet's testnet toggle returns to it. Throws
595
- * `MidnightNetworkNotConfiguredError` for a network the loadout has no
596
- * endpoints for: one outside `MIDNIGHT_PUBLIC_ENDPOINTS` whose `networks`
597
- * override lacks `nodeAddress` or `indexerAddress`.
598
- */
599
- const selectMidnightNetwork = (wallet, networkId) => {
600
- if (!(wallet.getState().midnightContext?.supportedNetworksIds ?? []).includes(networkId)) throw new MidnightNetworkNotConfiguredError(networkId);
601
- if (networkId === MidnightSDKNetworkIds.MainNet) {
602
- wallet.dispatch("network.setNetworkType", "mainnet");
603
- return;
604
- }
605
- wallet.dispatch("network.setBlockchainNetworks", {
606
- blockchain: "Midnight",
607
- mainnet: MidnightNetworkId(MidnightSDKNetworkIds.MainNet),
608
- testnet: MidnightNetworkId(networkId)
609
- });
610
- wallet.dispatch("network.setNetworkType", "testnet");
611
- };
612
- //#endregion
613
- //#region src/midnight-timeouts.ts
614
- /** The longest delay a timer honours; a longer one, or `Infinity`, fires at once. */
615
- const MAX_TIMEOUT_MS = 2 ** 31 - 1;
616
- /**
617
- * Applies a timeout option's default and refuses a value no timer can honour:
618
- * not a finite positive number of milliseconds, or above `MAX_TIMEOUT_MS`.
619
- */
620
- const resolveTimeoutMs = (name, value, fallback) => {
621
- const resolved = value ?? fallback;
622
- if (typeof resolved !== "number" || !Number.isFinite(resolved) || resolved <= 0 || resolved > MAX_TIMEOUT_MS) throw new RangeError(`${name} must be a positive number of milliseconds up to ${MAX_TIMEOUT_MS}; got ${String(resolved)}`);
623
- return resolved;
624
- };
625
- //#endregion
626
- //#region src/midnight-wallet.ts
627
- const DEFAULT_START_TIMEOUT_MS = 12e4;
628
- const resolveMidnightAccountId = async ({ stateObservables }, requestedAccountId) => {
629
- const wallets = await firstValueFrom(stateObservables.wallets.selectAll$);
630
- const activeNetworkIds = await firstValueFrom(stateObservables.network.selectAllActiveNetworkIds$);
631
- const accounts = wallets.flatMap((wallet) => wallet.accounts).filter(isInMemoryMidnightAccount).filter((account) => activeNetworkIds.includes(account.blockchainNetworkId));
632
- if (requestedAccountId) {
633
- const found = accounts.find((account) => account.accountId === requestedAccountId);
634
- if (!found) throw new MidnightAccountNotFoundError(`Midnight account "${requestedAccountId}" not found on the active network`);
635
- return found.accountId;
636
- }
637
- if (accounts.length === 0) throw new MidnightAccountNotFoundError("No Midnight accounts found on the active network");
638
- if (accounts.length > 1) throw new MidnightAccountNotFoundError(`Multiple Midnight accounts found (${accounts.length}) — specify accountId to disambiguate`);
639
- return accounts[0].accountId;
640
- };
641
- /**
642
- * The engine's wallet for the account, emitted once the engine starts it and
643
- * again whenever the engine replaces it (a sync reset or a restart). Emits
644
- * `undefined` while the engine has stopped the account's wallet and not yet
645
- * replaced it. Resolves the account on subscription and errors with
646
- * `MidnightAccountNotFoundError`, or with `MidnightWalletNotReadyError` when
647
- * no wallet arrives within `startTimeout`, at first or after a stop, so a
648
- * subscriber that was already watching fails the same way a new one would.
649
- */
650
- const observeMidnightWallet = (wallet, { accountId, startTimeout: requestedStartTimeout }) => defer(async () => {
651
- const startTimeout = resolveTimeoutMs("startTimeout", requestedStartTimeout, DEFAULT_START_TIMEOUT_MS);
652
- const resolvedAccountId = await resolveMidnightAccountId(wallet, accountId);
653
- const [registry$] = await wallet._loadModules("addons.loadMidnightEngine");
654
- if (!registry$) throw new MidnightWalletNotReadyError(resolvedAccountId, startTimeout);
655
- return {
656
- resolvedAccountId,
657
- registry$,
658
- startTimeout
659
- };
660
- }).pipe(switchMap(({ resolvedAccountId, registry$, startTimeout }) => {
661
- const notReady = () => throwError(() => new MidnightWalletNotReadyError(resolvedAccountId, startTimeout));
662
- return registry$.pipe(map((wallets) => wallets[resolvedAccountId]), distinctUntilChanged(), skipWhile((candidate) => !candidate), timeout({
663
- first: startTimeout,
664
- with: notReady
665
- }), switchMap((candidate) => candidate ? of(candidate) : concat(of(void 0), timer(startTimeout).pipe(switchMap(notReady)))));
666
- }));
667
- /** The engine's wallet for the account, once the engine has started it. */
668
- const midnightWalletFor = async (wallet, props) => firstValueFrom(observeMidnightWallet(wallet, props).pipe(filter((candidate) => !!candidate)));
669
- const toError = (error) => error instanceof Error ? error : new Error(String(error));
670
- /** Runs one engine operation for the account and settles it as a `Result`. */
671
- const withMidnightWallet = async (wallet, props, operation) => {
672
- try {
673
- return Ok(await firstValueFrom(operation(await midnightWalletFor(wallet, props))));
674
- } catch (error) {
675
- return Err(toError(error));
676
- }
677
- };
678
- //#endregion
679
- //#region src/observe-midnight-balances.ts
680
- const sumNight = (coins) => coins.filter(({ utxo }) => utxo.type === NIGHT_TOKEN_ID).reduce((sum, { utxo }) => sum + utxo.value, 0n);
681
- const sameBalances = (a, b) => a.address.unshielded === b.address.unshielded && a.night.available === b.night.available && a.night.pending === b.night.pending && a.dust.balance === b.dust.balance && a.dust.available === b.dust.available && a.synced.unshielded === b.synced.unshielded && a.synced.shielded === b.synced.shielded && a.synced.dust === b.synced.dust;
682
- const NOT_SYNCED = {
683
- unshielded: false,
684
- shielded: false,
685
- dust: false
686
- };
687
- const balancesOf = (midnightWallet) => combineLatest([
688
- midnightWallet.state(),
689
- midnightWallet.syncProgress$,
690
- midnightWallet.address$
691
- ]).pipe(map(([state, progress, address]) => ({
692
- accountId: midnightWallet.accountId,
693
- address,
694
- night: {
695
- available: sumNight(state.unshielded.availableCoins),
696
- pending: sumNight(state.unshielded.pendingCoins)
697
- },
698
- dust: midnightDustBalances(state),
699
- synced: progress.isStrictlyComplete
700
- })));
701
- /**
702
- * The account's NIGHT and DUST, straight from the engine, from the moment
703
- * it starts the account's wallets. Balances are complete once `synced`
704
- * reports the sub-wallet caught up; a transfer needs unshielded and dust.
705
- * NIGHT is summed from the engine's state, not from the store's token
706
- * balances; DUST is summed as the store sums it.
707
- *
708
- * Follows the engine across a sync reset or restart. While the engine has
709
- * stopped the account's wallets and not yet replaced them, it repeats the
710
- * last balances with every `synced` flag false; once the new wallets start,
711
- * it emits theirs.
712
- *
713
- * Cold: the account is resolved on subscription. Errors the subscriber with
714
- * `MidnightAccountNotFoundError`, or with `MidnightWalletNotReadyError` when
715
- * no wallets run for `startTimeout`, at first or after a stop.
716
- */
717
- const observeMidnightBalances = (wallet, props = {}) => observeMidnightWallet(wallet, props).pipe(switchMap((midnightWallet) => midnightWallet ? balancesOf(midnightWallet) : of(void 0)), scan((last, next) => next ?? (last && {
718
- ...last,
719
- synced: NOT_SYNCED
720
- }), void 0), filter((balances) => !!balances), distinctUntilChanged(sameBalances));
721
- //#endregion
722
- //#region src/balance-midnight-recipe.ts
723
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
724
- /**
725
- * Releases a recipe the engine built, then rethrows the error that made it
726
- * useless. The engine reserves a recipe's inputs when it builds it and the
727
- * caller never receives this recipe, so nothing else could release them. If
728
- * the release fails too, the error is an `AggregateError` of both failures and
729
- * the coins stay reserved until a sync reset.
730
- */
731
- const releaseThenThrow = (midnightWallet, recipe, error) => concat(midnightWallet.revert(recipe).pipe(ignoreElements(), catchError((releaseError) => throwError(() => new AggregateError([error, releaseError], `${messageOf(error)}; the coins it reserved could not be released: ${messageOf(releaseError)}`)))), throwError(() => error));
732
- /**
733
- * Pays a built recipe's fee with DUST. The engine books the recipe's inputs
734
- * when it builds it, so a failure here releases them before the error is
735
- * returned: the caller has no recipe to discard.
736
- */
737
- const balanceMidnightRecipe = (midnightWallet, recipe, ttl) => midnightWallet.balanceUnprovenTransaction(recipe.transaction, {
738
- ttl,
739
- tokenKindsToBalance: ["dust"]
740
- }).pipe(catchError((balancingError) => releaseThenThrow(midnightWallet, recipe, balancingError)));
741
- //#endregion
742
- //#region src/build-midnight-transfer.ts
743
- /**
744
- * Builds an unshielded NIGHT transfer, selecting the inputs and the DUST
745
- * that pays its fee. The recipe is unsigned and unproven, and reserves its
746
- * inputs (see `MidnightTxRecipe`): obtain consent from `estimateMidnightFee`,
747
- * which reserves nothing, before building. When the fee cannot be paid, the
748
- * inputs the build reserved are released and the balancing error is returned;
749
- * if that release fails too, the error is an `AggregateError` of both failures
750
- * and the NIGHT stays reserved until a sync reset.
751
- */
752
- const buildMidnightTransfer = async (wallet, { to, amount, ttl, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => defer(() => {
753
- normalizeMidnightTransfers(midnightWallet.networkId, "unshielded", [{
754
- to,
755
- amount,
756
- tokenId: toUnshieldedTokenType(NIGHT_TOKEN_ID, midnightWallet.networkId)
757
- }]);
758
- const resolvedTtl = ttl ?? new Date(Date.now() + 36e5);
759
- return midnightWallet.transferTransaction([{
760
- type: "unshielded",
761
- outputs: [{
762
- type: NIGHT_TOKEN_ID,
763
- receiverAddress: UnshieldedAddress.codec.decode(midnightWallet.networkId, MidnightBech32m.parse(to)),
764
- amount
765
- }]
766
- }], {
767
- ttl: resolvedTtl,
768
- payFees: false
769
- }).pipe(switchMap((recipe) => balanceMidnightRecipe(midnightWallet, recipe, resolvedTtl)));
770
- }));
771
- //#endregion
772
- //#region src/build-midnight-transfers.ts
773
- /**
774
- * Builds an unsigned, unproven batch. The engine selects tokens and fee DUST
775
- * and reserves them (see `MidnightTxRecipe`): obtain consent from
776
- * `estimateMidnightFee`, which reserves nothing, before building. When the
777
- * fee cannot be paid, the inputs the build reserved are released and the
778
- * balancing error is returned; if that release fails too, the error is an
779
- * `AggregateError` of both failures and the coins stay reserved until a sync
780
- * reset.
781
- */
782
- const buildMidnightTransfers = async (wallet, { kind, outputs, ttl, ...account }) => withMidnightWallet(wallet, account, (engine) => defer(() => {
783
- const transfers = normalizeMidnightTransfers(engine.networkId, kind, outputs);
784
- const desiredOutputs = kind === "shielded" ? {
785
- type: "shielded",
786
- outputs: transfers.map(({ address, tokenId, amount }) => ({
787
- type: tokenId,
788
- amount,
789
- receiverAddress: ShieldedAddress.codec.decode(engine.networkId, MidnightBech32m.parse(address))
790
- }))
791
- } : {
792
- type: "unshielded",
793
- outputs: transfers.map(({ address, tokenId, amount }) => ({
794
- type: tokenId,
795
- amount,
796
- receiverAddress: UnshieldedAddress.codec.decode(engine.networkId, MidnightBech32m.parse(address))
797
- }))
798
- };
799
- const resolvedTtl = ttl ?? new Date(Date.now() + 36e5);
800
- return engine.transferTransaction([desiredOutputs], {
801
- ttl: resolvedTtl,
802
- payFees: false
803
- }).pipe(switchMap((recipe) => balanceMidnightRecipe(engine, recipe, resolvedTtl)));
804
- }));
805
- //#endregion
806
- //#region src/register-midnight-dust.ts
807
- /**
808
- * Whether the account already takes part in DUST generation: registered
809
- * NIGHT, generated DUST, or generation capacity (the contract's
810
- * `getDesignationTargetType` plus capacity). The engine does not report where
811
- * registered NIGHT generates, so this covers a designation to the account's
812
- * own address and to an external one alike.
813
- */
814
- const isDesignatedForDust = (state, nightCoins) => getDesignationTargetType(nightCoins.map(({ utxo, meta }) => ({
815
- status: "available",
816
- value: BigNumber(utxo.value),
817
- registeredForDustGeneration: meta.registeredForDustGeneration
818
- })), state.dust.totalCoins.reduce((sum, coin) => sum + coin.generatedNow, 0n)) !== "none" || state.dust.totalCoins.some((coin) => coin.maxCap > 0n);
819
- /** Internal unsigned selection shared with fee estimation. */
820
- const prepareMidnightDustRegistration = (midnightWallet, { dustAddress: destination, ttl }) => combineLatest([midnightWallet.state().pipe(take(1)), midnightWallet.address$.pipe(take(1))]).pipe(map(([state, address]) => {
821
- if (ttl !== void 0) throw new Error("A DUST registration does not accept ttl: the engine sets its validity window");
822
- const nightCoins = state.unshielded.availableCoins.filter(({ utxo }) => utxo.type === NIGHT_TOKEN_ID);
823
- if (nightCoins.length === 0 || nightCoins.every(({ utxo }) => utxo.value <= 0n)) throw new MidnightNothingToRegisterError(midnightWallet.accountId);
824
- const dustAddress = DustAddress.codec.decode(midnightWallet.networkId, MidnightBech32m.parse(destination ?? address.dust));
825
- if (destination !== void 0 && isDesignatedForDust(state, nightCoins)) throw new Error("DUST destination cannot be changed while the account is designated for DUST generation");
826
- return {
827
- state,
828
- nightCoins,
829
- dustAddress,
830
- destination: destination ?? address.dust,
831
- isRepeatRegistration: nightCoins.some((coin) => coin.meta.registeredForDustGeneration)
832
- };
833
- }));
834
- /**
835
- * Registers every available NIGHT UTXO. Obtain consumer consent before
836
- * calling: registration signs internally.
837
- *
838
- * - An explicit `dustAddress` is refused while the account is designated for
839
- * DUST generation (registered NIGHT, generated DUST or generation capacity),
840
- * so it never redirects an existing designation.
841
- * - Without `dustAddress` the NIGHT is registered to the account's own DUST
842
- * address, whatever it is registered to now. NIGHT registered to an external
843
- * address is therefore re-registered to the account's own address. When some
844
- * NIGHT is already registered, the registration is balanced with DUST.
845
- *
846
- * The returned recipe reserves the NIGHT it registers (see `MidnightTxRecipe`).
847
- * When the registration cannot be built, the NIGHT it reserved is released
848
- * and the build error is returned; if that release fails too, the error is an
849
- * `AggregateError` of both failures, and the NIGHT stays reserved until a
850
- * sync reset. The wallet library does not release it when the fee query of a
851
- * first registration fails; it then also stays reserved until a sync reset.
852
- */
853
- const registerMidnightDust = async (wallet, { ttl, dustAddress: destination, ...account } = {}) => withMidnightWallet(wallet, account, (midnightWallet) => prepareMidnightDustRegistration(midnightWallet, {
854
- dustAddress: destination,
855
- ttl
856
- }).pipe(switchMap(({ nightCoins, dustAddress, isRepeatRegistration }) => {
857
- const registration$ = midnightWallet.registerNightUtxosForDustGeneration(nightCoins, dustAddress);
858
- if (!isRepeatRegistration) return registration$;
859
- return registration$.pipe(switchMap((registration) => balanceMidnightRecipe(midnightWallet, registration, new Date(Date.now() + defaultTxTtlLength))));
860
- })));
861
- //#endregion
862
- //#region src/estimate-midnight-fee.ts
863
- /**
864
- * Estimates DUST from unsigned preparation, without registering or signing.
865
- * A first registration with no spendable DUST estimates zero; a repeat
866
- * registration is estimated like the DUST balancing it performs.
867
- * Estimates depend on current state/time and are not guaranteed final charges.
868
- * Insufficient spendable DUST returns an error.
869
- */
870
- const estimateMidnightFee = async (wallet, request) => {
871
- return withMidnightWallet(wallet, request.kind === "transfer" ? request.transfer : request.registration, (engine) => defer(() => {
872
- return combineLatest([request.kind === "transfer" ? engine.state().pipe(take(1), map((state) => {
873
- const { kind, outputs, ttl } = request.transfer;
874
- const transfers = normalizeMidnightTransfers(engine.networkId, kind, outputs);
875
- return {
876
- state,
877
- tx: (kind === "shielded" ? constructShieldedTransaction : constructUnshieldedTransaction)({
878
- networkId: engine.networkId,
879
- transfers,
880
- ttl
881
- }),
882
- isFirstDesignation: false
883
- };
884
- })) : prepareMidnightDustRegistration(engine, request.registration).pipe(map(({ state, nightCoins, destination, isRepeatRegistration }) => ({
885
- state,
886
- tx: constructDustDesignationTransaction({
887
- networkId: engine.networkId,
888
- address: destination,
889
- nightUtxos: nightCoins,
890
- nightVerifyingKey: engine.nightVerifyingKey,
891
- allowFeePayment: isRepeatRegistration ? 0n : void 0
892
- }),
893
- isFirstDesignation: !isRepeatRegistration
894
- }))), engine.areKeysAvailable$.pipe(take(1))]).pipe(switchMap(([{ state, tx, isFirstDesignation }, areKeysAvailable]) => {
895
- const availableDust = state.dust.balance(/* @__PURE__ */ new Date());
896
- return estimatePreparedMidnightFee(engine, tx, {
897
- isDustDesignation: isFirstDesignation,
898
- dustBalance: availableDust,
899
- areKeysAvailable
900
- }).pipe(map((dustFee) => {
901
- if (dustFee > availableDust) throw new Error("Insufficient spendable DUST");
902
- return {
903
- dustFee,
904
- availableDust
905
- };
906
- }));
907
- }));
908
- }));
909
- };
910
- //#endregion
911
- //#region ../../packages/lib/vendor/src/midnight-sign-data.ts
912
- init__polyfill_buffer_patch();
913
- /** Decode the connector transport form, preserving Buffer's permissive hex/base64 handling. */
914
- const decodeMidnightSignData = (data, encoding) => {
915
- switch (encoding) {
916
- case "hex": return new Uint8Array(import_buffer.Buffer.from(data, "hex"));
917
- case "base64": return new Uint8Array(import_buffer.Buffer.from(data, "base64"));
918
- case "text": return new TextEncoder().encode(data);
919
- default: throw new Error(`Unsupported encoding: ${String(encoding)}`);
920
- }
921
- };
922
- const SIGNED_MESSAGE_PREFIX = "midnight_signed_message:";
923
- /**
924
- * Prefixes decoded payload bytes with UTF-8 `midnight_signed_message:<byteLength>:`.
925
- * The length excludes the prefix; sign and verify these bytes, not the transport encoding.
926
- */
927
- const applyMidnightSignedMessagePrefix = (data) => {
928
- const header = new TextEncoder().encode(`${SIGNED_MESSAGE_PREFIX}${data.length}:`);
929
- const prefixed = new Uint8Array(header.length + data.length);
930
- prefixed.set(header, 0);
931
- prefixed.set(data, header.length);
932
- return prefixed;
933
- };
934
- //#endregion
935
- //#region src/sign-midnight-data.ts
936
- /**
937
- * Signs a connector-compatible message with the selected account's unshielded
938
- * NIGHT key. Obtain consumer consent for this payload and account before calling;
939
- * this helper shows no prompt and the module's password unlocks the key.
940
- *
941
- * Decodes hex/base64 with Buffer (including permissive malformed input), or text
942
- * as UTF-8, then prefixes `midnight_signed_message:<byteLength>:`. Empty payloads
943
- * still receive the prefix. Only the `unshielded` key type is supported.
944
- * Returns the original payload, signature and verifying key. Account resolution,
945
- * unsupported options and signing failures settle as `Err<Error>`.
946
- */
947
- const signMidnightData = async (wallet, { data, options, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => defer(() => {
948
- if (options.keyType !== "unshielded") throw new Error(`Unsupported key type: ${String(options.keyType)}`);
949
- const bytes = applyMidnightSignedMessagePrefix(decodeMidnightSignData(data, options.encoding));
950
- return midnightWallet.signData(bytes).pipe(map(({ signature, verifyingKey }) => ({
951
- data,
952
- signature,
953
- verifyingKey
954
- })));
955
- }));
956
- //#endregion
957
- //#region src/discard-midnight-tx.ts
958
- /**
959
- * Releases the coins a built recipe holds, so they return to the account's
960
- * available balance and a later build can select them.
961
- *
962
- * Discard only a recipe that never reached proving: consent declined,
963
- * `signMidnightTx` failed, or `proveMidnightTx` returned
964
- * `MidnightAccountNotFoundError`, `MidnightWalletNotReadyError` or a
965
- * `RangeError` for its `proveTimeout`, which are raised before proving. Do
966
- * not discard after any other `proveMidnightTx`
967
- * error, including a timeout, nor after it returned a transaction: the engine
968
- * releases a recipe whose proving fails, and releases a proved transaction
969
- * that never reaches the chain once its validity window (`ttl`) has passed.
970
- * Pass the `accountId` the recipe was built with: under another account the
971
- * release finds no reserved coins and still reports `Ok`. The release works
972
- * per coin, not per transaction, so discarding a recipe the engine has
973
- * already released, or one built before a sync reset cleared its
974
- * reservation, can free coins that a later build reserved
975
- * for a transaction still in flight. For the same reason, never discard a
976
- * recipe whose transaction was passed to `submitMidnightTx`.
977
- */
978
- const discardMidnightTx = async (wallet, { recipe, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => defer(() => midnightWallet.revert(recipe)));
979
- //#endregion
980
- //#region src/sign-midnight-tx.ts
981
- /**
982
- * Signs the recipe's unshielded inputs with the account's NIGHT key. The
983
- * module's password unlocks the key; no prompt is shown. Obtain consumer consent
984
- * for the exact transaction and account before invoking this helper.
985
- */
986
- const signMidnightTx = async (wallet, { recipe, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => defer(() => midnightWallet.signRecipe(recipe)));
987
- //#endregion
988
- //#region src/prove-midnight-tx.ts
989
- /** How long every proving helper waits for the proof server unless told otherwise. */
990
- const DEFAULT_PROVE_TIMEOUT_MS = 10 * 6e4;
991
- /** Applies the default `proveTimeout` and refuses a value no timer can honour. */
992
- const resolveProveTimeout = (proveTimeout) => resolveTimeoutMs("proveTimeout", proveTimeout, DEFAULT_PROVE_TIMEOUT_MS);
993
- /**
994
- * Proves the recipe through the proof server the module was configured
995
- * with. Timeout stops observation; it does not cancel underlying proving.
996
- */
997
- const proveMidnightTx = async (wallet, { recipe, onProgress, proveTimeout, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => {
998
- const limit = resolveProveTimeout(proveTimeout);
999
- let observer = onProgress;
1000
- return defer(() => onProgress ? midnightWallet.finalizeRecipe(recipe, (event) => observer?.(event)) : midnightWallet.finalizeRecipe(recipe)).pipe(timeout(limit), finalize(() => {
1001
- observer = void 0;
1002
- }));
1003
- });
1004
- //#endregion
1005
- //#region ../../packages/module/dapp-connector-midnight/src/store/helpers/derive-pending-activity-from-midnight-tx.ts
1006
- const utxoKey = (intentHash, outputNo) => `${intentHash}#${outputNo}`;
1007
- const processOffer = (offer, ownUtxoIndex, ownUserAddressHex) => {
1008
- if (!offer) return {
1009
- nightDelta: 0n,
1010
- isInvolved: false
1011
- };
1012
- let nightDelta = 0n;
1013
- let isInvolved = false;
1014
- for (const input of offer.inputs) {
1015
- const own = ownUtxoIndex.get(utxoKey(input.intentHash, input.outputNo));
1016
- if (!own) continue;
1017
- isInvolved = true;
1018
- if (own.utxo.type === "0000000000000000000000000000000000000000000000000000000000000000") nightDelta -= own.utxo.value;
1019
- }
1020
- for (const output of offer.outputs) {
1021
- if (output.owner !== ownUserAddressHex) continue;
1022
- isInvolved = true;
1023
- if (output.type === "0000000000000000000000000000000000000000000000000000000000000000") nightDelta += output.value;
1024
- }
1025
- return {
1026
- nightDelta,
1027
- isInvolved
1028
- };
1029
- };
1030
- const buildOwnUtxoIndex = (nightUtxos) => {
1031
- const index = /* @__PURE__ */ new Map();
1032
- for (const entry of nightUtxos) index.set(utxoKey(entry.utxo.intentHash, entry.utxo.outputNo), entry);
1033
- return index;
1034
- };
1035
- const derivePendingActivityFromMidnightTx = ({ deserializedTx, accountId, ownUserAddressHex, nightUtxos, networkId }) => {
1036
- const ownUtxoIndex = buildOwnUtxoIndex(nightUtxos);
1037
- let nightAmount = 0n;
1038
- let isAccountInvolved = false;
1039
- for (const intent of deserializedTx.intents?.values() ?? []) for (const offer of [intent.guaranteedUnshieldedOffer, intent.fallibleUnshieldedOffer]) {
1040
- const { nightDelta, isInvolved } = processOffer(offer, ownUtxoIndex, ownUserAddressHex);
1041
- nightAmount += nightDelta;
1042
- isAccountInvolved = isAccountInvolved || isInvolved;
1043
- }
1044
- if (!isAccountInvolved) return void 0;
1045
- const tokenBalanceChanges = nightAmount === 0n ? [] : [{
1046
- tokenId: TokenId(toUnshieldedTokenType(NIGHT_TOKEN_ID, networkId)),
1047
- amount: BigNumber(nightAmount)
1048
- }];
1049
- return {
1050
- accountId,
1051
- activityId: deserializedTx.transactionHash(),
1052
- timestamp: Timestamp(Date.now()),
1053
- tokenBalanceChanges,
1054
- type: ActivityType.Pending
1055
- };
1056
- };
1057
- //#endregion
1058
- //#region src/submit-midnight-tx.ts
1059
- const DEFAULT_SUBMIT_TIMEOUT_MS = 5 * 6e4;
1060
- const PENDING_ROW_STATE_TIMEOUT_MS = 1e4;
1061
- /** Records the Pending activity unless the account already has a confirmed row for the transaction. */
1062
- const recordPendingActivity = ({ dispatch, activities, midnightWallet, transaction, utxos }) => {
1063
- try {
1064
- const activity = derivePendingActivityFromMidnightTx({
1065
- deserializedTx: transaction,
1066
- accountId: midnightWallet.accountId,
1067
- ownUserAddressHex: addressFromKey(midnightWallet.nightVerifyingKey),
1068
- nightUtxos: utxos,
1069
- networkId: midnightWallet.networkId
1070
- });
1071
- if (!activity) return void 0;
1072
- const current = activities[activity.accountId]?.find((row) => row.activityId === activity.activityId);
1073
- if (current && current.type !== ActivityType.Pending) return void 0;
1074
- dispatch("activities.upsertActivities", {
1075
- accountId: activity.accountId,
1076
- activities: [activity]
1077
- });
1078
- return activity;
1079
- } catch {
1080
- return;
1081
- }
1082
- };
1083
- /**
1084
- * Submits a proved transaction after consumer authorization and resolves once the node reports it final: the
1085
- * engine submits at its `Finalized` stage, so `Ok` means the transaction is on chain. `txId` is the engine's
1086
- * identifier, which is not the activity hash; the activity hash is `transaction.transactionHash()`.
1087
- *
1088
- * On an instance that tracks activities, the transaction's Pending activity, keyed by the activity hash, is
1089
- * recorded when the submission is handed to the engine, before finality; the history sync then replaces it with
1090
- * the confirmed row. The engine reports no acceptance before finality, so the row is written as soon as the call
1091
- * is issued. When the engine fails the submission it releases the transaction's coins and the Pending row is
1092
- * removed; if the transaction reaches the chain anyway, the history sync records it. Tracking failures never fail
1093
- * a submission.
1094
- *
1095
- * An `Err` does not prove that nothing was broadcast. {@link MidnightSubmitTimeoutError} (`code`
1096
- * `midnight-submit-timeout`) means the node did not report finality within `submitTimeout`: the transaction may
1097
- * still reach the chain, and its Pending row stays. The SDK keeps listening to the engine's submission after the
1098
- * timeout, for as long as that submission runs in this process: a failure it reports later removes the row, a
1099
- * confirmation reaches the history sync. A row whose outcome this process never learns (it ends first) stays
1100
- * until the history sync confirms it or the consumer removes it. The account-resolution errors
1101
- * (`MidnightAccountNotFoundError`, `MidnightWalletNotReadyError`) precede the call and so precede any broadcast;
1102
- * any other error is the engine's, and may also arrive after broadcast. Before retrying, check the account's
1103
- * activities for the activity hash.
1104
- */
1105
- const submitMidnightTx = async (wallet, { transaction, submitTimeout: requestedSubmitTimeout, ...account }) => withMidnightWallet(wallet, account, (midnightWallet) => defer(() => {
1106
- const submitTimeout = resolveTimeoutMs("submitTimeout", requestedSubmitTimeout, DEFAULT_SUBMIT_TIMEOUT_MS);
1107
- const { dispatch } = wallet;
1108
- const activities$ = dispatch ? wallet.stateObservables.activities?.selectAllMap$ : void 0;
1109
- const latestActivities$ = activities$ ? activities$.pipe(startWith(void 0), catchError(() => of(void 0))) : of(void 0);
1110
- const utxos$ = activities$ ? defer(() => midnightWallet.state()).pipe(take(1), map((state) => [...state.unshielded.availableCoins, ...state.unshielded.pendingCoins]), defaultIfEmpty(void 0), catchError(() => of(void 0))) : of(void 0);
1111
- const removePendingRow = (pending) => {
1112
- if (!dispatch || !activities$) return;
1113
- activities$.pipe(take(1), catchError(() => of(void 0))).subscribe((latest) => {
1114
- if ((latest?.[pending.accountId]?.find((row) => row.activityId === pending.activityId))?.type !== ActivityType.Pending) return;
1115
- try {
1116
- dispatch("activities.removeActivities", {
1117
- accountId: pending.accountId,
1118
- activityIds: [pending.activityId]
1119
- });
1120
- } catch {}
1121
- });
1122
- };
1123
- const settle = (finality$, pending) => {
1124
- const outcome$ = finality$.pipe(share({
1125
- connector: () => new ReplaySubject(1),
1126
- resetOnError: false,
1127
- resetOnComplete: false
1128
- }));
1129
- if (pending) outcome$.subscribe({
1130
- next: () => void 0,
1131
- error: () => {
1132
- removePendingRow(pending);
1133
- }
1134
- });
1135
- return outcome$.pipe(timeout({
1136
- first: submitTimeout,
1137
- with: () => throwError(() => new MidnightSubmitTimeoutError(transaction.transactionHash(), submitTimeout))
1138
- }), map((txId) => ({ txId })));
1139
- };
1140
- return utxos$.pipe(timeout({
1141
- first: Math.min(PENDING_ROW_STATE_TIMEOUT_MS, submitTimeout),
1142
- with: () => of(void 0)
1143
- }), switchMap((utxos) => {
1144
- const finality$ = midnightWallet.submitTransaction(transaction);
1145
- return of(utxos).pipe(withLatestFrom(latestActivities$), map(([coins, activities]) => dispatch && activities && coins ? recordPendingActivity({
1146
- dispatch,
1147
- activities,
1148
- midnightWallet,
1149
- transaction,
1150
- utxos: coins
1151
- }) : void 0), switchMap((pending) => settle(finality$, pending)));
1152
- }));
1153
- }));
1154
- //#endregion
1155
- //#region src/modules-midnight.ts
1156
- var modules_midnight_exports = /* @__PURE__ */ __exportAll({
1157
- featureDev: () => sdk_default,
1158
- storageInMemory: () => sdk_default$1,
1159
- storageWebIndexeddb: () => sdk_default$2
1160
- });
1161
- //#endregion
1162
- //#region src/midnight-proving-provider.ts
1163
- const withinTimeout = async (operation, milliseconds) => firstValueFrom(from(operation).pipe(timeout(milliseconds)));
1164
- /**
1165
- * Captures one account identity and resolves its current engine on every use.
1166
- * No proof-server URL or wallet keys are exposed. Factory failures are `Err`;
1167
- * `check`/`prove` reject on transport or attestation failure without fallback,
1168
- * and on timeout.
1169
- * The consumer must authorize disclosure of the circuit preimage to the configured prover.
1170
- */
1171
- const getMidnightProvingProvider = async (wallet, { keyMaterialProvider, proveTimeout: requestedProveTimeout, ...selection }) => {
1172
- try {
1173
- const proveTimeout = resolveProveTimeout(requestedProveTimeout);
1174
- const accountId = await resolveMidnightAccountId(wallet, selection.accountId);
1175
- const account = {
1176
- ...selection,
1177
- accountId
1178
- };
1179
- await midnightWalletFor(wallet, account);
1180
- const provider = createProvingProviderFromTransport({
1181
- check: async (payload) => (await midnightWalletFor(wallet, account)).proofServerTransport.check(payload),
1182
- prove: async (payload) => (await midnightWalletFor(wallet, account)).proofServerTransport.prove(payload)
1183
- }, keyMaterialProvider, { onKeyMaterialError: "propagate" });
1184
- return Ok({
1185
- check: async (serializedPreimage, keyLocation) => withinTimeout(provider.check(serializedPreimage, keyLocation), proveTimeout),
1186
- prove: async (serializedPreimage, keyLocation, overwriteBindingInput) => withinTimeout(provider.prove(serializedPreimage, keyLocation, overwriteBindingInput), proveTimeout)
1187
- });
1188
- } catch (error) {
1189
- return Err(error instanceof Error ? error : new Error(String(error)));
1190
- }
1191
- };
1192
- //#endregion
1193
- //#region ../../packages/lib/vendor/src/midnight-connector-transaction.ts
1194
- init__polyfill_buffer_patch();
1195
- /** Deserialize a hex-encoded, proven and bound connector transaction. */
1196
- const deserializeMidnightSealedTransaction = async (tx) => ledger.Transaction.deserialize("signature", "proof", "binding", import_buffer.Buffer.from(tx, "hex"));
1197
- /** Deserialize a hex-encoded, proven connector transaction that is not yet bound. */
1198
- const deserializeMidnightUnsealedTransaction = async (tx) => ledger.Transaction.deserialize("signature", "proof", "pre-binding", import_buffer.Buffer.from(tx, "hex"));
1199
- /**
1200
- * Groups connector outputs into the wallet SDK's transfer shape, unshielded
1201
- * first; a kind without outputs is omitted. Throws when a recipient is not a
1202
- * Bech32m address of its kind on `networkId`.
1203
- */
1204
- const groupMidnightConnectorOutputs = (desiredOutputs, networkId) => {
1205
- const unshielded = [];
1206
- const shielded = [];
1207
- for (const { kind, type, recipient, value } of desiredOutputs) {
1208
- const parsedAddress = MidnightBech32m.parse(recipient);
1209
- if (kind === "unshielded") unshielded.push({
1210
- type,
1211
- receiverAddress: UnshieldedAddress.codec.decode(networkId, parsedAddress),
1212
- amount: value
1213
- });
1214
- if (kind === "shielded") shielded.push({
1215
- type,
1216
- receiverAddress: ShieldedAddress.codec.decode(networkId, parsedAddress),
1217
- amount: value
1218
- });
1219
- }
1220
- const result = [];
1221
- if (unshielded.length) result.push({
1222
- type: "unshielded",
1223
- outputs: unshielded
1224
- });
1225
- if (shielded.length) result.push({
1226
- type: "shielded",
1227
- outputs: shielded
1228
- });
1229
- return result;
1230
- };
1231
- /** Sums connector inputs per kind and token type into the wallet SDK's swap shape. */
1232
- const groupMidnightConnectorInputs = (desiredInputs) => desiredInputs.reduce((inputs, { kind, type, value }) => {
1233
- if (kind === "shielded" || kind === "unshielded") {
1234
- const tokens = inputs[kind] ?? {};
1235
- tokens[type] = (tokens[type] ?? 0n) + value;
1236
- inputs[kind] = tokens;
1237
- }
1238
- return inputs;
1239
- }, {});
1240
- //#endregion
1241
- //#region src/midnight-connector-transactions.ts
1242
- const validateOptions = (options) => {
1243
- if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options) || options.payFees !== void 0 && typeof options.payFees !== "boolean")) throw new Error("Invalid Midnight fee options");
1244
- };
1245
- const validateTokens = (tokens) => {
1246
- if (!Array.isArray(tokens)) throw new Error("Expected Midnight token array");
1247
- for (const token of tokens) {
1248
- if (!token || token.kind !== "shielded" && token.kind !== "unshielded") throw new Error("Unsupported Midnight token kind");
1249
- if (typeof token.type !== "string" || !/^[\da-f]{64}$/i.test(token.type)) throw new Error("Expected a raw Midnight ledger token type");
1250
- if (typeof token.value !== "bigint" || token.value < 0n) throw new Error("Expected a non-negative Midnight token value");
1251
- }
1252
- };
1253
- const validateBalance = ({ tx, options }) => {
1254
- validateOptions(options);
1255
- if (typeof tx !== "string" || !/^(?:[\da-f]{2})+$/i.test(tx)) throw new Error("Expected a hexadecimal Midnight transaction");
1256
- };
1257
- const reservedBy = (recipe) => recipe.type === "UNPROVEN_TRANSACTION" ? recipe : recipe.balancingTransaction && {
1258
- type: "UNPROVEN_TRANSACTION",
1259
- transaction: recipe.balancingTransaction
1260
- };
1261
- const finalize$1 = async (wallet, recipe, { sign, proveTimeout }) => {
1262
- const reserved = reservedBy(recipe);
1263
- const prepared = sign ? await firstValueFrom(wallet.signRecipe(recipe).pipe(catchError((signingError) => reserved ? releaseThenThrow(wallet, reserved, signingError) : throwError(() => signingError)))) : recipe;
1264
- return firstValueFrom(wallet.finalizeRecipe(prepared).pipe(timeout(proveTimeout)));
1265
- };
1266
- /**
1267
- * Balances, signs and proves a binding transaction; never submits it.
1268
- * Obtain consumer consent for the transaction, account and prover disclosure before calling.
1269
- */
1270
- const balanceMidnightSealedTransaction = async (wallet, props) => withMidnightWallet(wallet, props, (engine) => defer(async () => {
1271
- const proveTimeout = resolveProveTimeout(props.proveTimeout);
1272
- validateBalance(props);
1273
- const transaction = await deserializeMidnightSealedTransaction(props.tx);
1274
- return finalize$1(engine, await firstValueFrom(engine.balanceFinalizedTransaction(transaction, {
1275
- ttl: new Date(Date.now() + defaultTxTtlLength),
1276
- tokenKindsToBalance: props.options?.payFees === false ? ["shielded", "unshielded"] : void 0
1277
- })), {
1278
- sign: true,
1279
- proveTimeout
1280
- });
1281
- }));
1282
- /**
1283
- * Balances, signs and proves a pre-binding transaction; never submits it.
1284
- * Obtain consumer consent for the transaction, account and prover disclosure before calling.
1285
- */
1286
- const balanceMidnightUnsealedTransaction = async (wallet, props) => withMidnightWallet(wallet, props, (engine) => defer(async () => {
1287
- const proveTimeout = resolveProveTimeout(props.proveTimeout);
1288
- validateBalance(props);
1289
- const transaction = await deserializeMidnightUnsealedTransaction(props.tx);
1290
- return finalize$1(engine, await firstValueFrom(engine.balanceUnboundTransaction(transaction, {
1291
- ttl: new Date(Date.now() + defaultTxTtlLength),
1292
- tokenKindsToBalance: props.options?.payFees === false ? ["shielded", "unshielded"] : void 0
1293
- })), {
1294
- sign: true,
1295
- proveTimeout
1296
- });
1297
- }));
1298
- /**
1299
- * Builds and proves connector transfers, including mixed token kinds; signs when unshielded outputs exist.
1300
- * Obtain consumer consent before calling. Returns a native finalized transaction without submitting.
1301
- * Fees default to enabled; use `buildMidnightTransfers` for separate homogeneous build/sign/prove stages.
1302
- */
1303
- const makeMidnightTransfer = async (wallet, props) => withMidnightWallet(wallet, props, (engine) => defer(async () => {
1304
- const proveTimeout = resolveProveTimeout(props.proveTimeout);
1305
- validateOptions(props.options);
1306
- validateTokens(props.desiredOutputs);
1307
- const outputs = groupMidnightConnectorOutputs(props.desiredOutputs, engine.networkId);
1308
- const ttl = new Date(Date.now() + defaultTxTtlLength);
1309
- return finalize$1(engine, await firstValueFrom(engine.transferTransaction(outputs, {
1310
- ttl,
1311
- payFees: false
1312
- }).pipe(switchMap((built) => props.options?.payFees ?? true ? balanceMidnightRecipe(engine, built, ttl) : of(built)))), {
1313
- sign: outputs.some((output) => output.type === "unshielded"),
1314
- proveTimeout
1315
- });
1316
- }));
1317
- const assertOutputKindsHaveInputs = (inputs, outputs) => {
1318
- const missing = outputs.map((output) => output.type).filter((kind) => inputs[kind] === void 0);
1319
- if (missing.length > 0) throw new Error(`Midnight intent requests ${missing.join(" and ")} outputs without inputs of that kind, which the wallet library would drop`);
1320
- };
1321
- /**
1322
- * Builds and proves an intent, signing when inputs or outputs include unshielded tokens.
1323
- * Obtain consumer consent before calling. Never submits. `intentId` is accepted but ignored,
1324
- * matching the existing connector; no intent ordering is guaranteed. Every output kind
1325
- * needs an input of the same kind: the wallet library builds a leg from its inputs and
1326
- * drops the outputs of a kind without any, so such a request is refused before anything
1327
- * is reserved or signed. When the fee cannot be paid, the inputs the build reserved are
1328
- * released and the balancing error is returned; if that release fails too, the error is
1329
- * an `AggregateError` of both failures and the coins stay reserved until a sync reset.
1330
- */
1331
- const makeMidnightIntent = async (wallet, props) => withMidnightWallet(wallet, props, (engine) => defer(async () => {
1332
- const proveTimeout = resolveProveTimeout(props.proveTimeout);
1333
- validateOptions(props.options);
1334
- if (!props.options || typeof props.options.payFees !== "boolean" || props.options.intentId !== "random" && typeof props.options.intentId !== "number") throw new Error("Invalid Midnight intent options");
1335
- validateTokens(props.desiredInputs);
1336
- validateTokens(props.desiredOutputs);
1337
- const inputs = groupMidnightConnectorInputs(props.desiredInputs);
1338
- const outputs = groupMidnightConnectorOutputs(props.desiredOutputs, engine.networkId);
1339
- assertOutputKindsHaveInputs(inputs, outputs);
1340
- const ttl = new Date(Date.now() + defaultTxTtlLength);
1341
- return finalize$1(engine, await firstValueFrom(engine.initSwap(inputs, outputs, {
1342
- ttl,
1343
- payFees: false
1344
- }).pipe(switchMap((built) => props.options.payFees ? balanceMidnightRecipe(engine, built, ttl) : of(built)))), {
1345
- sign: !!inputs.unshielded || outputs.some((output) => output.type === "unshielded"),
1346
- proveTimeout
1347
- });
1348
- }));
1349
- //#endregion
1350
- export { AccountId, Err, FEATURE_FLAG_MIDNIGHT, FEATURE_FLAG_MIDNIGHT_UNSHIELDED, FEATURE_FLAG_NETWORK_TYPE, MIDNIGHT_LOCAL_PROOF_SERVER_URL, MIDNIGHT_PREVIEW_INDEXER_URL, MIDNIGHT_PREVIEW_NODE_URL, MIDNIGHT_PUBLIC_ENDPOINTS, MidnightAccountId, MidnightAccountNotFoundError, MidnightNetworkId, MidnightNetworkNotConfiguredError, MidnightNothingToRegisterError, MidnightSDKNetworkIds, MidnightSubmitTimeoutError, MidnightWalletNotReadyError, NIGHT_TOKEN_ID, Ok, WalletId, WalletType, balanceMidnightSealedTransaction, balanceMidnightUnsealedTransaction, buildMidnightTransfer, buildMidnightTransfers, createInMemoryWalletEntity, createLaceWallet, createMidnightAccounts, createMidnightModule, createMidnightPasskeyWalletEntity, createPasskeyKeySource, createTemenosAttestedProver, discardMidnightTx, estimateMidnightFee, getMidnightProvingProvider, isForbiddenTokenName, isTakenTokenName, isTokenFullNameValid, isTokenShortNameValid, modules_midnight_exports as m, makeMidnightIntent, makeMidnightTransfer, observeMidnightBalances, proveMidnightTx, registerMidnightDust, selectMidnightNetwork, signMidnightData, signMidnightTx, submitMidnightTx };