@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
@@ -1,3791 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-Br2OG8yv.cjs");
2
- const require__polyfill_buffer_patch = require("./_polyfill-buffer-patch-CM8X7JiY.cjs");
3
- require("./codecs-Cswkg7Tm.cjs");
4
- const require_bytes_vo = require("./bytes.vo-BNRquqaO.cjs");
5
- const require_time_vo = require("./time.vo-D3wWRw9L.cjs");
6
- const require_bignum_vo = require("./bignum.vo-hx2kuqlA.cjs");
7
- const require_auto_dismiss_failure_on_success = require("./auto-dismiss-failure-on-success-C-qoJuid.cjs");
8
- require("./retry-config-BaCfVC1H.cjs");
9
- const require_activity_type = require("./activity-type-Ch6ljxBy.cjs");
10
- const require_token_id_vo = require("./token-id.vo-DXv5uS9n.cjs");
11
- const require_types = require("./types-DWbVZpnF.cjs");
12
- require("./bn-d3nSOIf7.cjs");
13
- const require_const = require("./const-DLrX5SD9.cjs");
14
- const require_watch = require("./watch-Cz1J42um.cjs");
15
- const require_slice = require("./slice-BOyAAaj0.cjs");
16
- const require_utils = require("./utils-BfMdr_1w.cjs");
17
- const require_midnight_wallet = require("./midnight-wallet-XTZc2li7.cjs");
18
- const require_dist = require("./dist-BtIq4XFn.cjs");
19
- require("./client-DXBLHk7K.cjs");
20
- const require_send_proof_progress = require("./send-proof-progress-dDoqIohG.cjs");
21
- let _laceio_cardano_util = require("@laceio/cardano/util");
22
- let rxjs = require("rxjs");
23
- rxjs = require_rolldown_runtime.__toESM(rxjs);
24
- let lodash_isEqual = require("lodash/isEqual.js");
25
- lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
26
- let _midnight_ntwrk_ledger_v8 = require("@midnight-ntwrk/ledger-v8");
27
- _midnight_ntwrk_ledger_v8 = require_rolldown_runtime.__toESM(_midnight_ntwrk_ledger_v8);
28
- //#region ../../packages/contract/midnight-context/src/value-objects/midnight-address.vo.ts
29
- const MidnightShieldedAddress = (address) => address;
30
- const MidnightUnshieldedAddress = (address) => address;
31
- const MidnightDustAddress = (address) => address;
32
- //#endregion
33
- //#region ../../packages/contract/midnight-context/src/value-objects/serialised-wallet-state.vo.ts
34
- /**
35
- * Either encoding. Production only ever constructs this from the SDK's
36
- * verbatim JSON; the hex form comes back from storage on older profiles.
37
- */
38
- const SerialisedWalletState = (value) => value;
39
- /**
40
- * A heuristic over the values we actually persist, not a parse: hex and JSON
41
- * overlap (`12345678` is both), so nothing can separate them in general. Every
42
- * blob written here opens with `{`; `[` is headroom for a serialiser that
43
- * returns a top-level array. Anything else reads as hex, and a wrong guess
44
- * costs a rebuild from seed, which the restore path already handles.
45
- *
46
- * First character only: matching hex across the whole payload cost ~2500ms
47
- * against 10k documents of 100k characters, against ~8ms here, and was
48
- * case-sensitive so it missed uppercase hex besides.
49
- */
50
- const isVerbatimJson = (value) => value.startsWith("{") || value.startsWith("[");
51
- SerialisedWalletState.toJSON = (value) => isVerbatimJson(value) ? value : require_bytes_vo.HexBytes.toUTF8(value);
52
- //#endregion
53
- //#region ../../packages/contract/midnight-context/src/midnight-accounts.ts
54
- /** Two account lists are the same run of accounts when their ids line up in
55
- * order — the identity the account stream re-emits on. */
56
- const sameAccounts = (accounts1, accounts2) => {
57
- if (accounts1.length !== accounts2.length) return false;
58
- for (let index = 0; index < accounts1.length; index++) if (accounts1[index].accountId !== accounts2[index].accountId) return false;
59
- return true;
60
- };
61
- /**
62
- * The in-memory Midnight accounts on the active Midnight network, as a stream
63
- * that only re-emits when the run of account ids actually changes. Emits an
64
- * empty list while the wallet repo is migrating, so a consumer never acts on a
65
- * half-migrated repo. Nothing is emitted until a Midnight network is registered.
66
- */
67
- const midnightAccounts$ = (state) => (0, rxjs.combineLatest)([
68
- state.wallets.selectActiveNetworkAccounts$,
69
- state.midnightContext.selectMidnightBlockchainNetworkId$.pipe((0, rxjs.filter)(Boolean)),
70
- state.wallets.selectIsWalletRepoMigrating$
71
- ]).pipe((0, rxjs.map)(([accounts, activeNetwork, isWalletRepoMigrating]) => isWalletRepoMigrating ? [] : accounts.filter(require_utils.isInMemoryMidnightAccount).filter((account) => account.blockchainNetworkId === activeNetwork)), (0, rxjs.distinctUntilChanged)(sameAccounts));
72
- //#endregion
73
- //#region ../../packages/contract/midnight-context/src/register-midnight-blockchain-networks.ts
74
- /**
75
- * Registers the Midnight networks with the global network store once, the
76
- * first time it reports Midnight absent. Every loadout with Midnight accounts
77
- * needs this: `wallets.selectActiveNetworkAccounts` drops the accounts of an
78
- * unregistered blockchain. The registration lands a tick after this decides,
79
- * so it sets the networks only while Midnight still has none: a network the
80
- * consumer selected in between keeps precedence.
81
- *
82
- * An existing Midnight account pins the testnet selection to its own network,
83
- * so a profile created before the network store existed keeps syncing where
84
- * its account lives; otherwise the default testnet is selected.
85
- */
86
- const registerMidnightBlockchainNetworks = (_, { network: { selectBlockchainNetworks$ }, midnightContext: { selectDefaultTestNetNetworkId$ }, wallets: { selectAll$ } }, { actions }) => selectBlockchainNetworks$.pipe((0, rxjs.filter)((blockchainNetworks) => !blockchainNetworks?.Midnight), (0, rxjs.withLatestFrom)(selectDefaultTestNetNetworkId$, selectAll$.pipe((0, rxjs.map)((allWallets) => allWallets.flatMap((wallet) => wallet.accounts)))), (0, rxjs.map)(([, defaultTestNetNetworkId, accounts]) => {
87
- const existingMidnightAccount = accounts.find((account) => account.blockchainName === "Midnight");
88
- const testnetNetworkId = existingMidnightAccount ? existingMidnightAccount.blockchainSpecific.networkId : defaultTestNetNetworkId;
89
- return actions.network.registerBlockchainNetworks({
90
- blockchain: "Midnight",
91
- mainnet: require_const.MidnightNetworkId("mainnet"),
92
- testnet: require_const.MidnightNetworkId(testnetNetworkId)
93
- });
94
- }));
95
- //#endregion
96
- //#region ../../packages/lib/vendor/src/midnight-facade-reservations.ts
97
- const NO_BALANCING_TRANSACTION = "No balancing transaction was created. Please check your transaction.";
98
- const releasingOnFailure = async (build) => {
99
- const releases = [];
100
- const reserve = (transaction, holder) => {
101
- if (transaction) releases.push(async () => holder.revertTransaction(transaction));
102
- return transaction;
103
- };
104
- try {
105
- return await build(reserve);
106
- } catch (error) {
107
- await Promise.allSettled(releases.map(async (release) => release()));
108
- throw error;
109
- }
110
- };
111
- const merge$2 = (first, second) => first && second ? first.merge(second) : first ?? second;
112
- const kindsToBalance = (tokenKindsToBalance = "all") => {
113
- const kinds = tokenKindsToBalance === "all" ? [
114
- "shielded",
115
- "unshielded",
116
- "dust"
117
- ] : tokenKindsToBalance;
118
- return {
119
- dust: kinds.includes("dust"),
120
- shielded: kinds.includes("shielded"),
121
- unshielded: kinds.includes("unshielded")
122
- };
123
- };
124
- /**
125
- * The wallet SDK's multi-step builds over `facade`, releasing the coins the
126
- * completed steps reserved when a later step fails. The wallet SDK keeps
127
- * them, and its caller gets an error with no recipe to release. Each build
128
- * takes the same steps over the same sub-wallets as its `WalletFacade`
129
- * namesake and returns the same recipe.
130
- */
131
- const withReservationRelease = (facade) => ({
132
- balanceFinalizedTransaction: async (transaction, { shieldedSecretKeys, dustSecretKey }, { ttl, tokenKindsToBalance }) => releasingOnFailure(async (reserve) => {
133
- const balance = kindsToBalance(tokenKindsToBalance);
134
- const unshieldedBalancing = balance.unshielded ? reserve(await facade.unshielded.balanceFinalizedTransaction(transaction), facade.unshielded) : void 0;
135
- const tokenBalancing = merge$2(balance.shielded ? reserve(await facade.shielded.balanceTransaction(shieldedSecretKeys, transaction), facade.shielded) : void 0, unshieldedBalancing);
136
- const balancingTransaction = merge$2(tokenBalancing, balance.dust ? await facade.dust.balanceTransactions(dustSecretKey, tokenBalancing ? [transaction, tokenBalancing] : [transaction], ttl) : void 0);
137
- if (!balancingTransaction) throw new Error(NO_BALANCING_TRANSACTION);
138
- return {
139
- type: "FINALIZED_TRANSACTION",
140
- originalTransaction: transaction,
141
- balancingTransaction
142
- };
143
- }),
144
- balanceUnboundTransaction: async (transaction, { shieldedSecretKeys, dustSecretKey }, { ttl, tokenKindsToBalance }) => releasingOnFailure(async (reserve) => {
145
- const balance = kindsToBalance(tokenKindsToBalance);
146
- const shieldedBalancing = balance.shielded ? reserve(await facade.shielded.balanceTransaction(shieldedSecretKeys, transaction), facade.shielded) : void 0;
147
- const balancedUnshielded = balance.unshielded ? await facade.unshielded.balanceUnboundTransaction(transaction) : void 0;
148
- const baseTransaction = balancedUnshielded ?? transaction;
149
- const balancingTransaction = merge$2(shieldedBalancing, balance.dust ? await facade.dust.balanceTransactions(dustSecretKey, shieldedBalancing ? [baseTransaction, shieldedBalancing] : [baseTransaction], ttl) : void 0);
150
- if (!balancingTransaction && !balancedUnshielded) throw new Error(NO_BALANCING_TRANSACTION);
151
- return {
152
- type: "UNBOUND_TRANSACTION",
153
- baseTransaction,
154
- balancingTransaction: balancingTransaction ?? void 0
155
- };
156
- }),
157
- transferTransaction: async (outputs, { shieldedSecretKeys, dustSecretKey }, { ttl, payFees = true }) => releasingOnFailure(async (reserve) => {
158
- const shieldedOutputs = outputs.flatMap((output) => output.type === "shielded" ? output.outputs : []);
159
- const unshieldedOutputs = outputs.flatMap((output) => output.type === "unshielded" ? output.outputs : []);
160
- if (unshieldedOutputs.length === 0 && shieldedOutputs.length === 0) throw new Error("At least one shielded or unshielded output is required.");
161
- const transfer = merge$2(shieldedOutputs.length > 0 ? reserve(await facade.shielded.transferTransaction(shieldedSecretKeys, shieldedOutputs), facade.shielded) : void 0, unshieldedOutputs.length > 0 ? reserve(await facade.unshielded.transferTransaction(unshieldedOutputs, ttl), facade.unshielded) : void 0);
162
- if (!transfer) throw new Error("Unexpected transaction state.");
163
- return {
164
- type: "UNPROVEN_TRANSACTION",
165
- transaction: merge$2(transfer, payFees ? await facade.dust.balanceTransactions(dustSecretKey, [transfer], ttl) : void 0) ?? transfer
166
- };
167
- }),
168
- initSwap: async ({ desiredInputs, desiredOutputs }, { shieldedSecretKeys, dustSecretKey }, { ttl, payFees = false }) => releasingOnFailure(async (reserve) => {
169
- const { shielded: shieldedInputs, unshielded: unshieldedInputs } = desiredInputs;
170
- const shieldedOutputs = desiredOutputs.flatMap((output) => output.type === "shielded" ? output.outputs : []);
171
- const unshieldedOutputs = desiredOutputs.flatMap((output) => output.type === "unshielded" ? output.outputs : []);
172
- const hasShieldedPart = !!shieldedInputs && Object.keys(shieldedInputs).length > 0 || shieldedOutputs.length > 0;
173
- const hasUnshieldedPart = !!unshieldedInputs && Object.keys(unshieldedInputs).length > 0 || unshieldedOutputs.length > 0;
174
- if (!hasShieldedPart && !hasUnshieldedPart) throw new Error("At least one shielded or unshielded swap is required.");
175
- const swap = merge$2(hasShieldedPart && shieldedInputs !== void 0 ? reserve(await facade.shielded.initSwap(shieldedSecretKeys, shieldedInputs, shieldedOutputs), facade.shielded) : void 0, hasUnshieldedPart && unshieldedInputs !== void 0 ? reserve(await facade.unshielded.initSwap(unshieldedInputs, unshieldedOutputs, ttl), facade.unshielded) : void 0);
176
- if (!swap) throw new Error("Unexpected transaction state.");
177
- return {
178
- type: "UNPROVEN_TRANSACTION",
179
- transaction: merge$2(swap, payFees ? await facade.dust.balanceTransactions(dustSecretKey, [swap], ttl) : void 0) ?? swap
180
- };
181
- })
182
- });
183
- //#endregion
184
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/CoreWallet.js
185
- const PublicKey = { fromSecretKey: (secretKey) => {
186
- return { publicKey: secretKey.publicKey };
187
- } };
188
- const CoreWallet$1 = {
189
- init(localState, secretKey, networkId) {
190
- return CoreWallet$1.empty(localState, PublicKey.fromSecretKey(secretKey), networkId);
191
- },
192
- initEmpty(dustParameters, secretKey, networkId) {
193
- return CoreWallet$1.empty(new _midnight_ntwrk_ledger_v8.DustLocalState(dustParameters), PublicKey.fromSecretKey(secretKey), networkId);
194
- },
195
- empty(localState, publicKey, networkId) {
196
- return {
197
- state: localState,
198
- publicKey,
199
- networkId,
200
- pendingDust: [],
201
- progress: require_const.createSyncProgress(),
202
- protocolVersion: require_const.MinSupportedVersion
203
- };
204
- },
205
- restore(localState, publicKey, pendingTokens, syncProgress, protocolVersion, networkId) {
206
- return {
207
- state: localState,
208
- publicKey,
209
- networkId,
210
- pendingDust: pendingTokens,
211
- progress: require_const.createSyncProgress(syncProgress),
212
- protocolVersion: require_const.ProtocolVersion(protocolVersion)
213
- };
214
- },
215
- applyEventsWithChanges(wallet, secretKey, events, currentTime) {
216
- const stateWithChanges = wallet.state.replayEventsWithChanges(secretKey, events);
217
- const updatedState = stateWithChanges.state.processTtls(currentTime);
218
- const availableNonces = updatedState.utxos.map((utxo) => utxo.nonce);
219
- return [{
220
- ...wallet,
221
- state: updatedState,
222
- pendingDust: wallet.pendingDust.filter((t) => availableNonces.includes(t.nonce))
223
- }, stateWithChanges.changes];
224
- },
225
- applyFailed(wallet, tx) {
226
- const pendingSpendsMap = CoreWallet$1.pendingDustToMap(wallet.pendingDust);
227
- const [updatedState, removedNullifiers] = require_const.pipe(require_const.pipe([...tx.intents?.values() ?? []], require_const.flatMap$3((intent) => {
228
- const spendTime = intent.dustActions?.ctime;
229
- return (intent.dustActions?.spends ?? []).map((spend) => ({
230
- spend,
231
- spendTime
232
- }));
233
- }), require_const.filterMap$1(({ spend, spendTime }) => require_const.pipe(require_const.fromNullable(pendingSpendsMap.get(spend.oldNullifier)), require_const.map$8(() => ({
234
- spend,
235
- spendTime
236
- }))))), require_const.reduce$3([wallet.state, []], ([state, removed], { spend, spendTime }) => [state.processTtls(require_watch.addSeconds(spendTime, wallet.state.params.dustGracePeriodSeconds)), require_const.append$1(removed, spend.oldNullifier)]));
237
- return {
238
- ...wallet,
239
- state: updatedState,
240
- pendingDust: wallet.pendingDust.filter((coin) => !removedNullifiers.includes(coin.nullifier))
241
- };
242
- },
243
- revertTransaction(wallet, tx) {
244
- return CoreWallet$1.applyFailed(wallet, tx);
245
- },
246
- updateProgress(wallet, { appliedIndex, highestRelevantWalletIndex, highestIndex, highestRelevantIndex, isConnected }) {
247
- const updatedProgress = require_const.createSyncProgress({
248
- appliedIndex: appliedIndex ?? wallet.progress.appliedIndex,
249
- highestRelevantWalletIndex: highestRelevantWalletIndex ?? wallet.progress.highestRelevantWalletIndex,
250
- highestIndex: highestIndex ?? wallet.progress.highestIndex,
251
- highestRelevantIndex: highestRelevantIndex ?? wallet.progress.highestRelevantIndex,
252
- isConnected: isConnected ?? wallet.progress.isConnected
253
- });
254
- return {
255
- ...wallet,
256
- progress: updatedProgress
257
- };
258
- },
259
- spendCoins(wallet, secretKey, coins, currentTime) {
260
- const [output, newState, newPending] = require_const.pipe(coins, require_const.reduce$3([
261
- [],
262
- wallet.state,
263
- wallet.pendingDust
264
- ], ([spends, localState, pending], { token: coinToSpend, value: takeFee }) => {
265
- const [newState, dustSpend] = localState.spend(secretKey, coinToSpend, takeFee, currentTime);
266
- const newPending = [...pending, {
267
- ...coinToSpend,
268
- nullifier: dustSpend.oldNullifier
269
- }];
270
- return [
271
- require_const.append$1(spends, dustSpend),
272
- newState,
273
- newPending
274
- ];
275
- }));
276
- return [output, {
277
- ...wallet,
278
- state: newState,
279
- pendingDust: newPending
280
- }];
281
- },
282
- pendingDustToMap(coins) {
283
- return new Map(coins.map(({ nullifier, ...coins }) => [nullifier, coins]));
284
- }
285
- };
286
- //#endregion
287
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/WalletError.js
288
- var OtherWalletError$1 = class extends require_const.TaggedError("Wallet.Other") {};
289
- var SyncWalletError$1 = class extends require_const.TaggedError("Wallet.Sync") {};
290
- var TransactingError = class extends require_const.TaggedError("Wallet.Transacting") {};
291
- var InsufficientFundsError$1 = class extends require_const.TaggedError("Wallet.InsufficientFunds") {};
292
- var TransactionHistoryError$1 = class extends require_const.TaggedError("Wallet.TransactionHistory") {};
293
- //#endregion
294
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/RunningV1Variant.js
295
- const progress$1 = (state) => {
296
- const appliedIndex = state.progress?.appliedIndex ?? 0n;
297
- const highestRelevantWalletIndex = state.progress?.highestRelevantWalletIndex ?? 0n;
298
- const sourceGap = (state.progress?.highestIndex ?? 0n) - (state.progress?.highestRelevantIndex ?? 0n);
299
- const applyGap = highestRelevantWalletIndex - appliedIndex;
300
- return [require_watch.ProgressUpdate({
301
- sourceGap,
302
- applyGap
303
- })];
304
- };
305
- const protocolVersionChange$1 = (previous, current) => {
306
- return previous.protocolVersion != current.protocolVersion ? [require_watch.VersionChange({ change: require_watch.Version({ version: require_const.ProtocolVersion(current.protocolVersion) }) })] : [];
307
- };
308
- const V1Tag$1 = Symbol("V1");
309
- var RunningV1Variant$1 = class {
310
- __polyTag__ = V1Tag$1;
311
- #scope;
312
- #context;
313
- #v1Context;
314
- state;
315
- constructor(scope, context, v1Context) {
316
- this.#scope = scope;
317
- this.#context = context;
318
- this.#v1Context = v1Context;
319
- this.state = require_watch.fromEffect(context.stateRef.get).pipe(require_watch.flatMap((initialState) => context.stateRef.changes.pipe(require_watch.mapAccum(initialState, (previous, current) => {
320
- return [current, [previous, current]];
321
- }))), require_watch.mapConcat(([previous, current]) => {
322
- return [
323
- require_watch.State({ state: current }),
324
- ...progress$1(current),
325
- ...protocolVersionChange$1(previous, current)
326
- ];
327
- }));
328
- }
329
- startSyncInBackground(startAux) {
330
- return this.startSync(startAux).pipe(require_watch.runScoped(require_watch.drain), require_const.forkScoped, require_const.provideService(require_const.Scope, this.#scope));
331
- }
332
- startSync(startAux) {
333
- return require_const.pipe(require_watch.get(this.#context.stateRef), require_watch.fromEffect, require_watch.flatMap((state) => this.#v1Context.syncService.updates(state, startAux)), require_watch.mapEffect((update) => require_watch.modifyEffect(this.#context.stateRef, (state) => require_const.try_({
334
- try: () => {
335
- const [newState, changesResult] = this.#v1Context.syncCapability.applyUpdate(state, update);
336
- return [changesResult, newState];
337
- },
338
- catch: (err) => new OtherWalletError$1({
339
- message: "Error while applying sync update",
340
- cause: err
341
- })
342
- })).pipe(require_const.flatMap(({ changes, protocolVersion }) => changes.length === 0 ? require_const._void : require_const.pipe(require_const.forEach(changes, (change) => require_const.pipe(this.#v1Context.transactionHistoryService.getTransactionDetails(change.source), require_const.flatMap((metadata) => this.#v1Context.transactionHistoryService.put(change, metadata, protocolVersion)), require_const.catchAllCause((cause) => require_watch.error("Error processing tx history metadata", cause))), {
343
- discard: true,
344
- concurrency: "unbounded"
345
- }), require_const.forkScoped)), require_const.provideService(require_const.Scope, this.#scope))), require_watch.tapError((error$2) => require_watch.error(error$2)), require_watch.retry(require_const.pipe(require_watch.exponential(require_const.seconds(1), 2), require_watch.map$1((delay) => {
346
- const maxDelay = require_const.minutes(2);
347
- const jitter = require_const.millis(Math.floor(Math.random() * 1e3));
348
- const delayWithJitter = require_const.toMillis(delay) + require_const.toMillis(jitter);
349
- return require_const.millis(Math.min(delayWithJitter, require_const.toMillis(maxDelay)));
350
- }))));
351
- }
352
- createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
353
- if (nightUtxos.some((utxo) => utxo.type !== (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw)) return require_const.fail$1(new OtherWalletError$1({ message: "Token of a non-Night type received" }));
354
- return require_const.gen(this, function* () {
355
- const currentState = yield* require_watch.get(this.#context.stateRef);
356
- const blockData = yield* this.#v1Context.syncService.blockData();
357
- const resolvedTime = currentTime ?? blockData.timestamp;
358
- const utxosWithDustValue = this.#v1Context.coinsAndBalancesCapability.estimateDustGeneration(currentState, nightUtxos, resolvedTime);
359
- return yield* this.#v1Context.transactingCapability.createDustGenerationTransaction(resolvedTime, ttl, utxosWithDustValue, nightVerifyingKey, dustReceiverAddress).pipe(require_watch.toEffect);
360
- });
361
- }
362
- splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) {
363
- if (nightUtxos.some((utxo) => utxo.type !== (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw)) return require_const.fail$1(new OtherWalletError$1({ message: "Token of a non-Night type received" }));
364
- return require_const.gen(this, function* () {
365
- const currentState = yield* require_watch.get(this.#context.stateRef);
366
- const utxosWithDustValue = this.#v1Context.coinsAndBalancesCapability.estimateDustGeneration(currentState, nightUtxos, currentTime);
367
- return this.#v1Context.transactingCapability.splitNightUtxosForDustRegistration(utxosWithDustValue, isRegistration);
368
- });
369
- }
370
- attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
371
- return this.#v1Context.transactingCapability.attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment).pipe(require_watch.toEffect);
372
- }
373
- addDustGenerationSignature(transaction, signature) {
374
- return this.#v1Context.transactingCapability.addDustGenerationSignature(transaction, signature).pipe(require_watch.toEffect);
375
- }
376
- addDustRegistrationSignature(transaction, signature) {
377
- return this.#v1Context.transactingCapability.addDustRegistrationSignature(transaction, signature).pipe(require_watch.toEffect);
378
- }
379
- calculateFee(transactions) {
380
- return require_const.pipe(this.#v1Context.syncService.blockData(), require_const.map((blockData) => require_const.pipe(transactions, require_const.map$6((transaction) => this.#v1Context.transactingCapability.calculateFee(transaction, blockData.ledgerParameters)), require_watch.sumBigInt)));
381
- }
382
- estimateFee(secretKey, transactions, ttl, currentTime) {
383
- return require_const.pipe(require_const.all([require_watch.get(this.#context.stateRef), this.#v1Context.syncService.blockData()]), require_const.flatMap(([state, blockData]) => require_const.pipe(this.#v1Context.transactingCapability.estimateFee(secretKey, state, transactions, ttl, currentTime ?? blockData.timestamp, blockData.ledgerParameters), require_watch.toEffect)));
384
- }
385
- balanceTransactions(secretKey, transactions, ttl, currentTime) {
386
- return require_watch.modifyEffect(this.#context.stateRef, (state) => {
387
- return require_const.pipe(this.#v1Context.syncService.blockData(), require_const.flatMap((blockData) => this.#v1Context.transactingCapability.balanceTransactions(secretKey, state, transactions, ttl, currentTime ?? blockData.timestamp, blockData.ledgerParameters)));
388
- });
389
- }
390
- revertTransaction(transaction) {
391
- return require_watch.updateEffect(this.#context.stateRef, (state) => {
392
- return require_const.pipe(this.#v1Context.transactingCapability.revertTransaction(state, transaction), require_watch.toEffect);
393
- });
394
- }
395
- };
396
- //#endregion
397
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Serialization.js
398
- require__polyfill_buffer_patch.init__polyfill_buffer_patch();
399
- const StateSchema$1 = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.DustLocalState).annotations({ identifier: "ledger.DustLocalState" });
400
- const Uint8ArraySchema$2 = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
401
- const StateFromUInt8Array$1 = require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$2, StateSchema$1, {
402
- encode: (state) => {
403
- return require_const.try_({
404
- try: () => {
405
- return state.serialize();
406
- },
407
- catch: (err) => {
408
- return new require_const.Unexpected(err, "Could not serialize local state");
409
- }
410
- });
411
- },
412
- decode: (bytes) => require_const.try_({
413
- try: () => _midnight_ntwrk_ledger_v8.DustLocalState.deserialize(bytes),
414
- catch: (err) => {
415
- return new require_const.Unexpected(err, "Could not deserialize local state");
416
- }
417
- })
418
- }));
419
- const HexedState$1 = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(StateFromUInt8Array$1));
420
- const SnapshotSchema = require_const.Struct({
421
- publicKey: require_const.Struct({ publicKey: require_const.BigInt$ }),
422
- state: HexedState$1,
423
- protocolVersion: require_const.BigInt$,
424
- networkId: require_const.String$,
425
- offset: require_const.optional(require_const.BigInt$)
426
- });
427
- const makeDefaultV1SerializationCapability$1 = () => {
428
- return {
429
- serialize: (wallet) => {
430
- const buildSnapshot = (w) => ({
431
- publicKey: w.publicKey,
432
- state: w.state,
433
- protocolVersion: w.protocolVersion,
434
- networkId: w.networkId,
435
- offset: w.progress?.appliedIndex
436
- });
437
- return require_const.pipe(wallet, buildSnapshot, require_const.encodeSync(SnapshotSchema), JSON.stringify);
438
- },
439
- deserialize: (aux, serialized) => {
440
- return require_const.pipe(serialized, require_const.decodeUnknownEither(require_const.parseJson(SnapshotSchema)), require_const.mapLeft((err) => new OtherWalletError$1({
441
- message: "Error while deserializing snapshot",
442
- cause: err
443
- })), require_const.flatMap$4((snapshot) => require_const.try_$1({
444
- try: () => CoreWallet$1.restore(snapshot.state, snapshot.publicKey, [], {
445
- appliedIndex: snapshot.offset ?? 0n,
446
- highestRelevantWalletIndex: 0n,
447
- highestIndex: 0n,
448
- highestRelevantIndex: 0n
449
- }, snapshot.protocolVersion, snapshot.networkId),
450
- catch: (err) => new OtherWalletError$1({
451
- message: "Error while restoring core wallet",
452
- cause: err
453
- })
454
- })));
455
- }
456
- };
457
- };
458
- //#endregion
459
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Sync.js
460
- const LedgerEventSchema$1 = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.Event).annotations({ identifier: "ledger.Event" });
461
- const LedgerEventFromUInt8Array = require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$2, LedgerEventSchema$1, {
462
- encode: (e) => require_const.try_({
463
- try: () => e.serialize(),
464
- catch: (err) => new require_const.Unexpected(err, "Could not serialize Ledger Event")
465
- }),
466
- decode: (bytes) => require_const.try_({
467
- try: () => _midnight_ntwrk_ledger_v8.Event.deserialize(bytes),
468
- catch: (err) => new require_const.Unexpected(err, "Could not deserialize Ledger Event")
469
- })
470
- }));
471
- const HexedEvent = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(LedgerEventFromUInt8Array));
472
- const SyncEventsUpdateSchema = require_const.Struct({
473
- id: require_const.Number$,
474
- raw: HexedEvent,
475
- maxId: require_const.Number$
476
- });
477
- const WalletSyncUpdate$1 = { create: (updates, secretKey, timestamp) => {
478
- return {
479
- updates,
480
- secretKey,
481
- timestamp
482
- };
483
- } };
484
- const makeDefaultSyncService = (config) => {
485
- const indexerSyncService = makeIndexerSyncService(config);
486
- return {
487
- updates: (state, secretKey) => {
488
- const batchSize = config.batchUpdates?.size ?? 10;
489
- const batchTimeout = require_const.millis(config.batchUpdates?.timeout ?? 1);
490
- const batchSpacing = config.batchUpdates?.spacing ?? 4;
491
- return require_const.pipe(indexerSyncService.subscribeWallet(state), require_watch.groupedWithin(batchSize, batchTimeout), require_watch.map(require_const.toArray), require_watch.map((data) => WalletSyncUpdate$1.create(data, secretKey, /* @__PURE__ */ new Date())), batchSpacing > 0 ? require_watch.schedule(require_watch.spaced(require_const.millis(batchSpacing))) : (eventsStream) => eventsStream, require_watch.provideSomeLayer(indexerSyncService.connectionLayer()));
492
- },
493
- blockData: () => {
494
- return require_const.gen(function* () {
495
- return (yield* (yield* require_watch.BlockHash)({ offset: null })).block;
496
- }).pipe(require_const.provide(indexerSyncService.queryClient()), require_const.scoped$1, require_const.catchAll((err) => require_const.fail$1(new OtherWalletError$1({
497
- message: `Encountered unexpected error: ${err.message}`,
498
- cause: err
499
- }))), require_const.flatMap((blockData) => {
500
- if (!blockData) throw new OtherWalletError$1({ message: "Unable to fetch block data" });
501
- return require_watch.ledgerTry(() => ({
502
- hash: blockData.hash,
503
- height: blockData.height,
504
- ledgerParameters: _midnight_ntwrk_ledger_v8.LedgerParameters.deserialize(require__polyfill_buffer_patch.import_buffer.Buffer.from(blockData.ledgerParameters, "hex")),
505
- timestamp: new Date(blockData.timestamp)
506
- }));
507
- }));
508
- }
509
- };
510
- };
511
- const makeIndexerSyncService = (config) => {
512
- return {
513
- queryClient() {
514
- return require_const.pipe(require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl }), require_const.mapError((error) => new OtherWalletError$1(error)));
515
- },
516
- connectionLayer() {
517
- const { indexerClientConnection } = config;
518
- return require_watch.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl).pipe(require_const.flatMap$4((url) => require_watch.make(url)), require_const.match$4({
519
- onLeft: (error) => require_const.fail(error),
520
- onRight: (url) => require_watch.layer({
521
- url,
522
- keepAlive: indexerClientConnection.keepAlive
523
- })
524
- }), require_const.mapError((e) => new SyncWalletError$1({
525
- message: "Failed to to obtain correct indexer URLs",
526
- cause: e
527
- })));
528
- },
529
- subscribeWallet(state) {
530
- const { appliedIndex } = state.progress;
531
- const bufferSize = config.indexerClientConnection.bufferSize ?? 1e4;
532
- const resumeThreshold = config.indexerClientConnection.resumeThreshold ?? 100;
533
- const resumeFrom = appliedIndex - 1n;
534
- return require_const.pipe(require_watch.DustLedgerEvents.runWithBackpressure({
535
- bufferSize,
536
- resumeThreshold,
537
- from: resumeFrom,
538
- variables: (cursor) => ({ id: cursor < 0n ? null : Number(cursor) }),
539
- key: (r) => BigInt(r.dustLedgerEvents.id)
540
- }), require_watch.mapEffect((subscription) => require_const.pipe(require_const.decodeUnknownEither(SyncEventsUpdateSchema)(subscription.dustLedgerEvents), require_const.mapLeft((err) => new SyncWalletError$1(err)), require_watch.toEffect)), require_watch.mapError((error) => new SyncWalletError$1(error)));
541
- }
542
- };
543
- };
544
- const makeDefaultSyncCapability = () => {
545
- return { applyUpdate(state, wrappedUpdate) {
546
- const { updates, secretKey } = wrappedUpdate;
547
- if (updates.length === 0) return [state, {
548
- changes: [],
549
- protocolVersion: Number(state.protocolVersion)
550
- }];
551
- const appliedIndex = state.progress.appliedIndex;
552
- const freshUpdates = updates.filter((u) => BigInt(u.id) > appliedIndex);
553
- const highestRelevantWalletIndex = BigInt(updates.at(-1).maxId);
554
- const [newState, changes] = freshUpdates.length === 0 ? [state, []] : CoreWallet$1.applyEventsWithChanges(state, secretKey, freshUpdates.map((u) => u.raw), wrappedUpdate.timestamp);
555
- const updatedState = CoreWallet$1.updateProgress(newState, {
556
- appliedIndex: freshUpdates.length === 0 ? appliedIndex : BigInt(freshUpdates.at(-1).id),
557
- highestRelevantWalletIndex,
558
- isConnected: true
559
- });
560
- return [updatedState, {
561
- changes,
562
- protocolVersion: Number(updatedState.protocolVersion)
563
- }];
564
- } };
565
- };
566
- //#endregion
567
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/TransactionHistory.js
568
- const DustUtxoInfoSchema = require_const.Struct({
569
- initialValue: require_const.BigInt$,
570
- nonce: require_const.BigInt$,
571
- seq: require_const.Number$,
572
- backingNight: require_const.String$,
573
- mtIndex: require_const.BigInt$
574
- });
575
- const DustSectionSchema = require_const.Struct({
576
- receivedUtxos: require_const.Array$(DustUtxoInfoSchema),
577
- spentUtxos: require_const.Array$(DustUtxoInfoSchema)
578
- });
579
- require_const.Struct({
580
- hash: require_const.TransactionHashSchema,
581
- protocolVersion: require_const.Number$,
582
- status: require_const.TransactionHistoryStatusSchema,
583
- dust: DustSectionSchema
584
- });
585
- const utxoEquals = require_const.equivalence(DustUtxoInfoSchema);
586
- const mergeDustSections = (existing, incoming) => ({
587
- receivedUtxos: require_const.unionWith$1(existing.receivedUtxos, incoming.receivedUtxos, utxoEquals),
588
- spentUtxos: require_const.unionWith$1(existing.spentUtxos, incoming.spentUtxos, utxoEquals)
589
- });
590
- const convertQualifiedDustOutput = (utxo) => ({
591
- initialValue: utxo.initialValue,
592
- nonce: utxo.nonce,
593
- seq: utxo.seq,
594
- backingNight: utxo.backingNight,
595
- mtIndex: utxo.mtIndex
596
- });
597
- const convertUpdateToStorageEntry$1 = (changes, metadata, protocolVersion) => ({
598
- hash: changes.source,
599
- protocolVersion,
600
- status: metadata.status,
601
- dust: {
602
- receivedUtxos: changes.receivedUtxos.map(convertQualifiedDustOutput),
603
- spentUtxos: changes.spentUtxos.map(convertQualifiedDustOutput)
604
- }
605
- });
606
- const upsertDustEntry = (txHistoryStorage, entry) => require_const.tryPromise({
607
- try: () => txHistoryStorage.upsert(entry),
608
- catch: (e) => new TransactionHistoryError$1({
609
- message: `Failed to upsert history entry for ${entry.hash}`,
610
- cause: e
611
- })
612
- });
613
- const makeDefaultTransactionHistoryService$1 = (config, _getContext) => {
614
- const txHistoryStorage = config.txHistoryStorage;
615
- const queryClientLayer = require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl });
616
- return {
617
- put: (changes, metadata, protocolVersion) => {
618
- return upsertDustEntry(txHistoryStorage, convertUpdateToStorageEntry$1(changes, metadata, protocolVersion));
619
- },
620
- getTransactionDetails: (hash) => require_const.gen(function* () {
621
- const tx = (yield* (yield* require_watch.TransactionHistoryDetail)({ transactionHash: hash })).transactions[0];
622
- const rawStatus = tx.__typename === "RegularTransaction" ? tx.transactionResult.status : void 0;
623
- const status = rawStatus === "FAILURE" || rawStatus === "PARTIAL_SUCCESS" ? rawStatus : "SUCCESS";
624
- return {
625
- hash: tx.hash,
626
- timestamp: tx.block.timestamp,
627
- status
628
- };
629
- }).pipe(require_const.provide(queryClientLayer), require_const.scoped$1, require_const.retry(require_watch.exponential(require_const.seconds(1)).pipe(require_watch.compose(require_watch.recurs(3)))), require_const.mapError$1((cause) => new TransactionHistoryError$1({
630
- message: `Failed to fetch transaction metadata for ${hash}`,
631
- cause
632
- })))
633
- };
634
- };
635
- //#endregion
636
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Keys.js
637
- const makeDefaultKeysCapability$1 = () => {
638
- return {
639
- getPublicKey: (state) => {
640
- return state.publicKey.publicKey;
641
- },
642
- getAddress: (state) => {
643
- return new require_dist.DustAddress(state.publicKey.publicKey);
644
- }
645
- };
646
- };
647
- //#endregion
648
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/CoinsAndBalances.js
649
- const chooseCoin = (coins) => coins.filter((coin) => coin.value > 0n).toSorted((a, b) => Number(a.value - b.value)).at(0);
650
- const FAKE_NONCE = "0".repeat(64);
651
- const makeDefaultCoinsAndBalancesCapability$1 = (_config, getContext) => {
652
- const getWalletBalance = (state, time) => {
653
- return state.state.walletBalance(time);
654
- };
655
- const getGenerationInfo = (state, coin) => {
656
- const info = state.state.generationInfo(coin);
657
- return info && info.dtime ? {
658
- ...info,
659
- dtime: /* @__PURE__ */ new Date(+info.dtime)
660
- } : info;
661
- };
662
- const resolveTime = (state, time) => time ?? state.state.syncTime;
663
- const toFullInfo = (state, coins, time) => coins.flatMap((coin) => {
664
- const genInfo = getGenerationInfo(state, coin);
665
- return genInfo ? [{
666
- token: coin,
667
- ...getFullDustInfo(state.state.params, genInfo, coin, time)
668
- }] : [];
669
- });
670
- const availableDustTokens = (state) => {
671
- const pendingSpends = new Set([...state.pendingDust.values()].map((coin) => coin.nonce));
672
- return require_const.pipe(state.state.utxos, require_const.filter$2((coin) => !pendingSpends.has(coin.nonce)));
673
- };
674
- const getAvailableCoins = (state, time) => toFullInfo(state, availableDustTokens(state), resolveTime(state, time));
675
- const getPendingCoins = (state, time) => toFullInfo(state, state.pendingDust, resolveTime(state, time));
676
- const getTotalCoins = (state, time) => {
677
- const effectiveTime = resolveTime(state, time);
678
- return [...getAvailableCoins(state, effectiveTime), ...getPendingCoins(state, effectiveTime)];
679
- };
680
- const getAvailableCoinsWithGeneratedDust = (state, currentTime) => getAvailableCoins(state, currentTime).map((info) => ({
681
- token: info.token,
682
- value: info.generatedNow
683
- }));
684
- const getFullDustInfo = (parameters, genInfo, coin, currentTime) => {
685
- const generatedValue = _midnight_ntwrk_ledger_v8.updatedValue(coin.ctime, coin.initialValue, genInfo, currentTime, parameters);
686
- return {
687
- dtime: genInfo.dtime,
688
- maxCap: genInfo.value * parameters.nightDustRatio,
689
- maxCapReachedAt: require_watch.addSeconds(coin.ctime, parameters.timeToCapSeconds),
690
- generatedNow: generatedValue,
691
- rate: genInfo.value * parameters.generationDecayRate
692
- };
693
- };
694
- const estimateDustGeneration = (state, nightUtxos, currentTime) => {
695
- const dustPublicKey = getContext().keysCapability.getPublicKey(state);
696
- return require_const.pipe(nightUtxos, require_const.map$6((utxo) => {
697
- const genInfo = fakeGenerationInfo(utxo, dustPublicKey);
698
- const fakeDustCoin = fakeDustToken(dustPublicKey, utxo);
699
- return {
700
- utxo,
701
- dust: getFullDustInfo(state.state.params, genInfo, fakeDustCoin, currentTime)
702
- };
703
- }));
704
- };
705
- /** Create a fake generation info for a given Utxo. It allows to estimate the Dust generation from it */
706
- const fakeGenerationInfo = (utxo, dustPublicKey) => {
707
- return {
708
- value: utxo.value,
709
- owner: dustPublicKey,
710
- nonce: FAKE_NONCE,
711
- dtime: void 0
712
- };
713
- };
714
- /** Create a fake dust coin for a given Utxo. It allows to estimate full details of the Dust generation from it */
715
- const fakeDustToken = (dustPublicKey, utxo) => ({
716
- initialValue: 0n,
717
- owner: dustPublicKey,
718
- nonce: 0n,
719
- seq: 0,
720
- ctime: utxo.ctime,
721
- backingNight: "",
722
- mtIndex: 0n
723
- });
724
- const splitNightUtxos = (utxos) => {
725
- const [guaranteed, fallible] = require_const.pipe(utxos, require_const.sort(require_const.pipe(require_const.bigint, require_const.reverse, require_const.mapInput$1((coin) => coin.dust.generatedNow))), require_const.splitAt$1(1));
726
- return {
727
- guaranteed,
728
- fallible
729
- };
730
- };
731
- return {
732
- getWalletBalance,
733
- getAvailableCoins,
734
- getPendingCoins,
735
- getTotalCoins,
736
- getAvailableCoinsWithGeneratedDust,
737
- getGenerationInfo,
738
- estimateDustGeneration,
739
- splitNightUtxos
740
- };
741
- };
742
- //#endregion
743
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Utils.js
744
- const SignatureMarker = {
745
- signature: "signature",
746
- signatureErased: "signature-erased"
747
- };
748
- const ProofMarker = {
749
- proof: "proof",
750
- preProof: "pre-proof",
751
- noProof: "no-proof"
752
- };
753
- const BindingMarker = {
754
- binding: "binding",
755
- preBinding: "pre-binding",
756
- noBinding: "no-binding"
757
- };
758
- //#endregion
759
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Transacting.js
760
- const makeDefaultTransactingCapability$1 = (config, getContext) => {
761
- return new TransactingCapabilityImplementation$1(config.networkId, config.costParameters, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability);
762
- };
763
- /**
764
- * Distributes the fee across multiple inputs, draining smaller inputs first when the fee exceeds any single input's
765
- * value. Finds the next available intent segment id in a transaction.
766
- *
767
- * Fallible intent segments occupy the range `[1, 65535]`; segment `0` is reserved for the guaranteed section and is
768
- * never returned.
769
- *
770
- * @param transaction - Transaction whose intent map is inspected.
771
- * @returns `Some(segmentId)` with the lowest unused id, or `None` if all 65535 fallible segments are taken.
772
- */
773
- const findAvailableSegmentId = (transaction) => {
774
- const used = new Set(transaction.intents?.keys() ?? []);
775
- return require_const.pipe(require_const.range$1(1, 65535), require_const.findFirst$2((segmentId) => !used.has(segmentId)));
776
- };
777
- /**
778
- * Distributes the fee across multiple inputs, draining smaller inputs first when the fee exceeds any single input's
779
- * value.
780
- */
781
- const distributeFeeAcrossInputs = (inputs, fee) => inputs.reduce(({ result, remaining }, input) => {
782
- const deduction = remaining >= input.value ? input.value : remaining;
783
- return {
784
- result: [...result, {
785
- ...input,
786
- value: deduction
787
- }],
788
- remaining: remaining - deduction
789
- };
790
- }, {
791
- result: [],
792
- remaining: fee
793
- }).result;
794
- var TransactingCapabilityImplementation$1 = class TransactingCapabilityImplementation$1 {
795
- networkId;
796
- costParams;
797
- getCoinSelection;
798
- getCoins;
799
- getKeys;
800
- constructor(networkId, costParams, getCoinSelection, getCoins, getKeys) {
801
- this.getCoins = getCoins;
802
- this.networkId = networkId;
803
- this.costParams = costParams;
804
- this.getCoinSelection = getCoinSelection;
805
- this.getKeys = getKeys;
806
- }
807
- createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
808
- const makeOffer = (utxos) => {
809
- if (utxos.length === 0) return require_const.none();
810
- const totalValue = require_const.pipe(utxos, require_const.map$7((coin) => coin.utxo.value), require_const.sumAll);
811
- const inputs = utxos.map(({ utxo }) => ({
812
- ...utxo,
813
- owner: nightVerifyingKey
814
- }));
815
- const output = {
816
- owner: (0, _midnight_ntwrk_ledger_v8.addressFromKey)(nightVerifyingKey),
817
- type: (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw,
818
- value: totalValue
819
- };
820
- return require_const.some(_midnight_ntwrk_ledger_v8.UnshieldedOffer.new(inputs, [output], []));
821
- };
822
- return require_const.gen$1(this, function* () {
823
- const receiver = dustReceiverAddress ? dustReceiverAddress.data : void 0;
824
- return yield* require_watch.ledgerTry(() => {
825
- const network = this.networkId;
826
- const splitResult = this.getCoins().splitNightUtxos(nightUtxos);
827
- const feePayment = receiver ? require_const.pipe(splitResult.guaranteed, require_const.filter$3((coin) => !coin.utxo.registeredForDustGeneration), require_const.map$7((coin) => coin.dust.generatedNow), require_const.sumAll) : 0n;
828
- const maybeGuaranteedOffer = makeOffer(splitResult.guaranteed);
829
- const maybeFallibleOffer = makeOffer(splitResult.fallible);
830
- const dustRegistration = new _midnight_ntwrk_ledger_v8.DustRegistration(SignatureMarker.signature, nightVerifyingKey, receiver, feePayment);
831
- const dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [], [dustRegistration]);
832
- const intent = require_const.pipe(_midnight_ntwrk_ledger_v8.Intent.new(ttl), (intent) => require_const.match$3(maybeGuaranteedOffer, {
833
- onNone: () => intent,
834
- onSome: (guaranteedOffer) => {
835
- intent.guaranteedUnshieldedOffer = guaranteedOffer;
836
- return intent;
837
- }
838
- }), (intent) => require_const.match$3(maybeFallibleOffer, {
839
- onNone: () => intent,
840
- onSome: (fallibleOffer) => {
841
- intent.fallibleUnshieldedOffer = fallibleOffer;
842
- return intent;
843
- }
844
- }), (intent) => {
845
- intent.dustActions = dustActions;
846
- return intent;
847
- });
848
- return _midnight_ntwrk_ledger_v8.Transaction.fromParts(network, void 0, void 0, intent);
849
- });
850
- });
851
- }
852
- splitNightUtxosForDustRegistration(utxosWithDustValue, isRegistration) {
853
- const splitResult = this.getCoins().splitNightUtxos(utxosWithDustValue);
854
- const feePayment = isRegistration ? require_const.pipe(splitResult.guaranteed, require_const.filter$3((coin) => !coin.utxo.registeredForDustGeneration), require_const.map$7((coin) => coin.dust.generatedNow), require_const.sumAll) : 0n;
855
- return {
856
- guaranteedUtxos: splitResult.guaranteed,
857
- fallibleUtxos: splitResult.fallible,
858
- feePayment
859
- };
860
- }
861
- attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
862
- return require_const.gen$1(this, function* () {
863
- const intent = transaction.intents?.get(1);
864
- if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found at segment 1; expected an intent built by rotateUtxos" }));
865
- if (intent.dustActions !== void 0 && intent.dustActions.registrations.length > 0) return yield* require_const.left(new TransactingError({ message: "Intent at segment 1 already has a dust registration attached" }));
866
- return yield* require_watch.ledgerTry(() => {
867
- const receiver = dustReceiverAddress ? dustReceiverAddress.data : void 0;
868
- const dustRegistration = new _midnight_ntwrk_ledger_v8.DustRegistration(SignatureMarker.signature, nightVerifyingKey, receiver, feePayment);
869
- const dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [], [dustRegistration]);
870
- const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(SignatureMarker.signature, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
871
- newIntent.dustActions = dustActions;
872
- const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(SignatureMarker.signature, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
873
- newTransaction.intents = newTransaction.intents.set(1, newIntent);
874
- return newTransaction;
875
- });
876
- });
877
- }
878
- addDustRegistrationSignature(transaction, signatureData) {
879
- return require_const.gen$1(this, function* () {
880
- const intent = transaction.intents?.get(1);
881
- if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found in the transaction intents with segment = 1" }));
882
- const { dustActions } = intent;
883
- if (!dustActions) return yield* require_const.left(new TransactingError({ message: "No dustActions found in intent" }));
884
- const [registration, ...restRegistrations] = dustActions.registrations;
885
- if (!registration) return yield* require_const.left(new TransactingError({ message: "No registrations found in dustActions" }));
886
- return yield* require_watch.ledgerTry(() => {
887
- const signature = new _midnight_ntwrk_ledger_v8.SignatureEnabled(signatureData);
888
- const registrationWithSignature = new _midnight_ntwrk_ledger_v8.DustRegistration(signature.instance, registration.nightKey, registration.dustAddress, registration.allowFeePayment, signature);
889
- const newDustActions = new _midnight_ntwrk_ledger_v8.DustActions(signature.instance, ProofMarker.preProof, dustActions.ctime, dustActions.spends, [registrationWithSignature, ...restRegistrations]);
890
- const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
891
- newIntent.dustActions = newDustActions;
892
- const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
893
- newTransaction.intents = newTransaction.intents.set(1, newIntent);
894
- return newTransaction;
895
- });
896
- });
897
- }
898
- addDustGenerationSignature(transaction, signatureData) {
899
- return require_const.gen$1(this, function* () {
900
- const intent = transaction.intents?.get(1);
901
- if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found in the transaction intents with segment = 1" }));
902
- const { dustActions, guaranteedUnshieldedOffer, fallibleUnshieldedOffer } = intent;
903
- if (!dustActions) return yield* require_const.left(new TransactingError({ message: "No dustActions found in intent" }));
904
- if (!guaranteedUnshieldedOffer) return yield* require_const.left(new TransactingError({ message: "No guaranteedUnshieldedOffer found in intent" }));
905
- const [registration, ...restRegistrations] = dustActions.registrations;
906
- if (!registration) return yield* require_const.left(new TransactingError({ message: "No registrations found in dustActions" }));
907
- return yield* require_watch.ledgerTry(() => {
908
- const signature = new _midnight_ntwrk_ledger_v8.SignatureEnabled(signatureData);
909
- const registrationWithSignature = new _midnight_ntwrk_ledger_v8.DustRegistration(signature.instance, registration.nightKey, registration.dustAddress, registration.allowFeePayment, signature);
910
- const newDustActions = new _midnight_ntwrk_ledger_v8.DustActions(signature.instance, ProofMarker.preProof, dustActions.ctime, dustActions.spends, [registrationWithSignature, ...restRegistrations]);
911
- const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
912
- newIntent.dustActions = newDustActions;
913
- const inputsLen = guaranteedUnshieldedOffer.inputs.length;
914
- const signatures = [];
915
- for (let i = 0; i < inputsLen; ++i) signatures.push(guaranteedUnshieldedOffer.signatures.at(i) ?? signatureData);
916
- newIntent.guaranteedUnshieldedOffer = guaranteedUnshieldedOffer.addSignatures(signatures);
917
- if (fallibleUnshieldedOffer) {
918
- const inputsLen = fallibleUnshieldedOffer.inputs.length;
919
- const signatures = [];
920
- for (let i = 0; i < inputsLen; ++i) signatures.push(fallibleUnshieldedOffer.signatures.at(i) ?? signatureData);
921
- newIntent.fallibleUnshieldedOffer = fallibleUnshieldedOffer.addSignatures(signatures);
922
- }
923
- const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
924
- newTransaction.intents = newTransaction.intents.set(1, newIntent);
925
- return newTransaction;
926
- });
927
- });
928
- }
929
- calculateFee(transaction, ledgerParams) {
930
- return transaction.feesWithMargin(ledgerParams, this.costParams.feeBlocksMargin) + (this.costParams.additionalFeeOverhead ?? 0n);
931
- }
932
- dryRunFee(recipeInputs, transactions, secretKey, state, ttl, currentTime, ledgerParams) {
933
- const network = this.networkId;
934
- const [spends] = CoreWallet$1.spendCoins(state, secretKey, recipeInputs, currentTime);
935
- const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
936
- intent.dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [...spends], []);
937
- const [first, ...rest] = transactions.map((tx) => tx.eraseProofs());
938
- const mergedExisting = first ? rest.reduce((acc, tx) => acc.merge(tx), first) : void 0;
939
- const segmentId = mergedExisting ? require_const.getOrElse(findAvailableSegmentId(mergedExisting), () => 1) : 1;
940
- const erasedBalancing = _midnight_ntwrk_ledger_v8.Transaction.fromParts(network).addIntent({
941
- tag: "specific",
942
- value: segmentId
943
- }, intent).eraseProofs();
944
- const mergedTx = mergedExisting ? mergedExisting.merge(erasedBalancing) : erasedBalancing;
945
- return this.calculateFee(mergedTx, ledgerParams);
946
- }
947
- static feeImbalance(transaction, totalFee) {
948
- const [_, imbalance] = transaction.imbalances(0, totalFee).entries().find(([tt, _]) => tt.tag === "dust") ?? [];
949
- return imbalance ?? 0n;
950
- }
951
- computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
952
- const initialFees = transactions.reduce((total, transaction) => total + TransactingCapabilityImplementation$1.feeImbalance(transaction, this.calculateFee(transaction, ledgerParams)), 0n);
953
- const dust = this.getCoins().getAvailableCoinsWithGeneratedDust(state, currentTime);
954
- return require_const.pipe(require_const.iterate({
955
- currentFee: initialFees,
956
- recipeInputs: [],
957
- converged: false
958
- }, {
959
- while: (s) => !s.converged,
960
- body: ({ currentFee }) => require_const.try_({
961
- try: () => {
962
- const recipeInputs = require_watch.getBalanceRecipe({
963
- coins: dust.map((coin) => ({
964
- type: "dust",
965
- value: coin.value,
966
- token: coin.token
967
- })),
968
- initialImbalances: require_watch.Imbalances.fromEntry("dust", currentFee),
969
- feeTokenType: "dust",
970
- coinSelection: this.getCoinSelection(),
971
- transactionCostModel: {
972
- inputFeeOverhead: 0n,
973
- outputFeeOverhead: 0n
974
- },
975
- createOutput: (coin) => coin,
976
- isCoinEqual: (a, b) => a.token.nonce === b.token.nonce
977
- }).inputs.map(({ token, value }) => ({
978
- token,
979
- value
980
- }));
981
- const newFee = this.dryRunFee(recipeInputs, transactions, secretKey, state, ttl, currentTime, ledgerParams);
982
- return {
983
- currentFee: newFee,
984
- recipeInputs,
985
- converged: newFee <= recipeInputs.reduce((sum, input) => sum + input.value, 0n)
986
- };
987
- },
988
- catch: (err) => {
989
- if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError$1({
990
- message: err.message,
991
- tokenType: err.tokenType
992
- });
993
- else return new OtherWalletError$1({
994
- message: err instanceof Error ? err.message : "Dust balancing failed",
995
- cause: err
996
- });
997
- }
998
- })
999
- }), require_const.either, require_const.runSync, require_const.map$9(({ currentFee, recipeInputs }) => ({
1000
- fee: currentFee,
1001
- recipeInputs: distributeFeeAcrossInputs(recipeInputs, currentFee)
1002
- })));
1003
- }
1004
- estimateFee(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
1005
- return require_const.pipe(this.computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams), require_const.map$9(({ fee }) => fee));
1006
- }
1007
- balanceTransactions(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
1008
- const networkId = this.networkId;
1009
- return require_const.pipe(this.computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams), require_const.flatMap$4(({ recipeInputs }) => {
1010
- return require_watch.ledgerTry(() => {
1011
- const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
1012
- const [spends, updatedState] = CoreWallet$1.spendCoins(state, secretKey, recipeInputs, currentTime);
1013
- intent.dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [...spends], []);
1014
- const [first, ...rest] = transactions.map((tx) => tx.eraseProofs());
1015
- const mergedExisting = first ? rest.reduce((acc, tx) => acc.merge(tx), first) : void 0;
1016
- const segmentId = mergedExisting ? require_const.getOrElse(findAvailableSegmentId(mergedExisting), () => 1) : 1;
1017
- return [_midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId).addIntent({
1018
- tag: "specific",
1019
- value: segmentId
1020
- }, intent), updatedState];
1021
- });
1022
- }));
1023
- }
1024
- revertTransaction(state, transaction) {
1025
- return require_const.try_$1({
1026
- try: () => CoreWallet$1.revertTransaction(state, transaction),
1027
- catch: (err) => {
1028
- return new OtherWalletError$1({
1029
- message: `Error while reverting transaction ${transaction.identifiers().at(0)}`,
1030
- cause: err
1031
- });
1032
- }
1033
- });
1034
- }
1035
- };
1036
- //#endregion
1037
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/V1Builder.js
1038
- var V1Builder$1 = class V1Builder$1 {
1039
- #buildState;
1040
- constructor(buildState = {}) {
1041
- this.#buildState = buildState;
1042
- }
1043
- withDefaults() {
1044
- return this.withDefaultTransactionType().withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
1045
- }
1046
- withTransactionType() {
1047
- return new V1Builder$1({
1048
- ...this.#buildState,
1049
- transactingCapability: void 0
1050
- });
1051
- }
1052
- withDefaultTransactionType() {
1053
- return this.withTransactionType();
1054
- }
1055
- withSyncDefaults() {
1056
- return this.withSync(makeDefaultSyncService, makeDefaultSyncCapability);
1057
- }
1058
- withSync(syncService, syncCapability) {
1059
- return new V1Builder$1({
1060
- ...this.#buildState,
1061
- syncService,
1062
- syncCapability
1063
- });
1064
- }
1065
- withSerializationDefaults() {
1066
- return this.withSerialization(makeDefaultV1SerializationCapability$1);
1067
- }
1068
- withSerialization(serializationCapability) {
1069
- return new V1Builder$1({
1070
- ...this.#buildState,
1071
- serializationCapability
1072
- });
1073
- }
1074
- withTransactingDefaults() {
1075
- return this.withTransacting(makeDefaultTransactingCapability$1);
1076
- }
1077
- withTransacting(transactingCapability) {
1078
- return new V1Builder$1({
1079
- ...this.#buildState,
1080
- transactingCapability
1081
- });
1082
- }
1083
- withCoinSelection(coinSelection) {
1084
- return new V1Builder$1({
1085
- ...this.#buildState,
1086
- coinSelection
1087
- });
1088
- }
1089
- withCoinSelectionDefaults() {
1090
- return this.withCoinSelection(() => chooseCoin);
1091
- }
1092
- withCoinsAndBalancesDefaults() {
1093
- return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability$1);
1094
- }
1095
- withCoinsAndBalances(coinsAndBalancesCapability) {
1096
- return new V1Builder$1({
1097
- ...this.#buildState,
1098
- coinsAndBalancesCapability
1099
- });
1100
- }
1101
- withTransactionHistoryDefaults() {
1102
- return this.withTransactionHistory(makeDefaultTransactionHistoryService$1);
1103
- }
1104
- withTransactionHistory(transactionHistoryService) {
1105
- return new V1Builder$1({
1106
- ...this.#buildState,
1107
- transactionHistoryService
1108
- });
1109
- }
1110
- withKeysDefaults() {
1111
- return this.withKeys(makeDefaultKeysCapability$1);
1112
- }
1113
- withKeys(keysCapability) {
1114
- return new V1Builder$1({
1115
- ...this.#buildState,
1116
- keysCapability
1117
- });
1118
- }
1119
- build(configuration) {
1120
- const v1Context = this.#buildContextFromBuildState(configuration);
1121
- return {
1122
- __polyTag__: V1Tag$1,
1123
- coinsAndBalances: v1Context.coinsAndBalancesCapability,
1124
- keys: v1Context.keysCapability,
1125
- serialization: v1Context.serializationCapability,
1126
- transactionHistory: v1Context.transactionHistoryService,
1127
- start(context) {
1128
- return require_const.gen(function* () {
1129
- return new RunningV1Variant$1(yield* require_const.Scope, context, v1Context);
1130
- });
1131
- },
1132
- migrateState(prevState) {
1133
- return require_const.succeed(prevState);
1134
- },
1135
- deserializeState: (serialized) => {
1136
- return v1Context.serializationCapability.deserialize(null, serialized);
1137
- }
1138
- };
1139
- }
1140
- #buildContextFromBuildState(configuration) {
1141
- if (!isBuildStateFull$1(this.#buildState)) throw new Error("Not all components are configured in V1 Builder");
1142
- const { syncCapability, syncService, transactingCapability, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
1143
- const getContext = () => context;
1144
- const context = {
1145
- serializationCapability: serializationCapability(configuration, getContext),
1146
- syncCapability: syncCapability(configuration, getContext),
1147
- syncService: syncService(configuration, getContext),
1148
- transactingCapability: transactingCapability(configuration, getContext),
1149
- coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
1150
- keysCapability: keysCapability(configuration, getContext),
1151
- coinSelection: coinSelection(configuration, getContext),
1152
- transactionHistoryService: transactionHistoryService(configuration, getContext)
1153
- };
1154
- return context;
1155
- }
1156
- };
1157
- const isBuildStateFull$1 = (buildState) => {
1158
- return [
1159
- "syncService",
1160
- "syncCapability",
1161
- "transactingCapability",
1162
- "coinSelection",
1163
- "serializationCapability",
1164
- "coinsAndBalancesCapability",
1165
- "keysCapability",
1166
- "transactionHistoryService"
1167
- ].every((key) => typeof buildState[key] == "function");
1168
- };
1169
- //#endregion
1170
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/DustWallet.js
1171
- var DustWalletState = class DustWalletState {
1172
- static mapState = (variant) => (state) => {
1173
- const { serialization, coinsAndBalances, keys } = variant;
1174
- const { transactionHistory } = variant;
1175
- return new DustWalletState(state, {
1176
- serialization,
1177
- coinsAndBalances,
1178
- keys
1179
- }, { transactionHistory });
1180
- };
1181
- protocolVersion;
1182
- state;
1183
- capabilities;
1184
- services;
1185
- get totalCoins() {
1186
- return this.capabilities.coinsAndBalances.getTotalCoins(this.state);
1187
- }
1188
- get availableCoins() {
1189
- return this.capabilities.coinsAndBalances.getAvailableCoins(this.state);
1190
- }
1191
- get pendingCoins() {
1192
- return this.capabilities.coinsAndBalances.getPendingCoins(this.state);
1193
- }
1194
- get publicKey() {
1195
- return this.capabilities.keys.getPublicKey(this.state);
1196
- }
1197
- get address() {
1198
- return this.capabilities.keys.getAddress(this.state);
1199
- }
1200
- get progress() {
1201
- return this.state.progress;
1202
- }
1203
- constructor(state, capabilities, services) {
1204
- this.protocolVersion = state.version;
1205
- this.state = state.state;
1206
- this.capabilities = capabilities;
1207
- this.services = services;
1208
- }
1209
- balance(time) {
1210
- return this.capabilities.coinsAndBalances.getWalletBalance(this.state, time);
1211
- }
1212
- estimateDustGeneration(nightUtxos, currentTime) {
1213
- return this.capabilities.coinsAndBalances.estimateDustGeneration(this.state, nightUtxos, currentTime);
1214
- }
1215
- serialize() {
1216
- return this.capabilities.serialization.serialize(this.state);
1217
- }
1218
- };
1219
- function DustWallet(configuration) {
1220
- return CustomDustWallet(configuration, new V1Builder$1().withDefaults());
1221
- }
1222
- function CustomDustWallet(configuration, builder) {
1223
- const buildArgs = [configuration];
1224
- const BaseWallet = require_watch.WalletBuilder.init().withVariant(require_const.MinSupportedVersion, builder).build(...buildArgs);
1225
- return class CustomDustWalletImplementation extends BaseWallet {
1226
- static startWithSeed(seed, dustParameters) {
1227
- const dustSecretKey = _midnight_ntwrk_ledger_v8.DustSecretKey.fromSeed(seed);
1228
- return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, CoreWallet$1.initEmpty(dustParameters, dustSecretKey, CustomDustWalletImplementation.configuration.networkId));
1229
- }
1230
- static startWithSecretKey(secretKey, dustParameters) {
1231
- return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, CoreWallet$1.initEmpty(dustParameters, secretKey, CustomDustWalletImplementation.configuration.networkId));
1232
- }
1233
- static restore(serializedState) {
1234
- const deserialized = CustomDustWalletImplementation.allVariantsRecord()[V1Tag$1].variant.deserializeState(serializedState).pipe(require_const.getOrThrow$1);
1235
- return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, deserialized);
1236
- }
1237
- state;
1238
- constructor(runtime, scope) {
1239
- super(runtime, scope);
1240
- this.state = this.rawState.pipe(rxjs.map(DustWalletState.mapState(CustomDustWalletImplementation.allVariantsRecord()[V1Tag$1].variant)), rxjs.shareReplay({
1241
- refCount: true,
1242
- bufferSize: 1
1243
- }));
1244
- }
1245
- start(secretKey) {
1246
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.startSyncInBackground(secretKey) }).pipe(require_const.runPromise);
1247
- }
1248
- async createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
1249
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) }).pipe(require_const.runPromise);
1250
- }
1251
- async splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) {
1252
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) }).pipe(require_const.runPromise);
1253
- }
1254
- async attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
1255
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) }).pipe(require_const.runPromise);
1256
- }
1257
- addDustGenerationSignature(transaction, signature) {
1258
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.addDustGenerationSignature(transaction, signature) }).pipe(require_const.runPromise);
1259
- }
1260
- addDustRegistrationSignature(transaction, signature) {
1261
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.addDustRegistrationSignature(transaction, signature) }).pipe(require_const.runPromise);
1262
- }
1263
- calculateFee(transactions) {
1264
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.calculateFee(transactions) }).pipe(require_const.runPromise);
1265
- }
1266
- estimateFee(secretKey, transactions, ttl, currentTime) {
1267
- const effectiveTtl = ttl ?? new Date(Date.now() + 3600 * 1e3);
1268
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.estimateFee(secretKey, transactions, effectiveTtl, currentTime) }).pipe(require_const.runPromise);
1269
- }
1270
- balanceTransactions(secretKey, transactions, ttl, currentTime) {
1271
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.balanceTransactions(secretKey, transactions, ttl, currentTime) }).pipe(require_const.runPromise);
1272
- }
1273
- revertTransaction(transaction) {
1274
- return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.revertTransaction(transaction) }).pipe(require_const.runPromise);
1275
- }
1276
- waitForSyncedState(allowedGap = 0n) {
1277
- return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
1278
- }
1279
- async waitForGeneratedDust(nightUtxos, requiredAmount, clock, opts) {
1280
- if (nightUtxos.length === 0) throw Error("At least one Night UTXO is required.");
1281
- if (requiredAmount <= 0n) return;
1282
- const timeoutMs = opts?.timeoutMs ?? 3e5;
1283
- await rxjs.firstValueFrom(rxjs.combineLatest([this.state, rxjs.timer(0, 1e3)]).pipe(rxjs.filter(([dustState]) => {
1284
- return dustState.estimateDustGeneration(nightUtxos, clock.now()).filter((u) => !u.utxo.registeredForDustGeneration).reduce((max, u) => u.dust.generatedNow > max ? u.dust.generatedNow : max, 0n) >= requiredAmount;
1285
- }), rxjs.timeout({ first: timeoutMs })));
1286
- }
1287
- serializeState() {
1288
- return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
1289
- }
1290
- getAddress() {
1291
- return rxjs.firstValueFrom(this.state).then((state) => state.address);
1292
- }
1293
- };
1294
- }
1295
- //#endregion
1296
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/WalletError.js
1297
- const WalletError = {
1298
- other(err) {
1299
- let message;
1300
- if (err) if (typeof err == "object" && "message" in err) message = String(err.message);
1301
- else if (typeof err == "string") message = err;
1302
- else message = "";
1303
- else message = "";
1304
- return new OtherWalletError({
1305
- message: `Other wallet error: ${message}`,
1306
- cause: err
1307
- });
1308
- },
1309
- submission(err) {
1310
- return new SubmissionError({
1311
- message: `Transaction submission error: ${err && typeof err == "object" && "message" in err ? String(err.message) : ""}`,
1312
- cause: err
1313
- });
1314
- }
1315
- };
1316
- var OtherWalletError = class extends require_const.TaggedError("Wallet.Other") {};
1317
- var SyncWalletError = class extends require_const.TaggedError("Wallet.Sync") {};
1318
- var SubmissionError = class extends require_const.TaggedError("Wallet.SubmissionWalletError") {};
1319
- var InsufficientFundsError = class extends require_const.TaggedError("Wallet.InsufficientFunds") {};
1320
- var InvalidCoinHashesError = class extends require_const.TaggedError("Wallet.InvalidCoinHashes") {};
1321
- var TransactionHistoryError = class extends require_const.TaggedError("Wallet.TransactionHistory") {};
1322
- //#endregion
1323
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/RunningV1Variant.js
1324
- const progress = (state) => {
1325
- const appliedIndex = state.progress?.appliedIndex ?? 0n;
1326
- const highestRelevantWalletIndex = state.progress?.highestRelevantWalletIndex ?? 0n;
1327
- const sourceGap = (state.progress?.highestIndex ?? 0n) - (state.progress?.highestRelevantIndex ?? 0n);
1328
- const applyGap = highestRelevantWalletIndex - appliedIndex;
1329
- return [require_watch.ProgressUpdate({
1330
- sourceGap,
1331
- applyGap
1332
- })];
1333
- };
1334
- const protocolVersionChange = (previous, current) => {
1335
- return previous.protocolVersion != current.protocolVersion ? [require_watch.VersionChange({ change: require_watch.Version({ version: require_const.ProtocolVersion(current.protocolVersion) }) })] : [];
1336
- };
1337
- const V1Tag = Symbol("V1");
1338
- var RunningV1Variant = class {
1339
- __polyTag__ = V1Tag;
1340
- #scope;
1341
- #context;
1342
- #v1Context;
1343
- state;
1344
- constructor(scope, context, v1Context) {
1345
- this.#scope = scope;
1346
- this.#context = context;
1347
- this.#v1Context = v1Context;
1348
- this.state = require_watch.fromEffect(context.stateRef.get).pipe(require_watch.flatMap((initialState) => context.stateRef.changes.pipe(require_watch.mapAccum(initialState, (previous, current) => {
1349
- return [current, [previous, current]];
1350
- }))), require_watch.mapConcat(([previous, current]) => {
1351
- return [
1352
- require_watch.State({ state: current }),
1353
- ...progress(current),
1354
- ...protocolVersionChange(previous, current)
1355
- ];
1356
- }));
1357
- }
1358
- startSyncInBackground(startAux) {
1359
- return this.startSync(startAux).pipe(require_watch.runScoped(require_watch.drain), require_const.forkScoped, require_const.provideService(require_const.Scope, this.#scope));
1360
- }
1361
- startSync(startAux) {
1362
- return require_const.pipe(require_watch.get(this.#context.stateRef), require_watch.fromEffect, require_watch.flatMap((state) => this.#v1Context.syncService.updates(state, startAux)), require_watch.mapEffect((update) => require_watch.modifyEffect(this.#context.stateRef, (state) => require_const.try_({
1363
- try: () => {
1364
- const [newState, changesResult] = this.#v1Context.syncCapability.applyUpdate(state, update);
1365
- return [changesResult, newState];
1366
- },
1367
- catch: (err) => new OtherWalletError({
1368
- message: "Error while applying sync update",
1369
- cause: err
1370
- })
1371
- })).pipe(require_const.flatMap(({ changes, protocolVersion }) => changes.length === 0 ? require_const._void : require_const.pipe(require_const.forEach(changes, (change) => require_const.pipe(this.#v1Context.transactionHistoryService.getTransactionDetails(change.source), require_const.flatMap((metadata) => this.#v1Context.transactionHistoryService.put(change, metadata, protocolVersion)), require_const.catchAllCause((cause) => require_watch.error("Error processing tx history metadata", cause))), {
1372
- discard: true,
1373
- concurrency: "unbounded"
1374
- }), require_const.forkScoped)), require_const.provideService(require_const.Scope, this.#scope))), require_watch.tapError((error$1) => require_watch.error(error$1)), require_watch.retry(require_const.pipe(require_watch.exponential(require_const.seconds(1), 2), require_watch.map$1((delay) => {
1375
- const maxDelay = require_const.minutes(2);
1376
- const jitter = require_const.millis(Math.floor(Math.random() * 1e3));
1377
- const delayWithJitter = require_const.toMillis(delay) + require_const.toMillis(jitter);
1378
- return require_const.millis(Math.min(delayWithJitter, require_const.toMillis(maxDelay)));
1379
- }))));
1380
- }
1381
- balanceTransaction(secretKeys, tx) {
1382
- return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1383
- return require_const.pipe(this.#v1Context.transactingCapability.balanceTransaction(secretKeys, state, tx), require_watch.toEffect);
1384
- });
1385
- }
1386
- transferTransaction(secretKeys, outputs) {
1387
- return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1388
- return require_const.pipe(this.#v1Context.transactingCapability.makeTransfer(secretKeys, state, outputs), require_watch.toEffect);
1389
- });
1390
- }
1391
- initSwap(secretKeys, desiredInputs, desiredOutputs) {
1392
- return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1393
- return require_const.pipe(this.#v1Context.transactingCapability.initSwap(secretKeys, state, desiredInputs, desiredOutputs), require_watch.toEffect);
1394
- });
1395
- }
1396
- revertTransaction(transaction) {
1397
- return require_watch.updateEffect(this.#context.stateRef, (state) => {
1398
- return require_const.pipe(this.#v1Context.transactingCapability.revertTransaction(state, transaction), require_watch.toEffect);
1399
- });
1400
- }
1401
- serializeState(state) {
1402
- return this.#v1Context.serializationCapability.serialize(state);
1403
- }
1404
- };
1405
- //#endregion
1406
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/CoreWallet.js
1407
- const PublicKeys = { fromSecretKeys: (secretKeys) => {
1408
- return {
1409
- coinPublicKey: secretKeys.coinPublicKey,
1410
- encryptionPublicKey: secretKeys.encryptionPublicKey
1411
- };
1412
- } };
1413
- const CoinHashesMap = {
1414
- empty: {},
1415
- pickAllCoins(state) {
1416
- return [...state.coins, ...state.pendingOutputs.values().map(([coin]) => coin)];
1417
- },
1418
- assertValid(map, state) {
1419
- const coins = CoinHashesMap.pickAllCoins(state);
1420
- const coinNonces = new Set(require_const.map$7(coins, (coin) => coin.nonce));
1421
- const definedNonces = new Set(Object.keys(map));
1422
- const missingNonces = coinNonces.difference(definedNonces);
1423
- return missingNonces.size === 0 ? require_const.void_$2 : require_const.left(missingNonces);
1424
- },
1425
- updateWithCoins(secretKeys, existing, coins) {
1426
- return require_const.fromIterableWith(coins, (coin) => [coin.nonce, existing[coin.nonce] ?? {
1427
- commitment: _midnight_ntwrk_ledger_v8.coinCommitment(coin, secretKeys.coinPublicKey),
1428
- nullifier: _midnight_ntwrk_ledger_v8.coinNullifier(coin, secretKeys.coinSecretKey)
1429
- }]);
1430
- },
1431
- updateWithNewCoins(secretKeys, existing, coins) {
1432
- const newMap = CoinHashesMap.updateWithCoins(secretKeys, CoinHashesMap.empty, coins);
1433
- return require_const.union$2(existing, newMap, (a) => a);
1434
- },
1435
- init(secretKeys, coins) {
1436
- return CoinHashesMap.updateWithCoins(secretKeys, {}, coins);
1437
- }
1438
- };
1439
- const CoreWallet = {
1440
- init(localState, secretKeys, networkId) {
1441
- return {
1442
- state: localState,
1443
- publicKeys: PublicKeys.fromSecretKeys(secretKeys),
1444
- networkId,
1445
- coinHashes: CoinHashesMap.init(secretKeys, CoinHashesMap.pickAllCoins(localState)),
1446
- progress: require_const.createSyncProgress(),
1447
- protocolVersion: require_const.MinSupportedVersion
1448
- };
1449
- },
1450
- empty(publicKeys, networkId) {
1451
- return {
1452
- state: new _midnight_ntwrk_ledger_v8.ZswapLocalState(),
1453
- publicKeys,
1454
- networkId,
1455
- coinHashes: CoinHashesMap.empty,
1456
- progress: require_const.createSyncProgress(),
1457
- protocolVersion: require_const.MinSupportedVersion
1458
- };
1459
- },
1460
- restore(localState, secretKeys, syncProgress, protocolVersion, networkId) {
1461
- return {
1462
- state: localState,
1463
- publicKeys: PublicKeys.fromSecretKeys(secretKeys),
1464
- networkId,
1465
- coinHashes: CoinHashesMap.init(secretKeys, CoinHashesMap.pickAllCoins(localState)),
1466
- progress: require_const.createSyncProgress(syncProgress),
1467
- protocolVersion: require_const.ProtocolVersion(protocolVersion)
1468
- };
1469
- },
1470
- restoreWithCoinHashes(publicKeys, localState, coinHashes, syncProgress, protocolVersion, networkId) {
1471
- return CoinHashesMap.assertValid(coinHashes, localState).pipe(require_const.mapBoth$3({
1472
- onLeft: (missingNonces) => new InvalidCoinHashesError({
1473
- message: "Missing coin hashes for coins present in the state",
1474
- missingNonces
1475
- }),
1476
- onRight: () => ({
1477
- state: localState,
1478
- publicKeys,
1479
- networkId,
1480
- coinHashes,
1481
- progress: require_const.createSyncProgress(syncProgress),
1482
- protocolVersion: require_const.ProtocolVersion(protocolVersion)
1483
- })
1484
- }));
1485
- },
1486
- initEmpty(keys, networkId) {
1487
- return this.empty(PublicKeys.fromSecretKeys(keys), networkId);
1488
- },
1489
- applyCollapsedUpdate(wallet, collapsed) {
1490
- const newState = wallet.state.applyCollapsedUpdate(collapsed);
1491
- return {
1492
- ...wallet,
1493
- state: newState
1494
- };
1495
- },
1496
- apply(wallet, secretKeys, offer) {
1497
- const newState = wallet.state.apply(secretKeys, offer);
1498
- const newCoinHashes = CoinHashesMap.updateWithCoins(secretKeys, wallet.coinHashes, CoinHashesMap.pickAllCoins(newState));
1499
- return {
1500
- ...wallet,
1501
- state: newState,
1502
- coinHashes: newCoinHashes
1503
- };
1504
- },
1505
- replayEventsWithChanges(wallet, secretKeys, events) {
1506
- const stateWithChanges = wallet.state.replayEventsWithChanges(secretKeys, events);
1507
- const newState = stateWithChanges.state;
1508
- const newCoinHashes = CoinHashesMap.updateWithCoins(secretKeys, wallet.coinHashes, CoinHashesMap.pickAllCoins(newState));
1509
- return [{
1510
- ...wallet,
1511
- state: newState,
1512
- coinHashes: newCoinHashes
1513
- }, stateWithChanges.changes];
1514
- },
1515
- updateProgress(wallet, { appliedIndex, highestRelevantWalletIndex, highestIndex, highestRelevantIndex, isConnected }) {
1516
- const updatedProgress = require_const.createSyncProgress({
1517
- appliedIndex: appliedIndex ?? wallet.progress.appliedIndex,
1518
- highestRelevantWalletIndex: highestRelevantWalletIndex ?? wallet.progress.highestRelevantWalletIndex,
1519
- highestIndex: highestIndex ?? wallet.progress.highestIndex,
1520
- highestRelevantIndex: highestRelevantIndex ?? wallet.progress.highestRelevantIndex,
1521
- isConnected: isConnected ?? wallet.progress.isConnected
1522
- });
1523
- return {
1524
- ...wallet,
1525
- progress: updatedProgress
1526
- };
1527
- },
1528
- addTransaction(wallet, _tx) {
1529
- return wallet;
1530
- },
1531
- revertTransaction(wallet, tx) {
1532
- const newState = wallet.state.revertTransaction(tx);
1533
- return {
1534
- ...wallet,
1535
- state: newState
1536
- };
1537
- },
1538
- updateTxHistory(wallet, _newTxs) {
1539
- return wallet;
1540
- },
1541
- spendCoins(wallet, secretKeys, coins, segment) {
1542
- const [offers, newLocalState] = require_const.pipe(coins, require_const.reduce$3([[], wallet.state], ([accOffers, localState], coinToSpend) => {
1543
- const [nextState, newInput] = localState.spend(secretKeys, coinToSpend, segment);
1544
- const inputOffer = _midnight_ntwrk_ledger_v8.ZswapOffer.fromInput(newInput, coinToSpend.type, coinToSpend.value);
1545
- return [accOffers.concat([inputOffer]), nextState];
1546
- }));
1547
- return [offers, {
1548
- ...wallet,
1549
- state: newLocalState
1550
- }];
1551
- },
1552
- watchCoins(wallet, secretKeys, coins) {
1553
- const newLocalState = coins.reduce((localState, coin) => localState.watchFor(wallet.publicKeys.coinPublicKey, coin), wallet.state);
1554
- const newCoinHashes = CoinHashesMap.updateWithNewCoins(secretKeys, wallet.coinHashes, coins);
1555
- return {
1556
- ...wallet,
1557
- state: newLocalState,
1558
- coinHashes: newCoinHashes
1559
- };
1560
- }
1561
- };
1562
- //#endregion
1563
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Serialization.js
1564
- const StateSchema = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.ZswapLocalState).annotations({ identifier: "ledger.ZswapLocalState" });
1565
- const Uint8ArraySchema$1 = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
1566
- const StateFromUInt8Array = () => require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$1, StateSchema, {
1567
- encode: (state) => {
1568
- return require_const.try_({
1569
- try: () => {
1570
- return state.serialize();
1571
- },
1572
- catch: (err) => {
1573
- return new require_const.Unexpected(err, "Could not serialize local state");
1574
- }
1575
- });
1576
- },
1577
- decode: (bytes) => require_const.try_({
1578
- try: () => _midnight_ntwrk_ledger_v8.ZswapLocalState.deserialize(bytes),
1579
- catch: (err) => {
1580
- return new require_const.Unexpected(err, "Could not deserialize local state");
1581
- }
1582
- })
1583
- }));
1584
- const HexedState = () => require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(StateFromUInt8Array()));
1585
- const makeDefaultV1SerializationCapability = () => {
1586
- const SnapshotSchema = require_const.Struct({
1587
- publicKeys: require_const.Struct({
1588
- coinPublicKey: require_const.String$,
1589
- encryptionPublicKey: require_const.String$
1590
- }),
1591
- state: HexedState(),
1592
- protocolVersion: require_const.BigInt$,
1593
- offset: require_const.optional(require_const.BigInt$),
1594
- networkId: require_const.String$,
1595
- coinHashes: require_const.Record({
1596
- key: require_const.String$,
1597
- value: require_const.Struct({
1598
- nullifier: require_const.String$,
1599
- commitment: require_const.String$
1600
- })
1601
- })
1602
- });
1603
- return {
1604
- serialize: (wallet) => {
1605
- const buildSnapshot = (w) => ({
1606
- publicKeys: w.publicKeys,
1607
- state: w.state,
1608
- protocolVersion: w.protocolVersion,
1609
- networkId: w.networkId,
1610
- offset: w.progress?.appliedIndex,
1611
- coinHashes: w.coinHashes
1612
- });
1613
- return require_const.pipe(wallet, buildSnapshot, require_const.encodeSync(SnapshotSchema), JSON.stringify);
1614
- },
1615
- deserialize: (aux, serialized) => {
1616
- return require_const.pipe(serialized, require_const.decodeUnknownEither(require_const.parseJson(SnapshotSchema)), require_const.mapLeft((err) => WalletError.other(err)), require_const.flatMap$4((snapshot) => CoreWallet.restoreWithCoinHashes(snapshot.publicKeys, snapshot.state, snapshot.coinHashes, {
1617
- appliedIndex: snapshot.offset ?? 0n,
1618
- highestRelevantWalletIndex: 0n,
1619
- highestIndex: 0n,
1620
- highestRelevantIndex: 0n,
1621
- isConnected: false
1622
- }, snapshot.protocolVersion, snapshot.networkId)));
1623
- }
1624
- };
1625
- };
1626
- //#endregion
1627
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Sync.js
1628
- const Uint8ArraySchema = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
1629
- const WalletSyncUpdate = { create: (updates, secretKeys) => {
1630
- return {
1631
- updates,
1632
- secretKeys
1633
- };
1634
- } };
1635
- const LedgerEventSchema = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.Event).annotations({ identifier: "ledger.Event" });
1636
- const LedgerEventFromUint8Array = require_const.transformOrFail(Uint8ArraySchema, LedgerEventSchema, {
1637
- encode: (event) => require_const.try_({
1638
- try: () => event.serialize(),
1639
- catch: (error) => new require_const.Unexpected(error, "Could not serialize ledger event")
1640
- }),
1641
- decode: (bytes) => require_const.try_({
1642
- try: () => _midnight_ntwrk_ledger_v8.Event.deserialize(bytes),
1643
- catch: (error) => new require_const.Unexpected(error, "Could not deserialize ledger event")
1644
- })
1645
- });
1646
- const HexedLedgerEvent = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(LedgerEventFromUint8Array));
1647
- const EventsSyncUpdatePayload = require_const.Struct({
1648
- id: require_const.Number$,
1649
- raw: require_const.String$,
1650
- protocolVersion: require_const.Number$,
1651
- maxId: require_const.Number$
1652
- });
1653
- const EventsSyncUpdate = require_const.TaggedStruct("EventsSyncUpdate", {
1654
- id: require_const.Number$,
1655
- protocolVersion: require_const.Number$,
1656
- maxId: require_const.Number$,
1657
- event: LedgerEventSchema
1658
- });
1659
- const EventsSyncUpdateFromPayload = require_const.transformOrFail(EventsSyncUpdatePayload, EventsSyncUpdate, {
1660
- decode: (input) => require_const.pipe(require_const.decodeUnknownEither(HexedLedgerEvent)(input.raw), require_const.map$9((event) => ({
1661
- _tag: "EventsSyncUpdate",
1662
- id: input.id,
1663
- protocolVersion: input.protocolVersion,
1664
- maxId: input.maxId,
1665
- event
1666
- })), require_const.mapLeft((error) => new require_const.Unexpected(error, "Failed to decode ledger event payload")), require_watch.toEffect),
1667
- encode: (output) => require_const.pipe(require_const.encodeEither(HexedLedgerEvent)(output.event), require_const.map$9((raw) => ({
1668
- id: output.id,
1669
- raw,
1670
- protocolVersion: output.protocolVersion,
1671
- maxId: output.maxId
1672
- })), require_const.mapLeft((error) => new require_const.Unexpected(error, "Failed to encode ledger event payload")), require_watch.toEffect)
1673
- });
1674
- const makeEventsSyncService = (config) => {
1675
- return { updates: (state, secretKeys) => {
1676
- const { indexerClientConnection } = config;
1677
- const webSocketUrlResult = require_watch.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl);
1678
- if (require_const.isLeft(webSocketUrlResult)) return require_watch.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Could not derive WebSocket URL from indexer HTTP URL: ${webSocketUrlResult.left.message}`)));
1679
- const indexerWsUrlResult = require_watch.make(webSocketUrlResult.right);
1680
- if (require_const.isLeft(indexerWsUrlResult)) return require_watch.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Invalid indexer WS URL: ${indexerWsUrlResult.left.message}`)));
1681
- const indexerWsUrl = indexerWsUrlResult.right;
1682
- const resumeFrom = (state.progress?.appliedIndex ?? 0n) - 1n;
1683
- const batchSize = config.batchUpdates?.size ?? 10;
1684
- const batchTimeout = require_const.millis(config.batchUpdates?.timeout ?? 1);
1685
- const batchSpacing = config.batchUpdates?.spacing ?? 4;
1686
- const bufferSize = config.indexerClientConnection.bufferSize ?? 1e4;
1687
- const resumeThreshold = config.indexerClientConnection.resumeThreshold ?? 100;
1688
- const eventsStream = require_const.pipe(require_watch.ZswapEvents.runWithBackpressure({
1689
- bufferSize,
1690
- resumeThreshold,
1691
- from: resumeFrom,
1692
- variables: (cursor) => ({ id: cursor < 0n ? null : Number(cursor) }),
1693
- key: (r) => BigInt(r.zswapLedgerEvents.id)
1694
- }), require_watch.provideLayer(require_watch.layer({
1695
- url: indexerWsUrl,
1696
- keepAlive: config.indexerClientConnection.keepAlive
1697
- })), require_watch.mapError((error) => new SyncWalletError(error)), require_watch.mapEffect((subscription) => require_const.pipe(subscription.zswapLedgerEvents, require_const.decodeUnknownEither(EventsSyncUpdateFromPayload), require_const.mapLeft((err) => new SyncWalletError(err)), require_watch.toEffect)), require_watch.groupedWithin(batchSize, batchTimeout), require_watch.map(require_const.toArray), require_watch.map((data) => WalletSyncUpdate.create(data, secretKeys)));
1698
- return batchSpacing > 0 ? require_watch.schedule(eventsStream, require_watch.spaced(require_const.millis(batchSpacing))) : eventsStream;
1699
- } };
1700
- };
1701
- const makeEventsSyncCapability = () => {
1702
- return { applyUpdate: (state, wrappedUpdate) => {
1703
- if (wrappedUpdate.updates.length === 0) return [state, {
1704
- changes: [],
1705
- protocolVersion: Number(state.protocolVersion)
1706
- }];
1707
- const appliedIndex = state.progress?.appliedIndex ?? 0n;
1708
- const freshUpdates = wrappedUpdate.updates.filter((u) => BigInt(u.id) > appliedIndex);
1709
- const lastUpdate = wrappedUpdate.updates.at(-1);
1710
- const highestRelevantWalletIndex = BigInt(lastUpdate.maxId);
1711
- const [newState, newChanges] = freshUpdates.length === 0 ? [state, []] : CoreWallet.replayEventsWithChanges(state, wrappedUpdate.secretKeys, freshUpdates.map((u) => u.event));
1712
- return [CoreWallet.updateProgress(newState, {
1713
- highestRelevantWalletIndex,
1714
- appliedIndex: freshUpdates.length === 0 ? appliedIndex : BigInt(freshUpdates.at(-1).id),
1715
- isConnected: true
1716
- }), {
1717
- changes: newChanges,
1718
- protocolVersion: lastUpdate.protocolVersion
1719
- }];
1720
- } };
1721
- };
1722
- //#endregion
1723
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionImbalances.js
1724
- const ShieldedCostModel = {
1725
- inputFeeOverhead: 0n,
1726
- outputFeeOverhead: 0n
1727
- };
1728
- const TransactionImbalances = new class {
1729
- empty = () => {
1730
- return {
1731
- guaranteed: require_watch.Imbalances.empty(),
1732
- fallible: /* @__PURE__ */ new Map()
1733
- };
1734
- };
1735
- areBalanced = (imbalances) => {
1736
- const areGuaranteedAllZeroes = imbalances.guaranteed.entries().every(([, value]) => value === 0n);
1737
- const areFallibleAllZeroes = Array.from(imbalances.fallible.values()).every((segmentImbalances) => segmentImbalances.entries().every(([, value]) => value === 0n));
1738
- return areGuaranteedAllZeroes && areFallibleAllZeroes;
1739
- };
1740
- }();
1741
- //#endregion
1742
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionOps.js
1743
- const TransactionOps = new class {
1744
- default = {
1745
- getImbalances(tx) {
1746
- return TransactionOps.shared.getImbalances(tx);
1747
- },
1748
- id(tx) {
1749
- return tx.identifiers().at(0);
1750
- }
1751
- };
1752
- proofErased = {
1753
- getImbalances(tx) {
1754
- return TransactionOps.shared.getImbalances(tx);
1755
- },
1756
- id(tx) {
1757
- return tx.identifiers().at(0);
1758
- }
1759
- };
1760
- unproven = {
1761
- getImbalances(tx) {
1762
- return TransactionOps.shared.getImbalances(tx);
1763
- },
1764
- id(tx) {
1765
- return tx.identifiers().at(0);
1766
- }
1767
- };
1768
- shared = {
1769
- getImbalances(tx) {
1770
- return {
1771
- guaranteed: TransactionOps.shared.getGuaranteedImbalances(tx),
1772
- fallible: TransactionOps.shared.getFallibleImbalances(tx)
1773
- };
1774
- },
1775
- getGuaranteedImbalances: (tx) => {
1776
- const rawGuaranteedImbalances = tx.imbalances(0).entries().filter(([token]) => token.tag === "shielded").map(([token, value]) => {
1777
- return [token.raw, value];
1778
- });
1779
- return require_watch.Imbalances.fromEntries(rawGuaranteedImbalances);
1780
- },
1781
- getFallibleImbalances: (tx) => {
1782
- const fallibleImbalances = Array.from(tx.fallibleOffer?.keys() ?? []).flatMap((segment) => {
1783
- const rawImbalances = tx.imbalances(segment).entries().filter(([token]) => token.tag === "shielded").map(([token, value]) => {
1784
- return [token.raw, value];
1785
- });
1786
- return [[segment, require_watch.Imbalances.fromEntries(rawImbalances)]];
1787
- });
1788
- return new Map(fallibleImbalances);
1789
- }
1790
- };
1791
- }();
1792
- //#endregion
1793
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Transacting.js
1794
- const makeDefaultTransactingCapability = (config, getContext) => {
1795
- return new TransactingCapabilityImplementation(config.networkId, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability, TransactionOps.default);
1796
- };
1797
- var TransactingCapabilityImplementation = class {
1798
- networkId;
1799
- getCoinSelection;
1800
- txOps;
1801
- getCoins;
1802
- getKeys;
1803
- constructor(networkId, getCoinSelection, getCoins, getKeys, txOps) {
1804
- this.getCoins = getCoins;
1805
- this.networkId = networkId;
1806
- this.getCoinSelection = getCoinSelection;
1807
- this.getKeys = getKeys;
1808
- this.txOps = txOps;
1809
- }
1810
- balanceTransaction(secretKeys, state, tx) {
1811
- return require_const.gen$1(this, function* () {
1812
- const coinSelection = this.getCoinSelection();
1813
- const initialImbalances = this.txOps.getImbalances(tx);
1814
- if (TransactionImbalances.areBalanced(initialImbalances)) return [void 0, state];
1815
- const { newState: afterFallible, fallibleOffers } = yield* this.balanceFallibleSection(secretKeys, state, initialImbalances, coinSelection);
1816
- const { newState: afterGuaranteed, offer: guaranteed } = yield* this.#balanceGuaranteedSection(secretKeys, afterFallible, initialImbalances, coinSelection, require_watch.Imbalances.empty());
1817
- return [Array.from(fallibleOffers.entries()).reduce((tx, [segment, offer]) => tx.addZswapOffer({
1818
- tag: "specific",
1819
- value: segment
1820
- }, offer), _midnight_ntwrk_ledger_v8.Transaction.fromParts(this.networkId, guaranteed)), afterGuaranteed];
1821
- });
1822
- }
1823
- makeTransfer(secretKeys, state, transfers) {
1824
- return require_const.gen$1(this, function* () {
1825
- const positiveTransfers = yield* require_const.pipe(transfers, require_const.filter$2((t) => t.amount > 0n), require_const.match$2({
1826
- onEmpty: () => require_const.left(new OtherWalletError({ message: "The amount needs to be positive" })),
1827
- onNonEmpty: (nonEmpty) => require_const.right(nonEmpty)
1828
- }));
1829
- const networkId = this.networkId;
1830
- const { initialOffersAndCoins, selfCoins } = yield* this.#processDesiredOutputs(state, positiveTransfers);
1831
- const offerToBalance = require_const.pipe(initialOffersAndCoins, require_const.map$6((o) => o.outputOffer), require_watch.fold((a, b) => a.merge(b)));
1832
- const unprovenTxToBalance = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offerToBalance);
1833
- const imbalances = TransactionOps.unproven.getImbalances(unprovenTxToBalance);
1834
- const { offer, newState } = yield* this.#balanceGuaranteedSection(secretKeys, state, imbalances, this.getCoinSelection(), require_watch.Imbalances.empty());
1835
- const finalState = CoreWallet.watchCoins(newState, secretKeys, selfCoins);
1836
- return [unprovenTxToBalance.merge(_midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offer)), finalState];
1837
- });
1838
- }
1839
- initSwap(secretKeys, state, desiredInputs, desiredOutputs) {
1840
- return require_const.gen$1(this, function* () {
1841
- if (!desiredOutputs.every((output) => output.amount > 0n)) return yield* require_const.left(new OtherWalletError({ message: "The amount needs to be positive" }));
1842
- if (!Object.entries(desiredInputs).every(([, amount]) => amount > 0n)) return yield* require_const.left(new OtherWalletError({ message: "The input amounts need to be positive" }));
1843
- const outputsParseResult = yield* this.#processDesiredOutputsPossiblyEmpty(state, desiredOutputs);
1844
- const inputsParseResult = require_watch.Imbalances.fromEntries(require_const.toEntries(desiredInputs));
1845
- const networkId = this.networkId;
1846
- const { offer, newState } = yield* this.#balanceGuaranteedSection(secretKeys, state, TransactionImbalances.empty(), this.getCoinSelection(), inputsParseResult);
1847
- const finalState = CoreWallet.watchCoins(newState, secretKeys, outputsParseResult.selfCoins);
1848
- const balancingTx = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offer);
1849
- return [outputsParseResult.unprovenTxToBalance ? outputsParseResult.unprovenTxToBalance.merge(balancingTx) : balancingTx, finalState];
1850
- });
1851
- }
1852
- revertTransaction(state, transaction) {
1853
- return require_const.try_$1({
1854
- try: () => {
1855
- return CoreWallet.revertTransaction(state, transaction);
1856
- },
1857
- catch: (err) => {
1858
- return new OtherWalletError({
1859
- message: `Error while reverting transaction ${transaction.identifiers().at(0)}`,
1860
- cause: err
1861
- });
1862
- }
1863
- });
1864
- }
1865
- #prepareOffer(secretKeys, state, recipe, segment) {
1866
- const [inputOffers, stateAfterSpends] = CoreWallet.spendCoins(state, secretKeys, recipe.inputs, segment);
1867
- const stateAfterWatches = CoreWallet.watchCoins(stateAfterSpends, secretKeys, recipe.outputs);
1868
- const outputOffers = recipe.outputs.map((coin) => {
1869
- const output = _midnight_ntwrk_ledger_v8.ZswapOutput.new(coin, segment, this.getKeys().getCoinPublicKey(state).toHexString(), this.getKeys().getEncryptionPublicKey(state).toHexString());
1870
- return _midnight_ntwrk_ledger_v8.ZswapOffer.fromOutput(output, coin.type, coin.value);
1871
- });
1872
- return require_const.pipe(require_const.appendAll$1(inputOffers, outputOffers), require_const.match$2({
1873
- onEmpty: () => require_const.none(),
1874
- onNonEmpty: (nonEmpty) => require_const.pipe(nonEmpty, require_watch.fold((a, b) => a.merge(b)), require_const.some)
1875
- }), require_const.map$8((offer) => ({
1876
- offer,
1877
- newState: stateAfterWatches
1878
- })));
1879
- }
1880
- balanceFallibleSection(secretKeys, state, imbalances, coinSelection) {
1881
- return Array.from(imbalances.fallible.entries()).reduce((acc, [segment, segmentImbalances]) => require_const.flatMap$4(acc, ({ fallibleOffers, newState }) => require_const.pipe(require_const.try_$1({
1882
- try: () => {
1883
- const fallibleBalanceRecipe = require_watch.getBalanceRecipe({
1884
- coins: this.getCoins().getAvailableCoins(newState).map((c) => c.coin),
1885
- initialImbalances: segmentImbalances,
1886
- transactionCostModel: ShieldedCostModel,
1887
- feeTokenType: "",
1888
- coinSelection,
1889
- createOutput: (coin) => _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(coin.type, coin.value),
1890
- isCoinEqual: (a, b) => a.type === b.type && a.value === b.value
1891
- });
1892
- return this.#prepareOffer(secretKeys, newState, fallibleBalanceRecipe, segment);
1893
- },
1894
- catch: (err) => {
1895
- if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError({
1896
- message: `Insufficient funds for fallible segment ${segment}`,
1897
- tokenType: err.tokenType,
1898
- amount: segmentImbalances.get(err.tokenType) ?? 0n
1899
- });
1900
- return new OtherWalletError({
1901
- message: `Balancing fallible segment ${segment} failed`,
1902
- cause: err
1903
- });
1904
- }
1905
- }), require_const.map$9(require_const.match$3({
1906
- onNone: () => ({
1907
- fallibleOffers,
1908
- newState
1909
- }),
1910
- onSome: (res) => ({
1911
- fallibleOffers: new Map([...fallibleOffers, [segment, res.offer]]),
1912
- newState: res.newState
1913
- })
1914
- })))), require_const.right({
1915
- fallibleOffers: /* @__PURE__ */ new Map(),
1916
- newState: state
1917
- }));
1918
- }
1919
- #balanceGuaranteedSection(secretKeys, state, imbalances, coinSelection, targetImbalances) {
1920
- return require_const.gen$1(this, function* () {
1921
- const balanceRecipe = yield* require_const.try_$1({
1922
- try: () => require_watch.getBalanceRecipe({
1923
- coins: this.getCoins().getAvailableCoins(state).map((c) => c.coin),
1924
- initialImbalances: imbalances.guaranteed,
1925
- transactionCostModel: ShieldedCostModel,
1926
- feeTokenType: "",
1927
- coinSelection,
1928
- createOutput: (coin) => _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(coin.type, coin.value),
1929
- isCoinEqual: (a, b) => a.nonce === b.nonce,
1930
- targetImbalances
1931
- }),
1932
- catch: (err) => {
1933
- if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError({
1934
- message: "Insufficient funds",
1935
- tokenType: err.tokenType,
1936
- amount: imbalances.guaranteed.get(err.tokenType) ?? 0n
1937
- });
1938
- else return new OtherWalletError({
1939
- message: "Balancing guaranteed section failed",
1940
- cause: err
1941
- });
1942
- }
1943
- });
1944
- return require_const.pipe(this.#prepareOffer(secretKeys, state, balanceRecipe, 0), require_const.match$3({
1945
- onNone: () => ({
1946
- offer: void 0,
1947
- newState: state
1948
- }),
1949
- onSome: (result) => result
1950
- }));
1951
- });
1952
- }
1953
- #processDesiredOutputs(state, transfers) {
1954
- return require_const.try_$1({
1955
- try: () => {
1956
- const initialOffersAndCoins = require_const.pipe(transfers, require_const.map$6((transfer) => {
1957
- const { receiverAddress, type, amount } = transfer;
1958
- const coin = _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(type, amount);
1959
- const output = _midnight_ntwrk_ledger_v8.ZswapOutput.new(coin, 0, receiverAddress.coinPublicKey.toHexString(), receiverAddress.encryptionPublicKey.toHexString());
1960
- return {
1961
- coin,
1962
- outputOffer: _midnight_ntwrk_ledger_v8.ZswapOffer.fromOutput(output, type, amount),
1963
- isForSelf: receiverAddress.coinPublicKey.equals(this.getKeys().getCoinPublicKey(state))
1964
- };
1965
- }));
1966
- return {
1967
- initialOffersAndCoins,
1968
- selfCoins: require_const.flatMap$3(initialOffersAndCoins, ({ coin, isForSelf }) => {
1969
- if (isForSelf) return [coin];
1970
- else return [];
1971
- })
1972
- };
1973
- },
1974
- catch: (err) => {
1975
- return new OtherWalletError({
1976
- message: "Failed to process desired outputs",
1977
- cause: err
1978
- });
1979
- }
1980
- });
1981
- }
1982
- #processDesiredOutputsPossiblyEmpty(state, desiredOutputs) {
1983
- return require_const.pipe(desiredOutputs, require_const.match$2({
1984
- onEmpty: () => {
1985
- return require_const.right({
1986
- imbalances: TransactionImbalances.empty(),
1987
- selfCoins: [],
1988
- unprovenTxToBalance: null
1989
- });
1990
- },
1991
- onNonEmpty: (desiredOutputs) => {
1992
- return require_const.pipe(this.#processDesiredOutputs(state, desiredOutputs), require_const.map$9(({ initialOffersAndCoins, selfCoins }) => {
1993
- const networkId = this.networkId;
1994
- const offerToBalance = require_const.pipe(initialOffersAndCoins, require_const.map$6((o) => o.outputOffer), require_watch.fold((a, b) => a.merge(b)));
1995
- const unprovenTxToBalance = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offerToBalance);
1996
- return {
1997
- imbalances: TransactionOps.unproven.getImbalances(unprovenTxToBalance),
1998
- selfCoins,
1999
- unprovenTxToBalance
2000
- };
2001
- }));
2002
- }
2003
- }));
2004
- }
2005
- };
2006
- //#endregion
2007
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/CoinsAndBalances.js
2008
- const calculateBalances = (coins) => coins.reduce((acc, { coin }) => ({
2009
- ...acc,
2010
- [coin.type]: acc[coin.type] === void 0 ? coin.value : acc[coin.type] + coin.value
2011
- }), {});
2012
- const makeDefaultCoinsAndBalancesCapability = () => {
2013
- const getAvailableBalances = (state) => {
2014
- return calculateBalances(getAvailableCoins(state));
2015
- };
2016
- const getPendingBalances = (state) => {
2017
- return calculateBalances(getPendingCoins(state));
2018
- };
2019
- const getTotalBalances = (state) => {
2020
- return require_const.pipe([getAvailableBalances(state), getPendingBalances(state)], require_watch.mergeWithAccumulator(0n, (a, b) => a + b));
2021
- };
2022
- const getAvailableCoins = (state) => {
2023
- const pendingSpends = new Set([...state.state.pendingSpends.values()].map(([coin]) => coin.nonce));
2024
- return require_const.pipe([...state.state.coins], require_const.filter$2((coin) => !pendingSpends.has(coin.nonce)), require_const.map$6((coin) => {
2025
- return {
2026
- coin,
2027
- commitment: state.coinHashes[coin.nonce].commitment,
2028
- nullifier: state.coinHashes[coin.nonce].nullifier
2029
- };
2030
- }));
2031
- };
2032
- const getPendingCoins = (state) => require_const.pipe([...state.state.pendingOutputs.values()], require_const.map$6(([coin, ttl]) => ({
2033
- coin,
2034
- ttl,
2035
- commitment: state.coinHashes[coin.nonce].commitment,
2036
- nullifier: state.coinHashes[coin.nonce].nullifier
2037
- })));
2038
- const getTotalCoins = (state) => [...getAvailableCoins(state), ...getPendingCoins(state)];
2039
- return {
2040
- getAvailableBalances,
2041
- getPendingBalances,
2042
- getTotalBalances,
2043
- getAvailableCoins,
2044
- getPendingCoins,
2045
- getTotalCoins
2046
- };
2047
- };
2048
- //#endregion
2049
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Keys.js
2050
- require__polyfill_buffer_patch.init__polyfill_buffer_patch();
2051
- const makeDefaultKeysCapability = () => {
2052
- return {
2053
- getCoinPublicKey: (state) => {
2054
- return new require_dist.ShieldedCoinPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.coinPublicKey, "hex"));
2055
- },
2056
- getEncryptionPublicKey: (state) => {
2057
- return new require_dist.ShieldedEncryptionPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.encryptionPublicKey, "hex"));
2058
- },
2059
- getAddress: (state) => {
2060
- return new require_dist.ShieldedAddress(new require_dist.ShieldedCoinPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.coinPublicKey, "hex")), new require_dist.ShieldedEncryptionPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.encryptionPublicKey, "hex")));
2061
- }
2062
- };
2063
- };
2064
- //#endregion
2065
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionHistory.js
2066
- const QualifiedShieldedCoinInfoSchema = require_const.Struct({
2067
- type: require_const.String$,
2068
- nonce: require_const.String$,
2069
- value: require_const.BigInt$,
2070
- mtIndex: require_const.BigInt$
2071
- });
2072
- const ShieldedSectionSchema = require_const.Struct({
2073
- receivedCoins: require_const.Array$(QualifiedShieldedCoinInfoSchema),
2074
- spentCoins: require_const.Array$(QualifiedShieldedCoinInfoSchema)
2075
- });
2076
- require_const.Struct({
2077
- hash: require_const.TransactionHashSchema,
2078
- protocolVersion: require_const.Number$,
2079
- status: require_const.TransactionHistoryStatusSchema,
2080
- shielded: ShieldedSectionSchema
2081
- });
2082
- const coinEquals = require_const.equivalence(QualifiedShieldedCoinInfoSchema);
2083
- const mergeShieldedSections = (existing, incoming) => ({
2084
- receivedCoins: require_const.unionWith$1(existing.receivedCoins, incoming.receivedCoins, coinEquals),
2085
- spentCoins: require_const.unionWith$1(existing.spentCoins, incoming.spentCoins, coinEquals)
2086
- });
2087
- const convertUpdateToStorageEntry = (changes, metadata, protocolVersion) => ({
2088
- hash: changes.source,
2089
- protocolVersion,
2090
- status: metadata.status,
2091
- shielded: {
2092
- receivedCoins: changes.receivedCoins.map(({ mt_index, ...rest }) => ({
2093
- ...rest,
2094
- mtIndex: mt_index
2095
- })),
2096
- spentCoins: changes.spentCoins.map(({ mt_index, ...rest }) => ({
2097
- ...rest,
2098
- mtIndex: mt_index
2099
- }))
2100
- }
2101
- });
2102
- const upsertShieldedEntry = (txHistoryStorage, entry) => require_const.tryPromise({
2103
- try: () => txHistoryStorage.upsert(entry),
2104
- catch: (e) => new TransactionHistoryError({
2105
- message: `Failed to upsert history entry for ${entry.hash}`,
2106
- cause: e
2107
- })
2108
- });
2109
- const makeDefaultTransactionHistoryService = (config, _getContext) => {
2110
- const txHistoryStorage = config.txHistoryStorage;
2111
- const queryClientLayer = require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl });
2112
- return {
2113
- put: (changes, metadata, protocolVersion) => {
2114
- return upsertShieldedEntry(txHistoryStorage, convertUpdateToStorageEntry(changes, metadata, protocolVersion));
2115
- },
2116
- getTransactionDetails: (hash) => require_const.gen(function* () {
2117
- const tx = (yield* (yield* require_watch.TransactionHistoryDetail)({ transactionHash: hash })).transactions[0];
2118
- const rawStatus = tx.__typename === "RegularTransaction" ? tx.transactionResult.status : void 0;
2119
- const status = rawStatus === "FAILURE" || rawStatus === "PARTIAL_SUCCESS" ? rawStatus : "SUCCESS";
2120
- return {
2121
- hash: tx.hash,
2122
- timestamp: tx.block.timestamp,
2123
- status
2124
- };
2125
- }).pipe(require_const.provide(queryClientLayer), require_const.scoped$1, require_const.retry(require_watch.exponential(require_const.seconds(1)).pipe(require_watch.compose(require_watch.recurs(3)))), require_const.mapError$1((cause) => new TransactionHistoryError({
2126
- message: `Failed to fetch transaction metadata for ${hash}`,
2127
- cause
2128
- })))
2129
- };
2130
- };
2131
- //#endregion
2132
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/V1Builder.js
2133
- var V1Builder = class V1Builder {
2134
- #buildState;
2135
- constructor(buildState = {}) {
2136
- this.#buildState = buildState;
2137
- }
2138
- withDefaults() {
2139
- return this.withDefaultTransactionType().withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
2140
- }
2141
- withTransactionType() {
2142
- return new V1Builder({
2143
- ...this.#buildState,
2144
- transactingCapability: void 0,
2145
- transactionHistoryService: void 0
2146
- });
2147
- }
2148
- withDefaultTransactionType() {
2149
- return this.withTransactionType();
2150
- }
2151
- withSyncDefaults() {
2152
- return this.withSync(makeEventsSyncService, makeEventsSyncCapability);
2153
- }
2154
- withSync(syncService, syncCapability) {
2155
- return new V1Builder({
2156
- ...this.#buildState,
2157
- syncService,
2158
- syncCapability
2159
- });
2160
- }
2161
- withSerializationDefaults() {
2162
- return this.withSerialization(makeDefaultV1SerializationCapability);
2163
- }
2164
- withSerialization(serializationCapability) {
2165
- return new V1Builder({
2166
- ...this.#buildState,
2167
- serializationCapability
2168
- });
2169
- }
2170
- withTransactingDefaults() {
2171
- return this.withTransacting(makeDefaultTransactingCapability);
2172
- }
2173
- withTransacting(transactingCapability) {
2174
- return new V1Builder({
2175
- ...this.#buildState,
2176
- transactingCapability
2177
- });
2178
- }
2179
- withCoinSelection(coinSelection) {
2180
- return new V1Builder({
2181
- ...this.#buildState,
2182
- coinSelection
2183
- });
2184
- }
2185
- withCoinSelectionDefaults() {
2186
- return this.withCoinSelection(() => require_watch.chooseCoin);
2187
- }
2188
- withCoinsAndBalancesDefaults() {
2189
- return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability);
2190
- }
2191
- withCoinsAndBalances(coinsAndBalancesCapability) {
2192
- return new V1Builder({
2193
- ...this.#buildState,
2194
- coinsAndBalancesCapability
2195
- });
2196
- }
2197
- withTransactionHistoryDefaults() {
2198
- return this.withTransactionHistory(makeDefaultTransactionHistoryService);
2199
- }
2200
- withTransactionHistory(transactionHistoryService) {
2201
- return new V1Builder({
2202
- ...this.#buildState,
2203
- transactionHistoryService
2204
- });
2205
- }
2206
- withKeysDefaults() {
2207
- return this.withKeys(makeDefaultKeysCapability);
2208
- }
2209
- withKeys(keysCapability) {
2210
- return new V1Builder({
2211
- ...this.#buildState,
2212
- keysCapability
2213
- });
2214
- }
2215
- build(configuration) {
2216
- const v1Context = this.#buildContextFromBuildState(configuration);
2217
- const { networkId } = configuration;
2218
- return {
2219
- __polyTag__: V1Tag,
2220
- coinsAndBalances: v1Context.coinsAndBalancesCapability,
2221
- keys: v1Context.keysCapability,
2222
- serialization: v1Context.serializationCapability,
2223
- transactionHistory: v1Context.transactionHistoryService,
2224
- start(context) {
2225
- return require_const.gen(function* () {
2226
- return new RunningV1Variant(yield* require_const.Scope, context, v1Context);
2227
- });
2228
- },
2229
- migrateState(_previousState) {
2230
- const seed = require_const.fromString("0000000000000000000000000000000000000000000000000000000000000001");
2231
- return require_const.succeed(CoreWallet.empty(PublicKeys.fromSecretKeys(_midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(seed)), networkId));
2232
- },
2233
- deserializeState: (serialized) => {
2234
- return v1Context.serializationCapability.deserialize(null, serialized);
2235
- }
2236
- };
2237
- }
2238
- #buildContextFromBuildState(configuration) {
2239
- if (!isBuildStateFull(this.#buildState)) throw new Error("Not all components are configured in V1 Builder");
2240
- const { syncCapability, syncService, transactingCapability, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
2241
- const getContext = () => context;
2242
- const context = {
2243
- serializationCapability: serializationCapability(configuration, getContext),
2244
- syncCapability: syncCapability(configuration, getContext),
2245
- syncService: syncService(configuration, getContext),
2246
- transactingCapability: transactingCapability(configuration, getContext),
2247
- coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
2248
- keysCapability: keysCapability(configuration, getContext),
2249
- coinSelection: coinSelection(configuration, getContext),
2250
- transactionHistoryService: transactionHistoryService(configuration, getContext)
2251
- };
2252
- return context;
2253
- }
2254
- };
2255
- const isBuildStateFull = (buildState) => {
2256
- return [
2257
- "syncService",
2258
- "syncCapability",
2259
- "transactingCapability",
2260
- "coinSelection",
2261
- "serializationCapability",
2262
- "coinsAndBalancesCapability",
2263
- "keysCapability",
2264
- "transactionHistoryService"
2265
- ].every((key) => typeof buildState[key] == "function");
2266
- };
2267
- //#endregion
2268
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/ShieldedWallet.js
2269
- var ShieldedWalletState = class ShieldedWalletState {
2270
- static mapState = (variant) => (state) => {
2271
- const { serialization, coinsAndBalances, keys } = variant;
2272
- const { transactionHistory } = variant;
2273
- return new ShieldedWalletState(state, {
2274
- serialization,
2275
- coinsAndBalances,
2276
- keys
2277
- }, { transactionHistory });
2278
- };
2279
- protocolVersion;
2280
- state;
2281
- capabilities;
2282
- services;
2283
- get balances() {
2284
- return this.capabilities.coinsAndBalances.getAvailableBalances(this.state);
2285
- }
2286
- get totalCoins() {
2287
- return this.capabilities.coinsAndBalances.getTotalCoins(this.state);
2288
- }
2289
- get availableCoins() {
2290
- return this.capabilities.coinsAndBalances.getAvailableCoins(this.state);
2291
- }
2292
- get pendingCoins() {
2293
- return this.capabilities.coinsAndBalances.getPendingCoins(this.state);
2294
- }
2295
- get coinPublicKey() {
2296
- return this.capabilities.keys.getCoinPublicKey(this.state);
2297
- }
2298
- get encryptionPublicKey() {
2299
- return this.capabilities.keys.getEncryptionPublicKey(this.state);
2300
- }
2301
- get address() {
2302
- return this.capabilities.keys.getAddress(this.state);
2303
- }
2304
- get progress() {
2305
- return this.state.progress;
2306
- }
2307
- constructor(state, capabilities, services) {
2308
- this.protocolVersion = state.version;
2309
- this.state = state.state;
2310
- this.capabilities = capabilities;
2311
- this.services = services;
2312
- }
2313
- serialize() {
2314
- return this.capabilities.serialization.serialize(this.state);
2315
- }
2316
- };
2317
- function ShieldedWallet(configuration) {
2318
- return CustomShieldedWallet(configuration, new V1Builder().withDefaults());
2319
- }
2320
- function CustomShieldedWallet(configuration, builder) {
2321
- const buildArgs = [configuration];
2322
- const BaseWallet = require_watch.WalletBuilder.init().withVariant(require_const.MinSupportedVersion, builder).build(...buildArgs);
2323
- return class CustomShieldedWalletImplementation extends BaseWallet {
2324
- static startWithSecretKeys(secretKeys) {
2325
- return CustomShieldedWalletImplementation.startFirst(CustomShieldedWalletImplementation, CoreWallet.initEmpty(secretKeys, CustomShieldedWalletImplementation.configuration.networkId));
2326
- }
2327
- static startWithSeed(seed) {
2328
- const secretKeys = _midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(seed);
2329
- return CustomShieldedWalletImplementation.startWithSecretKeys(secretKeys);
2330
- }
2331
- static restore(serializedState) {
2332
- const deserialized = CustomShieldedWalletImplementation.allVariantsRecord()[V1Tag].variant.deserializeState(serializedState).pipe(require_const.getOrThrow$1);
2333
- return CustomShieldedWalletImplementation.startFirst(CustomShieldedWalletImplementation, deserialized);
2334
- }
2335
- state;
2336
- constructor(runtime, scope) {
2337
- super(runtime, scope);
2338
- this.state = this.rawState.pipe(rxjs.map(ShieldedWalletState.mapState(CustomShieldedWalletImplementation.allVariantsRecord()[V1Tag].variant)), rxjs.shareReplay({
2339
- refCount: true,
2340
- bufferSize: 1
2341
- }));
2342
- }
2343
- start(secretKeys) {
2344
- return this.runtime.dispatch({ [V1Tag]: (v1) => v1.startSyncInBackground(secretKeys) }).pipe(require_const.runPromise);
2345
- }
2346
- balanceTransaction(secretKeys, tx) {
2347
- return this.runtime.dispatch({ [V1Tag]: (v1) => v1.balanceTransaction(secretKeys, tx) }).pipe(require_const.runPromise);
2348
- }
2349
- transferTransaction(secretKeys, outputs) {
2350
- return this.runtime.dispatch({ [V1Tag]: (v1) => v1.transferTransaction(secretKeys, outputs) }).pipe(require_const.runPromise);
2351
- }
2352
- initSwap(secretKeys, desiredInputs, desiredOutputs) {
2353
- return this.runtime.dispatch({ [V1Tag]: (v1) => v1.initSwap(secretKeys, desiredInputs, desiredOutputs) }).pipe(require_const.runPromise);
2354
- }
2355
- revertTransaction(transaction) {
2356
- return this.runtime.dispatch({ [V1Tag]: (v1) => v1.revertTransaction(transaction) }).pipe(require_const.runPromise);
2357
- }
2358
- waitForSyncedState(allowedGap = 0n) {
2359
- return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
2360
- }
2361
- /**
2362
- * Serializes the most recent state It's preferable to use [[ShieldedWalletState.serialize]] instead, to know
2363
- * exactly, which state is serialized
2364
- */
2365
- serializeState() {
2366
- return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
2367
- }
2368
- getAddress() {
2369
- return rxjs.firstValueFrom(this.state).then((state) => state.address);
2370
- }
2371
- };
2372
- }
2373
- //#endregion
2374
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-facade/dist/transaction.js
2375
- const finalizedTransactionTrait = {
2376
- areAllTxIdsIncluded(tx, txIds) {
2377
- const txIdsSet = require_const.fromIterable$1(tx.identifiers());
2378
- const expectedIdSet = require_const.fromIterable$1(txIds);
2379
- return require_const.isSubset(txIdsSet, expectedIdSet);
2380
- },
2381
- deserialize(serialized) {
2382
- return _midnight_ntwrk_ledger_v8.Transaction.deserialize("signature", "proof", "binding", serialized);
2383
- },
2384
- firstId(tx) {
2385
- return tx.identifiers()[0];
2386
- },
2387
- hasTTLExpired(tx, creationTime, now) {
2388
- const defaultShieldedGracePeriod = _midnight_ntwrk_ledger_v8.LedgerParameters.initialParameters().dust.dustGracePeriodSeconds;
2389
- const intentTTLs = require_const.pipe(tx.intents?.values().toArray() ?? [], require_const.map$6((i) => i.ttl), require_const.filterMap$1(require_const.make));
2390
- const hasDustPayments = require_const.pipe(tx.intents?.values().toArray() ?? [], require_const.flatMap$3((i) => i.dustActions?.spends ?? []), require_const.isNonEmptyArray);
2391
- const hasShieldedOffers = tx.guaranteedOffer != null || (tx.fallibleOffer?.size ?? 0) == 0;
2392
- const maybeShieldedTTL = hasDustPayments || hasShieldedOffers ? require_const.pipe(creationTime, require_const.addDuration(require_const.seconds(Number(defaultShieldedGracePeriod))), require_const.of$2) : require_const.empty$3();
2393
- return require_const.pipe(intentTTLs, require_const.appendAll$1(maybeShieldedTTL), (arr) => require_const.isNonEmptyReadonlyArray(arr) ? require_const.some(require_const.min(arr, require_const.mapInput$1(require_const.Date, require_const.toDate))) : require_const.none(), require_const.match$3({
2394
- onNone: () => false,
2395
- onSome: (finalTTL) => require_const.distance(finalTTL, now) > 0
2396
- }));
2397
- },
2398
- ids(tx) {
2399
- return tx.identifiers();
2400
- },
2401
- isOneIncludedInOther(tx, otherTx) {
2402
- const txIds = require_const.fromIterable$1(tx.identifiers());
2403
- const otherTxIds = require_const.fromIterable$1(otherTx.identifiers());
2404
- const smallerSize = require_const.min$1(require_const.number)(require_const.size(txIds), require_const.size(otherTxIds));
2405
- const intersection$1 = require_const.intersection(txIds, otherTxIds);
2406
- return require_const.size(intersection$1) == smallerSize;
2407
- },
2408
- isTx(tx) {
2409
- return tx instanceof _midnight_ntwrk_ledger_v8.Transaction;
2410
- },
2411
- serialize(tx) {
2412
- return tx.serialize();
2413
- }
2414
- };
2415
- //#endregion
2416
- //#region ../../node_modules/@midnightntwrk/wallet-sdk-facade/dist/index.js
2417
- /**
2418
- * Full entry schema for transaction history — common fields + all wallet sections. Pass this to
2419
- * `InMemoryTransactionHistoryStorage` to enable serialize/restore.
2420
- */
2421
- const WalletEntrySchema = require_const.Struct({
2422
- ...require_const.TransactionHistoryCommonSchema.fields,
2423
- shielded: require_const.optional(ShieldedSectionSchema),
2424
- unshielded: require_const.optional(require_watch.UnshieldedSectionSchema),
2425
- dust: require_const.optional(DustSectionSchema)
2426
- });
2427
- const mergeWalletEntries = (existing, incoming) => ({
2428
- ...existing,
2429
- ...incoming,
2430
- ...existing.shielded !== void 0 && incoming.shielded !== void 0 ? { shielded: mergeShieldedSections(existing.shielded, incoming.shielded) } : {},
2431
- ...existing.unshielded !== void 0 && incoming.unshielded !== void 0 ? { unshielded: {
2432
- ...existing.unshielded,
2433
- ...incoming.unshielded
2434
- } } : {},
2435
- ...existing.dust !== void 0 && incoming.dust !== void 0 ? { dust: mergeDustSections(existing.dust, incoming.dust) } : {}
2436
- });
2437
- const isWalletEntry = require_const.is(WalletEntrySchema);
2438
- const TokenKindsToBalance = new class {
2439
- allTokenKinds = [
2440
- "shielded",
2441
- "unshielded",
2442
- "dust"
2443
- ];
2444
- toFlags = (tokenKinds) => {
2445
- return require_const.pipe(tokenKinds, (kinds) => kinds === "all" ? this.allTokenKinds : kinds, (kinds) => ({
2446
- shouldBalanceUnshielded: kinds.includes("unshielded"),
2447
- shouldBalanceShielded: kinds.includes("shielded"),
2448
- shouldBalanceDust: kinds.includes("dust")
2449
- }));
2450
- };
2451
- }();
2452
- const BalancingRecipe = {
2453
- isRecipe: (value) => {
2454
- return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && [
2455
- "FINALIZED_TRANSACTION",
2456
- "UNBOUND_TRANSACTION",
2457
- "UNPROVEN_TRANSACTION"
2458
- ].includes(value.type);
2459
- },
2460
- getTransactions: (recipe) => {
2461
- switch (recipe.type) {
2462
- case "FINALIZED_TRANSACTION": return [recipe.originalTransaction, recipe.balancingTransaction];
2463
- case "UNBOUND_TRANSACTION": {
2464
- const balancingPart = recipe.balancingTransaction ? [recipe.balancingTransaction] : [];
2465
- return [recipe.baseTransaction, ...balancingPart];
2466
- }
2467
- case "UNPROVEN_TRANSACTION": return [recipe.transaction];
2468
- }
2469
- }
2470
- };
2471
- var FacadeState = class {
2472
- shielded;
2473
- unshielded;
2474
- dust;
2475
- pending;
2476
- get isSynced() {
2477
- return this.shielded.state.progress.isStrictlyComplete() && this.dust.state.progress.isStrictlyComplete() && this.unshielded.progress.isStrictlyComplete();
2478
- }
2479
- constructor(shielded, unshielded, dust, pending) {
2480
- this.shielded = shielded;
2481
- this.unshielded = unshielded;
2482
- this.dust = dust;
2483
- this.pending = pending;
2484
- }
2485
- };
2486
- const DEFAULT_TTL_MS = 3600 * 1e3;
2487
- var WalletFacade = class WalletFacade {
2488
- static makeDefaultSubmissionService(config) {
2489
- return require_watch.makeDefaultSubmissionService(config);
2490
- }
2491
- static makeDefaultPendingTransactionsService(config) {
2492
- return require_watch.PendingTransactionsServiceImpl.init({
2493
- configuration: config,
2494
- txTrait: finalizedTransactionTrait
2495
- });
2496
- }
2497
- static makeDefaultProvingService(config) {
2498
- if (config.provingServerUrl) return require_watch.makeDefaultProvingService({ provingServerUrl: config.provingServerUrl });
2499
- else throw new Error("Missing required configuration: 'provingServerUrl' must be set in config, or provide a custom provingService in init parameters.");
2500
- }
2501
- /**
2502
- * Fetches the current Terms and Conditions from the network indexer.
2503
- *
2504
- * This is a static, pre-initialization utility — no wallet instance is required. Wallet builders should call this
2505
- * before or independently of wallet initialization to display the current T&C to end users and obtain the hash for
2506
- * content verification.
2507
- *
2508
- * The returned `hash` is the hex-encoded SHA-256 hash of the document at `url`. Wallet builders are responsible for
2509
- * fetching and rendering the document content via `url` in whatever manner suits their application.
2510
- *
2511
- * @param configuration - An object with an `indexerClientConnection.indexerHttpUrl`. Any wallet configuration that
2512
- * satisfies {@link FetchTermsAndConditionsConfiguration} can be passed directly.
2513
- * @returns A promise resolving to the current {@link TermsAndConditions}, or rejecting if no Terms and Conditions have
2514
- * been set on the network yet.
2515
- */
2516
- static async fetchTermsAndConditions(configuration) {
2517
- const tc = (await require_watch.runPromise(require_watch.FetchTermsAndConditions, {}, { url: configuration.indexerClientConnection.indexerHttpUrl })).block?.systemParameters?.termsAndConditions;
2518
- if (!tc) throw new Error("Terms and Conditions are not currently set on the network.");
2519
- return tc;
2520
- }
2521
- /**
2522
- * Default initialization for {@link WalletFacade}. It is a static method, which takes an object holding configuration
2523
- * and initialization of necessary components. Specifically - it requires following fields:
2524
- *
2525
- * - `configuration` - holding a configuration, which needs to extend {@link DefaultConfiguration} - this way allows to
2526
- * convey use-case-specific settings in the same way, as the SDK works by default
2527
- * - `shielded` - a function taking the configuration and returning shielded wallet (or a promise with such)
2528
- * implementing {@link ShieldedWalletAPI}
2529
- * - `unshielded` - a function taking the configuration and returning unshielded wallet (or a promise with such)
2530
- * implementing {@link UnshieldedWalletAPI}
2531
- * - `dust` - a function taking the configuration and returning Dust wallet (or a promise with such) implementing
2532
- * {@link DustWalletAPI} There are some optional services/abstractions to provide, too. If not provided - default
2533
- * implementations will be used, each of them is initialized by a function taking the configuration and returning
2534
- * proper implementation (wrapped in a {@link Promise} or not).
2535
- * - `submissionService` - needs to implement {@link SubmissionService} for a {@link ledger.FinalizedTransaction} to
2536
- * submit transactions to the network, default uses Node RPC connection
2537
- * - `pendingTransactionsService` - needs to implement {@link PendingTransactionsService} for a
2538
- * {@link ledger.FinalizedTransaction} to keep track of pending transactions, default uses in-memory implementation
2539
- * - `provingService` - needs to implement {@link ProvingService} to prove it, default uses proving server
2540
- * - `clock` - needs to implement {@link Clock.Clock} for getting current time, default uses system clock
2541
- */
2542
- static async init(initParams) {
2543
- const submissionService = await Promise.resolve(initParams.submissionService ? initParams.submissionService(initParams.configuration) : WalletFacade.makeDefaultSubmissionService(initParams.configuration));
2544
- const pendingTransactionsService = await Promise.resolve(initParams.pendingTransactionsService ? initParams.pendingTransactionsService(initParams.configuration) : WalletFacade.makeDefaultPendingTransactionsService(initParams.configuration));
2545
- const provingService = await Promise.resolve(initParams.provingService ? initParams.provingService(initParams.configuration) : WalletFacade.makeDefaultProvingService(initParams.configuration));
2546
- const shielded = await Promise.resolve(initParams.shielded(initParams.configuration));
2547
- const unshielded = await Promise.resolve(initParams.unshielded(initParams.configuration));
2548
- const dust = await Promise.resolve(initParams.dust(initParams.configuration));
2549
- const clock = await Promise.resolve(initParams.clock ? initParams.clock(initParams.configuration) : require_watch.systemClock);
2550
- return new WalletFacade(shielded, unshielded, dust, submissionService, pendingTransactionsService, provingService, initParams.configuration.txHistoryStorage, clock);
2551
- }
2552
- shielded;
2553
- unshielded;
2554
- dust;
2555
- submissionService;
2556
- pendingTransactionsService;
2557
- provingService;
2558
- #txHistoryStorage;
2559
- clock;
2560
- #pendingSubscription;
2561
- /**
2562
- * Constructor is private on purpose - much of initialization of the facade is potentially asynchronous, and adding
2563
- * new parameters is a breaking change to the users Use {@link WalletFacade.init} instead
2564
- *
2565
- * @private
2566
- */
2567
- constructor(shieldedWallet, unshieldedWallet, dustWallet, submissionService, pendingTransactionsService, provingService, txHistoryStorage, clock = require_watch.systemClock) {
2568
- this.shielded = shieldedWallet;
2569
- this.unshielded = unshieldedWallet;
2570
- this.dust = dustWallet;
2571
- this.submissionService = submissionService;
2572
- this.pendingTransactionsService = pendingTransactionsService;
2573
- this.provingService = provingService;
2574
- this.#txHistoryStorage = txHistoryStorage;
2575
- this.clock = clock;
2576
- this.#pendingSubscription = this.pendingTransactionsService.state().pipe((0, rxjs.concatMap)((pending) => require_watch.allFailed(pending)), (0, rxjs.concatMap)((item) => this.revert(item.tx))).subscribe();
2577
- }
2578
- defaultTtl() {
2579
- return new Date(this.clock.now().getTime() + DEFAULT_TTL_MS);
2580
- }
2581
- mergeUnprovenTransactions(a, b) {
2582
- if (a && b) return a.merge(b);
2583
- return a ?? b;
2584
- }
2585
- async createDustActionTransaction(action, nightUtxos, nightVerifyingKey, signDustRegistration) {
2586
- const ttl = this.defaultTtl();
2587
- const now = this.clock.now();
2588
- const isRegistration = action.type === "registration";
2589
- const dustReceiverAddress = isRegistration ? action.dustReceiverAddress : void 0;
2590
- const split = await this.dust.splitNightUtxosForDustRegistration(now, nightUtxos.map(({ utxo, meta }) => ({
2591
- ...utxo,
2592
- ctime: meta.ctime,
2593
- registeredForDustGeneration: meta.registeredForDustGeneration
2594
- })), isRegistration);
2595
- const toUnshieldedUtxoWithMeta = (u) => ({
2596
- utxo: {
2597
- value: u.utxo.value,
2598
- type: u.utxo.type,
2599
- owner: u.utxo.owner,
2600
- intentHash: u.utxo.intentHash,
2601
- outputNo: u.utxo.outputNo
2602
- },
2603
- meta: {
2604
- ctime: u.utxo.ctime,
2605
- registeredForDustGeneration: u.utxo.registeredForDustGeneration
2606
- }
2607
- });
2608
- const guaranteedForUnshielded = split.guaranteedUtxos.map(toUnshieldedUtxoWithMeta);
2609
- const fallibleForUnshielded = split.fallibleUtxos.map(toUnshieldedUtxoWithMeta);
2610
- const txWithOffers = await this.unshielded.rotateUtxos(guaranteedForUnshielded, fallibleForUnshielded, nightVerifyingKey, ttl);
2611
- let txWithDustActions;
2612
- try {
2613
- txWithDustActions = await this.dust.attachDustRegistration(txWithOffers, now, nightVerifyingKey, dustReceiverAddress, split.feePayment);
2614
- } catch (error) {
2615
- await this.unshielded.revertTransaction(txWithOffers);
2616
- throw error;
2617
- }
2618
- const hasUnregisteredGuaranteed = split.guaranteedUtxos.some((u) => !u.utxo.registeredForDustGeneration);
2619
- if (isRegistration && hasUnregisteredGuaranteed) {
2620
- const fee = await this.dust.calculateFee([txWithDustActions]);
2621
- if (split.feePayment < fee) {
2622
- await this.unshielded.revertTransaction(txWithOffers);
2623
- throw Error(`Insufficient generated dust to cover registration fee (have ${split.feePayment}, need ${fee}). Use WalletFacade.waitForGeneratedDust(utxos, ${fee}) before retrying.`);
2624
- }
2625
- }
2626
- try {
2627
- const signedRecipe = await this.signRecipe({
2628
- type: "UNPROVEN_TRANSACTION",
2629
- transaction: txWithDustActions
2630
- }, signDustRegistration);
2631
- if (signedRecipe.type !== "UNPROVEN_TRANSACTION") throw Error("signRecipe returned unexpected recipe type for dust action transaction.");
2632
- return signedRecipe.transaction;
2633
- } catch (error) {
2634
- await this.unshielded.revertTransaction(txWithOffers);
2635
- throw error;
2636
- }
2637
- }
2638
- state() {
2639
- return (0, rxjs.combineLatest)([
2640
- this.shielded.state,
2641
- this.unshielded.state,
2642
- this.dust.state,
2643
- this.pendingTransactionsService.state()
2644
- ]).pipe((0, rxjs.map)(([shieldedState, unshieldedState, dustState, pending]) => new FacadeState(shieldedState, unshieldedState, dustState, pending)));
2645
- }
2646
- async waitForSyncedState() {
2647
- const [shieldedState, unshieldedState, dustState, pending] = await Promise.all([
2648
- this.shielded.waitForSyncedState(),
2649
- this.unshielded.waitForSyncedState(),
2650
- this.dust.waitForSyncedState(),
2651
- (0, rxjs.firstValueFrom)(this.pendingTransactionsService.state())
2652
- ]);
2653
- return new FacadeState(shieldedState, unshieldedState, dustState, pending);
2654
- }
2655
- async submitTransaction(tx) {
2656
- try {
2657
- await this.pendingTransactionsService.addPendingTransaction(tx);
2658
- await this.submissionService.submitTransaction(tx, "Finalized");
2659
- return tx.identifiers().at(-1);
2660
- } catch (error) {
2661
- await this.revert(tx);
2662
- throw error;
2663
- }
2664
- }
2665
- async balanceFinalizedTransaction(tx, secretKeys, options) {
2666
- const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2667
- const { ttl, tokenKindsToBalance = "all" } = options;
2668
- const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2669
- const unshieldedBalancingTx = shouldBalanceUnshielded ? await this.unshielded.balanceFinalizedTransaction(tx) : void 0;
2670
- const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2671
- const mergedBalancingTx = this.mergeUnprovenTransactions(shieldedBalancingTx, unshieldedBalancingTx);
2672
- const feeBalancingTx = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, mergedBalancingTx ? [tx, mergedBalancingTx] : [tx], ttl) : void 0;
2673
- const balancingTx = this.mergeUnprovenTransactions(mergedBalancingTx, feeBalancingTx);
2674
- if (!balancingTx) throw new Error("No balancing transaction was created. Please check your transaction.");
2675
- return {
2676
- type: "FINALIZED_TRANSACTION",
2677
- originalTransaction: tx,
2678
- balancingTransaction: balancingTx
2679
- };
2680
- }
2681
- async balanceUnboundTransaction(tx, secretKeys, options) {
2682
- const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2683
- const { ttl, tokenKindsToBalance = "all" } = options;
2684
- const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2685
- const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2686
- const balancedUnshieldedTx = shouldBalanceUnshielded ? await this.unshielded.balanceUnboundTransaction(tx) : void 0;
2687
- const baseTx = balancedUnshieldedTx ?? tx;
2688
- const feeBalancingTransaction = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, shieldedBalancingTx ? [baseTx, shieldedBalancingTx] : [baseTx], ttl) : void 0;
2689
- const balancingTransaction = this.mergeUnprovenTransactions(shieldedBalancingTx, feeBalancingTransaction);
2690
- if (!balancingTransaction && !balancedUnshieldedTx) throw new Error("No balancing transaction was created. Please check your transaction.");
2691
- return {
2692
- type: "UNBOUND_TRANSACTION",
2693
- baseTransaction: baseTx,
2694
- balancingTransaction: balancingTransaction ?? void 0
2695
- };
2696
- }
2697
- async balanceUnprovenTransaction(tx, secretKeys, options) {
2698
- const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2699
- const { ttl, tokenKindsToBalance = "all" } = options;
2700
- const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2701
- const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2702
- const baseTx = (shouldBalanceUnshielded ? await this.unshielded.balanceUnprovenTransaction(tx) : void 0) ?? tx;
2703
- const mergedTx = this.mergeUnprovenTransactions(baseTx, shieldedBalancingTx);
2704
- const feeBalancingTx = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, [mergedTx], ttl) : void 0;
2705
- return {
2706
- type: "UNPROVEN_TRANSACTION",
2707
- transaction: this.mergeUnprovenTransactions(mergedTx, feeBalancingTx)
2708
- };
2709
- }
2710
- async finalizeRecipe(recipe) {
2711
- return Promise.resolve(recipe).then(async (recipe) => {
2712
- switch (recipe.type) {
2713
- case "FINALIZED_TRANSACTION": {
2714
- const finalizedBalancing = await this.finalizeTransaction(recipe.balancingTransaction);
2715
- return recipe.originalTransaction.merge(finalizedBalancing);
2716
- }
2717
- case "UNBOUND_TRANSACTION": {
2718
- const finalizedBalancingTx = recipe.balancingTransaction ? await this.finalizeTransaction(recipe.balancingTransaction) : void 0;
2719
- const finalizedTransaction = recipe.baseTransaction.bind();
2720
- return finalizedBalancingTx ? finalizedTransaction.merge(finalizedBalancingTx) : finalizedTransaction;
2721
- }
2722
- case "UNPROVEN_TRANSACTION": return await this.finalizeTransaction(recipe.transaction);
2723
- }
2724
- }).then(async (finalizedTx) => {
2725
- await this.pendingTransactionsService.addPendingTransaction(finalizedTx);
2726
- return finalizedTx;
2727
- });
2728
- }
2729
- async signRecipe(recipe, signSegment) {
2730
- switch (recipe.type) {
2731
- case "FINALIZED_TRANSACTION": {
2732
- const signedBalancingTx = await this.signUnprovenTransaction(recipe.balancingTransaction, signSegment);
2733
- const withDustSig = await this.#signDustRegistrationIfPresent(signedBalancingTx, signSegment);
2734
- return {
2735
- type: "FINALIZED_TRANSACTION",
2736
- originalTransaction: recipe.originalTransaction,
2737
- balancingTransaction: withDustSig
2738
- };
2739
- }
2740
- case "UNBOUND_TRANSACTION": {
2741
- const signedBalancingTx = recipe.balancingTransaction ? await this.signUnprovenTransaction(recipe.balancingTransaction, signSegment).then((tx) => this.#signDustRegistrationIfPresent(tx, signSegment)) : void 0;
2742
- return {
2743
- type: "UNBOUND_TRANSACTION",
2744
- baseTransaction: await this.signUnboundTransaction(recipe.baseTransaction, signSegment),
2745
- balancingTransaction: signedBalancingTx
2746
- };
2747
- }
2748
- case "UNPROVEN_TRANSACTION": {
2749
- const signedTx = await this.signUnprovenTransaction(recipe.transaction, signSegment);
2750
- return {
2751
- type: "UNPROVEN_TRANSACTION",
2752
- transaction: await this.#signDustRegistrationIfPresent(signedTx, signSegment)
2753
- };
2754
- }
2755
- }
2756
- }
2757
- async #signDustRegistrationIfPresent(tx, signSegment) {
2758
- const intent = tx.intents?.get(1);
2759
- const registrations = intent?.dustActions?.registrations ?? [];
2760
- if (!intent || registrations.length === 0) return tx;
2761
- const signature = signSegment(intent.signatureData(1));
2762
- return await this.dust.addDustRegistrationSignature(tx, signature);
2763
- }
2764
- async signUnprovenTransaction(tx, signSegment) {
2765
- return await this.unshielded.signUnprovenTransaction(tx, signSegment);
2766
- }
2767
- async signUnboundTransaction(tx, signSegment) {
2768
- return await this.unshielded.signUnboundTransaction(tx, signSegment);
2769
- }
2770
- async finalizeTransaction(tx) {
2771
- try {
2772
- const finalizedTx = (await this.provingService.prove(tx)).bind();
2773
- await this.pendingTransactionsService.addPendingTransaction(finalizedTx);
2774
- return finalizedTx;
2775
- } catch (error) {
2776
- await Promise.allSettled([
2777
- this.shielded.revertTransaction(tx),
2778
- this.unshielded.revertTransaction(tx),
2779
- this.dust.revertTransaction(tx)
2780
- ]);
2781
- throw error;
2782
- }
2783
- }
2784
- /** Estimates the fee for the given transaction only. This lacks the fees of the balancing transaction. */
2785
- async calculateTransactionFee(tx) {
2786
- return await this.dust.calculateFee([tx]);
2787
- }
2788
- /** Calculates the total fee for the given transaction plus the fee of the balancing transaction. */
2789
- async estimateTransactionFee(tx, secretKey, options) {
2790
- const ttl = options?.ttl ?? this.defaultTtl();
2791
- return await this.dust.estimateFee(secretKey, [tx], ttl, options?.currentTime);
2792
- }
2793
- async transferTransaction(outputs, secretKeys, options) {
2794
- const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2795
- const { ttl, payFees = true } = options;
2796
- const unshieldedOutputs = outputs.filter((output) => output.type === "unshielded").flatMap((output) => output.outputs);
2797
- const shieldedOutputs = outputs.filter((output) => output.type === "shielded").flatMap((output) => output.outputs);
2798
- if (unshieldedOutputs.length === 0 && shieldedOutputs.length === 0) throw Error("At least one shielded or unshielded output is required.");
2799
- const shieldedTx = shieldedOutputs.length > 0 ? await this.shielded.transferTransaction(shieldedSecretKeys, shieldedOutputs) : void 0;
2800
- const unshieldedTx = unshieldedOutputs.length > 0 ? await this.unshielded.transferTransaction(unshieldedOutputs, ttl) : void 0;
2801
- const mergedTxs = this.mergeUnprovenTransactions(shieldedTx, unshieldedTx);
2802
- const feeBalancingTx = payFees ? await this.dust.balanceTransactions(dustSecretKey, [mergedTxs], ttl) : void 0;
2803
- return {
2804
- type: "UNPROVEN_TRANSACTION",
2805
- transaction: this.mergeUnprovenTransactions(mergedTxs, feeBalancingTx)
2806
- };
2807
- }
2808
- /**
2809
- * Provides estimate of the fee of issuing registration transaction with provided UTxOs
2810
- *
2811
- * @param nightUtxos - Night UTxOs to use for the registration
2812
- * @returns And object informing about fee at the moment, as well as estimation of dust generation of the UTxO(s),
2813
- * that would be used for paying the fee. These include data that allows to compute when the fee could be paid
2814
- */
2815
- async estimateRegistration(nightUtxos) {
2816
- const now = this.clock.now();
2817
- const dustState = await this.dust.waitForSyncedState();
2818
- const dustGenerationEstimations = require_const.pipe(nightUtxos, require_const.map$6(({ utxo, meta }) => ({
2819
- ...utxo,
2820
- ctime: meta.ctime,
2821
- registeredForDustGeneration: meta.registeredForDustGeneration
2822
- })), (utxosWithMeta) => dustState.estimateDustGeneration(utxosWithMeta, now), (estimatedUtxos) => dustState.capabilities.coinsAndBalances.splitNightUtxos(estimatedUtxos), (split) => split.guaranteed);
2823
- const fakeSigningKey = _midnight_ntwrk_ledger_v8.sampleSigningKey();
2824
- const fakeVerifyingKey = _midnight_ntwrk_ledger_v8.signatureVerifyingKey(fakeSigningKey);
2825
- const ttl = this.defaultTtl();
2826
- const fakeUnsignedTx = await this.dust.createDustGenerationTransaction(void 0, ttl, nightUtxos.map(({ utxo, meta }) => ({
2827
- ...utxo,
2828
- ctime: meta.ctime,
2829
- registeredForDustGeneration: meta.registeredForDustGeneration
2830
- })), fakeVerifyingKey, dustState.address);
2831
- const intent = fakeUnsignedTx.intents?.get(1);
2832
- if (!intent) throw Error("Dust generation transaction is missing intent segment 1.");
2833
- const signatureData = intent.signatureData(1);
2834
- const signature = _midnight_ntwrk_ledger_v8.signData(fakeSigningKey, signatureData);
2835
- const finalizedFakeTx = (await this.dust.addDustGenerationSignature(fakeUnsignedTx, signature)).mockProve().bind();
2836
- return {
2837
- fee: await this.calculateTransactionFee(finalizedFakeTx),
2838
- dustGenerationEstimations
2839
- };
2840
- }
2841
- async initSwap(desiredInputs, desiredOutputs, secretKeys, options) {
2842
- const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2843
- const { ttl, payFees = false } = options;
2844
- const { shielded: shieldedInputs, unshielded: unshieldedInputs } = desiredInputs;
2845
- const shieldedOutputs = desiredOutputs.filter((output) => output.type === "shielded").flatMap((output) => output.outputs);
2846
- const unshieldedOutputs = desiredOutputs.filter((output) => output.type === "unshielded").flatMap((output) => output.outputs);
2847
- const hasShieldedPart = shieldedInputs && Object.keys(shieldedInputs).length > 0 || shieldedOutputs.length > 0;
2848
- const hasUnshieldedPart = unshieldedInputs && Object.keys(unshieldedInputs).length > 0 || unshieldedOutputs.length > 0;
2849
- if (!hasShieldedPart && !hasUnshieldedPart) throw Error("At least one shielded or unshielded swap is required.");
2850
- const shieldedTx = hasShieldedPart && shieldedInputs !== void 0 ? await this.shielded.initSwap(shieldedSecretKeys, shieldedInputs, shieldedOutputs) : void 0;
2851
- const unshieldedTx = hasUnshieldedPart && unshieldedInputs !== void 0 ? await this.unshielded.initSwap(unshieldedInputs, unshieldedOutputs, ttl) : void 0;
2852
- const combinedTx = this.mergeUnprovenTransactions(shieldedTx, unshieldedTx);
2853
- if (!combinedTx) throw Error("Unexpected transaction state.");
2854
- const feeBalancingTx = payFees ? await this.dust.balanceTransactions(dustSecretKey, [combinedTx], ttl) : void 0;
2855
- return {
2856
- type: "UNPROVEN_TRANSACTION",
2857
- transaction: this.mergeUnprovenTransactions(combinedTx, feeBalancingTx)
2858
- };
2859
- }
2860
- async registerNightUtxosForDustGeneration(nightUtxos, nightVerifyingKey, signDustRegistration, dustReceiverAddress) {
2861
- if (nightUtxos.length === 0) throw Error("At least one Night UTXO is required.");
2862
- const receiverAddress = dustReceiverAddress ?? await this.dust.getAddress();
2863
- return {
2864
- type: "UNPROVEN_TRANSACTION",
2865
- transaction: await this.createDustActionTransaction({
2866
- type: "registration",
2867
- dustReceiverAddress: receiverAddress
2868
- }, nightUtxos, nightVerifyingKey, signDustRegistration)
2869
- };
2870
- }
2871
- /**
2872
- * Waits until the dust projected to be generated by the given Night UTxOs reaches `requiredAmount`, re-checking every
2873
- * second. Pair with {@link estimateRegistration} to pick `requiredAmount`, then call before
2874
- * {@link registerNightUtxosForDustGeneration} so the registration covers its own fee.
2875
- *
2876
- * @param nightUtxos - Night UTxOs to project generation for; the same set passed to the registration.
2877
- * @param requiredAmount - Dust threshold to wait for. Resolves immediately if `<= 0n`.
2878
- * @param opts.timeoutMs - Deadline, in ms, for the threshold to be reached. Rejects otherwise. Default `300_000`.
2879
- * @throws If `nightUtxos` is empty, or if `requiredAmount` is not reached within `opts.timeoutMs`.
2880
- */
2881
- async waitForGeneratedDust(nightUtxos, requiredAmount, opts) {
2882
- await this.dust.waitForGeneratedDust(nightUtxos.map(({ utxo, meta }) => ({
2883
- ...utxo,
2884
- ctime: meta.ctime,
2885
- registeredForDustGeneration: meta.registeredForDustGeneration
2886
- })), requiredAmount, this.clock, opts);
2887
- }
2888
- async deregisterFromDustGeneration(nightUtxos, nightVerifyingKey, signDustRegistration) {
2889
- return {
2890
- type: "UNPROVEN_TRANSACTION",
2891
- transaction: await this.createDustActionTransaction({ type: "deregistration" }, nightUtxos, nightVerifyingKey, signDustRegistration)
2892
- };
2893
- }
2894
- async revert(txOrRecipe) {
2895
- const transactionsToRevert = BalancingRecipe.isRecipe(txOrRecipe) ? BalancingRecipe.getTransactions(txOrRecipe) : [txOrRecipe];
2896
- await Promise.all(transactionsToRevert.map((tx) => this.revertTransaction(tx)));
2897
- }
2898
- async revertTransaction(tx) {
2899
- await Promise.all([
2900
- this.shielded.revertTransaction(tx),
2901
- this.unshielded.revertTransaction(tx),
2902
- this.dust.revertTransaction(tx)
2903
- ]).then(() => this.pendingTransactionsService.clear(tx));
2904
- }
2905
- async start(shieldedSecretKeys, dustSecretKey) {
2906
- await Promise.all([
2907
- this.shielded.start(shieldedSecretKeys),
2908
- this.unshielded.start(),
2909
- this.dust.start(dustSecretKey),
2910
- this.pendingTransactionsService.start()
2911
- ]);
2912
- }
2913
- async stop() {
2914
- await Promise.all([
2915
- this.shielded.stop(),
2916
- this.unshielded.stop(),
2917
- this.dust.stop(),
2918
- this.submissionService.close(),
2919
- this.pendingTransactionsService.stop(),
2920
- Promise.resolve(this.#pendingSubscription?.unsubscribe())
2921
- ]);
2922
- }
2923
- async queryTxHistoryByHash(hash) {
2924
- const raw = await this.#txHistoryStorage.get(hash);
2925
- return raw && isWalletEntry(raw) ? raw : void 0;
2926
- }
2927
- async getAllFromTxHistory() {
2928
- return [...await this.#txHistoryStorage.getAll()];
2929
- }
2930
- };
2931
- //#endregion
2932
- //#region ../../packages/module/midnight-sync/src/store/compute-sync-ratio.ts
2933
- const computeConnectedSyncRatio = (applied, highest, isConnected) => isConnected && applied === 0n && highest === 0n ? (0, _laceio_cardano_util.Percent)(1) : computeSyncRatio(applied, highest);
2934
- const computeSyncRatio = (applied, highest) => {
2935
- if (highest === 0n) {
2936
- if (applied === 0n) return (0, _laceio_cardano_util.Percent)(0);
2937
- const ratio = 1 - 1 / (1 + Number(applied) / 1e3);
2938
- return (0, _laceio_cardano_util.Percent)(Math.min(.99, ratio));
2939
- }
2940
- return (0, _laceio_cardano_util.Percent)(Math.min(1, Number(applied) / Number(highest)));
2941
- };
2942
- //#endregion
2943
- //#region ../../packages/module/midnight-sync/src/store/dependencies.ts
2944
- /**
2945
- * Wraps keyManager.keys$ with recovery for AuthenticationCancelledError.
2946
- * If the user cancels the auth prompt, waits for keys to become available
2947
- * from another source (e.g., an unlock triggered by a different flow)
2948
- * and retries.
2949
- */
2950
- const keysWithAuthCancelledRecovery$ = (keyManager) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.catchError)((error) => {
2951
- if (!(error instanceof require_types.AuthenticationCancelledError)) return (0, rxjs.throwError)(() => error);
2952
- return keyManager.areKeysAvailable$.pipe((0, rxjs.filter)((available) => available), (0, rxjs.take)(1), (0, rxjs.switchMap)(() => keyManager.keys$.pipe((0, rxjs.take)(1))));
2953
- }));
2954
- const STATE_SERIALISATION_THROTTLE_TIME = require_time_vo.Milliseconds(5e3);
2955
- const DEFAULT_BATCH_UPDATES = {
2956
- size: 12,
2957
- spacing: 4
2958
- };
2959
- /**
2960
- * Restore accepts the legacy `unshieldedTxHistory` key so profiles written
2961
- * before the persisted key was renamed load without a resync; the next persist
2962
- * rewrites the doc under `txHistory`, migrating it lazily.
2963
- */
2964
- const readPersistedTxHistory = (serializedState) => serializedState.txHistory ?? serializedState.unshieldedTxHistory;
2965
- /**
2966
- * djb2 over the serialized states. The previous-persist comparator must not
2967
- * RETAIN the inputs: keeping the raw serialized strings would pin ~10MB per
2968
- * synced wallet in service worker memory between persist cycles.
2969
- */
2970
- const fingerprintOf = (parts) => {
2971
- let hash = 5381;
2972
- for (const part of parts) for (let index = 0; index < part.length; index += 1) {
2973
- hash = hash * 33 ^ part.charCodeAt(index);
2974
- hash |= 0;
2975
- }
2976
- return `${hash}:${parts.map((part) => part.length).join(":")}`;
2977
- };
2978
- const getAccountWalletInstance = async ({ account, config, getTemenosLedgerIndexerUrl, store, keyManager }, logger, { createAttestedProver, batchUpdates = DEFAULT_BATCH_UPDATES }) => {
2979
- const walletState = await (0, rxjs.firstValueFrom)(store.get(String(account.accountId)).pipe((0, rxjs.defaultIfEmpty)(void 0)));
2980
- const indexerClientConnection = {
2981
- indexerHttpUrl: config.indexerAddress,
2982
- indexerWsUrl: require_utils.convertHttpUrlToWebsocket(config.indexerAddress),
2983
- keepAlive: 15e3
2984
- };
2985
- const { networkId } = account.blockchainSpecific;
2986
- const proofServerUrl = require_const.getProofServerEndpoint(config.proofServer);
2987
- if (!proofServerUrl) throw new Error(`Cannot start Midnight wallet: proof server mode "${config.proofServer.kind}" has no HTTP endpoint`);
2988
- require_const.assertProofServerRouting(config.proofServer, !!createAttestedProver);
2989
- const createAccess = (onProgress) => config.proofServer.kind === "tee-delegated" && createAttestedProver ? require_watch.createAttestedProofServerAccess(createAttestedProver({
2990
- networkId,
2991
- proofServerApiUrl: config.proofServer.url,
2992
- getLedgerIndexerUrl: async () => {
2993
- if (!getTemenosLedgerIndexerUrl) throw new Error("Temenos attestation requires a ledger indexer resolver");
2994
- return getTemenosLedgerIndexerUrl();
2995
- }
2996
- }), onProgress) : require_watch.createProofServerAccess(require_watch.createHttpProofServerTransport(proofServerUrl));
2997
- const proofServer = require_watch.createScopedProofServerAccess(createAccess);
2998
- const { finalizeRecipe } = proofServer;
2999
- const configuration = {
3000
- costParameters: {
3001
- additionalFeeOverhead: 300000000000000n,
3002
- feeBlocksMargin: 5
3003
- },
3004
- networkId,
3005
- batchUpdates,
3006
- indexerClientConnection,
3007
- relayURL: new URL(require_utils.convertHttpUrlToWebsocket(config.nodeAddress)),
3008
- txHistoryStorage: new require_const.InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries)
3009
- };
3010
- if (walletState) {
3011
- const { dust, shielded, unshielded } = walletState.serializedState;
3012
- let restoredTxHistoryStorage;
3013
- try {
3014
- restoredTxHistoryStorage = require_const.InMemoryTransactionHistoryStorage.restore(SerialisedWalletState.toJSON(readPersistedTxHistory(walletState.serializedState)), WalletEntrySchema, mergeWalletEntries);
3015
- } catch (error) {
3016
- logger.warn(`Discarding unreadable persisted Midnight wallet state for account ${account.accountId}; rebuilding from seed`, error instanceof Error ? error.message : String(error));
3017
- await (0, rxjs.firstValueFrom)(store.removeWhere((state) => state.accountId === account.accountId).pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((wipeError) => {
3018
- logger.error(`Failed to discard unreadable Midnight wallet state for account ${account.accountId}`, wipeError);
3019
- return (0, rxjs.of)(void 0);
3020
- })));
3021
- }
3022
- if (restoredTxHistoryStorage) {
3023
- configuration.txHistoryStorage = restoredTxHistoryStorage;
3024
- return {
3025
- walletFacade: await WalletFacade.init({
3026
- configuration,
3027
- provingService: () => proofServer.provingService,
3028
- shielded: (config) => ShieldedWallet(config).restore(SerialisedWalletState.toJSON(shielded)),
3029
- unshielded: (config) => require_watch.UnshieldedWallet(config).restore(SerialisedWalletState.toJSON(unshielded)),
3030
- dust: (config) => DustWallet(config).restore(SerialisedWalletState.toJSON(dust))
3031
- }),
3032
- txHistoryStorage: restoredTxHistoryStorage,
3033
- proofServerTransport: proofServer.transport,
3034
- finalizeRecipe
3035
- };
3036
- }
3037
- }
3038
- const { walletKeys: { dustKeyBuffer, zswapKeyBuffer }, unshieldedKeystore } = await (0, rxjs.firstValueFrom)(keysWithAuthCancelledRecovery$(keyManager));
3039
- const dustParameters = _midnight_ntwrk_ledger_v8.LedgerParameters.initialParameters().dust;
3040
- const txHistoryStorage = new require_const.InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries);
3041
- configuration.txHistoryStorage = txHistoryStorage;
3042
- return {
3043
- walletFacade: await WalletFacade.init({
3044
- configuration,
3045
- provingService: () => proofServer.provingService,
3046
- shielded: (config) => ShieldedWallet(config).startWithSeed(zswapKeyBuffer),
3047
- unshielded: (config) => require_watch.UnshieldedWallet(config).startWithPublicKey(require_watch.PublicKey.fromKeyStore(unshieldedKeystore)),
3048
- dust: (config) => DustWallet(config).startWithSeed(dustKeyBuffer, dustParameters)
3049
- }),
3050
- txHistoryStorage,
3051
- proofServerTransport: proofServer.transport,
3052
- finalizeRecipe
3053
- };
3054
- };
3055
- /**
3056
- * Creates an observable MidnightWallet from wallet instances.
3057
- *
3058
- * The nightVerifyingKey is obtained from the wallet state, which works
3059
- * for both restored and new wallets.
3060
- */
3061
- const createAccountObservableMidnightWallet = ({ account, keyManager, walletFacade, haltPersistence, proofServerTransport, finalizeRecipe }) => {
3062
- const { networkId } = account.blockchainSpecific;
3063
- const state$ = walletFacade.state().pipe((0, rxjs.shareReplay)({
3064
- bufferSize: 1,
3065
- refCount: true
3066
- }));
3067
- const releasing = withReservationRelease(walletFacade);
3068
- return state$.pipe((0, rxjs.take)(1), (0, rxjs.map)((initialState) => {
3069
- const nightVerifyingKey = initialState.unshielded.capabilities.keys.getPublicKey(initialState.unshielded.state);
3070
- return {
3071
- accountId: account.accountId,
3072
- areKeysAvailable$: keyManager.areKeysAvailable$,
3073
- networkId,
3074
- nightVerifyingKey,
3075
- proofServerTransport,
3076
- walletId: account.walletId,
3077
- address$: state$.pipe((0, rxjs.map)(({ dust, shielded, unshielded }) => ({
3078
- dust: MidnightDustAddress(require_dist.DustAddress.codec.encode(networkId, dust.capabilities.keys.getAddress(dust.state)).asString()),
3079
- shielded: MidnightShieldedAddress(require_dist.ShieldedAddress.codec.encode(networkId, shielded.address).asString()),
3080
- unshielded: MidnightUnshieldedAddress(require_dist.UnshieldedAddress.codec.encode(networkId, unshielded.address).asString())
3081
- })), (0, rxjs.distinctUntilChanged)(_laceio_cardano_util.deepEquals)),
3082
- coinsByTokenType$: state$.pipe((0, rxjs.map)(({ shielded, unshielded }) => {
3083
- const shieldedCoins = {};
3084
- const unshieldedCoins = {};
3085
- for (const { coin } of shielded.totalCoins) {
3086
- const previousCoinsList = shieldedCoins[coin.type] || [];
3087
- shieldedCoins[coin.type] = previousCoinsList.concat({
3088
- status: "mt_index" in coin ? "available" : "pending",
3089
- value: require_bignum_vo.BigNumber(coin.value)
3090
- });
3091
- }
3092
- const parseUnshieldedCoins = (status, coins) => {
3093
- for (const { meta, utxo } of coins) {
3094
- const tokenType = require_utils.toUnshieldedTokenType(utxo.type, networkId);
3095
- unshieldedCoins[tokenType] = (unshieldedCoins[tokenType] || []).concat({
3096
- status,
3097
- value: require_bignum_vo.BigNumber(utxo.value),
3098
- registeredForDustGeneration: meta.registeredForDustGeneration,
3099
- ownerAddress: utxo.owner
3100
- });
3101
- }
3102
- };
3103
- parseUnshieldedCoins("pending", unshielded.pendingCoins);
3104
- parseUnshieldedCoins("available", unshielded.availableCoins);
3105
- return {
3106
- shielded: shieldedCoins,
3107
- unshielded: unshieldedCoins
3108
- };
3109
- }), (0, rxjs.distinctUntilChanged)(_laceio_cardano_util.deepEquals)),
3110
- syncProgress$: state$.pipe((0, rxjs.map)(({ dust, shielded, unshielded }) => ({
3111
- dust: computeConnectedSyncRatio(dust.state.progress.appliedIndex, dust.state.progress.highestRelevantWalletIndex, dust.state.progress.isConnected),
3112
- shielded: computeConnectedSyncRatio(shielded.state.progress.appliedIndex, shielded.state.progress.highestRelevantWalletIndex, shielded.state.progress.isConnected),
3113
- unshielded: computeConnectedSyncRatio(unshielded.state.progress.appliedId, unshielded.state.progress.highestTransactionId, unshielded.state.progress.isConnected),
3114
- isStrictlyComplete: {
3115
- dust: dust.state.progress.isStrictlyComplete(),
3116
- shielded: shielded.state.progress.isStrictlyComplete(),
3117
- unshielded: unshielded.state.progress.isStrictlyComplete()
3118
- }
3119
- })), (0, rxjs.distinctUntilChanged)(_laceio_cardano_util.deepEquals)),
3120
- transactionHistory$: state$.pipe((0, rxjs.throttleTime)(500, void 0, {
3121
- leading: true,
3122
- trailing: true
3123
- }), (0, rxjs.switchMap)(() => (0, rxjs.from)(walletFacade.getAllFromTxHistory())), (0, rxjs.distinctUntilChanged)(_laceio_cardano_util.deepEquals)),
3124
- balanceFinalizedTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.balanceFinalizedTransaction(tx, {
3125
- shieldedSecretKeys: zswapSecretKeys,
3126
- dustSecretKey
3127
- }, {
3128
- ttl,
3129
- tokenKindsToBalance
3130
- })))),
3131
- balanceUnboundTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.balanceUnboundTransaction(tx, {
3132
- shieldedSecretKeys: zswapSecretKeys,
3133
- dustSecretKey
3134
- }, {
3135
- ttl,
3136
- tokenKindsToBalance
3137
- })))),
3138
- balanceUnprovenTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(walletFacade.balanceUnprovenTransaction(tx, {
3139
- shieldedSecretKeys: zswapSecretKeys,
3140
- dustSecretKey
3141
- }, {
3142
- ttl,
3143
- tokenKindsToBalance
3144
- })))),
3145
- calculateTransactionFee: (tx) => (0, rxjs.from)(walletFacade.calculateTransactionFee(tx)),
3146
- estimateTransactionFee: (tx, options) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey } }) => (0, rxjs.from)(walletFacade.estimateTransactionFee(tx, dustSecretKey, options)))),
3147
- deregisterFromDustGeneration: (nightUtxos) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.deregisterFromDustGeneration(nightUtxos, unshieldedKeystore.getPublicKey(), (data) => unshieldedKeystore.signData(data))))),
3148
- getTransactionHistoryEntryByHash: (hash) => (0, rxjs.from)(walletFacade.queryTxHistoryByHash(hash)),
3149
- finalizeRecipe: (recipe, onProgress) => (0, rxjs.defer)(async () => finalizeRecipe(walletFacade, recipe, onProgress)),
3150
- finalizeTransaction: (recipe) => (0, rxjs.from)(walletFacade.finalizeTransaction(recipe)),
3151
- registerNightUtxosForDustGeneration: (nightUtxos, dustAddress) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.registerNightUtxosForDustGeneration(nightUtxos, unshieldedKeystore.getPublicKey(), (data) => unshieldedKeystore.signData(data), dustAddress)))),
3152
- revert: (recipe) => (0, rxjs.from)(walletFacade.revert(recipe)),
3153
- state: () => state$,
3154
- stop: () => {
3155
- haltPersistence();
3156
- return (0, rxjs.from)(walletFacade.stop());
3157
- },
3158
- signUnprovenTransaction: (tx) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.signUnprovenTransaction(tx, (data) => unshieldedKeystore.signData(data))))),
3159
- signRecipe: (recipe) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.signRecipe(recipe, (data) => unshieldedKeystore.signData(data))))),
3160
- signData: (data) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.map)(({ unshieldedKeystore }) => ({
3161
- signature: unshieldedKeystore.signData(data),
3162
- verifyingKey: unshieldedKeystore.getPublicKey()
3163
- }))),
3164
- submitTransaction: (tx) => (0, rxjs.from)(walletFacade.submitTransaction(tx)),
3165
- transferTransaction: (outputs, { ttl, payFees }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.transferTransaction(outputs, {
3166
- shieldedSecretKeys: zswapSecretKeys,
3167
- dustSecretKey
3168
- }, {
3169
- ttl,
3170
- payFees
3171
- })))),
3172
- initSwap: (desiredInputs, desiredOutputs, { ttl, payFees }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.initSwap({
3173
- desiredInputs,
3174
- desiredOutputs
3175
- }, {
3176
- shieldedSecretKeys: zswapSecretKeys,
3177
- dustSecretKey
3178
- }, {
3179
- ttl,
3180
- payFees
3181
- }))))
3182
- };
3183
- }));
3184
- };
3185
- /**
3186
- * Creates and manages the lifecycle of Midnight SDK wallet instances.
3187
- *
3188
- * Lifecycle:
3189
- * - Creates all 3 wallets (Unshielded, Shielded, Dust) via getAccountWalletInstance
3190
- * - Starts UnshieldedWallet immediately (no keys needed)
3191
- * - Starts ShieldedWallet and DustWallet once account keys become available
3192
- * (one auth prompt; sync then runs for the wallet's lifetime, surviving
3193
- * the key manager's idle zeroization — see the start step below)
3194
- * - DustWallet is never stopped once started
3195
- * (SDK limitation: stop() closes Effect runtime, breaking calculateFee)
3196
- * - On unsubscribe: stops all wallets and clears the sync key copy
3197
- */
3198
- const createAndManageWallets = (props, { logger }, options) => {
3199
- const { keyManager, account, store } = props;
3200
- return new rxjs.Observable((subscriber) => {
3201
- let walletFacade = null;
3202
- let syncSecretKeys = null;
3203
- let syncDustSecretKey = null;
3204
- let syncStartSubscription = null;
3205
- let persistSubscription = null;
3206
- let isDestroyed = false;
3207
- let isPersistenceHalted = false;
3208
- const init = async () => {
3209
- const { walletFacade: facade, txHistoryStorage, proofServerTransport, finalizeRecipe } = await getAccountWalletInstance(props, logger, options);
3210
- if (isDestroyed) {
3211
- facade.stop();
3212
- return;
3213
- }
3214
- walletFacade = facade;
3215
- await walletFacade.unshielded.start();
3216
- syncStartSubscription = keysWithAuthCancelledRecovery$(keyManager).pipe((0, rxjs.switchMap)((keys) => {
3217
- if (!walletFacade) return (0, rxjs.from)(Promise.resolve());
3218
- syncSecretKeys = _midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(keys.walletKeys.zswapKeyBuffer);
3219
- syncDustSecretKey = _midnight_ntwrk_ledger_v8.DustSecretKey.fromSeed(keys.walletKeys.dustKeyBuffer);
3220
- const facade = walletFacade;
3221
- const syncKeys = syncSecretKeys;
3222
- const dustSyncKey = syncDustSecretKey;
3223
- return (0, rxjs.from)((async () => {
3224
- const failures = [];
3225
- try {
3226
- await facade.shielded.start(syncKeys);
3227
- } catch (error) {
3228
- logger.error(`Midnight shielded wallet failed to start for account ${account.accountId}:`, error);
3229
- failures.push(error);
3230
- }
3231
- try {
3232
- await facade.dust.start(dustSyncKey);
3233
- } catch (error) {
3234
- logger.error(`Midnight dust wallet failed to start for account ${account.accountId}:`, error);
3235
- failures.push(error);
3236
- }
3237
- if (failures.length > 0) throw failures[0];
3238
- })());
3239
- })).subscribe({ error: (error) => {
3240
- logger.error(`Wallet sync start error for account ${account.accountId}:`, error);
3241
- subscriber.error(error);
3242
- } });
3243
- let lastPersistedFingerprint;
3244
- const persistOnce = async () => {
3245
- const [dust, shielded, unshielded, txHistory] = (await (0, rxjs.firstValueFrom)((0, rxjs.zip)((0, rxjs.from)(walletFacade.dust.serializeState()), (0, rxjs.from)(walletFacade.shielded.serializeState()), (0, rxjs.from)(walletFacade.unshielded.serializeState()), (0, rxjs.from)(txHistoryStorage.serialize())))).map(SerialisedWalletState);
3246
- const fingerprint = fingerprintOf([
3247
- dust,
3248
- shielded,
3249
- unshielded,
3250
- txHistory
3251
- ]);
3252
- if (fingerprint === lastPersistedFingerprint) return;
3253
- if (isPersistenceHalted || isDestroyed) return;
3254
- await (0, rxjs.firstValueFrom)(store.upsert({
3255
- serializedState: {
3256
- dust,
3257
- shielded,
3258
- unshielded,
3259
- txHistory
3260
- },
3261
- accountId: account.accountId,
3262
- walletId: account.walletId,
3263
- networkId: account.blockchainSpecific.networkId
3264
- }).pipe((0, rxjs.defaultIfEmpty)(void 0)));
3265
- lastPersistedFingerprint = fingerprint;
3266
- };
3267
- persistSubscription = walletFacade.state().pipe((0, rxjs.throttleTime)(STATE_SERIALISATION_THROTTLE_TIME, void 0, {
3268
- leading: true,
3269
- trailing: true
3270
- }), (0, rxjs.exhaustMap)(() => (0, rxjs.from)(persistOnce()).pipe((0, rxjs.catchError)((error) => {
3271
- logger.error(`Failed to persist wallet state for account ${account.accountId}:`, error);
3272
- return (0, rxjs.of)(void 0);
3273
- })))).subscribe();
3274
- subscriber.next({
3275
- walletFacade,
3276
- haltPersistence: () => {
3277
- isPersistenceHalted = true;
3278
- },
3279
- proofServerTransport,
3280
- finalizeRecipe
3281
- });
3282
- };
3283
- init().catch((error) => {
3284
- subscriber.error(error);
3285
- });
3286
- return () => {
3287
- isDestroyed = true;
3288
- syncStartSubscription?.unsubscribe();
3289
- persistSubscription?.unsubscribe();
3290
- if (walletFacade) walletFacade.stop().catch(() => void 0).finally(() => {
3291
- syncSecretKeys?.clear();
3292
- syncDustSecretKey?.clear();
3293
- });
3294
- };
3295
- });
3296
- };
3297
- /**
3298
- * Starts a Midnight account wallet with full lifecycle management.
3299
- *
3300
- * Creates SDK wallets, manages their start/stop lifecycle, and converts
3301
- * to the MidnightWallet interface used by the rest of the application.
3302
- */
3303
- const createStartMidnightAccountWallet = (dependencies, options) => (props) => createAndManageWallets(props, dependencies, options).pipe((0, rxjs.switchMap)(({ walletFacade, haltPersistence, proofServerTransport, finalizeRecipe }) => createAccountObservableMidnightWallet({
3304
- account: props.account,
3305
- keyManager: props.keyManager,
3306
- walletFacade,
3307
- haltPersistence,
3308
- proofServerTransport,
3309
- finalizeRecipe
3310
- })));
3311
- /**
3312
- * The engine's side-effect dependencies. The attested prover is the
3313
- * loadout's: the app proves through the bundled Temenos deployment, which a
3314
- * headless loadout does not ship.
3315
- */
3316
- const createMidnightSideEffectDependencies = (options = {}) => ({ runtime }, dependencies) => {
3317
- const midnightWallets$ = require_midnight_wallet.midnightWalletsForRuntime(runtime);
3318
- return {
3319
- midnightWallets$,
3320
- teeAttestationProgress$: require_send_proof_progress.teeAttestationProgress$,
3321
- getMidnightWalletByAccountId: (accountId) => midnightWallets$.pipe((0, rxjs.take)(1), (0, rxjs.map)((wallets) => wallets[accountId]), (0, rxjs.switchMap)((wallet) => wallet ? (0, rxjs.of)(wallet) : (0, rxjs.throwError)(() => /* @__PURE__ */ new Error(`Could not load midnight wallet for account ${accountId}`)))),
3322
- stopAllMidnightWallets: () => {
3323
- const walletsArray = Object.values(midnightWallets$.value);
3324
- midnightWallets$.next({});
3325
- if (walletsArray.length === 0) return (0, rxjs.of)(void 0);
3326
- return (0, rxjs.forkJoin)(walletsArray.map((wallet) => wallet.stop())).pipe((0, rxjs.map)(() => void 0));
3327
- },
3328
- stopMidnightWallet: (accountId) => {
3329
- const wallet = midnightWallets$.value[accountId];
3330
- if (!wallet) return (0, rxjs.of)(void 0);
3331
- const { [accountId]: _, ...remaining } = midnightWallets$.value;
3332
- midnightWallets$.next(remaining);
3333
- return wallet.stop().pipe((0, rxjs.map)(() => void 0));
3334
- },
3335
- startMidnightAccountWallet: createStartMidnightAccountWallet(dependencies, options)
3336
- };
3337
- };
3338
- //#endregion
3339
- //#region ../../packages/module/midnight-sync/src/store/utils/activities.ts
3340
- const toBigInt = (v) => typeof v === "bigint" ? v : BigInt(v);
3341
- const buildTokenBalanceChangesFromUtxos = (createdUtxos, spentUtxos, networkId) => {
3342
- const changesByToken = /* @__PURE__ */ new Map();
3343
- for (const u of createdUtxos) {
3344
- const tokenId = require_token_id_vo.TokenId(require_utils.toUnshieldedTokenType(u.tokenType, networkId));
3345
- const existing = changesByToken.get(tokenId);
3346
- const value = toBigInt(u.value);
3347
- changesByToken.set(tokenId, {
3348
- tokenId,
3349
- amount: existing ? existing.amount + value : value
3350
- });
3351
- }
3352
- for (const u of spentUtxos) {
3353
- const tokenId = require_token_id_vo.TokenId(require_utils.toUnshieldedTokenType(u.tokenType, networkId));
3354
- const existing = changesByToken.get(tokenId);
3355
- const value = toBigInt(u.value);
3356
- changesByToken.set(tokenId, {
3357
- tokenId,
3358
- amount: existing ? existing.amount - value : -value
3359
- });
3360
- }
3361
- return [...changesByToken.values()].filter(({ amount }) => amount !== 0n).map(({ tokenId, amount }) => ({
3362
- tokenId,
3363
- amount: require_bignum_vo.BigNumber(amount)
3364
- }));
3365
- };
3366
- const getAddressFromUtxos = (createdUtxos, spentUtxos) => {
3367
- return (createdUtxos[0] ?? spentUtxos[0])?.owner ?? "";
3368
- };
3369
- /**
3370
- * Whether the wallet took part in an unshielded movement in this transaction —
3371
- * the gate for surfacing it as an activity. True for unshielded and mixed sends,
3372
- * and for dust designation (which rotates night UTxOs into the unshielded
3373
- * section). False for shielded-only entries: their values are encrypted and
3374
- * unreadable, and the fee-dust they spend never lands in the unshielded section,
3375
- * so surfacing them would only produce an empty/unknown row.
3376
- */
3377
- const entryHasUnshieldedActivity = (entry) => (entry.unshielded?.createdUtxos.length ?? 0) > 0 || (entry.unshielded?.spentUtxos.length ?? 0) > 0;
3378
- const mapStatusToActivityType = (status, tokenBalanceChanges) => {
3379
- switch (status) {
3380
- case "SUCCESS":
3381
- case "PARTIAL_SUCCESS": return !tokenBalanceChanges?.length || tokenBalanceChanges.some(({ amount }) => BigInt(amount) > 0n) ? require_activity_type.ActivityType.Receive : require_activity_type.ActivityType.Send;
3382
- case "FAILURE": return require_activity_type.ActivityType.Failed;
3383
- }
3384
- };
3385
- /**
3386
- * Resolves the activity type and displayed token amounts for a transaction's
3387
- * unshielded section. A transaction that moved unshielded value but nets to zero
3388
- * is a self-transfer — a plain self-send, or a dust designation, which rotates
3389
- * NIGHT back to the owner — so it is surfaced as {@link ActivityType.Self}.
3390
- * No amount is shown: no value left the wallet, and the intended amount is not
3391
- * recoverable (a self output is indistinguishable from change). Failures keep
3392
- * their Failed type regardless.
3393
- */
3394
- const deriveUnshieldedActivity = ({ status, createdUtxos, spentUtxos, networkId }) => {
3395
- const netChanges = buildTokenBalanceChangesFromUtxos(createdUtxos, spentUtxos, networkId);
3396
- if (status !== "FAILURE" && netChanges.length === 0 && (createdUtxos.length > 0 || spentUtxos.length > 0)) return {
3397
- type: require_activity_type.ActivityType.Self,
3398
- tokenBalanceChanges: []
3399
- };
3400
- return {
3401
- type: mapStatusToActivityType(status, netChanges),
3402
- tokenBalanceChanges: netChanges
3403
- };
3404
- };
3405
- const formatFee = (fees) => fees === null || fees === void 0 ? "0" : String(fees);
3406
- //#endregion
3407
- //#region ../../packages/module/midnight-sync/src/store/side-effects/activities.ts
3408
- const mapTxHistoryEntryToActivity = ({ accountId, txHistoryEntry, networkId }) => {
3409
- const { hash, timestamp, status } = txHistoryEntry;
3410
- const { type, tokenBalanceChanges } = deriveUnshieldedActivity({
3411
- status,
3412
- createdUtxos: txHistoryEntry.unshielded?.createdUtxos ?? [],
3413
- spentUtxos: txHistoryEntry.unshielded?.spentUtxos ?? [],
3414
- networkId
3415
- });
3416
- return {
3417
- accountId,
3418
- activityId: hash,
3419
- type,
3420
- timestamp: require_time_vo.Timestamp(timestamp?.getTime() ?? 0),
3421
- tokenBalanceChanges
3422
- };
3423
- };
3424
- const mapTxHistoryEntryToActivityDetail = ({ accountId, txHistoryEntry, networkId }) => {
3425
- const createdUtxos = txHistoryEntry.unshielded?.createdUtxos ?? [];
3426
- const spentUtxos = txHistoryEntry.unshielded?.spentUtxos ?? [];
3427
- const activity = mapTxHistoryEntryToActivity({
3428
- accountId,
3429
- txHistoryEntry,
3430
- networkId
3431
- });
3432
- const address = getAddressFromUtxos(createdUtxos, spentUtxos);
3433
- return {
3434
- ...activity,
3435
- address,
3436
- fee: formatFee(txHistoryEntry.fees)
3437
- };
3438
- };
3439
- /**
3440
- * Whether confirmed rows with no unshielded section are shown. They carry no
3441
- * readable value or date, so they render as amount-less "unknown" / 1970 rows;
3442
- * hiding them is the default and the flag restores the earlier behaviour while
3443
- * the product decision is open.
3444
- */
3445
- const showShieldedOnlyRows$ = (stateObservables) => stateObservables.features.selectLoadedFeatures$.pipe((0, rxjs.map)((loaded) => loaded.featureFlags.some((flag) => flag.key === require_watch.FEATURE_FLAG_MIDNIGHT_SHIELDED_ACTIVITY_ROWS)), (0, rxjs.distinctUntilChanged)());
3446
- const updateActivities = (_, stateObservables, { actions, midnightWallets$ }) => midnightWallets$.pipe((0, rxjs.scan)((accumulator, wallets) => ({
3447
- current: wallets,
3448
- added: Object.values(wallets).filter((w) => !(w.accountId in accumulator.current))
3449
- }), {
3450
- current: {},
3451
- added: []
3452
- }), (0, rxjs.mergeMap)(({ added }) => added), (0, rxjs.mergeMap)((wallet) => (0, rxjs.combineLatest)([wallet.transactionHistory$, showShieldedOnlyRows$(stateObservables)]).pipe((0, rxjs.map)(([transactionHistory, showShieldedOnlyRows]) => ({
3453
- activities: transactionHistory.filter((entry) => showShieldedOnlyRows || entryHasUnshieldedActivity(entry)).map((txHistoryEntry) => mapTxHistoryEntryToActivity({
3454
- accountId: wallet.accountId,
3455
- txHistoryEntry,
3456
- networkId: wallet.networkId
3457
- })),
3458
- suppressedActivityIds: showShieldedOnlyRows ? [] : transactionHistory.filter((entry) => !entryHasUnshieldedActivity(entry)).map((entry) => entry.hash)
3459
- })), (0, rxjs.mergeMap)(({ activities, suppressedActivityIds }) => [
3460
- actions.activities.upsertActivities({
3461
- accountId: wallet.accountId,
3462
- activities
3463
- }),
3464
- ...suppressedActivityIds.length > 0 ? [actions.activities.removeActivities({
3465
- accountId: wallet.accountId,
3466
- activityIds: suppressedActivityIds
3467
- })] : [],
3468
- actions.activities.setHasLoadedOldestEntry({
3469
- accountId: wallet.accountId,
3470
- hasLoadedOldestEntry: true
3471
- }),
3472
- actions.activities.setDesiredLoadedActivitiesCount({
3473
- accountId: wallet.accountId,
3474
- desiredLoadedActivitiesCount: activities.length
3475
- })
3476
- ]), (0, rxjs.takeUntil)(midnightWallets$.pipe((0, rxjs.filter)((wallets) => !(wallet.accountId in wallets)))))));
3477
- const loadActivityDetails = ({ activities: { loadActivityDetails$ } }, _, { actions, getMidnightWalletByAccountId, logger }) => loadActivityDetails$.pipe((0, rxjs.filter)(({ payload: { blockchainName } }) => blockchainName === "Midnight"), (0, rxjs.map)((action) => action.payload.activity), (0, rxjs.switchMap)(({ activityId, accountId }) => getMidnightWalletByAccountId(accountId).pipe((0, rxjs.switchMap)((wallet) => wallet.getTransactionHistoryEntryByHash(activityId).pipe((0, rxjs.map)((txHistoryEntry) => {
3478
- if (!txHistoryEntry) return actions.activities.setActivityDetails({ activityDetails: void 0 });
3479
- return actions.activities.setActivityDetails({ activityDetails: mapTxHistoryEntryToActivityDetail({
3480
- accountId: wallet.accountId,
3481
- txHistoryEntry,
3482
- networkId: wallet.networkId
3483
- }) });
3484
- }), (0, rxjs.catchError)((error) => {
3485
- logger.error("Failed to load Midnight activity details", error);
3486
- return rxjs.EMPTY;
3487
- }))), (0, rxjs.catchError)(() => rxjs.EMPTY))));
3488
- //#endregion
3489
- //#region ../../packages/module/midnight-sync/src/store/side-effects/proof-server-kill-switch.ts
3490
- /** Persist the fallback when a selected provider is disabled or no longer
3491
- * belongs to the source-controlled catalogue. Notify once per affected batch. */
3492
- const migrateUnavailableProofServerSelection = (_, { midnightContext: { selectUnavailableProofServerNetworks$, selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => selectUnavailableProofServerNetworks$.pipe((0, rxjs.distinctUntilChanged)(lodash_isEqual.default), (0, rxjs.filter)((networkIds) => networkIds.length > 0), (0, rxjs.withLatestFrom)(selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$), (0, rxjs.mergeMap)(([networkIds, networksConfig, featureFlagsOverrides]) => (0, rxjs.from)([...networkIds.map((networkId) => actions.midnightContext.setUserNetworkConfigOverride({
3493
- networkId,
3494
- config: networksConfig[networkId],
3495
- featureFlagsOverrides: featureFlagsOverrides[networkId] ?? {}
3496
- })), actions.ui.showToast({
3497
- text: "midnight.proof-server.unavailable",
3498
- color: "neutral",
3499
- duration: 8,
3500
- leftIcon: {
3501
- name: "AlertTriangle",
3502
- size: 20
3503
- }
3504
- })])));
3505
- //#endregion
3506
- //#region ../../packages/module/midnight-sync/src/store/side-effects/resync.ts
3507
- const withMidnightAccounts = (makeSideEffect) => (actionObservables, stateObservables, dependencies) => makeSideEffect(midnightAccounts$(stateObservables))(actionObservables, stateObservables, dependencies);
3508
- const requestResyncWallet = withMidnightAccounts((midnightAccount$) => ({ midnightSync: { requestResync$ } }, _, { actions }) => (0, rxjs.merge)(requestResync$.pipe((0, rxjs.withLatestFrom)(midnightAccount$), (0, rxjs.switchMap)(([_, accounts]) => {
3509
- return (0, rxjs.from)([...accounts.map(({ accountId }) => actions.sync.addSyncOperation({
3510
- accountId,
3511
- operation: {
3512
- operationId: `${accountId}-midnight-sync`,
3513
- status: "Pending",
3514
- description: "sync.operation.midnight-resync",
3515
- startedAt: require_time_vo.Timestamp(Date.now())
3516
- }
3517
- })), actions.midnightSync.resync()]);
3518
- }))));
3519
- const createClearWalletStateOnResync = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightSync: { resync$ } }, _, { actions, stopAllMidnightWallets, logger }) => resync$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([_, midnightAccounts]) => stopAllMidnightWallets().pipe((0, rxjs.catchError)((error) => {
3520
- logger.error("Midnight resync: stop failed", error);
3521
- return (0, rxjs.of)(void 0);
3522
- }), (0, rxjs.switchMap)(() => store.clear().pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((error) => {
3523
- logger.error("Midnight resync: state wipe failed", error);
3524
- return (0, rxjs.of)(void 0);
3525
- }))), (0, rxjs.switchMap)(() => [...midnightAccounts.flatMap(({ accountId }) => [
3526
- actions.addresses.resetAddresses({ accountId }),
3527
- actions.tokens.resetAccountTokens({ accountId }),
3528
- actions.activities.resetActivities({ accountId }),
3529
- actions.midnightContext.resetAccountDust({ accountId })
3530
- ]), actions.midnightSync.restartWalletWatch()])))));
3531
- /**
3532
- * Side-effect that triggers a Midnight wallet resync whenever the config change
3533
- * is made with a feature flag override and the wallet is unlocked.
3534
- */
3535
- const resyncWalletOnConfigChangeFromFeatureFlags = withMidnightAccounts((midnightAccounts$) => (_, { appLock: { isUnlocked$ }, midnightContext: { selectCurrentNetwork$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => {
3536
- return selectNetworksConfigFeatureFlagsOverrides$.pipe((0, rxjs.withLatestFrom)(isUnlocked$), (0, rxjs.filter)(([_, isUnlocked]) => isUnlocked), (0, rxjs.switchMap)(() => selectCurrentNetwork$.pipe((0, rxjs.take)(1))), (0, rxjs.map)(({ config }) => config), (0, rxjs.distinctUntilChanged)(_laceio_cardano_util.deepEquals)).pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([_, midnightAccounts]) => (0, rxjs.from)([...midnightAccounts.map(({ accountId }) => actions.sync.addSyncOperation({
3537
- accountId,
3538
- operation: {
3539
- operationId: `${accountId}-midnight-sync`,
3540
- status: "Pending",
3541
- description: "sync.operation.midnight-resync",
3542
- startedAt: require_time_vo.Timestamp(Date.now())
3543
- }
3544
- })), actions.midnightSync.resync()])));
3545
- });
3546
- const createDeleteWalletSideEffect = (storage) => ({ wallets: { removeWallet$ } }, { wallets: { selectAll$ } }, { stopMidnightWallet, actions, logger }) => removeWallet$.pipe((0, rxjs.withLatestFrom)(selectAll$.pipe((0, rxjs.map)((wallets) => wallets.filter(require_utils.hasMidnightAccount)))), (0, rxjs.switchMap)(([{ payload }, midnightWallets]) => {
3547
- const walletId = typeof payload === "string" ? payload : payload.walletId;
3548
- const targetWallet = midnightWallets.find((w) => w.walletId === walletId);
3549
- if (!targetWallet) return rxjs.EMPTY;
3550
- const allMidnightAccounts = targetWallet.accounts.filter(require_utils.isInMemoryMidnightAccount);
3551
- return (allMidnightAccounts.length > 0 ? (0, rxjs.forkJoin)(allMidnightAccounts.map(({ accountId }) => stopMidnightWallet(accountId))) : (0, rxjs.of)([])).pipe((0, rxjs.switchMap)(() => storage.removeWhere((wallet) => wallet.walletId === walletId).pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((error) => {
3552
- logger.error("Midnight delete wallet: state wipe failed", error);
3553
- return (0, rxjs.of)(void 0);
3554
- }))), (0, rxjs.mergeMap)(() => allMidnightAccounts.flatMap(({ accountId }) => [
3555
- actions.addresses.resetAddresses({ accountId }),
3556
- actions.tokens.resetAccountTokens({ accountId }),
3557
- actions.activities.resetActivities({ accountId })
3558
- ])));
3559
- }));
3560
- /**
3561
- * Stops one Midnight account's wallet, wipes that account's persisted SDK
3562
- * state, then emits the actions that clear every redux cache the wiped state
3563
- * fed. Scoped to a single account, unlike `createClearWalletStateOnResync`,
3564
- * which wipes the whole chain.
3565
- *
3566
- * A step that errors or completes without emitting is handed to
3567
- * `onStepFailure`: return an observable that emits to carry on with the next
3568
- * step, or one that errors to abort the reset with that error.
3569
- */
3570
- const stopAndWipeAccountState$ = ({ accountId, actions, store, stop$, onStepFailure }) => stop$.pipe((0, rxjs.take)(1), (0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account stop did not acknowledge completion")), (0, rxjs.catchError)((error) => onStepFailure("stop", error)), (0, rxjs.switchMap)(() => store.removeWhere((wallet) => wallet?.accountId === accountId).pipe((0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account storage wipe did not acknowledge completion")), (0, rxjs.catchError)((error) => onStepFailure("wipe", error)))), (0, rxjs.mergeMap)(() => [
3571
- actions.addresses.resetAddresses({ accountId }),
3572
- actions.tokens.resetAccountTokens({ accountId }),
3573
- actions.activities.resetActivities({ accountId }),
3574
- actions.midnightContext.resetAccountDust({ accountId }),
3575
- actions.sync.resetAccountSyncStatus({ accountId })
3576
- ]));
3577
- /**
3578
- * The extension's per-account "reset sync state": stops and wipes the account,
3579
- * then reloads the app so every engine restarts from empty state. Stop and wipe
3580
- * failures are logged and the reset carries on, because the reload is what
3581
- * recovers the account.
3582
- *
3583
- * The reload is emitted LAST, after the storage write settles: sequencing it
3584
- * inside this chain (rather than firing it from a separate UI tap) is what stops
3585
- * a hard reload from preempting the wipe and leaving the old SDK document to
3586
- * restore from.
3587
- */
3588
- const createResetSyncStateSideEffect = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightContext: { resetSyncState$ } }, _, { actions, stopMidnightWallet, logger }) => resetSyncState$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([{ payload }, midnightAccounts]) => {
3589
- const account = midnightAccounts.find(({ accountId }) => accountId === payload.accountId);
3590
- if (!account) return rxjs.EMPTY;
3591
- const { accountId } = account;
3592
- return (0, rxjs.concat)(stopAndWipeAccountState$({
3593
- accountId,
3594
- actions,
3595
- store,
3596
- stop$: stopMidnightWallet(accountId),
3597
- onStepFailure: (step, error) => {
3598
- logger.error(`Midnight reset sync state: ${step} failed`, error);
3599
- return (0, rxjs.of)(void 0);
3600
- }
3601
- }), (0, rxjs.of)(actions.app.reloadApplication()));
3602
- })));
3603
- /**
3604
- * The headless per-account "reset sync state": stops and wipes the account,
3605
- * then restarts that account's watcher in place, since a headless runtime has
3606
- * no application to reload. The account's sync operation reads Pending while
3607
- * the reset runs and Failed if a stop or wipe fails, so the caller can observe
3608
- * the outcome and retry.
3609
- */
3610
- const createHeadlessResetSyncStateSideEffect = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightContext: { resetSyncState$ } }, _, { actions, stopMidnightWallet, logger }) => resetSyncState$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.groupBy)(([{ payload }]) => payload.accountId), (0, rxjs.mergeMap)((requests$) => requests$.pipe((0, rxjs.exhaustMap)(([{ payload }, midnightAccounts]) => {
3611
- const account = midnightAccounts.find(({ accountId }) => accountId === payload.accountId);
3612
- if (!account) return rxjs.EMPTY;
3613
- const { accountId } = account;
3614
- const pendingOperation = () => actions.sync.addSyncOperation({
3615
- accountId,
3616
- operation: {
3617
- operationId: `${accountId}-midnight-sync`,
3618
- status: "Pending",
3619
- description: "sync.operation.midnight-resync",
3620
- startedAt: require_time_vo.Timestamp(Date.now())
3621
- }
3622
- });
3623
- const stop$ = (0, rxjs.merge)((0, rxjs.of)(void 0), requests$).pipe((0, rxjs.switchMap)(() => (0, rxjs.defer)(() => stopMidnightWallet(accountId)).pipe((0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account stop did not acknowledge completion")))));
3624
- return (0, rxjs.concat)((0, rxjs.of)(pendingOperation()), stopAndWipeAccountState$({
3625
- accountId,
3626
- actions,
3627
- store,
3628
- stop$,
3629
- onStepFailure: (step, error) => {
3630
- logger.error(`Midnight reset sync state: ${step} failed`, error);
3631
- return (0, rxjs.throwError)(() => error);
3632
- }
3633
- }), (0, rxjs.defer)(() => (0, rxjs.of)(pendingOperation(), actions.midnightSync.restartAccountWatch({ accountId })))).pipe((0, rxjs.catchError)((error) => {
3634
- logger.error("Midnight account resync failed", error);
3635
- const failedAt = require_time_vo.Timestamp(Date.now());
3636
- return (0, rxjs.of)(actions.sync.addSyncOperation({
3637
- accountId,
3638
- operation: {
3639
- operationId: `${accountId}-midnight-sync`,
3640
- status: "Failed",
3641
- description: "sync.operation.midnight-resync",
3642
- error: "sync.error.midnight-sync-failed",
3643
- startedAt: failedAt,
3644
- failedAt
3645
- }
3646
- }));
3647
- }));
3648
- })))));
3649
- //#endregion
3650
- //#region ../../packages/module/midnight-sync/src/store/side-effects/sync-failure.ts
3651
- /**
3652
- * Dismiss a Midnight account's sync failure once its own sync recovers.
3653
- *
3654
- * The `completeSyncOperation` for `${accountId}-midnight-sync` is the
3655
- * "recovered" signal, whichever route got there — transparent retry, the
3656
- * failure's tap-to-retry `restartWalletWatch`, or the resubscription `whileActive`
3657
- * performs on unlock.
3658
- *
3659
- * Keyed per-account, so no lookup is needed: a completion for a sibling Midnight
3660
- * account (or a Cardano/Bitcoin one) maps to a different, non-existent
3661
- * MidnightSyncFailureId and no-ops, leaving a still-broken account's failure in
3662
- * place until its OWN sync completes.
3663
- */
3664
- const autoDismissMidnightSyncFailureOnSyncSuccess = ({ sync: { completeSyncOperation$ } }, { failures: { selectFailureById$ } }) => completeSyncOperation$.pipe((0, rxjs.map)(({ payload }) => require_watch.MidnightSyncFailureId(payload.accountId)), require_auto_dismiss_failure_on_success.autoDismissFailureOnSuccess(selectFailureById$));
3665
- /**
3666
- * On resume, clear the sync failure for every Midnight account.
3667
- *
3668
- * Complements the per-account recovery dismissal above by clearing a stale error
3669
- * immediately, rather than leaving it on screen for the length of the first sync
3670
- * after unlock. No restart is dispatched: `watchMidnightAccounts` ends its pipe
3671
- * with `whileActive`, so resuming already resubscribes every account watcher.
3672
- * Accounts with no failure are a no-op.
3673
- */
3674
- const autoDismissMidnightSyncFailureOnResume = (_, { wallets: { selectAll$ }, failures: { selectFailureById$ } }, { walletResumed$ }) => walletResumed$.pipe((0, rxjs.withLatestFrom)(selectAll$), (0, rxjs.mergeMap)(([, wallets]) => (0, rxjs.from)(wallets.flatMap((wallet) => wallet.accounts).filter(require_utils.isInMemoryMidnightAccount).map((account) => require_watch.MidnightSyncFailureId(account.accountId)))), require_auto_dismiss_failure_on_success.autoDismissFailureOnSuccess(selectFailureById$));
3675
- //#endregion
3676
- //#region ../../packages/module/midnight-sync/src/store/side-effects/tee-attestation-progress.ts
3677
- /**
3678
- * Forwards attested-proving progress from the dependency-level stream into
3679
- * redux, where the send-flow checklist UI reads it. Pure mapping — the
3680
- * events originate inside the proving service (ADR 19).
3681
- */
3682
- const watchTeeAttestationProgress = (_actionObservables, _stateObservables, { actions, teeAttestationProgress$ }) => teeAttestationProgress$.pipe((0, rxjs.map)((event) => event.type === "begin" ? actions.midnightContext.teeAttestationProgressStarted(event) : actions.midnightContext.teeAttestationProgressUpdated(event)));
3683
- /**
3684
- * Clears the previous run's checklist as soon as a new Midnight transaction
3685
- * starts building, so a redone send never opens the
3686
- * processing screen with stale step results. The attested proving service's
3687
- * `reset` then rebuilds the pending checklist when verification actually
3688
- * begins. The signer owns confirmation resets. Submit must not clear the
3689
- * completed checklist while the transaction is being submitted.
3690
- */
3691
- const clearTeeAttestationProgressOnNewTx = ({ txExecutor: { txPhaseRequested$ } }, _stateObservables, { actions }) => txPhaseRequested$.pipe((0, rxjs.filter)(({ payload: { config } }) => config.params.blockchainName === "Midnight" && config.type === "buildTx"), (0, rxjs.map)(() => actions.midnightContext.teeAttestationProgressCleared()));
3692
- //#endregion
3693
- //#region ../../packages/module/midnight-sync/src/store/side-effects/index.ts
3694
- /**
3695
- * The engine's side effects plus the ones a loadout adds over the same
3696
- * persisted wallet-state storage. The engine set reads only the contracts
3697
- * the engine itself depends on; a loadout decides what else it can run.
3698
- */
3699
- const createInitializeSideEffects = (loadoutSideEffects) => () => [(actionObservables, stateObservables, dependencies) => {
3700
- const midnightStateStorage = dependencies.createCollectionStorage({
3701
- collectionId: "midnightWalletState",
3702
- computeDocId: (wallet) => String(wallet.accountId)
3703
- });
3704
- return (0, rxjs.merge)(...[
3705
- updateActivities,
3706
- loadActivityDetails,
3707
- createDeleteWalletSideEffect(midnightStateStorage),
3708
- createClearWalletStateOnResync(midnightStateStorage),
3709
- requestResyncWallet,
3710
- autoDismissMidnightSyncFailureOnResume,
3711
- autoDismissMidnightSyncFailureOnSyncSuccess,
3712
- require_watch.watchMidnightAccounts(midnightStateStorage, require_watch.watchMidnightAccount),
3713
- ...loadoutSideEffects(midnightStateStorage)
3714
- ].map((sideEffect) => sideEffect(actionObservables, stateObservables, dependencies)));
3715
- }];
3716
- createInitializeSideEffects((storage) => [
3717
- createResetSyncStateSideEffect(storage),
3718
- resyncWalletOnConfigChangeFromFeatureFlags,
3719
- migrateUnavailableProofServerSelection,
3720
- watchTeeAttestationProgress,
3721
- clearTeeAttestationProgressOnNewTx
3722
- ]);
3723
- //#endregion
3724
- //#region ../../packages/module/midnight-sync/src/store/side-effects/network-config.ts
3725
- /**
3726
- * Applies a loadout's supported networks and default proof servers right
3727
- * after the first action the store handles, which redux-persist dispatches
3728
- * while the store is created. Both therefore hold before the store is handed
3729
- * out and before any side effect starts: a side effect would land a tick
3730
- * later, and a network selected in between would be checked against the
3731
- * contract's full list.
3732
- */
3733
- const createApplyNetworkDefaultsMiddleware = ({ supportedNetworkIds, defaultProofServers }) => {
3734
- const { setDefaultProofServers, setSupportedNetworksIds } = require_slice.midnightContextActions.midnightContext;
3735
- return (store) => (next) => {
3736
- let pending = [...supportedNetworkIds ? [setSupportedNetworksIds(supportedNetworkIds)] : [], ...defaultProofServers ? [setDefaultProofServers(defaultProofServers)] : []];
3737
- return (action) => {
3738
- const result = next(action);
3739
- const defaults = pending;
3740
- pending = [];
3741
- for (const defaultAction of defaults) store.dispatch(defaultAction);
3742
- return result;
3743
- };
3744
- };
3745
- };
3746
- /**
3747
- * Applies a loadout's endpoint choices as user overrides on startup, so they
3748
- * take precedence over the contract defaults and the feature-flag values
3749
- * without a settings UI to enter them through.
3750
- */
3751
- const createApplyNetworkConfigOverrides = (overrides) => (_, { midnightContext: { selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => (0, rxjs.zip)(selectNetworksConfig$.pipe((0, rxjs.take)(1)), selectNetworksConfigFeatureFlagsOverrides$.pipe((0, rxjs.take)(1))).pipe((0, rxjs.mergeMap)(([networksConfig, featureFlagsOverrides]) => Object.entries(overrides).map(([networkId, override]) => actions.midnightContext.setUserNetworkConfigOverride({
3752
- networkId,
3753
- config: {
3754
- ...networksConfig[networkId],
3755
- ...override
3756
- },
3757
- featureFlagsOverrides: featureFlagsOverrides[networkId]
3758
- }))));
3759
- //#endregion
3760
- //#region ../../packages/module/midnight-sync/src/store/sdk-init.ts
3761
- const assertDefaultTestnetConfigured = (config) => {
3762
- const networkId = config?.defaultMidnightTestnetNetworkId;
3763
- if (!networkId || !require_const.MidnightSDKTestNetworkId.includes(networkId)) throw new Error(`createLaceWallet needs config.defaultMidnightTestnetNetworkId, the Midnight testnet a wallet starts on: one of ${require_const.MidnightSDKTestNetworkId.join(", ")}; got ${String(networkId)}`);
3764
- };
3765
- const createSdkStoreInit = ({ auth, batchUpdates, createAttestedProver, networks = {}, supportedNetworkIds, defaultProofServers }) => {
3766
- const initializeSideEffects = createInitializeSideEffects((storage) => [
3767
- registerMidnightBlockchainNetworks,
3768
- createApplyNetworkConfigOverrides(networks),
3769
- createHeadlessResetSyncStateSideEffect(storage)
3770
- ]);
3771
- const initializeDependencies = createMidnightSideEffectDependencies({
3772
- batchUpdates,
3773
- createAttestedProver
3774
- });
3775
- return (props, dependencies) => {
3776
- assertDefaultTestnetConfigured(props.runtime.config);
3777
- return {
3778
- middleware: [createApplyNetworkDefaultsMiddleware({
3779
- supportedNetworkIds,
3780
- defaultProofServers
3781
- })],
3782
- sideEffects: initializeSideEffects(props, dependencies),
3783
- sideEffectDependencies: {
3784
- ...initializeDependencies(props, dependencies),
3785
- ...auth
3786
- }
3787
- };
3788
- };
3789
- };
3790
- //#endregion
3791
- exports.createSdkStoreInit = createSdkStoreInit;