@snowmonster_defi/widget 1.0.1 → 1.0.4

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 (177) hide show
  1. package/README.md +70 -39
  2. package/dist/{add-C1-3Nxd0.mjs → add-BPV517ty.mjs} +1 -1
  3. package/dist/{add-BMx827fr.js → add-BPho8Nes.js} +1 -1
  4. package/dist/{all-wallets-CeboYmll.mjs → all-wallets-CiIBeiWr.mjs} +1 -1
  5. package/dist/{all-wallets-Bw2RRXQf.js → all-wallets-vW2hc4rM.js} +1 -1
  6. package/dist/{app-store-C-SLhk-c.mjs → app-store-C6Z4049-.mjs} +1 -1
  7. package/dist/{app-store-DWCVxk5n.js → app-store-DsTJJkbc.js} +1 -1
  8. package/dist/{apple-C6JNxC7s.js → apple-BaIvScvo.js} +1 -1
  9. package/dist/{apple-C0-QMsmX.mjs → apple-BoVttKqM.mjs} +1 -1
  10. package/dist/{arrow-bottom-BQlfsLH7.js → arrow-bottom-B-4Ygcmm.js} +1 -1
  11. package/dist/{arrow-bottom-DBsoY1j4.mjs → arrow-bottom-IMykiiHq.mjs} +1 -1
  12. package/dist/{arrow-bottom-circle-BWbOWcMy.js → arrow-bottom-circle-u-wHHjSl.js} +1 -1
  13. package/dist/{arrow-bottom-circle-0d4DMC8k.mjs → arrow-bottom-circle-ww23Oo7w.mjs} +1 -1
  14. package/dist/{arrow-left-Buye_G_C.mjs → arrow-left-8UMbM21G.mjs} +1 -1
  15. package/dist/{arrow-left-CYea8lr5.js → arrow-left-D0A5ZeHX.js} +1 -1
  16. package/dist/{arrow-right-NcpIvTiP.mjs → arrow-right-D4msWuyB.mjs} +1 -1
  17. package/dist/{arrow-right-Bz07l-7m.js → arrow-right-Dof9_DCu.js} +1 -1
  18. package/dist/{arrow-top-CE8kNyrN.js → arrow-top-CvBYy8tE.js} +1 -1
  19. package/dist/{arrow-top-BHtmjrGh.mjs → arrow-top-GvPPq7Oj.mjs} +1 -1
  20. package/dist/{bank-54nZmUNU.js → bank-DVoUwWPa.js} +1 -1
  21. package/dist/{bank-foInih1V.mjs → bank-DitzyCyd.mjs} +1 -1
  22. package/dist/{basic-DgjjeOAX.js → basic-BZtwfI9s.js} +1 -1
  23. package/dist/{basic-BoWB3br8.mjs → basic-DaftXE56.mjs} +2 -2
  24. package/dist/{browser-b-nGXlqN.js → browser-BOjOgqqR.js} +1 -1
  25. package/dist/{browser-BC7vNobG.mjs → browser-DAoS0pqS.mjs} +1 -1
  26. package/dist/{card--XvDDn3y.mjs → card-BKTwGF3D.mjs} +1 -1
  27. package/dist/{card-BkMuyW1R.js → card-dnj6ci0D.js} +1 -1
  28. package/dist/{ccip-DKFQjR9A.mjs → ccip-C4MhpzIT.mjs} +1 -1
  29. package/dist/{ccip-B3WUowc8.js → ccip-D5uz0WmF.js} +1 -1
  30. package/dist/{checkmark-DXb72YHc.js → checkmark-X3jF2to2.js} +1 -1
  31. package/dist/{checkmark-BbGho5Io.mjs → checkmark-a4R9tQ59.mjs} +1 -1
  32. package/dist/{checkmark-bold-B1F7R5EK.mjs → checkmark-bold-B5m6nFJs.mjs} +1 -1
  33. package/dist/{checkmark-bold-DdBV1Lmi.js → checkmark-bold-CQsgaDa-.js} +1 -1
  34. package/dist/{chevron-bottom-XyYYwAR8.mjs → chevron-bottom-BxqBvchZ.mjs} +1 -1
  35. package/dist/{chevron-bottom-CQZ-Wq5W.js → chevron-bottom-DeedT_F1.js} +1 -1
  36. package/dist/{chevron-left-DuAvtNd0.mjs → chevron-left-BO7jNn6D.mjs} +1 -1
  37. package/dist/{chevron-left-8n-It-m1.js → chevron-left-CSnmuYaP.js} +1 -1
  38. package/dist/{chevron-right-W5vVm_KB.mjs → chevron-right-BDLOHLOC.mjs} +1 -1
  39. package/dist/{chevron-right-D59N_heq.js → chevron-right-C947RiRa.js} +1 -1
  40. package/dist/{chevron-top-DFkm04W3.mjs → chevron-top-DQeh2Y_5.mjs} +1 -1
  41. package/dist/{chevron-top-CEOzd8Ij.js → chevron-top-DcT74sQW.js} +1 -1
  42. package/dist/{chrome-store-BrkLwaGp.js → chrome-store-D5kzIuNb.js} +1 -1
  43. package/dist/{chrome-store-CP2NiEXz.mjs → chrome-store-N3_b-aes.mjs} +1 -1
  44. package/dist/{clock-B5JaCeFx.mjs → clock-CinkYoNf.mjs} +1 -1
  45. package/dist/{clock-LQXXXzZd.js → clock-Dtf4mH84.js} +1 -1
  46. package/dist/{close-w5A4PucI.mjs → close-D4MWwtJe.mjs} +1 -1
  47. package/dist/{close-CvPH2PaL.js → close-DI1RHF8v.js} +1 -1
  48. package/dist/{coinPlaceholder-haEbTDpA.mjs → coinPlaceholder-CsoXT7JB.mjs} +1 -1
  49. package/dist/{coinPlaceholder-DFh7VbZT.js → coinPlaceholder-DA1nHq9_.js} +1 -1
  50. package/dist/{compass-CvRkiQHa.mjs → compass-BLnQinlT.mjs} +1 -1
  51. package/dist/{compass-Df_6O9--.js → compass-C6vJRUYh.js} +1 -1
  52. package/dist/{copy-D0w04l-Q.js → copy-BrHIxCKf.js} +1 -1
  53. package/dist/{copy-CyrCMq2Q.mjs → copy-BuRNtKMA.mjs} +1 -1
  54. package/dist/{core-auWK_7Ox.mjs → core-7LtihVxb.mjs} +4 -4
  55. package/dist/{core-BdUBRviB.js → core-CKEBRqJG.js} +3 -3
  56. package/dist/{cursor-DFMotZ-L.js → cursor--U2SHjOW.js} +1 -1
  57. package/dist/{cursor-D5uRbW9D.mjs → cursor-B7D1R5Jx.mjs} +1 -1
  58. package/dist/{cursor-transparent-BanA5rDD.mjs → cursor-transparent-CLfz5eqc.mjs} +1 -1
  59. package/dist/{cursor-transparent-Cs4NrQu6.js → cursor-transparent-D8mgBLhV.js} +1 -1
  60. package/dist/{desktop-CheS5Az_.js → desktop-D15Zh6YB.js} +1 -1
  61. package/dist/{desktop-6Q-_rh47.mjs → desktop-LJLhtmCr.mjs} +1 -1
  62. package/dist/{disconnect-DltoX_gP.js → disconnect-Btu0RPvp.js} +1 -1
  63. package/dist/{disconnect-CRF11ye0.mjs → disconnect-DtHq3NW3.mjs} +1 -1
  64. package/dist/{discord-B6nj8oD_.mjs → discord-B2wex93m.mjs} +1 -1
  65. package/dist/{discord-CqY7Pilo.js → discord-D2XZHgYW.js} +1 -1
  66. package/dist/en_US-Y4ZOVFV4-D2wGVa2b.mjs +4 -0
  67. package/dist/{en_US-Y4ZOVFV4-Dn3zitY_.js → en_US-Y4ZOVFV4-DBqUKfQh.js} +1 -1
  68. package/dist/{etherscan-CLcbtjKR.mjs → etherscan-DnhJnMc1.mjs} +1 -1
  69. package/dist/{etherscan-DxjvKQo9.js → etherscan-DsJEkOUz.js} +1 -1
  70. package/dist/{exclamation-triangle-CxJuBpFB.mjs → exclamation-triangle-BU3gP5qY.mjs} +1 -1
  71. package/dist/{exclamation-triangle-D9vGQKFQ.js → exclamation-triangle-zwn1pVGJ.js} +1 -1
  72. package/dist/{extension-t0E2b7ef.mjs → extension-6YBZn5l5.mjs} +1 -1
  73. package/dist/{extension-CSqCxcZG.js → extension-tCaHxyD9.js} +1 -1
  74. package/dist/{external-link-B-Lcyi6R.mjs → external-link-DBT7XJ7w.mjs} +1 -1
  75. package/dist/{external-link-BoArXGTq.js → external-link-DvaiPeiZ.js} +1 -1
  76. package/dist/{facebook-DOkj8R5F.js → facebook-D_R2Ch8w.js} +1 -1
  77. package/dist/{facebook-Cnfem7th.mjs → facebook-Di4nk83F.mjs} +1 -1
  78. package/dist/{farcaster-BlN1w-oR.mjs → farcaster-DK7J9QZQ.mjs} +1 -1
  79. package/dist/{farcaster-DKhgfKln.js → farcaster-_bmxN7eE.js} +1 -1
  80. package/dist/{filters-w4oLgYuJ.js → filters-DMA0z9Xf.js} +1 -1
  81. package/dist/{filters-DY5tpPJB.mjs → filters-DYn3A8Qc.mjs} +1 -1
  82. package/dist/{github-Bq8YXj-l.js → github-BAqh5GDr.js} +1 -1
  83. package/dist/{github-BnOjmw_1.mjs → github-DTQwjsGN.mjs} +1 -1
  84. package/dist/{google-ySq_VIsy.mjs → google-Bxyl2WXy.mjs} +1 -1
  85. package/dist/{google-BjbAYNIf.js → google-Di6zv-2m.js} +1 -1
  86. package/dist/{help-circle-D_pee-dG.mjs → help-circle-BwuxonVp.mjs} +1 -1
  87. package/dist/{help-circle-MVmAyaVF.js → help-circle-CCnRbe9g.js} +1 -1
  88. package/dist/{id-ByfWOnEX.js → id-5NWvRbPW.js} +1 -1
  89. package/dist/{id-CuusF9Qd.mjs → id-CEIaI4H1.mjs} +1 -1
  90. package/dist/{image-BlN-YE3X.js → image-BO81Uk1U.js} +1 -1
  91. package/dist/{image-Cs26jwi7.mjs → image-ODLhaGq9.mjs} +1 -1
  92. package/dist/{index-BUG5Ve0i.mjs → index-C06gpTYX.mjs} +78 -78
  93. package/dist/{index-STIsWesT.js → index-CL3HAprc.js} +2 -2
  94. package/dist/{index-BKj9Y5tv.js → index-VHB4k7R7.js} +52 -52
  95. package/dist/{index-C8nreL9m.mjs → index-zFOcZ90F.mjs} +2785 -2791
  96. package/dist/index.cjs.js +1 -1
  97. package/dist/{index.es-e80IGd_J.mjs → index.es-0IhW12Mz.mjs} +3 -3
  98. package/dist/{index.es-APae9KBk.js → index.es-5uEkuPzw.js} +3 -3
  99. package/dist/index.es.js +1 -1
  100. package/dist/{info-Cb2Tnwp9.mjs → info-DOWjMq4g.mjs} +1 -1
  101. package/dist/{info-D7vY5t3I.js → info-Da_tw9Vb.js} +1 -1
  102. package/dist/{info-circle-CIVy5nVm.js → info-circle-BVI3pzZy.js} +1 -1
  103. package/dist/{info-circle-sI2i5HOv.mjs → info-circle-G3naLW3K.mjs} +1 -1
  104. package/dist/{lightbulb-5NUvCVy3.js → lightbulb-B-lGHBBk.js} +1 -1
  105. package/dist/{lightbulb-BYmcwWUA.mjs → lightbulb-BThmcys-.mjs} +1 -1
  106. package/dist/{mail-CT9BLct_.mjs → mail-BMjkQGoD.mjs} +1 -1
  107. package/dist/{mail-DAYPcxbx.js → mail-BXlcglnW.js} +1 -1
  108. package/dist/{metamask-sdk-5m3nvPtB.js → metamask-sdk-CKwOy3_1.js} +1 -1
  109. package/dist/{metamask-sdk-CPh1Wi1b.mjs → metamask-sdk-Y-ZzvFgh.mjs} +1 -1
  110. package/dist/{mobile-DNsm674z.js → mobile-BnBBc98F.js} +1 -1
  111. package/dist/{mobile-DRfo1ZAq.mjs → mobile-D7E8ud2a.mjs} +1 -1
  112. package/dist/{more-DFKbhNg4.js → more-CdcjjGWT.js} +1 -1
  113. package/dist/{more-DvtnI5Dv.mjs → more-st65oVJ-.mjs} +1 -1
  114. package/dist/{network-placeholder-BPGY0Pea.js → network-placeholder-BGP5yudU.js} +1 -1
  115. package/dist/{network-placeholder-DOmySIjI.mjs → network-placeholder-CIh7bVKs.mjs} +1 -1
  116. package/dist/{nftPlaceholder-CRB7uOjv.mjs → nftPlaceholder-B0i5-z9I.mjs} +1 -1
  117. package/dist/{nftPlaceholder-Dp6Tl1yi.js → nftPlaceholder-CHTKmYr7.js} +1 -1
  118. package/dist/{off-BVEy2I2N.js → off-CO2d06NG.js} +1 -1
  119. package/dist/{off-LjovEQOy.mjs → off-D3SBQ1uB.mjs} +1 -1
  120. package/dist/{play-store-DlHvVfW-.js → play-store-DqVbl3Da.js} +1 -1
  121. package/dist/{play-store-BwddU0Wq.mjs → play-store-md1rTEdi.mjs} +1 -1
  122. package/dist/{plus-ZMKluBd6.js → plus-9CuDNjjZ.js} +1 -1
  123. package/dist/{plus-C-X64_gj.mjs → plus-DKO6pqvO.mjs} +1 -1
  124. package/dist/{qr-code-bLEKEk0B.mjs → qr-code-CoBdSlMj.mjs} +1 -1
  125. package/dist/{qr-code-Dhu5TPha.js → qr-code-DnrpOmnA.js} +1 -1
  126. package/dist/{recycle-horizontal-9JHHDd4h.js → recycle-horizontal-FSLMVZm8.js} +1 -1
  127. package/dist/{recycle-horizontal-CS_0PZGV.mjs → recycle-horizontal-QVM9S5AC.mjs} +1 -1
  128. package/dist/{refresh-C_qXNL0S.mjs → refresh-BLIVGKaq.mjs} +1 -1
  129. package/dist/{refresh-DkMlARk7.js → refresh-COfPS7vr.js} +1 -1
  130. package/dist/{reown-logo-UwMrTrcX.js → reown-logo-CZAsRrs0.js} +1 -1
  131. package/dist/{reown-logo-CBPzCyQW.mjs → reown-logo-DUChpH7H.mjs} +1 -1
  132. package/dist/{search-CQuKFVAx.mjs → search-CLiLGFA4.mjs} +1 -1
  133. package/dist/{search-B4itLiVW.js → search-DLgB_GbD.js} +1 -1
  134. package/dist/{secp256k1-BB5DYugF.mjs → secp256k1-BJsOrooe.mjs} +1 -1
  135. package/dist/{secp256k1-BiRGPPqo.js → secp256k1-CNUh3htr.js} +1 -1
  136. package/dist/{secp256k1-Cf9t2cTM.mjs → secp256k1-Ccv5OiSV.mjs} +1 -1
  137. package/dist/{secp256k1-CI29X52U.js → secp256k1-bnuRwvDw.js} +1 -1
  138. package/dist/{send-qTi-ybzM.mjs → send-C1u-6SHt.mjs} +1 -1
  139. package/dist/{send-porC6mPB.js → send-DGshrpDA.js} +1 -1
  140. package/dist/{swapHorizontal-HantsmRd.js → swapHorizontal-CFbfyLgn.js} +1 -1
  141. package/dist/{swapHorizontal-C3MNcVMo.mjs → swapHorizontal-Cwjkdsr_.mjs} +1 -1
  142. package/dist/{swapHorizontalBold-XlXD6Scp.js → swapHorizontalBold-09z63E9T.js} +1 -1
  143. package/dist/{swapHorizontalBold-C_GQta-j.mjs → swapHorizontalBold-B28dKslj.mjs} +1 -1
  144. package/dist/{swapHorizontalMedium-ChYk0TiL.js → swapHorizontalMedium-DJYNXSPW.js} +1 -1
  145. package/dist/{swapHorizontalMedium-Bo6Sszm7.mjs → swapHorizontalMedium-trPBtiFC.mjs} +1 -1
  146. package/dist/{swapHorizontalRoundedBold-B5EvZSwz.mjs → swapHorizontalRoundedBold-CMZxOUua.mjs} +1 -1
  147. package/dist/{swapHorizontalRoundedBold-Dx_Co5wk.js → swapHorizontalRoundedBold-Ptc8r0vg.js} +1 -1
  148. package/dist/{swapVertical-cHQwpGr0.mjs → swapVertical-DY90vFiN.mjs} +1 -1
  149. package/dist/{swapVertical-fmzZLSPI.js → swapVertical-ny4gtovd.js} +1 -1
  150. package/dist/{telegram-Dv7wEgKb.js → telegram-C2ZKHNWF.js} +1 -1
  151. package/dist/{telegram-BdrptLN3.mjs → telegram-l0Kq7QNJ.mjs} +1 -1
  152. package/dist/{three-dots-DEs9ZhDC.mjs → three-dots-BfIVjHqD.mjs} +1 -1
  153. package/dist/{three-dots-CPXRPIKy.js → three-dots-D7fNl4Y3.js} +1 -1
  154. package/dist/{twitch-Ck5pSyDI.js → twitch-Cp3J00vk.js} +1 -1
  155. package/dist/{twitch-IQhZ8m1X.mjs → twitch-mse8Ps_4.mjs} +1 -1
  156. package/dist/{twitterIcon-DsS9CDA5.mjs → twitterIcon-BJ_sFyVT.mjs} +1 -1
  157. package/dist/{twitterIcon-DO8XDAwC.js → twitterIcon-H4h5Aywp.js} +1 -1
  158. package/dist/types/index.d.ts +7 -0
  159. package/dist/utils/constants.d.ts +15 -2
  160. package/dist/{verify-CgTgRejE.js → verify-CGPWx5np.js} +1 -1
  161. package/dist/{verify-filled-BhxgjhKC.js → verify-filled-D9Glq4lu.js} +1 -1
  162. package/dist/{verify-filled-QPe9Hi2W.mjs → verify-filled-DUK_OCSP.mjs} +1 -1
  163. package/dist/{verify-DOD4hBvs.mjs → verify-s1BE8BKh.mjs} +1 -1
  164. package/dist/{w3m-modal-DLEWxfrc.js → w3m-modal-B5jwhJmy.js} +1 -1
  165. package/dist/{w3m-modal-C3JE1VNb.mjs → w3m-modal-C6jLvRzV.mjs} +2 -2
  166. package/dist/{wallet-ByF6bf_R.mjs → wallet-Bzh0erOH.mjs} +1 -1
  167. package/dist/{wallet-DU_BeJ1K.js → wallet-g7RENq36.js} +1 -1
  168. package/dist/{wallet-placeholder-C3VkDDkp.js → wallet-placeholder-BcUgE4NN.js} +1 -1
  169. package/dist/{wallet-placeholder-DBpXjyqE.mjs → wallet-placeholder-CEzpeXcS.mjs} +1 -1
  170. package/dist/{walletconnect-DC4CEinm.js → walletconnect-BKjSlNIP.js} +1 -1
  171. package/dist/{walletconnect-B2bmSYc7.mjs → walletconnect-CK6Oi70p.mjs} +1 -1
  172. package/dist/{warning-circle-CYTT9cYz.mjs → warning-circle-A8bchW2N.mjs} +1 -1
  173. package/dist/{warning-circle-BBKO7OkV.js → warning-circle-CkEcV2BW.js} +1 -1
  174. package/dist/{x-DG2aE2ub.mjs → x-D9Vj3f9W.mjs} +1 -1
  175. package/dist/{x-PLo7_AhG.js → x-DZ3xIhAs.js} +1 -1
  176. package/package.json +9 -4
  177. package/dist/en_US-Y4ZOVFV4-hyEPVcDM.mjs +0 -4
@@ -1,4 +1,4 @@
1
- "use strict";const ze=require("./index-BKj9Y5tv.js");function gr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Ro(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const i=gr(r);return(s,n)=>i.then(o=>n(o.transaction(e,s).objectStore(e)))}let rn;function Li(){return rn||(rn=Ro("keyval-store","keyval")),rn}function qn(t,e=Li()){return e("readonly",r=>gr(r.get(t)))}function cl(t,e,r=Li()){return r("readwrite",i=>(i.put(e,t),gr(i.transaction)))}function ul(t,e=Li()){return e("readwrite",r=>(r.delete(t),gr(r.transaction)))}function ll(t=Li()){return t("readwrite",e=>(e.clear(),gr(e.transaction)))}function sp(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},gr(t.transaction)}function hl(t=Li()){return t("readonly",e=>{if(e.getAllKeys)return gr(e.getAllKeys());const r=[];return sp(e,i=>r.push(i.key)).then(()=>r)})}var No={exports:{}},Vr=typeof Reflect=="object"?Reflect:null,da=Vr&&typeof Vr.apply=="function"?Vr.apply:function(e,r,i){return Function.prototype.apply.call(e,r,i)},ms;Vr&&typeof Vr.ownKeys=="function"?ms=Vr.ownKeys:Object.getOwnPropertySymbols?ms=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:ms=function(e){return Object.getOwnPropertyNames(e)};function np(t){console&&console.warn&&console.warn(t)}var dl=Number.isNaN||function(e){return e!==e};function re(){re.init.call(this)}No.exports=re;No.exports.once=up;re.EventEmitter=re;re.prototype._events=void 0;re.prototype._eventsCount=0;re.prototype._maxListeners=void 0;var pa=10;function Ls(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(re,"defaultMaxListeners",{enumerable:!0,get:function(){return pa},set:function(t){if(typeof t!="number"||t<0||dl(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");pa=t}});re.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};re.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||dl(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function pl(t){return t._maxListeners===void 0?re.defaultMaxListeners:t._maxListeners}re.prototype.getMaxListeners=function(){return pl(this)};re.prototype.emit=function(e){for(var r=[],i=1;i<arguments.length;i++)r.push(arguments[i]);var s=e==="error",n=this._events;if(n!==void 0)s=s&&n.error===void 0;else if(!s)return!1;if(s){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(c===void 0)return!1;if(typeof c=="function")da(c,this,r);else for(var u=c.length,l=wl(c,u),i=0;i<u;++i)da(l[i],this,r);return!0};function fl(t,e,r,i){var s,n,o;if(Ls(r),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),o=n[e]),o===void 0)o=n[e]=r,++t._eventsCount;else if(typeof o=="function"?o=n[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),s=pl(t),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,np(a)}return t}re.prototype.addListener=function(e,r){return fl(this,e,r,!1)};re.prototype.on=re.prototype.addListener;re.prototype.prependListener=function(e,r){return fl(this,e,r,!0)};function op(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function gl(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},s=op.bind(i);return s.listener=r,i.wrapFn=s,s}re.prototype.once=function(e,r){return Ls(r),this.on(e,gl(this,e,r)),this};re.prototype.prependOnceListener=function(e,r){return Ls(r),this.prependListener(e,gl(this,e,r)),this};re.prototype.removeListener=function(e,r){var i,s,n,o,a;if(Ls(r),s=this._events,s===void 0)return this;if(i=s[e],i===void 0)return this;if(i===r||i.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||r));else if(typeof i!="function"){for(n=-1,o=i.length-1;o>=0;o--)if(i[o]===r||i[o].listener===r){a=i[o].listener,n=o;break}if(n<0)return this;n===0?i.shift():ap(i,n),i.length===1&&(s[e]=i[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};re.prototype.off=re.prototype.removeListener;re.prototype.removeAllListeners=function(e){var r,i,s;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var n=Object.keys(i),o;for(s=0;s<n.length;++s)o=n[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=i[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(s=r.length-1;s>=0;s--)this.removeListener(e,r[s]);return this};function yl(t,e,r){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?r?[s.listener||s]:[s]:r?cp(s):wl(s,s.length)}re.prototype.listeners=function(e){return yl(this,e,!0)};re.prototype.rawListeners=function(e){return yl(this,e,!1)};re.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ml.call(t,e)};re.prototype.listenerCount=ml;function ml(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}re.prototype.eventNames=function(){return this._eventsCount>0?ms(this._events):[]};function wl(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function ap(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function cp(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function up(t,e){return new Promise(function(r,i){function s(o){t.removeListener(e,n),i(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",s),r([].slice.call(arguments))}bl(t,e,n,{once:!0}),e!=="error"&&lp(t,s,{once:!0})})}function lp(t,e,r){typeof t.on=="function"&&bl(t,"error",e,r)}function bl(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(n){i.once&&t.removeEventListener(e,s),r(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var He=No.exports;const Us=ze.getDefaultExportFromCjs(He);var fa=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},hp=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),dp=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),pp=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),fp=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),gp=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),yp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,mp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,ga=3,wp=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",yp]],ya=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function vl(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new gp:typeof navigator<"u"?vp(navigator.userAgent):_p()}function bp(t){return t!==""&&wp.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function vp(t){var e=bp(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new fp;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<ga&&(s=fa(fa([],s,!0),Ip(ga-s.length),!0)):s=[];var n=s.join("."),o=Ep(t),a=mp.exec(t);return a&&a[1]?new pp(r,n,o,a[1]):new hp(r,n,o)}function Ep(t){for(var e=0,r=ya.length;e<r;e++){var i=ya[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function _p(){var t=typeof process<"u"&&process.version;return t?new dp(process.version.slice(1)):null}function Ip(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var N={};/*! *****************************************************************************
1
+ "use strict";const ze=require("./index-VHB4k7R7.js");function gr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Ro(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const i=gr(r);return(s,n)=>i.then(o=>n(o.transaction(e,s).objectStore(e)))}let rn;function Li(){return rn||(rn=Ro("keyval-store","keyval")),rn}function qn(t,e=Li()){return e("readonly",r=>gr(r.get(t)))}function cl(t,e,r=Li()){return r("readwrite",i=>(i.put(e,t),gr(i.transaction)))}function ul(t,e=Li()){return e("readwrite",r=>(r.delete(t),gr(r.transaction)))}function ll(t=Li()){return t("readwrite",e=>(e.clear(),gr(e.transaction)))}function sp(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},gr(t.transaction)}function hl(t=Li()){return t("readonly",e=>{if(e.getAllKeys)return gr(e.getAllKeys());const r=[];return sp(e,i=>r.push(i.key)).then(()=>r)})}var No={exports:{}},Vr=typeof Reflect=="object"?Reflect:null,da=Vr&&typeof Vr.apply=="function"?Vr.apply:function(e,r,i){return Function.prototype.apply.call(e,r,i)},ms;Vr&&typeof Vr.ownKeys=="function"?ms=Vr.ownKeys:Object.getOwnPropertySymbols?ms=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:ms=function(e){return Object.getOwnPropertyNames(e)};function np(t){console&&console.warn&&console.warn(t)}var dl=Number.isNaN||function(e){return e!==e};function re(){re.init.call(this)}No.exports=re;No.exports.once=up;re.EventEmitter=re;re.prototype._events=void 0;re.prototype._eventsCount=0;re.prototype._maxListeners=void 0;var pa=10;function Ls(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(re,"defaultMaxListeners",{enumerable:!0,get:function(){return pa},set:function(t){if(typeof t!="number"||t<0||dl(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");pa=t}});re.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};re.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||dl(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function pl(t){return t._maxListeners===void 0?re.defaultMaxListeners:t._maxListeners}re.prototype.getMaxListeners=function(){return pl(this)};re.prototype.emit=function(e){for(var r=[],i=1;i<arguments.length;i++)r.push(arguments[i]);var s=e==="error",n=this._events;if(n!==void 0)s=s&&n.error===void 0;else if(!s)return!1;if(s){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(c===void 0)return!1;if(typeof c=="function")da(c,this,r);else for(var u=c.length,l=wl(c,u),i=0;i<u;++i)da(l[i],this,r);return!0};function fl(t,e,r,i){var s,n,o;if(Ls(r),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),o=n[e]),o===void 0)o=n[e]=r,++t._eventsCount;else if(typeof o=="function"?o=n[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),s=pl(t),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,np(a)}return t}re.prototype.addListener=function(e,r){return fl(this,e,r,!1)};re.prototype.on=re.prototype.addListener;re.prototype.prependListener=function(e,r){return fl(this,e,r,!0)};function op(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function gl(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},s=op.bind(i);return s.listener=r,i.wrapFn=s,s}re.prototype.once=function(e,r){return Ls(r),this.on(e,gl(this,e,r)),this};re.prototype.prependOnceListener=function(e,r){return Ls(r),this.prependListener(e,gl(this,e,r)),this};re.prototype.removeListener=function(e,r){var i,s,n,o,a;if(Ls(r),s=this._events,s===void 0)return this;if(i=s[e],i===void 0)return this;if(i===r||i.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||r));else if(typeof i!="function"){for(n=-1,o=i.length-1;o>=0;o--)if(i[o]===r||i[o].listener===r){a=i[o].listener,n=o;break}if(n<0)return this;n===0?i.shift():ap(i,n),i.length===1&&(s[e]=i[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};re.prototype.off=re.prototype.removeListener;re.prototype.removeAllListeners=function(e){var r,i,s;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[e]),this;if(arguments.length===0){var n=Object.keys(i),o;for(s=0;s<n.length;++s)o=n[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=i[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(s=r.length-1;s>=0;s--)this.removeListener(e,r[s]);return this};function yl(t,e,r){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?r?[s.listener||s]:[s]:r?cp(s):wl(s,s.length)}re.prototype.listeners=function(e){return yl(this,e,!0)};re.prototype.rawListeners=function(e){return yl(this,e,!1)};re.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ml.call(t,e)};re.prototype.listenerCount=ml;function ml(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}re.prototype.eventNames=function(){return this._eventsCount>0?ms(this._events):[]};function wl(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function ap(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function cp(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function up(t,e){return new Promise(function(r,i){function s(o){t.removeListener(e,n),i(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",s),r([].slice.call(arguments))}bl(t,e,n,{once:!0}),e!=="error"&&lp(t,s,{once:!0})})}function lp(t,e,r){typeof t.on=="function"&&bl(t,"error",e,r)}function bl(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(n){i.once&&t.removeEventListener(e,s),r(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var He=No.exports;const Us=ze.getDefaultExportFromCjs(He);var fa=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},hp=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),dp=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),pp=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),fp=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),gp=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),yp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,mp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,ga=3,wp=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",yp]],ya=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function vl(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new gp:typeof navigator<"u"?vp(navigator.userAgent):_p()}function bp(t){return t!==""&&wp.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function vp(t){var e=bp(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new fp;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<ga&&(s=fa(fa([],s,!0),Ip(ga-s.length),!0)):s=[];var n=s.join("."),o=Ep(t),a=mp.exec(t);return a&&a[1]?new pp(r,n,o,a[1]):new hp(r,n,o)}function Ep(t){for(var e=0,r=ya.length;e<r;e++){var i=ya[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function _p(){var t=typeof process<"u"&&process.version;return t?new dp(process.version.slice(1)):null}function Ip(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var N={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -12,7 +12,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
14
  ***************************************************************************** */var zn=function(t,e){return zn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},zn(t,e)};function Dp(t,e){zn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Hn=function(){return Hn=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Hn.apply(this,arguments)};function Sp(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function Op(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function Pp(t,e){return function(r,i){e(r,i,t)}}function $p(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ap(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):s(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function xp(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){r.label=u[1];break}if(u[0]===6&&r.label<n[1]){r.label=n[1],n=u;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(u);break}n[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Cp(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function Tp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Vn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function El(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function Rp(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(El(arguments[e]));return t}function Np(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Ai(t){return this instanceof Ai?(this.v=t,this):new Ai(t)}function Fp(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(f){return new Promise(function(p,y){n.push([d,f,p,y])>1||a(d,f)})})}function a(d,f){try{c(i[d](f))}catch(p){h(n[0][3],p)}}function c(d){d.value instanceof Ai?Promise.resolve(d.value.v).then(u,l):h(n[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function Bp(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:Ai(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function jp(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Vn=="function"?Vn(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function Lp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Up(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function kp(t){return t&&t.__esModule?t:{default:t}}function Mp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function qp(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const zp=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Hn},__asyncDelegator:Bp,__asyncGenerator:Fp,__asyncValues:jp,__await:Ai,__awaiter:Ap,__classPrivateFieldGet:Mp,__classPrivateFieldSet:qp,__createBinding:Cp,__decorate:Op,__exportStar:Tp,__extends:Dp,__generator:xp,__importDefault:kp,__importStar:Up,__makeTemplateObject:Lp,__metadata:$p,__param:Pp,__read:El,__rest:Sp,__spread:Rp,__spreadArrays:Np,__values:Vn},Symbol.toStringTag,{value:"Module"})),Ui=ze.getAugmentedNamespace(zp);var sn={},li={},ma;function Hp(){if(ma)return li;ma=1,Object.defineProperty(li,"__esModule",{value:!0}),li.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return li.delay=t,li}var Xt={},nn={},er={},wa;function Vp(){return wa||(wa=1,Object.defineProperty(er,"__esModule",{value:!0}),er.ONE_THOUSAND=er.ONE_HUNDRED=void 0,er.ONE_HUNDRED=100,er.ONE_THOUSAND=1e3),er}var on={},ba;function Kp(){return ba||(ba=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(on)),on}var va;function _l(){return va||(va=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ui;e.__exportStar(Vp(),t),e.__exportStar(Kp(),t)}(nn)),nn}var Ea;function Wp(){if(Ea)return Xt;Ea=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.fromMiliseconds=Xt.toMiliseconds=void 0;const t=_l();function e(i){return i*t.ONE_THOUSAND}Xt.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Xt.fromMiliseconds=r,Xt}var _a;function Gp(){return _a||(_a=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ui;e.__exportStar(Hp(),t),e.__exportStar(Wp(),t)}(sn)),sn}var vr={},Ia;function Yp(){if(Ia)return vr;Ia=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return vr.Watch=t,vr.default=t,vr}var an={},hi={},Da;function Jp(){if(Da)return hi;Da=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.IWatch=void 0;class t{}return hi.IWatch=t,hi}var Sa;function Zp(){return Sa||(Sa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Ui.__exportStar(Jp(),t)}(an)),an}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ui;e.__exportStar(Gp(),t),e.__exportStar(Yp(),t),e.__exportStar(Zp(),t),e.__exportStar(_l(),t)})(N);var ae={};Object.defineProperty(ae,"__esModule",{value:!0});ae.getLocalStorage=ae.getLocalStorageOrThrow=ae.getCrypto=ae.getCryptoOrThrow=exports.getLocation_1=ae.getLocation=ae.getLocationOrThrow=exports.getNavigator_1=ae.getNavigator=ae.getNavigatorOrThrow=exports.getDocument_1=ae.getDocument=ae.getDocumentOrThrow=ae.getFromWindowOrThrow=ae.getFromWindow=void 0;function yr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ae.getFromWindow=yr;function ti(t){const e=yr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ae.getFromWindowOrThrow=ti;function Qp(){return ti("document")}ae.getDocumentOrThrow=Qp;function Xp(){return yr("document")}exports.getDocument_1=ae.getDocument=Xp;function ef(){return ti("navigator")}ae.getNavigatorOrThrow=ef;function tf(){return yr("navigator")}exports.getNavigator_1=ae.getNavigator=tf;function rf(){return ti("location")}ae.getLocationOrThrow=rf;function sf(){return yr("location")}exports.getLocation_1=ae.getLocation=sf;function nf(){return ti("crypto")}ae.getCryptoOrThrow=nf;function of(){return yr("crypto")}ae.getCrypto=of;function af(){return ti("localStorage")}ae.getLocalStorageOrThrow=af;function cf(){return yr("localStorage")}ae.getLocalStorage=cf;var Fo={};Object.defineProperty(Fo,"__esModule",{value:!0});exports.getWindowMetadata_1=Fo.getWindowMetadata=void 0;const Oa=ae;function uf(){let t,e;try{t=Oa.getDocumentOrThrow(),e=Oa.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),d=[];for(let f=0;f<h.length;f++){const p=h[f],y=p.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const w=p.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let v=e.protocol+"//"+e.host;if(w.indexOf("/")===0)v+=w;else{const b=e.pathname.split("/");b.pop();const E=b.join("/");v+=E+"/"+w}d.push(v)}else if(w.indexOf("//")===0){const v=e.protocol+w;d.push(v)}else d.push(w)}}return d}function i(...h){const d=t.getElementsByTagName("meta");for(let f=0;f<d.length;f++){const p=d[f],y=["itemprop","property","name"].map(w=>p.getAttribute(w)).filter(w=>w?h.includes(w):!1);if(y.length&&y){const w=p.getAttribute("content");if(w)return w}}return""}function s(){let h=i("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function n(){return i("description","og:description","twitter:description","keywords")}const o=s(),a=n(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}exports.getWindowMetadata_1=Fo.getWindowMetadata=uf;function xi(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Pa(t){return xi(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Il="2.23.2";let di={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Il}`};class hr extends Error{constructor(e,r={}){var a;const i=(()=>{var c;return r.cause instanceof hr?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof hr&&r.cause.docsPath||r.docsPath,n=(a=di.getDocsUrl)==null?void 0:a.call(di,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...di.version?[`Version: ${di.version}`]:[]].join(`
15
- `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Il}walk(e){return Dl(this,e)}}function Dl(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Dl(t.cause,e):e?null:t}class Sl extends hr{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function ri(t,{dir:e,size:r=32}={}){return typeof t=="string"?lf(t,{dir:e,size:r}):hf(t,{dir:e,size:r})}function lf(t,{dir:e,size:r=32}={}){if(r===null)return t;const i=t.replace("0x","");if(i.length>r*2)throw new Sl({size:Math.ceil(i.length/2),targetSize:r,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function hf(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new Sl({size:t.length,targetSize:r,type:"bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const n=e==="right";i[n?s:r-s-1]=t[n?s:t.length-s-1]}return i}class df extends hr{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class pf extends hr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ii(t,{size:e}){if(Pa(t)>e)throw new pf({givenSize:Pa(t),maxSize:e})}function Kn(t,e={}){const{signed:r}=e;e.size&&ii(t,{size:e.size});const i=BigInt(t);if(!r)return i;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function ff(t,e={}){return Number(Kn(t,e))}const gf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Wn(t,e={}){return typeof t=="number"||typeof t=="bigint"?Pl(t,e):typeof t=="string"?wf(t,e):typeof t=="boolean"?yf(t,e):Ol(t,e)}function yf(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{size:e.size})):r}function Ol(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=gf[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(ii(i,{size:e.size}),ri(i,{dir:"right",size:e.size})):i}function Pl(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new df({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:r,size:i,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?ri(a,{size:i}):a}const mf=new TextEncoder;function wf(t,e={}){const r=mf.encode(t);return Ol(r,e)}const bf=new TextEncoder;function vf(t,e={}){return typeof t=="number"||typeof t=="bigint"?_f(t,e):typeof t=="boolean"?Ef(t,e):xi(t)?$l(t,e):Al(t,e)}function Ef(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{size:e.size})):r}const Pt={zero:48,nine:57,A:65,F:70,a:97,f:102};function $a(t){if(t>=Pt.zero&&t<=Pt.nine)return t-Pt.zero;if(t>=Pt.A&&t<=Pt.F)return t-(Pt.A-10);if(t>=Pt.a&&t<=Pt.f)return t-(Pt.a-10)}function $l(t,e={}){let r=t;e.size&&(ii(r,{size:e.size}),r=ri(r,{dir:"right",size:e.size}));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=$a(i.charCodeAt(a++)),u=$a(i.charCodeAt(a++));if(c===void 0||u===void 0)throw new hr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+u}return n}function _f(t,e){const r=Pl(t,e);return $l(r)}function Al(t,e={}){const r=bf.encode(t);return typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{dir:"right",size:e.size})):r}function Ss(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function If(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ki(t,...e){if(!If(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Df(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ss(t.outputLen),Ss(t.blockLen)}function Gn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xl(t,e){ki(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const ts=BigInt(2**32-1),Aa=BigInt(32);function Sf(t,e=!1){return e?{h:Number(t&ts),l:Number(t>>Aa&ts)}:{h:Number(t>>Aa&ts)|0,l:Number(t&ts)|0}}function Of(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Sf(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Pf=(t,e,r)=>t<<r|e>>>32-r,$f=(t,e,r)=>e<<r|t>>>32-r,Af=(t,e,r)=>e<<r-32|t>>>64-r,xf=(t,e,r)=>t<<r-32|e>>>64-r,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Cf(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Tf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Rf(t,e){return t<<32-e|t>>>e}const xa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Nf(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ca(t){for(let e=0;e<t.length;e++)t[e]=Nf(t[e])}function Ff(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Bo(t){return typeof t=="string"&&(t=Ff(t)),ki(t),t}function Bf(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ki(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class Cl{clone(){return this._cloneInto()}}function Tl(t){const e=i=>t().update(Bo(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function jf(t=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(t));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Rl=[],Nl=[],Fl=[],Lf=BigInt(0),pi=BigInt(1),Uf=BigInt(2),kf=BigInt(7),Mf=BigInt(256),qf=BigInt(113);for(let t=0,e=pi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Rl.push(2*(5*i+r)),Nl.push((t+1)*(t+2)/2%64);let s=Lf;for(let n=0;n<7;n++)e=(e<<pi^(e>>kf)*qf)%Mf,e&Uf&&(s^=pi<<(pi<<BigInt(n))-pi);Fl.push(s)}const[zf,Hf]=Of(Fl,!0),Ta=(t,e,r)=>r>32?Af(t,e,r):Pf(t,e,r),Ra=(t,e,r)=>r>32?xf(t,e,r):$f(t,e,r);function Vf(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=Ta(u,l,1)^r[a],d=Ra(u,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=h,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Nl[o],c=Ta(s,n,a),u=Ra(s,n,a),l=Rl[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=zf[i],t[1]^=Hf[i]}r.fill(0)}class jo extends Cl{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ss(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Cf(this.state)}keccak(){xa||Ca(this.state32),Vf(this.state32,this.rounds),xa||Ca(this.state32),this.posOut=0,this.pos=0}update(e){Gn(this);const{blockLen:r,state:i}=this;e=Bo(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gn(this,!1),ki(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xl(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new jo(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Kf=(t,e,r)=>Tl(()=>new jo(e,t,r)),Wf=Kf(1,136,256/8);function Bl(t,e){const r=e||"hex",i=Wf(xi(t,{strict:!1})?vf(t):t);return r==="bytes"?i:Wn(i)}class Gf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const cn=new Gf(8192);function Yf(t,e){if(cn.has(`${t}.${e}`))return cn.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),i=Bl(Al(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return cn.set(`${t}.${e}`,n),n}function Jf(t){const e=Bl(`0x${t.substring(4)}`).substring(26);return Yf(`0x${e}`)}async function Zf({hash:t,signature:e}){const r=xi(t)?t:Wn(t),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-CI29X52U.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,f=Number(d??h),p=Na(f);return new i.Signature(Kn(u),Kn(l)).addRecoveryBit(p)}const o=xi(e)?e:Wn(e),a=ff(`0x${o.slice(130)}`),c=Na(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Na(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Qf({hash:t,signature:e}){return Jf(await Zf({hash:t,signature:e}))}function Xf(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,d=0;const f=u.length;for(;d!==f&&u[d]===0;)d++,l++;const p=(f-d)*n+1>>>0,y=new Uint8Array(p);for(;d!==f;){let b=u[d],E=0;for(let I=p-1;(b!==0||E<h)&&I!==-1;I--,E++)b+=256*y[I]>>>0,y[I]=b%r>>>0,b=b/r>>>0;if(b!==0)throw new Error("Non-zero carry");h=E,d++}let w=p-h;for(;w!==p&&y[w]===0;)w++;let v=i.repeat(l);for(;w<p;++w)v+=t.charAt(y[w]);return v}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===i;)h++,l++;const f=(u.length-l)*s+1>>>0,p=new Uint8Array(f);for(;l<u.length;){const b=u.charCodeAt(l);if(b>255)return;let E=e[b];if(E===255)return;let I=0;for(let $=f-1;(E!==0||I<d)&&$!==-1;$--,I++)E+=r*p[$]>>>0,p[$]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=I,l++}let y=f-d;for(;y!==f&&p[y]===0;)y++;const w=new Uint8Array(h+(f-y));let v=h;for(;y!==f;)w[v++]=p[y++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var eg="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const tg=Xf(eg),rg=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),ig=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Yt(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return ig(t)}catch{return t}}function St(t){return typeof t=="string"?t:rg(t)||""}function sg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function jl(t,...e){if(!sg(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Fa(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ng(t,e){jl(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function og(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Ll(t){return typeof t=="string"&&(t=og(t)),jl(t),t}let ag=class{clone(){return this._cloneInto()}};function cg(t){const e=i=>t().update(Ll(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ul(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function ug(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}let lg=class extends ag{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=un(this.buffer)}update(e){Fa(this);const{view:r,buffer:i,blockLen:s}=this;e=Ll(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=un(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fa(this),ng(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;ug(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=un(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const rs=BigInt(2**32-1),Yn=BigInt(32);function kl(t,e=!1){return e?{h:Number(t&rs),l:Number(t>>Yn&rs)}:{h:Number(t>>Yn&rs)|0,l:Number(t&rs)|0}}function hg(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=kl(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const dg=(t,e)=>BigInt(t>>>0)<<Yn|BigInt(e>>>0),pg=(t,e,r)=>t>>>r,fg=(t,e,r)=>t<<32-r|e>>>r,gg=(t,e,r)=>t>>>r|e<<32-r,yg=(t,e,r)=>t<<32-r|e>>>r,mg=(t,e,r)=>t<<64-r|e>>>r-32,wg=(t,e,r)=>t>>>r-32|e<<64-r,bg=(t,e)=>e,vg=(t,e)=>t,Eg=(t,e,r)=>t<<r|e>>>32-r,_g=(t,e,r)=>e<<r|t>>>32-r,Ig=(t,e,r)=>e<<r-32|t>>>64-r,Dg=(t,e,r)=>t<<r-32|e>>>64-r;function Sg(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Og=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Pg=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,$g=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Ag=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,xg=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Cg=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,V={fromBig:kl,split:hg,toBig:dg,shrSH:pg,shrSL:fg,rotrSH:gg,rotrSL:yg,rotrBH:mg,rotrBL:wg,rotr32H:bg,rotr32L:vg,rotlSH:Eg,rotlSL:_g,rotlBH:Ig,rotlBL:Dg,add:Sg,add3L:Og,add3H:Pg,add4L:$g,add4H:Ag,add5H:Cg,add5L:xg},[Tg,Rg]=V.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Ut=new Uint32Array(80),kt=new Uint32Array(80);let Ng=class extends lg{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:d,Gh:f,Gl:p,Hh:y,Hl:w}=this;return[e,r,i,s,n,o,a,c,u,l,h,d,f,p,y,w]}set(e,r,i,s,n,o,a,c,u,l,h,d,f,p,y,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=y|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Ut[E]=e.getUint32(r),kt[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const I=Ut[E-15]|0,$=kt[E-15]|0,A=V.rotrSH(I,$,1)^V.rotrSH(I,$,8)^V.shrSH(I,$,7),P=V.rotrSL(I,$,1)^V.rotrSL(I,$,8)^V.shrSL(I,$,7),C=Ut[E-2]|0,S=kt[E-2]|0,M=V.rotrSH(C,S,19)^V.rotrBH(C,S,61)^V.shrSH(C,S,6),j=V.rotrSL(C,S,19)^V.rotrBL(C,S,61)^V.shrSL(C,S,6),B=V.add4L(P,j,kt[E-7],kt[E-16]),q=V.add4H(B,A,M,Ut[E-7],Ut[E-16]);Ut[E]=q|0,kt[E]=B|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:f,Fl:p,Gh:y,Gl:w,Hh:v,Hl:b}=this;for(let E=0;E<80;E++){const I=V.rotrSH(h,d,14)^V.rotrSH(h,d,18)^V.rotrBH(h,d,41),$=V.rotrSL(h,d,14)^V.rotrSL(h,d,18)^V.rotrBL(h,d,41),A=h&f^~h&y,P=d&p^~d&w,C=V.add5L(b,$,P,Rg[E],kt[E]),S=V.add5H(C,v,I,A,Tg[E],Ut[E]),M=C|0,j=V.rotrSH(i,s,28)^V.rotrBH(i,s,34)^V.rotrBH(i,s,39),B=V.rotrSL(i,s,28)^V.rotrBL(i,s,34)^V.rotrBL(i,s,39),q=i&n^i&a^n&a,T=s&o^s&c^o&c;v=y|0,b=w|0,y=f|0,w=p|0,f=h|0,p=d|0,{h,l:d}=V.add(u|0,l|0,S|0,M|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=V.add3L(M,B,T);i=V.add3H(g,S,j,q),s=g|0}({h:i,l:s}=V.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=V.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=V.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=V.add(this.Eh|0,this.El|0,h|0,d|0),{h:f,l:p}=V.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:y,l:w}=V.add(this.Gh|0,this.Gl|0,y|0,w|0),{h:v,l:b}=V.add(this.Hh|0,this.Hl|0,v|0,b|0),this.set(i,s,n,o,a,c,u,l,h,d,f,p,y,w,v,b)}roundClean(){Ut.fill(0),kt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const Fg=cg(()=>new Ng);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Lo=BigInt(0),Ml=BigInt(1),Bg=BigInt(2);function Uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ko(t){if(!Uo(t))throw new Error("Uint8Array expected")}function ln(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const jg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mo(t){ko(t);let e="";for(let r=0;r<t.length;r++)e+=jg[t[r]];return e}function ql(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Lo:BigInt("0x"+t)}const $t={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ba(t){if(t>=$t._0&&t<=$t._9)return t-$t._0;if(t>=$t.A&&t<=$t.F)return t-($t.A-10);if(t>=$t.a&&t<=$t.f)return t-($t.a-10)}function zl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Ba(t.charCodeAt(n)),a=Ba(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function Lg(t){return ql(Mo(t))}function ws(t){return ko(t),ql(Mo(Uint8Array.from(t).reverse()))}function Hl(t,e){return zl(t.toString(16).padStart(e*2,"0"))}function Jn(t,e){return Hl(t,e).reverse()}function At(t,e,r){let i;if(typeof e=="string")try{i=zl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Uo(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function ja(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ko(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const hn=t=>typeof t=="bigint"&&Lo<=t;function Ug(t,e,r){return hn(t)&&hn(e)&&hn(r)&&e<=t&&t<r}function fi(t,e,r,i){if(!Ug(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function kg(t){let e;for(e=0;t>Lo;t>>=Ml,e+=1);return e}const Mg=t=>(Bg<<BigInt(t-1))-Ml,qg={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Uo(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function qo(t,e,r={}){const i=(s,n,o)=>{const a=qg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function La(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const ve=BigInt(0),ue=BigInt(1),nr=BigInt(2),zg=BigInt(3),Zn=BigInt(4),Ua=BigInt(5),ka=BigInt(8);function fe(t,e){const r=t%e;return r>=ve?r:e+r}function Hg(t,e,r){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(r<=ve)throw new Error("invalid modulus");if(r===ue)return ve;let i=ue;for(;e>ve;)e&ue&&(i=i*t%r),t=t*t%r,e>>=ue;return i}function mt(t,e,r){let i=t;for(;e-- >ve;)i*=i,i%=r;return i}function Ma(t,e){if(t===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let r=fe(t,e),i=e,s=ve,n=ue;for(;r!==ve;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==ue)throw new Error("invert: does not exist");return fe(s,e)}function Vg(t){const e=(t-ue)/nr;let r,i,s;for(r=t-ue,i=0;r%nr===ve;r/=nr,i++);for(s=nr;s<t&&Hg(s,e,t)!==t-ue;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ue)/Zn;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(r+ue)/nr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(h);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(u,ue<<BigInt(c-d-1));u=o.sqr(f),l=o.mul(l,f),h=o.mul(h,u),c=d}return l}}function Kg(t){if(t%Zn===zg){const e=(t+ue)/Zn;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%ka===Ua){const e=(t-Ua)/ka;return function(r,i){const s=r.mul(i,nr),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,nr),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Vg(t)}const Wg=(t,e)=>(fe(t,e)&ue)===ue,Gg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yg(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Gg.reduce((i,s)=>(i[s]="function",i),e);return qo(t,r)}function Jg(t,e,r){if(r<ve)throw new Error("invalid exponent, negatives unsupported");if(r===ve)return t.ONE;if(r===ue)return e;let i=t.ONE,s=e;for(;r>ve;)r&ue&&(i=t.mul(i,s)),s=t.sqr(s),r>>=ue;return i}function Zg(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Vl(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Kl(t,e,r=!1,i={}){if(t<=ve)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Vl(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Mg(s),ZERO:ve,ONE:ue,create:c=>fe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<t},is0:c=>c===ve,isOdd:c=>(c&ue)===ue,neg:c=>fe(-c,t),eql:(c,u)=>c===u,sqr:c=>fe(c*c,t),add:(c,u)=>fe(c+u,t),sub:(c,u)=>fe(c-u,t),mul:(c,u)=>fe(c*u,t),pow:(c,u)=>Jg(a,c,u),div:(c,u)=>fe(c*Ma(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ma(c,t),sqrt:i.sqrt||(c=>(o||(o=Kg(t)),o(a,c))),invertBatch:c=>Zg(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Jn(c,n):Hl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?ws(c):Lg(c)}});return Object.freeze(a)}const qa=BigInt(0),is=BigInt(1);function dn(t,e){const r=e.negate();return t?r:e}function Wl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function pn(t,e){Wl(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function Qg(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Xg(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const fn=new WeakMap,Gl=new WeakMap;function gn(t){return Gl.get(t)||1}function ey(t,e){return{constTimeNegate:dn,hasPrecomputes(r){return gn(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>qa;)i&is&&(s=s.add(n)),n=n.double(),i>>=is;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=pn(i,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=pn(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&u);s>>=h,p>o&&(p-=l,s+=is);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(dn(v,i[y])):a=a.add(dn(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=pn(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(s===qa)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=u,s+=is),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=fn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&fn.set(i,s(n))),n},wNAFCached(r,i,s){const n=gn(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=gn(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Wl(i,e),Gl.set(r,i),fn.delete(r)}}}function ty(t,e,r,i){if(Qg(r,t),Xg(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=kg(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),h!==0)for(let f=0;f<o;f++)l=l.double()}return l}function ry(t){return Yg(t.Fp),qo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Vl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const ct=BigInt(0),Le=BigInt(1),ss=BigInt(2),iy=BigInt(8),sy={zip215:!0};function ny(t){const e=ry(t);return qo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function oy(t){const e=ny(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=ss<<BigInt(a*8)-Le,l=r.create,h=Kl(e.n,e.nBitLength),d=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:ct}}}),f=e.adjustScalarBytes||(g=>g),p=e.domain||((g,m,_)=>{if(ln("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){fi("coordinate "+g,m,ct,u)}function w(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const v=La((g,m)=>{const{ex:_,ey:O,ez:D}=g,x=g.is0();m==null&&(m=x?iy:r.inv(D));const L=l(_*m),k=l(O*m),z=l(D*m);if(x)return{x:ct,y:Le};if(z!==Le)throw new Error("invZ was invalid");return{x:L,y:k}}),b=La(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:O,ey:D,ez:x,et:L}=g,k=l(O*O),z=l(D*D),U=l(x*x),H=l(U*U),G=l(k*m),ne=l(U*l(G+z)),ee=l(H+l(_*l(k*z)));if(ne!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(O*D),xe=l(x*L);if(Y!==xe)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,O,D){this.ex=m,this.ey=_,this.ez=O,this.et=D,y("x",m),y("y",_),y("z",O),y("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:O}=m||{};return y("x",_),y("y",O),new E(_,O,Le,l(_*O))}static normalizeZ(m){const _=r.invertBatch(m.map(O=>O.ez));return m.map((O,D)=>O.toAffine(_[D])).map(E.fromAffine)}static msm(m,_){return ty(E,h,m,_)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:_,ey:O,ez:D}=this,{ex:x,ey:L,ez:k}=m,z=l(_*k),U=l(x*D),H=l(O*k),G=l(L*D);return z===U&&H===G}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:O,ez:D}=this,x=l(_*_),L=l(O*O),k=l(ss*l(D*D)),z=l(m*x),U=_+O,H=l(l(U*U)-x-L),G=z+L,ne=G-k,ee=z-L,Y=l(H*ne),xe=l(G*ee),_e=l(H*ee),Re=l(ne*G);return new E(Y,xe,Re,_e)}add(m){w(m);const{a:_,d:O}=e,{ex:D,ey:x,ez:L,et:k}=this,{ex:z,ey:U,ez:H,et:G}=m;if(_===BigInt(-1)){const na=l((x-D)*(U+z)),oa=l((x+D)*(U-z)),tn=l(oa-na);if(tn===ct)return this.double();const aa=l(L*ss*G),ca=l(k*ss*H),ua=ca+aa,la=oa+na,ha=ca-aa,ep=l(ua*tn),tp=l(la*ha),rp=l(ua*ha),ip=l(tn*la);return new E(ep,tp,ip,rp)}const ne=l(D*z),ee=l(x*U),Y=l(k*O*G),xe=l(L*H),_e=l((D+x)*(z+U)-ne-ee),Re=xe-Y,tt=xe+Y,rt=l(ee-_*ne),br=l(_e*Re),Zd=l(tt*rt),Qd=l(_e*rt),Xd=l(Re*tt);return new E(br,Zd,Xd,Qd)}subtract(m){return this.add(m.negate())}wNAF(m){return A.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;fi("scalar",_,Le,i);const{p:O,f:D}=this.wNAF(_);return E.normalizeZ([O,D])[0]}multiplyUnsafe(m,_=E.ZERO){const O=m;return fi("scalar",O,ct,i),O===ct?$:this.is0()||O===Le?this:A.wNAFCachedUnsafe(this,O,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,i).is0()}toAffine(m){return v(this,m)}clearCofactor(){const{h:m}=e;return m===Le?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:O,a:D}=e,x=r.BYTES;m=At("pointHex",m,x),ln("zip215",_);const L=m.slice(),k=m[x-1];L[x-1]=k&-129;const z=ws(L),U=_?u:r.ORDER;fi("pointHex.y",z,ct,U);const H=l(z*z),G=l(H-Le),ne=l(O*H-D);let{isValid:ee,value:Y}=d(G,ne);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const xe=(Y&Le)===Le,_e=(k&128)!==0;if(!_&&Y===ct&&_e)throw new Error("Point.fromHex: x=0 and x_0=1");return _e!==xe&&(Y=l(-Y)),E.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return S(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),O=Jn(_,r.BYTES);return O[O.length-1]|=m&Le?128:0,O}toHex(){return Mo(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Le,l(e.Gx*e.Gy)),E.ZERO=new E(ct,Le,Le,ct);const{BASE:I,ZERO:$}=E,A=ey(E,a*8);function P(g){return fe(g,i)}function C(g){return P(ws(g))}function S(g){const m=r.BYTES;g=At("private key",g,m);const _=At("hashed private key",n(g),2*m),O=f(_.slice(0,m)),D=_.slice(m,2*m),x=C(O),L=I.multiply(x),k=L.toRawBytes();return{head:O,prefix:D,scalar:x,point:L,pointBytes:k}}function M(g){return S(g).pointBytes}function j(g=new Uint8Array,...m){const _=ja(...m);return C(n(p(_,At("context",g),!!s)))}function B(g,m,_={}){g=At("message",g),s&&(g=s(g));const{prefix:O,scalar:D,pointBytes:x}=S(m),L=j(_.context,O,g),k=I.multiply(L).toRawBytes(),z=j(_.context,k,x,g),U=P(L+z*D);fi("signature.s",U,ct,i);const H=ja(k,Jn(U,r.BYTES));return At("result",H,r.BYTES*2)}const q=sy;function T(g,m,_,O=q){const{context:D,zip215:x}=O,L=r.BYTES;g=At("signature",g,2*L),m=At("message",m),_=At("publicKey",_,L),x!==void 0&&ln("zip215",x),s&&(m=s(m));const k=ws(g.slice(L,2*L));let z,U,H;try{z=E.fromHex(_,x),U=E.fromHex(g.slice(0,L),x),H=I.multiplyUnsafe(k)}catch{return!1}if(!x&&z.isSmallOrder())return!1;const G=j(D,U.toRawBytes(),z.toRawBytes(),m);return U.add(z.multiplyUnsafe(G)).subtract(H).clearCofactor().equals(E.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:M,sign:B,verify:T,ExtendedPoint:E,utils:{getExtendedPublicKey:S,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const zo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const ay=BigInt(1),Ha=BigInt(2);BigInt(3);const cy=BigInt(5),uy=BigInt(8);function ly(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=zo,o=t*t%n*t%n,a=mt(o,Ha,n)*o%n,c=mt(a,ay,n)*t%n,u=mt(c,cy,n)*c%n,l=mt(u,e,n)*u%n,h=mt(l,r,n)*l%n,d=mt(h,i,n)*h%n,f=mt(d,s,n)*d%n,p=mt(f,s,n)*d%n,y=mt(p,e,n)*u%n;return{pow_p_5_8:mt(y,Ha,n)*t%n,b2:o}}function hy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function dy(t,e){const r=zo,i=fe(e*e*e,r),s=fe(i*i*e,r),n=ly(t*s).pow_p_5_8;let o=fe(t*i*n,r);const a=fe(e*o*o,r),c=o,u=fe(o*za,r),l=a===t,h=a===fe(-t,r),d=a===fe(-t*za,r);return l&&(o=c),(h||d)&&(o=u),Wg(o,r)&&(o=fe(-o,r)),{isValid:l||h,value:o}}const py=Kl(zo,void 0,!0),fy={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:py,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:uy,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Fg,randomBytes:Ul,adjustScalarBytes:hy,uvRatio:dy},Yl=oy(fy),gy="EdDSA",yy="JWT",Os=".",ks="base64url",Jl="utf8",Zl="utf8",my=":",wy="did",by="key",Va="base58btc",vy="z",Ey="K36",_y=32;function Ho(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Ql(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ho(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Xl(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Ql(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Ho(r)}function Iy(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var $=p[v],A=0,P=E-1;($!==0||A<w)&&P!==-1;P--,A++)$+=256*I[P]>>>0,I[P]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var S=c.repeat(y);C<E;++C)S+=t.charAt(I[C]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var $=0,A=b-1;(I!==0||$<v)&&A!==-1;A--,$++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=$,y++}if(p[y]!==" "){for(var P=b-v;P!==b&&E[P]===0;)P++;for(var C=new Uint8Array(w+(b-P)),S=w;P!==b;)C[S++]=E[P++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var Dy=Iy,Sy=Dy;const eh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Oy=t=>new TextEncoder().encode(t),Py=t=>new TextDecoder().decode(t);let $y=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ay=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return th(this,e)}},xy=class{constructor(e){this.decoders=e}or(e){return th(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const th=(t,e)=>new xy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Cy=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new $y(e,r,i),this.decoder=new Ay(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ms=({name:t,prefix:e,encode:r,decode:i})=>new Cy(t,e,r,i),Mi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Sy(r,e);return Ms({prefix:t,name:e,encode:i,decode:n=>eh(s(n))})},Ty=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Ry=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ms({prefix:e,name:t,encode(s){return Ry(s,i,r)},decode(s){return Ty(s,i,r,t)}}),Ny=Ms({prefix:"\0",name:"identity",encode:t=>Py(t),decode:t=>Oy(t)});var Fy=Object.freeze({__proto__:null,identity:Ny});const By=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jy=Object.freeze({__proto__:null,base2:By});const Ly=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uy=Object.freeze({__proto__:null,base8:Ly});const ky=Mi({prefix:"9",name:"base10",alphabet:"0123456789"});var My=Object.freeze({__proto__:null,base10:ky});const qy=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zy=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hy=Object.freeze({__proto__:null,base16:qy,base16upper:zy});const Vy=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ky=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wy=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gy=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Yy=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jy=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zy=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qy=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xy=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var em=Object.freeze({__proto__:null,base32:Vy,base32upper:Ky,base32pad:Wy,base32padupper:Gy,base32hex:Yy,base32hexupper:Jy,base32hexpad:Zy,base32hexpadupper:Qy,base32z:Xy});const tm=Mi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rm=Mi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var im=Object.freeze({__proto__:null,base36:tm,base36upper:rm});const sm=Mi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nm=Mi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var om=Object.freeze({__proto__:null,base58btc:sm,base58flickr:nm});const am=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cm=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),um=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lm=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hm=Object.freeze({__proto__:null,base64:am,base64pad:cm,base64url:um,base64urlpad:lm});const rh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),dm=rh.reduce((t,e,r)=>(t[r]=e,t),[]),pm=rh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fm(t){return t.reduce((e,r)=>(e+=dm[r],e),"")}function gm(t){const e=[];for(const r of t){const i=pm[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const ym=Ms({prefix:"🚀",name:"base256emoji",encode:fm,decode:gm});var mm=Object.freeze({__proto__:null,base256emoji:ym}),wm=ih,Ka=128,bm=-128,vm=Math.pow(2,31);function ih(t,e,r){e=e||[],r=r||0;for(var i=r;t>=vm;)e[r++]=t&255|Ka,t/=128;for(;t&bm;)e[r++]=t&255|Ka,t>>>=7;return e[r]=t|0,ih.bytes=r-i+1,e}var Em=Qn,_m=128,Wa=127;function Qn(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Qn.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Wa)<<s:(o&Wa)*Math.pow(2,s),s+=7}while(o>=_m);return Qn.bytes=n-i,r}var Im=Math.pow(2,7),Dm=Math.pow(2,14),Sm=Math.pow(2,21),Om=Math.pow(2,28),Pm=Math.pow(2,35),$m=Math.pow(2,42),Am=Math.pow(2,49),xm=Math.pow(2,56),Cm=Math.pow(2,63),Tm=function(t){return t<Im?1:t<Dm?2:t<Sm?3:t<Om?4:t<Pm?5:t<$m?6:t<Am?7:t<xm?8:t<Cm?9:10},Rm={encode:wm,decode:Em,encodingLength:Tm},sh=Rm;const Ga=(t,e,r=0)=>(sh.encode(t,e,r),e),Ya=t=>sh.encodingLength(t),Xn=(t,e)=>{const r=e.byteLength,i=Ya(t),s=i+Ya(r),n=new Uint8Array(s+r);return Ga(t,n,0),Ga(r,n,i),n.set(e,s),new Nm(t,r,e,n)};let Nm=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const nh=({name:t,code:e,encode:r})=>new Fm(t,e,r);let Fm=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Xn(this.code,r):r.then(i=>Xn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const oh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Bm=nh({name:"sha2-256",code:18,encode:oh("SHA-256")}),jm=nh({name:"sha2-512",code:19,encode:oh("SHA-512")});var Lm=Object.freeze({__proto__:null,sha256:Bm,sha512:jm});const ah=0,Um="identity",ch=eh,km=t=>Xn(ah,ch(t)),Mm={code:ah,name:Um,encode:ch,digest:km};var qm=Object.freeze({__proto__:null,identity:Mm});new TextEncoder,new TextDecoder;const Ja={...Fy,...jy,...Uy,...My,...Hy,...em,...im,...om,...hm,...mm};({...Lm,...qm});function uh(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Za=uh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),yn=uh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Ql(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),lh={utf8:Za,"utf-8":Za,hex:Ja.base16,latin1:yn,ascii:yn,binary:yn,...Ja};function qs(t,e="utf8"){const r=lh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function si(t,e="utf8"){const r=lh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ho(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Qa(t){return Yt(qs(si(t,ks),Jl))}function Ps(t){return qs(si(St(t),Jl),ks)}function Vo(t){const e=si(Ey,Va),r=vy+qs(Xl([e,t]),Va);return[wy,by,r].join(my)}function zm(t){return qs(t,ks)}function Hm(t){return si(t,ks)}function Vm(t){return si([Ps(t.header),Ps(t.payload)].join(Os),Zl)}function Km(t){return[Ps(t.header),Ps(t.payload),zm(t.signature)].join(Os)}function $s(t){const e=t.split(Os),r=Qa(e[0]),i=Qa(e[1]),s=Hm(e[2]),n=si(e.slice(0,2).join(Os),Zl);return{header:r,payload:i,signature:s,data:n}}function eo(t=Ul(_y)){const e=Yl.getPublicKey(t);return{secretKey:Xl([t,e]),publicKey:e}}async function hh(t,e,r,i,s=N.fromMiliseconds(Date.now())){const n={alg:gy,typ:yy},o=Vo(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},u=Vm({header:n,payload:c}),l=Yl.sign(u,i.secretKey.slice(0,32));return Km({header:n,payload:c,signature:l})}function dh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Kr(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=dh(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}function Wm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var $=p[v],A=0,P=E-1;($!==0||A<w)&&P!==-1;P--,A++)$+=256*I[P]>>>0,I[P]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var S=c.repeat(y);C<E;++C)S+=t.charAt(I[C]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var $=0,A=b-1;(I!==0||$<v)&&A!==-1;A--,$++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=$,y++}if(p[y]!==" "){for(var P=b-v;P!==b&&E[P]===0;)P++;for(var C=new Uint8Array(w+(b-P)),S=w;P!==b;)C[S++]=E[P++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var Gm=Wm,Ym=Gm;const Jm=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Zm=t=>new TextEncoder().encode(t),Qm=t=>new TextDecoder().decode(t);class Xm{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ew{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ph(this,e)}}class tw{constructor(e){this.decoders=e}or(e){return ph(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ph=(t,e)=>new tw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class rw{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new Xm(e,r,i),this.decoder=new ew(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const zs=({name:t,prefix:e,encode:r,decode:i})=>new rw(t,e,r,i),qi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Ym(r,e);return zs({prefix:t,name:e,encode:i,decode:n=>Jm(s(n))})},iw=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},sw=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},$e=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>zs({prefix:e,name:t,encode(s){return sw(s,i,r)},decode(s){return iw(s,i,r,t)}}),nw=zs({prefix:"\0",name:"identity",encode:t=>Qm(t),decode:t=>Zm(t)}),ow=Object.freeze(Object.defineProperty({__proto__:null,identity:nw},Symbol.toStringTag,{value:"Module"})),aw=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),cw=Object.freeze(Object.defineProperty({__proto__:null,base2:aw},Symbol.toStringTag,{value:"Module"})),uw=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),lw=Object.freeze(Object.defineProperty({__proto__:null,base8:uw},Symbol.toStringTag,{value:"Module"})),hw=qi({prefix:"9",name:"base10",alphabet:"0123456789"}),dw=Object.freeze(Object.defineProperty({__proto__:null,base10:hw},Symbol.toStringTag,{value:"Module"})),pw=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fw=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),gw=Object.freeze(Object.defineProperty({__proto__:null,base16:pw,base16upper:fw},Symbol.toStringTag,{value:"Module"})),yw=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mw=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ww=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bw=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vw=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ew=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_w=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Iw=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Dw=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Sw=Object.freeze(Object.defineProperty({__proto__:null,base32:yw,base32hex:vw,base32hexpad:_w,base32hexpadupper:Iw,base32hexupper:Ew,base32pad:ww,base32padupper:bw,base32upper:mw,base32z:Dw},Symbol.toStringTag,{value:"Module"})),Ow=qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Pw=qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),$w=Object.freeze(Object.defineProperty({__proto__:null,base36:Ow,base36upper:Pw},Symbol.toStringTag,{value:"Module"})),Aw=qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xw=qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Cw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Aw,base58flickr:xw},Symbol.toStringTag,{value:"Module"})),Tw=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rw=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Nw=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fw=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Bw=Object.freeze(Object.defineProperty({__proto__:null,base64:Tw,base64pad:Rw,base64url:Nw,base64urlpad:Fw},Symbol.toStringTag,{value:"Module"})),fh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),jw=fh.reduce((t,e,r)=>(t[r]=e,t),[]),Lw=fh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Uw(t){return t.reduce((e,r)=>(e+=jw[r],e),"")}function kw(t){const e=[];for(const r of t){const i=Lw[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Mw=zs({prefix:"🚀",name:"base256emoji",encode:Uw,decode:kw}),qw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Mw},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Xa={...ow,...cw,...lw,...dw,...gw,...Sw,...$w,...Cw,...Bw,...qw};function gh(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const ec=gh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),mn=gh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=dh(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yh={utf8:ec,"utf-8":ec,hex:Xa.base16,latin1:mn,ascii:mn,binary:mn,...Xa};function Ze(t,e="utf8"){const r=yh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Fe(t,e="utf8"){const r=yh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const mh={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},zw=":";function Wr(t){const[e,r]=t.split(zw);return{namespace:e,reference:r}}function tc(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function wh(t,e){return t.includes(":")?[t]:e.chains||[]}var Hw=Object.defineProperty,Vw=Object.defineProperties,Kw=Object.getOwnPropertyDescriptors,rc=Object.getOwnPropertySymbols,Ww=Object.prototype.hasOwnProperty,Gw=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?Hw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sc=(t,e)=>{for(var r in e||(e={}))Ww.call(e,r)&&ic(t,r,e[r]);if(rc)for(var r of rc(e))Gw.call(e,r)&&ic(t,r,e[r]);return t},Yw=(t,e)=>Vw(t,Kw(e));const Jw="ReactNative",Qe={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Zw="js";function As(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Jt(){return!exports.getDocument_1()&&!!exports.getNavigator_1()&&navigator.product===Jw}function Qw(){return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Xw(){return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ni(){return!As()&&!!exports.getNavigator_1()&&!!exports.getDocument_1()}function zi(){return Jt()?Qe.reactNative:As()?Qe.node:ni()?Qe.browser:Qe.unknown}function nc(){var t;try{return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function eb(t,e){const r=new URLSearchParams(t);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&r.set(i,s)}return r.toString()}function tb(t){var e,r;const i=bh();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),Yw(sc(sc({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function bh(){return exports.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function rb(){if(zi()===Qe.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=vl();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function ib(){var t;const e=zi();return e===Qe.browser?[e,((t=exports.getLocation_1())==null?void 0:t.host)||"unknown"].join(":"):e}function vh(t,e,r){const i=rb(),s=ib();return[[t,e].join("-"),[Zw,r].join("-"),i,s].join("/")}function sb({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=vh(t,e,i),h={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=eb(u[1]||"",h);return u[0]+"?"+d}function ur(t,e){return t.filter(r=>e.includes(r)).length===t.length}function to(t){return Object.fromEntries(t.entries())}function ro(t){return new Map(Object.entries(t))}function ir(t=N.FIVE_MINUTES,e){const r=N.toMiliseconds(t||N.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),i=a,s=c})}}function Vt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function Eh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function nb(t){return Eh("topic",t)}function ob(t){return Eh("id",t)}function _h(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function pe(t,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(t))}function zt(t){return Date.now()>=N.toMiliseconds(t)}function X(t,e){return`${t}${e?`:${e}`:""}`}function It(t=[],e=[]){return[...new Set([...t,...e])]}async function ab({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=cb(n,t,e),a=zi();if(a===Qe.browser){if(!((i=exports.getDocument_1())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}ub(o)}else a===Qe.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function cb(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${pb(i,!0)}`}else s=`${s}/wc?${i}`;return s}function ub(t){let e="_self";db()?e="_top":(hb()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function lb(t,e){let r="";try{if(ni()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function oc(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function ac(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Ko(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function hb(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function db(){try{return window.self!==window.top}catch{return!1}}function pb(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Ih(t){return Buffer.from(t,"base64").toString("utf-8")}function fb(t){return new Promise(e=>setTimeout(e,t))}function Ci(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function gb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hi(t,...e){if(!gb(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Wo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ci(t.outputLen),Ci(t.blockLen)}function Gr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Dh(t,e){Hi(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const ns=BigInt(2**32-1),cc=BigInt(32);function yb(t,e=!1){return e?{h:Number(t&ns),l:Number(t>>cc&ns)}:{h:Number(t>>cc&ns)|0,l:Number(t&ns)|0}}function mb(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=yb(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const wb=(t,e,r)=>t<<r|e>>>32-r,bb=(t,e,r)=>e<<r|t>>>32-r,vb=(t,e,r)=>e<<r-32|t>>>64-r,Eb=(t,e,r)=>t<<r-32|e>>>64-r,Ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _b(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function wn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function wt(t,e){return t<<32-e|t>>>e}const uc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ib(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function lc(t){for(let e=0;e<t.length;e++)t[e]=Ib(t[e])}function Db(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Yr(t){return typeof t=="string"&&(t=Db(t)),Hi(t),t}function Sb(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Hi(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Go=class{clone(){return this._cloneInto()}};function Sh(t){const e=i=>t().update(Yr(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function oi(t=32){if(Ir&&typeof Ir.getRandomValues=="function")return Ir.getRandomValues(new Uint8Array(t));if(Ir&&typeof Ir.randomBytes=="function")return Ir.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Oh=[],Ph=[],$h=[],Ob=BigInt(0),gi=BigInt(1),Pb=BigInt(2),$b=BigInt(7),Ab=BigInt(256),xb=BigInt(113);for(let t=0,e=gi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Oh.push(2*(5*i+r)),Ph.push((t+1)*(t+2)/2%64);let s=Ob;for(let n=0;n<7;n++)e=(e<<gi^(e>>$b)*xb)%Ab,e&Pb&&(s^=gi<<(gi<<BigInt(n))-gi);$h.push(s)}const[Cb,Tb]=mb($h,!0),hc=(t,e,r)=>r>32?vb(t,e,r):wb(t,e,r),dc=(t,e,r)=>r>32?Eb(t,e,r):bb(t,e,r);function Rb(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=hc(u,l,1)^r[a],d=dc(u,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=h,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Ph[o],c=hc(s,n,a),u=dc(s,n,a),l=Oh[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=Cb[i],t[1]^=Tb[i]}r.fill(0)}let Nb=class Ah extends Go{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ci(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=_b(this.state)}keccak(){uc||lc(this.state32),Rb(this.state32,this.rounds),uc||lc(this.state32),this.posOut=0,this.pos=0}update(e){Gr(this);const{blockLen:r,state:i}=this;e=Yr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gr(this,!1),Hi(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ci(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Dh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Ah(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Fb=(t,e,r)=>Sh(()=>new Nb(e,t,r)),Bb=Fb(1,136,256/8),jb="https://rpc.walletconnect.org/v1";function xh(t){const e=`Ethereum Signed Message:
15
+ `);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Il}walk(e){return Dl(this,e)}}function Dl(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Dl(t.cause,e):e?null:t}class Sl extends hr{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function ri(t,{dir:e,size:r=32}={}){return typeof t=="string"?lf(t,{dir:e,size:r}):hf(t,{dir:e,size:r})}function lf(t,{dir:e,size:r=32}={}){if(r===null)return t;const i=t.replace("0x","");if(i.length>r*2)throw new Sl({size:Math.ceil(i.length/2),targetSize:r,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function hf(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new Sl({size:t.length,targetSize:r,type:"bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const n=e==="right";i[n?s:r-s-1]=t[n?s:t.length-s-1]}return i}class df extends hr{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class pf extends hr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ii(t,{size:e}){if(Pa(t)>e)throw new pf({givenSize:Pa(t),maxSize:e})}function Kn(t,e={}){const{signed:r}=e;e.size&&ii(t,{size:e.size});const i=BigInt(t);if(!r)return i;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function ff(t,e={}){return Number(Kn(t,e))}const gf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Wn(t,e={}){return typeof t=="number"||typeof t=="bigint"?Pl(t,e):typeof t=="string"?wf(t,e):typeof t=="boolean"?yf(t,e):Ol(t,e)}function yf(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{size:e.size})):r}function Ol(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=gf[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(ii(i,{size:e.size}),ri(i,{dir:"right",size:e.size})):i}function Pl(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new df({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:r,size:i,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?ri(a,{size:i}):a}const mf=new TextEncoder;function wf(t,e={}){const r=mf.encode(t);return Ol(r,e)}const bf=new TextEncoder;function vf(t,e={}){return typeof t=="number"||typeof t=="bigint"?_f(t,e):typeof t=="boolean"?Ef(t,e):xi(t)?$l(t,e):Al(t,e)}function Ef(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{size:e.size})):r}const Pt={zero:48,nine:57,A:65,F:70,a:97,f:102};function $a(t){if(t>=Pt.zero&&t<=Pt.nine)return t-Pt.zero;if(t>=Pt.A&&t<=Pt.F)return t-(Pt.A-10);if(t>=Pt.a&&t<=Pt.f)return t-(Pt.a-10)}function $l(t,e={}){let r=t;e.size&&(ii(r,{size:e.size}),r=ri(r,{dir:"right",size:e.size}));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=$a(i.charCodeAt(a++)),u=$a(i.charCodeAt(a++));if(c===void 0||u===void 0)throw new hr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+u}return n}function _f(t,e){const r=Pl(t,e);return $l(r)}function Al(t,e={}){const r=bf.encode(t);return typeof e.size=="number"?(ii(r,{size:e.size}),ri(r,{dir:"right",size:e.size})):r}function Ss(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function If(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ki(t,...e){if(!If(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Df(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ss(t.outputLen),Ss(t.blockLen)}function Gn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xl(t,e){ki(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const ts=BigInt(2**32-1),Aa=BigInt(32);function Sf(t,e=!1){return e?{h:Number(t&ts),l:Number(t>>Aa&ts)}:{h:Number(t>>Aa&ts)|0,l:Number(t&ts)|0}}function Of(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Sf(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Pf=(t,e,r)=>t<<r|e>>>32-r,$f=(t,e,r)=>e<<r|t>>>32-r,Af=(t,e,r)=>e<<r-32|t>>>64-r,xf=(t,e,r)=>t<<r-32|e>>>64-r,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Cf(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Tf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Rf(t,e){return t<<32-e|t>>>e}const xa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Nf(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ca(t){for(let e=0;e<t.length;e++)t[e]=Nf(t[e])}function Ff(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Bo(t){return typeof t=="string"&&(t=Ff(t)),ki(t),t}function Bf(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ki(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class Cl{clone(){return this._cloneInto()}}function Tl(t){const e=i=>t().update(Bo(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function jf(t=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(t));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Rl=[],Nl=[],Fl=[],Lf=BigInt(0),pi=BigInt(1),Uf=BigInt(2),kf=BigInt(7),Mf=BigInt(256),qf=BigInt(113);for(let t=0,e=pi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Rl.push(2*(5*i+r)),Nl.push((t+1)*(t+2)/2%64);let s=Lf;for(let n=0;n<7;n++)e=(e<<pi^(e>>kf)*qf)%Mf,e&Uf&&(s^=pi<<(pi<<BigInt(n))-pi);Fl.push(s)}const[zf,Hf]=Of(Fl,!0),Ta=(t,e,r)=>r>32?Af(t,e,r):Pf(t,e,r),Ra=(t,e,r)=>r>32?xf(t,e,r):$f(t,e,r);function Vf(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=Ta(u,l,1)^r[a],d=Ra(u,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=h,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Nl[o],c=Ta(s,n,a),u=Ra(s,n,a),l=Rl[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=zf[i],t[1]^=Hf[i]}r.fill(0)}class jo extends Cl{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ss(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Cf(this.state)}keccak(){xa||Ca(this.state32),Vf(this.state32,this.rounds),xa||Ca(this.state32),this.posOut=0,this.pos=0}update(e){Gn(this);const{blockLen:r,state:i}=this;e=Bo(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gn(this,!1),ki(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ss(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xl(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new jo(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Kf=(t,e,r)=>Tl(()=>new jo(e,t,r)),Wf=Kf(1,136,256/8);function Bl(t,e){const r=e||"hex",i=Wf(xi(t,{strict:!1})?vf(t):t);return r==="bytes"?i:Wn(i)}class Gf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const cn=new Gf(8192);function Yf(t,e){if(cn.has(`${t}.${e}`))return cn.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),i=Bl(Al(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return cn.set(`${t}.${e}`,n),n}function Jf(t){const e=Bl(`0x${t.substring(4)}`).substring(26);return Yf(`0x${e}`)}async function Zf({hash:t,signature:e}){const r=xi(t)?t:Wn(t),{secp256k1:i}=await Promise.resolve().then(()=>require("./secp256k1-bnuRwvDw.js"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,f=Number(d??h),p=Na(f);return new i.Signature(Kn(u),Kn(l)).addRecoveryBit(p)}const o=xi(e)?e:Wn(e),a=ff(`0x${o.slice(130)}`),c=Na(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Na(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Qf({hash:t,signature:e}){return Jf(await Zf({hash:t,signature:e}))}function Xf(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,d=0;const f=u.length;for(;d!==f&&u[d]===0;)d++,l++;const p=(f-d)*n+1>>>0,y=new Uint8Array(p);for(;d!==f;){let b=u[d],E=0;for(let I=p-1;(b!==0||E<h)&&I!==-1;I--,E++)b+=256*y[I]>>>0,y[I]=b%r>>>0,b=b/r>>>0;if(b!==0)throw new Error("Non-zero carry");h=E,d++}let w=p-h;for(;w!==p&&y[w]===0;)w++;let v=i.repeat(l);for(;w<p;++w)v+=t.charAt(y[w]);return v}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===i;)h++,l++;const f=(u.length-l)*s+1>>>0,p=new Uint8Array(f);for(;l<u.length;){const b=u.charCodeAt(l);if(b>255)return;let E=e[b];if(E===255)return;let I=0;for(let $=f-1;(E!==0||I<d)&&$!==-1;$--,I++)E+=r*p[$]>>>0,p[$]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=I,l++}let y=f-d;for(;y!==f&&p[y]===0;)y++;const w=new Uint8Array(h+(f-y));let v=h;for(;y!==f;)w[v++]=p[y++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var eg="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const tg=Xf(eg),rg=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),ig=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Yt(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return ig(t)}catch{return t}}function St(t){return typeof t=="string"?t:rg(t)||""}function sg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function jl(t,...e){if(!sg(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Fa(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ng(t,e){jl(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function og(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Ll(t){return typeof t=="string"&&(t=og(t)),jl(t),t}let ag=class{clone(){return this._cloneInto()}};function cg(t){const e=i=>t().update(Ll(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ul(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function ug(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}let lg=class extends ag{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=un(this.buffer)}update(e){Fa(this);const{view:r,buffer:i,blockLen:s}=this;e=Ll(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=un(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fa(this),ng(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;ug(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=un(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const rs=BigInt(2**32-1),Yn=BigInt(32);function kl(t,e=!1){return e?{h:Number(t&rs),l:Number(t>>Yn&rs)}:{h:Number(t>>Yn&rs)|0,l:Number(t&rs)|0}}function hg(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=kl(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const dg=(t,e)=>BigInt(t>>>0)<<Yn|BigInt(e>>>0),pg=(t,e,r)=>t>>>r,fg=(t,e,r)=>t<<32-r|e>>>r,gg=(t,e,r)=>t>>>r|e<<32-r,yg=(t,e,r)=>t<<32-r|e>>>r,mg=(t,e,r)=>t<<64-r|e>>>r-32,wg=(t,e,r)=>t>>>r-32|e<<64-r,bg=(t,e)=>e,vg=(t,e)=>t,Eg=(t,e,r)=>t<<r|e>>>32-r,_g=(t,e,r)=>e<<r|t>>>32-r,Ig=(t,e,r)=>e<<r-32|t>>>64-r,Dg=(t,e,r)=>t<<r-32|e>>>64-r;function Sg(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Og=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Pg=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,$g=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Ag=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,xg=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Cg=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,V={fromBig:kl,split:hg,toBig:dg,shrSH:pg,shrSL:fg,rotrSH:gg,rotrSL:yg,rotrBH:mg,rotrBL:wg,rotr32H:bg,rotr32L:vg,rotlSH:Eg,rotlSL:_g,rotlBH:Ig,rotlBL:Dg,add:Sg,add3L:Og,add3H:Pg,add4L:$g,add4H:Ag,add5H:Cg,add5L:xg},[Tg,Rg]=V.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Ut=new Uint32Array(80),kt=new Uint32Array(80);let Ng=class extends lg{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:d,Gh:f,Gl:p,Hh:y,Hl:w}=this;return[e,r,i,s,n,o,a,c,u,l,h,d,f,p,y,w]}set(e,r,i,s,n,o,a,c,u,l,h,d,f,p,y,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=y|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Ut[E]=e.getUint32(r),kt[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const I=Ut[E-15]|0,$=kt[E-15]|0,A=V.rotrSH(I,$,1)^V.rotrSH(I,$,8)^V.shrSH(I,$,7),P=V.rotrSL(I,$,1)^V.rotrSL(I,$,8)^V.shrSL(I,$,7),C=Ut[E-2]|0,S=kt[E-2]|0,M=V.rotrSH(C,S,19)^V.rotrBH(C,S,61)^V.shrSH(C,S,6),j=V.rotrSL(C,S,19)^V.rotrBL(C,S,61)^V.shrSL(C,S,6),B=V.add4L(P,j,kt[E-7],kt[E-16]),q=V.add4H(B,A,M,Ut[E-7],Ut[E-16]);Ut[E]=q|0,kt[E]=B|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:f,Fl:p,Gh:y,Gl:w,Hh:v,Hl:b}=this;for(let E=0;E<80;E++){const I=V.rotrSH(h,d,14)^V.rotrSH(h,d,18)^V.rotrBH(h,d,41),$=V.rotrSL(h,d,14)^V.rotrSL(h,d,18)^V.rotrBL(h,d,41),A=h&f^~h&y,P=d&p^~d&w,C=V.add5L(b,$,P,Rg[E],kt[E]),S=V.add5H(C,v,I,A,Tg[E],Ut[E]),M=C|0,j=V.rotrSH(i,s,28)^V.rotrBH(i,s,34)^V.rotrBH(i,s,39),B=V.rotrSL(i,s,28)^V.rotrBL(i,s,34)^V.rotrBL(i,s,39),q=i&n^i&a^n&a,T=s&o^s&c^o&c;v=y|0,b=w|0,y=f|0,w=p|0,f=h|0,p=d|0,{h,l:d}=V.add(u|0,l|0,S|0,M|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=V.add3L(M,B,T);i=V.add3H(g,S,j,q),s=g|0}({h:i,l:s}=V.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=V.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=V.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=V.add(this.Eh|0,this.El|0,h|0,d|0),{h:f,l:p}=V.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:y,l:w}=V.add(this.Gh|0,this.Gl|0,y|0,w|0),{h:v,l:b}=V.add(this.Hh|0,this.Hl|0,v|0,b|0),this.set(i,s,n,o,a,c,u,l,h,d,f,p,y,w,v,b)}roundClean(){Ut.fill(0),kt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const Fg=cg(()=>new Ng);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Lo=BigInt(0),Ml=BigInt(1),Bg=BigInt(2);function Uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ko(t){if(!Uo(t))throw new Error("Uint8Array expected")}function ln(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const jg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mo(t){ko(t);let e="";for(let r=0;r<t.length;r++)e+=jg[t[r]];return e}function ql(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Lo:BigInt("0x"+t)}const $t={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ba(t){if(t>=$t._0&&t<=$t._9)return t-$t._0;if(t>=$t.A&&t<=$t.F)return t-($t.A-10);if(t>=$t.a&&t<=$t.f)return t-($t.a-10)}function zl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Ba(t.charCodeAt(n)),a=Ba(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function Lg(t){return ql(Mo(t))}function ws(t){return ko(t),ql(Mo(Uint8Array.from(t).reverse()))}function Hl(t,e){return zl(t.toString(16).padStart(e*2,"0"))}function Jn(t,e){return Hl(t,e).reverse()}function At(t,e,r){let i;if(typeof e=="string")try{i=zl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Uo(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function ja(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ko(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const hn=t=>typeof t=="bigint"&&Lo<=t;function Ug(t,e,r){return hn(t)&&hn(e)&&hn(r)&&e<=t&&t<r}function fi(t,e,r,i){if(!Ug(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function kg(t){let e;for(e=0;t>Lo;t>>=Ml,e+=1);return e}const Mg=t=>(Bg<<BigInt(t-1))-Ml,qg={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Uo(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function qo(t,e,r={}){const i=(s,n,o)=>{const a=qg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function La(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const ve=BigInt(0),ue=BigInt(1),nr=BigInt(2),zg=BigInt(3),Zn=BigInt(4),Ua=BigInt(5),ka=BigInt(8);function fe(t,e){const r=t%e;return r>=ve?r:e+r}function Hg(t,e,r){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(r<=ve)throw new Error("invalid modulus");if(r===ue)return ve;let i=ue;for(;e>ve;)e&ue&&(i=i*t%r),t=t*t%r,e>>=ue;return i}function mt(t,e,r){let i=t;for(;e-- >ve;)i*=i,i%=r;return i}function Ma(t,e){if(t===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let r=fe(t,e),i=e,s=ve,n=ue;for(;r!==ve;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==ue)throw new Error("invert: does not exist");return fe(s,e)}function Vg(t){const e=(t-ue)/nr;let r,i,s;for(r=t-ue,i=0;r%nr===ve;r/=nr,i++);for(s=nr;s<t&&Hg(s,e,t)!==t-ue;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ue)/Zn;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(r+ue)/nr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(h);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(u,ue<<BigInt(c-d-1));u=o.sqr(f),l=o.mul(l,f),h=o.mul(h,u),c=d}return l}}function Kg(t){if(t%Zn===zg){const e=(t+ue)/Zn;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%ka===Ua){const e=(t-Ua)/ka;return function(r,i){const s=r.mul(i,nr),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,nr),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Vg(t)}const Wg=(t,e)=>(fe(t,e)&ue)===ue,Gg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yg(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Gg.reduce((i,s)=>(i[s]="function",i),e);return qo(t,r)}function Jg(t,e,r){if(r<ve)throw new Error("invalid exponent, negatives unsupported");if(r===ve)return t.ONE;if(r===ue)return e;let i=t.ONE,s=e;for(;r>ve;)r&ue&&(i=t.mul(i,s)),s=t.sqr(s),r>>=ue;return i}function Zg(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Vl(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Kl(t,e,r=!1,i={}){if(t<=ve)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Vl(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Mg(s),ZERO:ve,ONE:ue,create:c=>fe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<t},is0:c=>c===ve,isOdd:c=>(c&ue)===ue,neg:c=>fe(-c,t),eql:(c,u)=>c===u,sqr:c=>fe(c*c,t),add:(c,u)=>fe(c+u,t),sub:(c,u)=>fe(c-u,t),mul:(c,u)=>fe(c*u,t),pow:(c,u)=>Jg(a,c,u),div:(c,u)=>fe(c*Ma(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ma(c,t),sqrt:i.sqrt||(c=>(o||(o=Kg(t)),o(a,c))),invertBatch:c=>Zg(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Jn(c,n):Hl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?ws(c):Lg(c)}});return Object.freeze(a)}const qa=BigInt(0),is=BigInt(1);function dn(t,e){const r=e.negate();return t?r:e}function Wl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function pn(t,e){Wl(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function Qg(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Xg(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const fn=new WeakMap,Gl=new WeakMap;function gn(t){return Gl.get(t)||1}function ey(t,e){return{constTimeNegate:dn,hasPrecomputes(r){return gn(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>qa;)i&is&&(s=s.add(n)),n=n.double(),i>>=is;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=pn(i,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=pn(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&u);s>>=h,p>o&&(p-=l,s+=is);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(dn(v,i[y])):a=a.add(dn(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=pn(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(s===qa)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=u,s+=is),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=fn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&fn.set(i,s(n))),n},wNAFCached(r,i,s){const n=gn(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=gn(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Wl(i,e),Gl.set(r,i),fn.delete(r)}}}function ty(t,e,r,i){if(Qg(r,t),Xg(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=kg(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),h!==0)for(let f=0;f<o;f++)l=l.double()}return l}function ry(t){return Yg(t.Fp),qo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Vl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const ct=BigInt(0),Le=BigInt(1),ss=BigInt(2),iy=BigInt(8),sy={zip215:!0};function ny(t){const e=ry(t);return qo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function oy(t){const e=ny(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=ss<<BigInt(a*8)-Le,l=r.create,h=Kl(e.n,e.nBitLength),d=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:ct}}}),f=e.adjustScalarBytes||(g=>g),p=e.domain||((g,m,_)=>{if(ln("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){fi("coordinate "+g,m,ct,u)}function w(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const v=La((g,m)=>{const{ex:_,ey:O,ez:D}=g,x=g.is0();m==null&&(m=x?iy:r.inv(D));const L=l(_*m),k=l(O*m),z=l(D*m);if(x)return{x:ct,y:Le};if(z!==Le)throw new Error("invZ was invalid");return{x:L,y:k}}),b=La(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:O,ey:D,ez:x,et:L}=g,k=l(O*O),z=l(D*D),U=l(x*x),H=l(U*U),G=l(k*m),ne=l(U*l(G+z)),ee=l(H+l(_*l(k*z)));if(ne!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(O*D),xe=l(x*L);if(Y!==xe)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,O,D){this.ex=m,this.ey=_,this.ez=O,this.et=D,y("x",m),y("y",_),y("z",O),y("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:O}=m||{};return y("x",_),y("y",O),new E(_,O,Le,l(_*O))}static normalizeZ(m){const _=r.invertBatch(m.map(O=>O.ez));return m.map((O,D)=>O.toAffine(_[D])).map(E.fromAffine)}static msm(m,_){return ty(E,h,m,_)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:_,ey:O,ez:D}=this,{ex:x,ey:L,ez:k}=m,z=l(_*k),U=l(x*D),H=l(O*k),G=l(L*D);return z===U&&H===G}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:O,ez:D}=this,x=l(_*_),L=l(O*O),k=l(ss*l(D*D)),z=l(m*x),U=_+O,H=l(l(U*U)-x-L),G=z+L,ne=G-k,ee=z-L,Y=l(H*ne),xe=l(G*ee),_e=l(H*ee),Re=l(ne*G);return new E(Y,xe,Re,_e)}add(m){w(m);const{a:_,d:O}=e,{ex:D,ey:x,ez:L,et:k}=this,{ex:z,ey:U,ez:H,et:G}=m;if(_===BigInt(-1)){const na=l((x-D)*(U+z)),oa=l((x+D)*(U-z)),tn=l(oa-na);if(tn===ct)return this.double();const aa=l(L*ss*G),ca=l(k*ss*H),ua=ca+aa,la=oa+na,ha=ca-aa,ep=l(ua*tn),tp=l(la*ha),rp=l(ua*ha),ip=l(tn*la);return new E(ep,tp,ip,rp)}const ne=l(D*z),ee=l(x*U),Y=l(k*O*G),xe=l(L*H),_e=l((D+x)*(z+U)-ne-ee),Re=xe-Y,tt=xe+Y,rt=l(ee-_*ne),br=l(_e*Re),Zd=l(tt*rt),Qd=l(_e*rt),Xd=l(Re*tt);return new E(br,Zd,Xd,Qd)}subtract(m){return this.add(m.negate())}wNAF(m){return A.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;fi("scalar",_,Le,i);const{p:O,f:D}=this.wNAF(_);return E.normalizeZ([O,D])[0]}multiplyUnsafe(m,_=E.ZERO){const O=m;return fi("scalar",O,ct,i),O===ct?$:this.is0()||O===Le?this:A.wNAFCachedUnsafe(this,O,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,i).is0()}toAffine(m){return v(this,m)}clearCofactor(){const{h:m}=e;return m===Le?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:O,a:D}=e,x=r.BYTES;m=At("pointHex",m,x),ln("zip215",_);const L=m.slice(),k=m[x-1];L[x-1]=k&-129;const z=ws(L),U=_?u:r.ORDER;fi("pointHex.y",z,ct,U);const H=l(z*z),G=l(H-Le),ne=l(O*H-D);let{isValid:ee,value:Y}=d(G,ne);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const xe=(Y&Le)===Le,_e=(k&128)!==0;if(!_&&Y===ct&&_e)throw new Error("Point.fromHex: x=0 and x_0=1");return _e!==xe&&(Y=l(-Y)),E.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return S(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),O=Jn(_,r.BYTES);return O[O.length-1]|=m&Le?128:0,O}toHex(){return Mo(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Le,l(e.Gx*e.Gy)),E.ZERO=new E(ct,Le,Le,ct);const{BASE:I,ZERO:$}=E,A=ey(E,a*8);function P(g){return fe(g,i)}function C(g){return P(ws(g))}function S(g){const m=r.BYTES;g=At("private key",g,m);const _=At("hashed private key",n(g),2*m),O=f(_.slice(0,m)),D=_.slice(m,2*m),x=C(O),L=I.multiply(x),k=L.toRawBytes();return{head:O,prefix:D,scalar:x,point:L,pointBytes:k}}function M(g){return S(g).pointBytes}function j(g=new Uint8Array,...m){const _=ja(...m);return C(n(p(_,At("context",g),!!s)))}function B(g,m,_={}){g=At("message",g),s&&(g=s(g));const{prefix:O,scalar:D,pointBytes:x}=S(m),L=j(_.context,O,g),k=I.multiply(L).toRawBytes(),z=j(_.context,k,x,g),U=P(L+z*D);fi("signature.s",U,ct,i);const H=ja(k,Jn(U,r.BYTES));return At("result",H,r.BYTES*2)}const q=sy;function T(g,m,_,O=q){const{context:D,zip215:x}=O,L=r.BYTES;g=At("signature",g,2*L),m=At("message",m),_=At("publicKey",_,L),x!==void 0&&ln("zip215",x),s&&(m=s(m));const k=ws(g.slice(L,2*L));let z,U,H;try{z=E.fromHex(_,x),U=E.fromHex(g.slice(0,L),x),H=I.multiplyUnsafe(k)}catch{return!1}if(!x&&z.isSmallOrder())return!1;const G=j(D,U.toRawBytes(),z.toRawBytes(),m);return U.add(z.multiplyUnsafe(G)).subtract(H).clearCofactor().equals(E.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:M,sign:B,verify:T,ExtendedPoint:E,utils:{getExtendedPublicKey:S,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const zo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),za=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const ay=BigInt(1),Ha=BigInt(2);BigInt(3);const cy=BigInt(5),uy=BigInt(8);function ly(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=zo,o=t*t%n*t%n,a=mt(o,Ha,n)*o%n,c=mt(a,ay,n)*t%n,u=mt(c,cy,n)*c%n,l=mt(u,e,n)*u%n,h=mt(l,r,n)*l%n,d=mt(h,i,n)*h%n,f=mt(d,s,n)*d%n,p=mt(f,s,n)*d%n,y=mt(p,e,n)*u%n;return{pow_p_5_8:mt(y,Ha,n)*t%n,b2:o}}function hy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function dy(t,e){const r=zo,i=fe(e*e*e,r),s=fe(i*i*e,r),n=ly(t*s).pow_p_5_8;let o=fe(t*i*n,r);const a=fe(e*o*o,r),c=o,u=fe(o*za,r),l=a===t,h=a===fe(-t,r),d=a===fe(-t*za,r);return l&&(o=c),(h||d)&&(o=u),Wg(o,r)&&(o=fe(-o,r)),{isValid:l||h,value:o}}const py=Kl(zo,void 0,!0),fy={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:py,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:uy,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Fg,randomBytes:Ul,adjustScalarBytes:hy,uvRatio:dy},Yl=oy(fy),gy="EdDSA",yy="JWT",Os=".",ks="base64url",Jl="utf8",Zl="utf8",my=":",wy="did",by="key",Va="base58btc",vy="z",Ey="K36",_y=32;function Ho(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Ql(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ho(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Xl(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Ql(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Ho(r)}function Iy(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var $=p[v],A=0,P=E-1;($!==0||A<w)&&P!==-1;P--,A++)$+=256*I[P]>>>0,I[P]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var S=c.repeat(y);C<E;++C)S+=t.charAt(I[C]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var $=0,A=b-1;(I!==0||$<v)&&A!==-1;A--,$++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=$,y++}if(p[y]!==" "){for(var P=b-v;P!==b&&E[P]===0;)P++;for(var C=new Uint8Array(w+(b-P)),S=w;P!==b;)C[S++]=E[P++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var Dy=Iy,Sy=Dy;const eh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Oy=t=>new TextEncoder().encode(t),Py=t=>new TextDecoder().decode(t);let $y=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ay=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return th(this,e)}},xy=class{constructor(e){this.decoders=e}or(e){return th(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const th=(t,e)=>new xy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Cy=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new $y(e,r,i),this.decoder=new Ay(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ms=({name:t,prefix:e,encode:r,decode:i})=>new Cy(t,e,r,i),Mi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Sy(r,e);return Ms({prefix:t,name:e,encode:i,decode:n=>eh(s(n))})},Ty=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Ry=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ms({prefix:e,name:t,encode(s){return Ry(s,i,r)},decode(s){return Ty(s,i,r,t)}}),Ny=Ms({prefix:"\0",name:"identity",encode:t=>Py(t),decode:t=>Oy(t)});var Fy=Object.freeze({__proto__:null,identity:Ny});const By=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var jy=Object.freeze({__proto__:null,base2:By});const Ly=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Uy=Object.freeze({__proto__:null,base8:Ly});const ky=Mi({prefix:"9",name:"base10",alphabet:"0123456789"});var My=Object.freeze({__proto__:null,base10:ky});const qy=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zy=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Hy=Object.freeze({__proto__:null,base16:qy,base16upper:zy});const Vy=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ky=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wy=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gy=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Yy=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jy=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zy=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qy=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xy=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var em=Object.freeze({__proto__:null,base32:Vy,base32upper:Ky,base32pad:Wy,base32padupper:Gy,base32hex:Yy,base32hexupper:Jy,base32hexpad:Zy,base32hexpadupper:Qy,base32z:Xy});const tm=Mi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rm=Mi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var im=Object.freeze({__proto__:null,base36:tm,base36upper:rm});const sm=Mi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nm=Mi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var om=Object.freeze({__proto__:null,base58btc:sm,base58flickr:nm});const am=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cm=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),um=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lm=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hm=Object.freeze({__proto__:null,base64:am,base64pad:cm,base64url:um,base64urlpad:lm});const rh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),dm=rh.reduce((t,e,r)=>(t[r]=e,t),[]),pm=rh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function fm(t){return t.reduce((e,r)=>(e+=dm[r],e),"")}function gm(t){const e=[];for(const r of t){const i=pm[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const ym=Ms({prefix:"🚀",name:"base256emoji",encode:fm,decode:gm});var mm=Object.freeze({__proto__:null,base256emoji:ym}),wm=ih,Ka=128,bm=-128,vm=Math.pow(2,31);function ih(t,e,r){e=e||[],r=r||0;for(var i=r;t>=vm;)e[r++]=t&255|Ka,t/=128;for(;t&bm;)e[r++]=t&255|Ka,t>>>=7;return e[r]=t|0,ih.bytes=r-i+1,e}var Em=Qn,_m=128,Wa=127;function Qn(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Qn.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Wa)<<s:(o&Wa)*Math.pow(2,s),s+=7}while(o>=_m);return Qn.bytes=n-i,r}var Im=Math.pow(2,7),Dm=Math.pow(2,14),Sm=Math.pow(2,21),Om=Math.pow(2,28),Pm=Math.pow(2,35),$m=Math.pow(2,42),Am=Math.pow(2,49),xm=Math.pow(2,56),Cm=Math.pow(2,63),Tm=function(t){return t<Im?1:t<Dm?2:t<Sm?3:t<Om?4:t<Pm?5:t<$m?6:t<Am?7:t<xm?8:t<Cm?9:10},Rm={encode:wm,decode:Em,encodingLength:Tm},sh=Rm;const Ga=(t,e,r=0)=>(sh.encode(t,e,r),e),Ya=t=>sh.encodingLength(t),Xn=(t,e)=>{const r=e.byteLength,i=Ya(t),s=i+Ya(r),n=new Uint8Array(s+r);return Ga(t,n,0),Ga(r,n,i),n.set(e,s),new Nm(t,r,e,n)};let Nm=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const nh=({name:t,code:e,encode:r})=>new Fm(t,e,r);let Fm=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Xn(this.code,r):r.then(i=>Xn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const oh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Bm=nh({name:"sha2-256",code:18,encode:oh("SHA-256")}),jm=nh({name:"sha2-512",code:19,encode:oh("SHA-512")});var Lm=Object.freeze({__proto__:null,sha256:Bm,sha512:jm});const ah=0,Um="identity",ch=eh,km=t=>Xn(ah,ch(t)),Mm={code:ah,name:Um,encode:ch,digest:km};var qm=Object.freeze({__proto__:null,identity:Mm});new TextEncoder,new TextDecoder;const Ja={...Fy,...jy,...Uy,...My,...Hy,...em,...im,...om,...hm,...mm};({...Lm,...qm});function uh(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Za=uh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),yn=uh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Ql(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),lh={utf8:Za,"utf-8":Za,hex:Ja.base16,latin1:yn,ascii:yn,binary:yn,...Ja};function qs(t,e="utf8"){const r=lh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function si(t,e="utf8"){const r=lh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ho(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Qa(t){return Yt(qs(si(t,ks),Jl))}function Ps(t){return qs(si(St(t),Jl),ks)}function Vo(t){const e=si(Ey,Va),r=vy+qs(Xl([e,t]),Va);return[wy,by,r].join(my)}function zm(t){return qs(t,ks)}function Hm(t){return si(t,ks)}function Vm(t){return si([Ps(t.header),Ps(t.payload)].join(Os),Zl)}function Km(t){return[Ps(t.header),Ps(t.payload),zm(t.signature)].join(Os)}function $s(t){const e=t.split(Os),r=Qa(e[0]),i=Qa(e[1]),s=Hm(e[2]),n=si(e.slice(0,2).join(Os),Zl);return{header:r,payload:i,signature:s,data:n}}function eo(t=Ul(_y)){const e=Yl.getPublicKey(t);return{secretKey:Xl([t,e]),publicKey:e}}async function hh(t,e,r,i,s=N.fromMiliseconds(Date.now())){const n={alg:gy,typ:yy},o=Vo(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},u=Vm({header:n,payload:c}),l=Yl.sign(u,i.secretKey.slice(0,32));return Km({header:n,payload:c,signature:l})}function dh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Kr(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=dh(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}function Wm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var $=p[v],A=0,P=E-1;($!==0||A<w)&&P!==-1;P--,A++)$+=256*I[P]>>>0,I[P]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var S=c.repeat(y);C<E;++C)S+=t.charAt(I[C]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var $=0,A=b-1;(I!==0||$<v)&&A!==-1;A--,$++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=$,y++}if(p[y]!==" "){for(var P=b-v;P!==b&&E[P]===0;)P++;for(var C=new Uint8Array(w+(b-P)),S=w;P!==b;)C[S++]=E[P++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var Gm=Wm,Ym=Gm;const Jm=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Zm=t=>new TextEncoder().encode(t),Qm=t=>new TextDecoder().decode(t);class Xm{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ew{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ph(this,e)}}class tw{constructor(e){this.decoders=e}or(e){return ph(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ph=(t,e)=>new tw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class rw{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new Xm(e,r,i),this.decoder=new ew(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const zs=({name:t,prefix:e,encode:r,decode:i})=>new rw(t,e,r,i),qi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Ym(r,e);return zs({prefix:t,name:e,encode:i,decode:n=>Jm(s(n))})},iw=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},sw=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},$e=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>zs({prefix:e,name:t,encode(s){return sw(s,i,r)},decode(s){return iw(s,i,r,t)}}),nw=zs({prefix:"\0",name:"identity",encode:t=>Qm(t),decode:t=>Zm(t)}),ow=Object.freeze(Object.defineProperty({__proto__:null,identity:nw},Symbol.toStringTag,{value:"Module"})),aw=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),cw=Object.freeze(Object.defineProperty({__proto__:null,base2:aw},Symbol.toStringTag,{value:"Module"})),uw=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),lw=Object.freeze(Object.defineProperty({__proto__:null,base8:uw},Symbol.toStringTag,{value:"Module"})),hw=qi({prefix:"9",name:"base10",alphabet:"0123456789"}),dw=Object.freeze(Object.defineProperty({__proto__:null,base10:hw},Symbol.toStringTag,{value:"Module"})),pw=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fw=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),gw=Object.freeze(Object.defineProperty({__proto__:null,base16:pw,base16upper:fw},Symbol.toStringTag,{value:"Module"})),yw=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mw=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ww=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bw=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vw=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ew=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_w=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Iw=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Dw=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Sw=Object.freeze(Object.defineProperty({__proto__:null,base32:yw,base32hex:vw,base32hexpad:_w,base32hexpadupper:Iw,base32hexupper:Ew,base32pad:ww,base32padupper:bw,base32upper:mw,base32z:Dw},Symbol.toStringTag,{value:"Module"})),Ow=qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Pw=qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),$w=Object.freeze(Object.defineProperty({__proto__:null,base36:Ow,base36upper:Pw},Symbol.toStringTag,{value:"Module"})),Aw=qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xw=qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Cw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Aw,base58flickr:xw},Symbol.toStringTag,{value:"Module"})),Tw=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Rw=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Nw=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Fw=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Bw=Object.freeze(Object.defineProperty({__proto__:null,base64:Tw,base64pad:Rw,base64url:Nw,base64urlpad:Fw},Symbol.toStringTag,{value:"Module"})),fh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),jw=fh.reduce((t,e,r)=>(t[r]=e,t),[]),Lw=fh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Uw(t){return t.reduce((e,r)=>(e+=jw[r],e),"")}function kw(t){const e=[];for(const r of t){const i=Lw[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Mw=zs({prefix:"🚀",name:"base256emoji",encode:Uw,decode:kw}),qw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Mw},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Xa={...ow,...cw,...lw,...dw,...gw,...Sw,...$w,...Cw,...Bw,...qw};function gh(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const ec=gh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),mn=gh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=dh(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yh={utf8:ec,"utf-8":ec,hex:Xa.base16,latin1:mn,ascii:mn,binary:mn,...Xa};function Ze(t,e="utf8"){const r=yh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Fe(t,e="utf8"){const r=yh[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const mh={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},zw=":";function Wr(t){const[e,r]=t.split(zw);return{namespace:e,reference:r}}function tc(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function wh(t,e){return t.includes(":")?[t]:e.chains||[]}var Hw=Object.defineProperty,Vw=Object.defineProperties,Kw=Object.getOwnPropertyDescriptors,rc=Object.getOwnPropertySymbols,Ww=Object.prototype.hasOwnProperty,Gw=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?Hw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sc=(t,e)=>{for(var r in e||(e={}))Ww.call(e,r)&&ic(t,r,e[r]);if(rc)for(var r of rc(e))Gw.call(e,r)&&ic(t,r,e[r]);return t},Yw=(t,e)=>Vw(t,Kw(e));const Jw="ReactNative",Qe={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Zw="js";function As(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Jt(){return!exports.getDocument_1()&&!!exports.getNavigator_1()&&navigator.product===Jw}function Qw(){return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Xw(){return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ni(){return!As()&&!!exports.getNavigator_1()&&!!exports.getDocument_1()}function zi(){return Jt()?Qe.reactNative:As()?Qe.node:ni()?Qe.browser:Qe.unknown}function nc(){var t;try{return Jt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function eb(t,e){const r=new URLSearchParams(t);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&r.set(i,s)}return r.toString()}function tb(t){var e,r;const i=bh();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),Yw(sc(sc({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function bh(){return exports.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function rb(){if(zi()===Qe.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=vl();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function ib(){var t;const e=zi();return e===Qe.browser?[e,((t=exports.getLocation_1())==null?void 0:t.host)||"unknown"].join(":"):e}function vh(t,e,r){const i=rb(),s=ib();return[[t,e].join("-"),[Zw,r].join("-"),i,s].join("/")}function sb({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=vh(t,e,i),h={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=eb(u[1]||"",h);return u[0]+"?"+d}function ur(t,e){return t.filter(r=>e.includes(r)).length===t.length}function to(t){return Object.fromEntries(t.entries())}function ro(t){return new Map(Object.entries(t))}function ir(t=N.FIVE_MINUTES,e){const r=N.toMiliseconds(t||N.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),i=a,s=c})}}function Vt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function Eh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function nb(t){return Eh("topic",t)}function ob(t){return Eh("id",t)}function _h(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function pe(t,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(t))}function zt(t){return Date.now()>=N.toMiliseconds(t)}function X(t,e){return`${t}${e?`:${e}`:""}`}function It(t=[],e=[]){return[...new Set([...t,...e])]}async function ab({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=cb(n,t,e),a=zi();if(a===Qe.browser){if(!((i=exports.getDocument_1())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}ub(o)}else a===Qe.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function cb(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${pb(i,!0)}`}else s=`${s}/wc?${i}`;return s}function ub(t){let e="_self";db()?e="_top":(hb()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function lb(t,e){let r="";try{if(ni()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function oc(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function ac(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Ko(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function hb(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function db(){try{return window.self!==window.top}catch{return!1}}function pb(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Ih(t){return Buffer.from(t,"base64").toString("utf-8")}function fb(t){return new Promise(e=>setTimeout(e,t))}function Ci(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function gb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hi(t,...e){if(!gb(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Wo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ci(t.outputLen),Ci(t.blockLen)}function Gr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Dh(t,e){Hi(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const ns=BigInt(2**32-1),cc=BigInt(32);function yb(t,e=!1){return e?{h:Number(t&ns),l:Number(t>>cc&ns)}:{h:Number(t>>cc&ns)|0,l:Number(t&ns)|0}}function mb(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=yb(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const wb=(t,e,r)=>t<<r|e>>>32-r,bb=(t,e,r)=>e<<r|t>>>32-r,vb=(t,e,r)=>e<<r-32|t>>>64-r,Eb=(t,e,r)=>t<<r-32|e>>>64-r,Ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function _b(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function wn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function wt(t,e){return t<<32-e|t>>>e}const uc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ib(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function lc(t){for(let e=0;e<t.length;e++)t[e]=Ib(t[e])}function Db(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Yr(t){return typeof t=="string"&&(t=Db(t)),Hi(t),t}function Sb(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Hi(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Go=class{clone(){return this._cloneInto()}};function Sh(t){const e=i=>t().update(Yr(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function oi(t=32){if(Ir&&typeof Ir.getRandomValues=="function")return Ir.getRandomValues(new Uint8Array(t));if(Ir&&typeof Ir.randomBytes=="function")return Ir.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Oh=[],Ph=[],$h=[],Ob=BigInt(0),gi=BigInt(1),Pb=BigInt(2),$b=BigInt(7),Ab=BigInt(256),xb=BigInt(113);for(let t=0,e=gi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Oh.push(2*(5*i+r)),Ph.push((t+1)*(t+2)/2%64);let s=Ob;for(let n=0;n<7;n++)e=(e<<gi^(e>>$b)*xb)%Ab,e&Pb&&(s^=gi<<(gi<<BigInt(n))-gi);$h.push(s)}const[Cb,Tb]=mb($h,!0),hc=(t,e,r)=>r>32?vb(t,e,r):wb(t,e,r),dc=(t,e,r)=>r>32?Eb(t,e,r):bb(t,e,r);function Rb(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=hc(u,l,1)^r[a],d=dc(u,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=h,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Ph[o],c=hc(s,n,a),u=dc(s,n,a),l=Oh[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=Cb[i],t[1]^=Tb[i]}r.fill(0)}let Nb=class Ah extends Go{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Ci(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=_b(this.state)}keccak(){uc||lc(this.state32),Rb(this.state32,this.rounds),uc||lc(this.state32),this.posOut=0,this.pos=0}update(e){Gr(this);const{blockLen:r,state:i}=this;e=Yr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gr(this,!1),Hi(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ci(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Dh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Ah(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Fb=(t,e,r)=>Sh(()=>new Nb(e,t,r)),Bb=Fb(1,136,256/8),jb="https://rpc.walletconnect.org/v1";function xh(t){const e=`Ethereum Signed Message:
16
16
  ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Bb(r)).toString("hex")}async function Lb(t,e,r,i,s,n){switch(r.t){case"eip191":return await Ub(t,e,r.s);case"eip1271":return await kb(t,e,r.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function Ub(t,e,r){return(await Qf({hash:xh(e),signature:r})).toLowerCase()===t.toLowerCase()}async function kb(t,e,r,i,s,n){const o=Wr(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),h=xh(e).substring(2),d=a+h+c+u+l,f=await fetch(`${n||jb}/?chainId=${i}&projectId=${s}`,{method:"POST",body:JSON.stringify({id:Mb(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:p}=await f.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Mb(){return Date.now()+Math.floor(Math.random()*1e3)}function qb(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(r.length<s)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const n=Buffer.from(t,"base64").slice(1,65);return tg.encode(n)}var zb=Object.defineProperty,Hb=Object.defineProperties,Vb=Object.getOwnPropertyDescriptors,pc=Object.getOwnPropertySymbols,Kb=Object.prototype.hasOwnProperty,Wb=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?zb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gb=(t,e)=>{for(var r in e||(e={}))Kb.call(e,r)&&fc(t,r,e[r]);if(pc)for(var r of pc(e))Wb.call(e,r)&&fc(t,r,e[r]);return t},Yb=(t,e)=>Hb(t,Vb(e));const Jb="did:pkh:",Yo=t=>t==null?void 0:t.split(":"),Zb=t=>{const e=t&&Yo(t);if(e)return t.includes(Jb)?e[3]:e[1]},io=t=>{const e=t&&Yo(t);if(e)return e[2]+":"+e[3]},xs=t=>{const e=t&&Yo(t);if(e)return e.pop()};async function gc(t){const{cacao:e,projectId:r}=t,{s:i,p:s}=e,n=Ch(s,s.iss),o=xs(s.iss);return await Lb(o,n,i,io(s.iss),r)}const Ch=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,i=xs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${Zb(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,f=t.resources?`Resources:${t.resources.map(y=>`
17
17
  - ${y}`).join("")}`:void 0,p=bs(t.resources);if(p){const y=Ti(p);s=ov(s,y)}return[r,i,"",s,"",n,o,a,c,u,l,h,d,f].filter(y=>y!=null).join(`
18
18
  `)};function Qb(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function Xb(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function dr(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function ev(t,e,r,i={}){return r==null||r.sort((s,n)=>s.localeCompare(n)),{att:{[t]:tv(e,r,i)}}}function tv(t,e,r={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${t}/${s}`]:[r]}));return Object.assign({},...i)}function Th(t){return dr(t),`urn:recap:${Qb(t).replace(/=/g,"")}`}function Ti(t){const e=Xb(t.replace("urn:recap:",""));return dr(e),e}function rv(t,e,r){const i=ev(t,e,r);return Th(i)}function iv(t){return t&&t.includes("urn:recap:")}function sv(t,e){const r=Ti(t),i=Ti(e),s=nv(r,i);return Th(s)}function nv(t,e){dr(t),dr(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return r.forEach(s=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;i.att[s]=Yb(Gb({},i.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((u=e.att[s])==null?void 0:u[a])})})}),i}function ov(t="",e){dr(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,d)=>h.action.localeCompare(d.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(s++,`(${s}) '${h}': '${u[h].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const n=i.join(" "),o=`${r}${n}`;return`${t?t+" ":""}${o}`}function yc(t){var e;const r=Ti(t);dr(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function mc(t){const e=Ti(t);dr(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&r.push(s[0].chains)})}),[...new Set(r.flat())]}function bs(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return iv(e)?e:void 0}function bn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Rh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Je(t,...e){if(!Rh(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function wc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function av(t,e){Je(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function bc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const Wt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),cv=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),uv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!uv)throw new Error("Non little-endian hardware is not supported");function lv(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function so(t){if(typeof t=="string")t=lv(t);else if(Rh(t))t=no(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function hv(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function dv(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const pv=(t,e)=>{function r(i,...s){if(Je(i),t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?Je(u):Je(u,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&Je(s[1]);const o=e(i,...s),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");Je(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Je(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(Je(u),n&&u.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function vc(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!fv(e))throw new Error("invalid output, must be aligned");return e}function Ec(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n);t.setUint32(e+4,o,i),t.setUint32(e+0,a,i)}function fv(t){return t.byteOffset%4===0}function no(t){return Uint8Array.from(t)}function Jr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Nh=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),gv=Nh("expand 16-byte k"),yv=Nh("expand 32-byte k"),mv=Wt(gv),wv=Wt(yv);function J(t,e){return t<<e|t>>>32-e}function oo(t){return t.byteOffset%4===0}const os=64,bv=16,Fh=2**32-1,_c=new Uint32Array;function vv(t,e,r,i,s,n,o,a){const c=s.length,u=new Uint8Array(os),l=Wt(u),h=oo(s)&&oo(n),d=h?Wt(s):_c,f=h?Wt(n):_c;for(let p=0;p<c;o++){if(t(e,r,i,l,o,a),o>=Fh)throw new Error("arx: counter overflow");const y=Math.min(os,c-p);if(h&&y===os){const w=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v<bv;v++)b=w+v,f[b]=d[b]^l[v];p+=os;continue}for(let w=0,v;w<y;w++)v=p+w,n[v]=s[v]^u[w];p+=y}}function Ev(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=hv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return bn(s),bn(o),bc(n),bc(r),(a,c,u,l,h=0)=>{Je(a),Je(c),Je(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),Je(l),bn(h),h<0||h>=Fh)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const f=[];let p=a.length,y,w;if(p===32)f.push(y=no(a)),w=wv;else if(p===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=mv,f.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);oo(c)||f.push(c=no(c));const v=Wt(y);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(w,v,Wt(c.subarray(0,16)),v),c=c.subarray(16)}const b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const I=new Uint8Array(12);I.set(c,n?0:12-c.length),c=I,f.push(c)}const E=Wt(c);return vv(t,w,v,E,u,l,h,o),Jr(...f),l}}const Ie=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class _v{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=so(e),Je(e,32);const r=Ie(e,0),i=Ie(e,2),s=Ie(e,4),n=Ie(e,6),o=Ie(e,8),a=Ie(e,10),c=Ie(e,12),u=Ie(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Ie(e,16+2*l)}process(e,r,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],d=o[5],f=o[6],p=o[7],y=o[8],w=o[9],v=Ie(e,r+0),b=Ie(e,r+2),E=Ie(e,r+4),I=Ie(e,r+6),$=Ie(e,r+8),A=Ie(e,r+10),P=Ie(e,r+12),C=Ie(e,r+14);let S=n[0]+(v&8191),M=n[1]+((v>>>13|b<<3)&8191),j=n[2]+((b>>>10|E<<6)&8191),B=n[3]+((E>>>7|I<<9)&8191),q=n[4]+((I>>>4|$<<12)&8191),T=n[5]+($>>>1&8191),g=n[6]+(($>>>14|A<<2)&8191),m=n[7]+((A>>>11|P<<5)&8191),_=n[8]+((P>>>8|C<<8)&8191),O=n[9]+(C>>>5|s),D=0,x=D+S*a+M*(5*w)+j*(5*y)+B*(5*p)+q*(5*f);D=x>>>13,x&=8191,x+=T*(5*d)+g*(5*h)+m*(5*l)+_*(5*u)+O*(5*c),D+=x>>>13,x&=8191;let L=D+S*c+M*a+j*(5*w)+B*(5*y)+q*(5*p);D=L>>>13,L&=8191,L+=T*(5*f)+g*(5*d)+m*(5*h)+_*(5*l)+O*(5*u),D+=L>>>13,L&=8191;let k=D+S*u+M*c+j*a+B*(5*w)+q*(5*y);D=k>>>13,k&=8191,k+=T*(5*p)+g*(5*f)+m*(5*d)+_*(5*h)+O*(5*l),D+=k>>>13,k&=8191;let z=D+S*l+M*u+j*c+B*a+q*(5*w);D=z>>>13,z&=8191,z+=T*(5*y)+g*(5*p)+m*(5*f)+_*(5*d)+O*(5*h),D+=z>>>13,z&=8191;let U=D+S*h+M*l+j*u+B*c+q*a;D=U>>>13,U&=8191,U+=T*(5*w)+g*(5*y)+m*(5*p)+_*(5*f)+O*(5*d),D+=U>>>13,U&=8191;let H=D+S*d+M*h+j*l+B*u+q*c;D=H>>>13,H&=8191,H+=T*a+g*(5*w)+m*(5*y)+_*(5*p)+O*(5*f),D+=H>>>13,H&=8191;let G=D+S*f+M*d+j*h+B*l+q*u;D=G>>>13,G&=8191,G+=T*c+g*a+m*(5*w)+_*(5*y)+O*(5*p),D+=G>>>13,G&=8191;let ne=D+S*p+M*f+j*d+B*h+q*l;D=ne>>>13,ne&=8191,ne+=T*u+g*c+m*a+_*(5*w)+O*(5*y),D+=ne>>>13,ne&=8191;let ee=D+S*y+M*p+j*f+B*d+q*h;D=ee>>>13,ee&=8191,ee+=T*l+g*u+m*c+_*a+O*(5*w),D+=ee>>>13,ee&=8191;let Y=D+S*w+M*y+j*p+B*f+q*d;D=Y>>>13,Y&=8191,Y+=T*h+g*l+m*u+_*c+O*a,D+=Y>>>13,Y&=8191,D=(D<<2)+D|0,D=D+x|0,x=D&8191,D=D>>>13,L+=D,n[0]=x,n[1]=L,n[2]=k,n[3]=z,n[4]=U,n[5]=H,n[6]=G,n[7]=ne,n[8]=ee,n[9]=Y}finalize(){const{h:e,pad:r}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Jr(i)}update(e){wc(this);const{buffer:r,blockLen:i}=this;e=so(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}r.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Jr(this.h,this.r,this.buffer,this.pad)}digestInto(e){wc(this),av(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function Iv(t){const e=(i,s)=>t(s).update(so(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const Dv=Iv(t=>new _v(t));function Sv(t,e,r,i,s,n=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],d=e[2],f=e[3],p=e[4],y=e[5],w=e[6],v=e[7],b=s,E=r[0],I=r[1],$=r[2],A=o,P=a,C=c,S=u,M=l,j=h,B=d,q=f,T=p,g=y,m=w,_=v,O=b,D=E,x=I,L=$;for(let z=0;z<n;z+=2)A=A+M|0,O=J(O^A,16),T=T+O|0,M=J(M^T,12),A=A+M|0,O=J(O^A,8),T=T+O|0,M=J(M^T,7),P=P+j|0,D=J(D^P,16),g=g+D|0,j=J(j^g,12),P=P+j|0,D=J(D^P,8),g=g+D|0,j=J(j^g,7),C=C+B|0,x=J(x^C,16),m=m+x|0,B=J(B^m,12),C=C+B|0,x=J(x^C,8),m=m+x|0,B=J(B^m,7),S=S+q|0,L=J(L^S,16),_=_+L|0,q=J(q^_,12),S=S+q|0,L=J(L^S,8),_=_+L|0,q=J(q^_,7),A=A+j|0,L=J(L^A,16),m=m+L|0,j=J(j^m,12),A=A+j|0,L=J(L^A,8),m=m+L|0,j=J(j^m,7),P=P+B|0,O=J(O^P,16),_=_+O|0,B=J(B^_,12),P=P+B|0,O=J(O^P,8),_=_+O|0,B=J(B^_,7),C=C+q|0,D=J(D^C,16),T=T+D|0,q=J(q^T,12),C=C+q|0,D=J(D^C,8),T=T+D|0,q=J(q^T,7),S=S+M|0,x=J(x^S,16),g=g+x|0,M=J(M^g,12),S=S+M|0,x=J(x^S,8),g=g+x|0,M=J(M^g,7);let k=0;i[k++]=o+A|0,i[k++]=a+P|0,i[k++]=c+C|0,i[k++]=u+S|0,i[k++]=l+M|0,i[k++]=h+j|0,i[k++]=d+B|0,i[k++]=f+q|0,i[k++]=p+T|0,i[k++]=y+g|0,i[k++]=w+m|0,i[k++]=v+_|0,i[k++]=b+O|0,i[k++]=E+D|0,i[k++]=I+x|0,i[k++]=$+L|0}const Ov=Ev(Sv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Pv=new Uint8Array(16),Ic=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(Pv.subarray(r))},$v=new Uint8Array(32);function Dc(t,e,r,i,s){const n=t(e,r,$v),o=Dv.create(n);s&&Ic(o,s),Ic(o,i);const a=new Uint8Array(16),c=cv(a);Ec(c,0,BigInt(s?s.length:0),!0),Ec(c,8,BigInt(i.length),!0),o.update(a);const u=o.digest();return Jr(n,a),u}const Av=t=>(e,r,i)=>({encrypt(s,n){const o=s.length;n=vc(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,r,a,a,1);const c=Dc(t,e,r,a,i);return n.set(c,o),Jr(c),n},decrypt(s,n){n=vc(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=Dc(t,e,r,o,i);if(!dv(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,r,n,n,1),Jr(c),n}}),Bh=pv({blockSize:64,nonceLength:12,tagLength:16},Av(Ov));let jh=class extends Go{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Wo(e);const i=Yr(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Gr(this),this.iHash.update(e),this}digestInto(e){Gr(this),Hi(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Hs=(t,e,r)=>new jh(t,e).update(r).digest();Hs.create=(t,e)=>new jh(t,e);function xv(t,e,r){return Wo(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Hs(t,Yr(r),Yr(e))}const vn=new Uint8Array([0]),Sc=new Uint8Array;function Cv(t,e,r,i=32){if(Wo(t),Ci(i),i>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/t.outputLen);r===void 0&&(r=Sc);const n=new Uint8Array(s*t.outputLen),o=Hs.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<s;u++)vn[0]=u+1,a.update(u===0?Sc:c).update(r).update(vn).digestInto(c),n.set(c,t.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),vn.fill(0),n.slice(0,i)}const Tv=(t,e,r,i,s)=>Cv(t,xv(t,e,r),i,s);function Rv(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}function Nv(t,e,r){return t&e^~t&r}function Fv(t,e,r){return t&e^t&r^e&r}let Bv=class extends Go{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=wn(this.buffer)}update(e){Gr(this);const{view:r,buffer:i,blockLen:s}=this;e=Yr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=wn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gr(this),Dh(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;Rv(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=wn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const jv=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Mt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=new Uint32Array(64);class Lv extends Bv{constructor(){super(64,32,8,!1),this.A=Mt[0]|0,this.B=Mt[1]|0,this.C=Mt[2]|0,this.D=Mt[3]|0,this.E=Mt[4]|0,this.F=Mt[5]|0,this.G=Mt[6]|0,this.H=Mt[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)qt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const d=qt[h-15],f=qt[h-2],p=wt(d,7)^wt(d,18)^d>>>3,y=wt(f,17)^wt(f,19)^f>>>10;qt[h]=y+qt[h-7]+p+qt[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const d=wt(a,6)^wt(a,11)^wt(a,25),f=l+d+Nv(a,c,u)+jv[h]+qt[h]|0,p=(wt(i,2)^wt(i,13)^wt(i,22))+Fv(i,s,n)|0;l=u,u=c,c=a,a=o+f|0,o=n,n=s,s=i,i=f+p|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(i,s,n,o,a,c,u,l)}roundClean(){qt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Vi=Sh(()=>new Lv);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vs=BigInt(0),Ks=BigInt(1),Uv=BigInt(2);function pr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ki(t){if(!pr(t))throw new Error("Uint8Array expected")}function Zr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const kv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Qr(t){Ki(t);let e="";for(let r=0;r<t.length;r++)e+=kv[t[r]];return e}function qr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Jo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Vs:BigInt("0x"+t)}const xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oc(t){if(t>=xt._0&&t<=xt._9)return t-xt._0;if(t>=xt.A&&t<=xt.F)return t-(xt.A-10);if(t>=xt.a&&t<=xt.f)return t-(xt.a-10)}function Xr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Oc(t.charCodeAt(n)),a=Oc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function lr(t){return Jo(Qr(t))}function Ri(t){return Ki(t),Jo(Qr(Uint8Array.from(t).reverse()))}function ei(t,e){return Xr(t.toString(16).padStart(e*2,"0"))}function Ws(t,e){return ei(t,e).reverse()}function Mv(t){return Xr(qr(t))}function Ge(t,e,r){let i;if(typeof e=="string")try{i=Xr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(pr(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Ni(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Ki(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}function qv(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}function zv(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const En=t=>typeof t=="bigint"&&Vs<=t;function Gs(t,e,r){return En(t)&&En(e)&&En(r)&&e<=t&&t<r}function jt(t,e,r,i){if(!Gs(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function Lh(t){let e;for(e=0;t>Vs;t>>=Ks,e+=1);return e}function Hv(t,e){return t>>BigInt(e)&Ks}function Vv(t,e,r){return t|(r?Ks:Vs)<<BigInt(e)}const Zo=t=>(Uv<<BigInt(t-1))-Ks,_n=t=>new Uint8Array(t),Pc=t=>Uint8Array.from(t);function Uh(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let i=_n(t),s=_n(t),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...l)=>r(s,i,...l),c=(l=_n())=>{s=a(Pc([0]),l),i=a(),l.length!==0&&(s=a(Pc([1]),l),i=a())},u=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){i=a();const d=i.slice();h.push(d),l+=i.length}return Ni(...h)};return(l,h)=>{o(),c(l);let d;for(;!(d=h(u()));)c();return o(),d}}const Kv={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||pr(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ai(t,e,r={}){const i=(s,n,o)=>{const a=Kv[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}const Wv=()=>{throw new Error("not implemented")};function ao(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}var Gv=Object.freeze({__proto__:null,isBytes:pr,abytes:Ki,abool:Zr,bytesToHex:Qr,numberToHexUnpadded:qr,hexToNumber:Jo,hexToBytes:Xr,bytesToNumberBE:lr,bytesToNumberLE:Ri,numberToBytesBE:ei,numberToBytesLE:Ws,numberToVarBytesBE:Mv,ensureBytes:Ge,concatBytes:Ni,equalBytes:qv,utf8ToBytes:zv,inRange:Gs,aInRange:jt,bitLen:Lh,bitGet:Hv,bitSet:Vv,bitMask:Zo,createHmacDrbg:Uh,validateObject:ai,notImplemented:Wv,memoized:ao});const Ee=BigInt(0),le=BigInt(1),or=BigInt(2),Yv=BigInt(3),co=BigInt(4),$c=BigInt(5),Ac=BigInt(8);function qe(t,e){const r=t%e;return r>=Ee?r:e+r}function kh(t,e,r){if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(r<=Ee)throw new Error("invalid modulus");if(r===le)return Ee;let i=le;for(;e>Ee;)e&le&&(i=i*t%r),t=t*t%r,e>>=le;return i}function dt(t,e,r){let i=t;for(;e-- >Ee;)i*=i,i%=r;return i}function uo(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let r=qe(t,e),i=e,s=Ee,n=le;for(;r!==Ee;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==le)throw new Error("invert: does not exist");return qe(s,e)}function Jv(t){const e=(t-le)/or;let r,i,s;for(r=t-le,i=0;r%or===Ee;r/=or,i++);for(s=or;s<t&&kh(s,e,t)!==t-le;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+le)/co;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(r+le)/or;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(h);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(u,le<<BigInt(c-d-1));u=o.sqr(f),l=o.mul(l,f),h=o.mul(h,u),c=d}return l}}function Zv(t){if(t%co===Yv){const e=(t+le)/co;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Ac===$c){const e=(t-$c)/Ac;return function(r,i){const s=r.mul(i,or),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,or),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Jv(t)}const Qv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Xv(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Qv.reduce((i,s)=>(i[s]="function",i),e);return ai(t,r)}function e0(t,e,r){if(r<Ee)throw new Error("invalid exponent, negatives unsupported");if(r===Ee)return t.ONE;if(r===le)return e;let i=t.ONE,s=e;for(;r>Ee;)r&le&&(i=t.mul(i,s)),s=t.sqr(s),r>>=le;return i}function t0(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Mh(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function qh(t,e,r=!1,i={}){if(t<=Ee)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Mh(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Zo(s),ZERO:Ee,ONE:le,create:c=>qe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ee<=c&&c<t},is0:c=>c===Ee,isOdd:c=>(c&le)===le,neg:c=>qe(-c,t),eql:(c,u)=>c===u,sqr:c=>qe(c*c,t),add:(c,u)=>qe(c+u,t),sub:(c,u)=>qe(c-u,t),mul:(c,u)=>qe(c*u,t),pow:(c,u)=>e0(a,c,u),div:(c,u)=>qe(c*uo(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>uo(c,t),sqrt:i.sqrt||(c=>(o||(o=Zv(t)),o(a,c))),invertBatch:c=>t0(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Ws(c,n):ei(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?Ri(c):lr(c)}});return Object.freeze(a)}function zh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Hh(t){const e=zh(t);return e+Math.ceil(e/2)}function r0(t,e,r=!1){const i=t.length,s=zh(e),n=Hh(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?Ri(t):lr(t),a=qe(o,e-le)+le;return r?Ws(a,s):ei(a,s)}const xc=BigInt(0),as=BigInt(1);function In(t,e){const r=e.negate();return t?r:e}function Vh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Dn(t,e){Vh(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function i0(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function s0(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Sn=new WeakMap,Kh=new WeakMap;function On(t){return Kh.get(t)||1}function n0(t,e){return{constTimeNegate:In,hasPrecomputes(r){return On(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>xc;)i&as&&(s=s.add(n)),n=n.double(),i>>=as;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=Dn(i,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=Dn(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&u);s>>=h,p>o&&(p-=l,s+=as);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(In(v,i[y])):a=a.add(In(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=Dn(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(s===xc)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=u,s+=as),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=Sn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&Sn.set(i,s(n))),n},wNAFCached(r,i,s){const n=On(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=On(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Vh(i,e),Kh.set(r,i),Sn.delete(r)}}}function o0(t,e,r,i){if(i0(r,t),s0(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=Lh(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),h!==0)for(let f=0;f<o;f++)l=l.double()}return l}function Wh(t){return Xv(t.Fp),ai(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Mh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Dr=BigInt(0),Pn=BigInt(1);function a0(t){return ai(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function c0(t){const e=a0(t),{P:r}=e,i=b=>qe(b,r),s=e.montgomeryBits,n=Math.ceil(s/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>kh(b,r-BigInt(2),r));function u(b,E,I){const $=i(b*(E-I));return E=i(E-$),I=i(I+$),[E,I]}const l=(e.a-BigInt(2))/BigInt(4);function h(b,E){jt("u",b,Dr,r),jt("scalar",E,Dr,r);const I=E,$=b;let A=Pn,P=Dr,C=b,S=Pn,M=Dr,j;for(let q=BigInt(s-1);q>=Dr;q--){const T=I>>q&Pn;M^=T,j=u(M,A,C),A=j[0],C=j[1],j=u(M,P,S),P=j[0],S=j[1],M=T;const g=A+P,m=i(g*g),_=A-P,O=i(_*_),D=m-O,x=C+S,L=C-S,k=i(L*g),z=i(x*_),U=k+z,H=k-z;C=i(U*U),S=i($*i(H*H)),A=i(m*O),P=i(D*(m+i(l*D)))}j=u(M,A,C),A=j[0],C=j[1],j=u(M,P,S),P=j[0],S=j[1];const B=c(P);return i(A*B)}function d(b){return Ws(i(b),n)}function f(b){const E=Ge("u coordinate",b,n);return o===32&&(E[31]&=127),Ri(E)}function p(b){const E=Ge("scalar",b),I=E.length;if(I!==n&&I!==o){let $=""+n+" or "+o;throw new Error("invalid scalar, expected "+$+" bytes, got "+I)}return Ri(a(E))}function y(b,E){const I=f(E),$=p(b),A=h(I,$);if(A===Dr)throw new Error("invalid private or public key received");return d(A)}const w=d(e.Gu);function v(b){return y(b,w)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(b,E)=>y(b,E),getPublicKey:b=>v(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}const lo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const u0=BigInt(1),Cc=BigInt(2),l0=BigInt(3),h0=BigInt(5);BigInt(8);function d0(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=lo,o=t*t%n*t%n,a=dt(o,Cc,n)*o%n,c=dt(a,u0,n)*t%n,u=dt(c,h0,n)*c%n,l=dt(u,e,n)*u%n,h=dt(l,r,n)*l%n,d=dt(h,i,n)*h%n,f=dt(d,s,n)*d%n,p=dt(f,s,n)*d%n,y=dt(p,e,n)*u%n;return{pow_p_5_8:dt(y,Cc,n)*t%n,b2:o}}function p0(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ho=c0({P:lo,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=lo,{pow_p_5_8:r,b2:i}=d0(t);return qe(dt(r,l0,e)*i,e)},adjustScalarBytes:p0,randomBytes:oi});function Tc(t){t.lowS!==void 0&&Zr("lowS",t.lowS),t.prehash!==void 0&&Zr("prehash",t.prehash)}function f0(t){const e=Wh(t);ai(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:i,a:s}=e;if(r){if(!i.eql(s,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:g0,hexToBytes:y0}=Gv;class m0 extends Error{constructor(e=""){super(e)}}const Nt={Err:m0,_tlv:{encode:(t,e)=>{const{Err:r}=Nt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=qr(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?qr(s.length/2|128):"";return qr(t)+n+s+e},decode(t,e){const{Err:r}=Nt;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=Nt;if(t<Ft)throw new e("integer: negative integers are not allowed");let r=qr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=Nt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return g0(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=Nt,s=typeof t=="string"?y0(t):t;Ki(s);const{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:u,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=Nt,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}},Ft=BigInt(0),we=BigInt(1);BigInt(2);const Rc=BigInt(3);BigInt(4);function w0(t){const e=f0(t),{Fp:r}=e,i=qh(e.n,e.nBitLength),s=e.toBytes||((y,w,v)=>{const b=w.toAffine();return Ni(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),n=e.fromBytes||(y=>{const w=y.subarray(1),v=r.fromBytes(w.subarray(0,r.BYTES)),b=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:v,y:b}});function o(y){const{a:w,b:v}=e,b=r.sqr(y),E=r.mul(b,y);return r.add(r.add(E,r.mul(y,w)),v)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Gs(y,we,e.n)}function c(y){const{allowedPrivateKeyLengths:w,nByteLength:v,wrapPrivateKey:b,n:E}=e;if(w&&typeof y!="bigint"){if(pr(y)&&(y=Qr(y)),typeof y!="string"||!w.includes(y.length))throw new Error("invalid private key");y=y.padStart(v*2,"0")}let I;try{I=typeof y=="bigint"?y:lr(Ge("private key",y,v))}catch{throw new Error("invalid private key, expected hex or "+v+" bytes, got "+typeof y)}return b&&(I=qe(I,E)),jt("private key",I,we,E),I}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=ao((y,w)=>{const{px:v,py:b,pz:E}=y;if(r.eql(E,r.ONE))return{x:v,y:b};const I=y.is0();w==null&&(w=I?r.ONE:r.inv(E));const $=r.mul(v,w),A=r.mul(b,w),P=r.mul(E,w);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(P,r.ONE))throw new Error("invZ was invalid");return{x:$,y:A}}),h=ao(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:w,y:v}=y.toAffine();if(!r.isValid(w)||!r.isValid(v))throw new Error("bad point: x or y not FE");const b=r.sqr(v),E=o(w);if(!r.eql(b,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(w,v,b){if(this.px=w,this.py=v,this.pz=b,w==null||!r.isValid(w))throw new Error("x required");if(v==null||!r.isValid(v))throw new Error("y required");if(b==null||!r.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(w){const{x:v,y:b}=w||{};if(!w||!r.isValid(v)||!r.isValid(b))throw new Error("invalid affine point");if(w instanceof d)throw new Error("projective point not allowed");const E=I=>r.eql(I,r.ZERO);return E(v)&&E(b)?d.ZERO:new d(v,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const v=r.invertBatch(w.map(b=>b.pz));return w.map((b,E)=>b.toAffine(v[E])).map(d.fromAffine)}static fromHex(w){const v=d.fromAffine(n(Ge("pointHex",w)));return v.assertValidity(),v}static fromPrivateKey(w){return d.BASE.multiply(c(w))}static msm(w,v){return o0(d,i,w,v)}_setWindowSize(w){p.setWindowSize(this,w)}assertValidity(){h(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){u(w);const{px:v,py:b,pz:E}=this,{px:I,py:$,pz:A}=w,P=r.eql(r.mul(v,A),r.mul(I,E)),C=r.eql(r.mul(b,A),r.mul($,E));return P&&C}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:v}=e,b=r.mul(v,Rc),{px:E,py:I,pz:$}=this;let A=r.ZERO,P=r.ZERO,C=r.ZERO,S=r.mul(E,E),M=r.mul(I,I),j=r.mul($,$),B=r.mul(E,I);return B=r.add(B,B),C=r.mul(E,$),C=r.add(C,C),A=r.mul(w,C),P=r.mul(b,j),P=r.add(A,P),A=r.sub(M,P),P=r.add(M,P),P=r.mul(A,P),A=r.mul(B,A),C=r.mul(b,C),j=r.mul(w,j),B=r.sub(S,j),B=r.mul(w,B),B=r.add(B,C),C=r.add(S,S),S=r.add(C,S),S=r.add(S,j),S=r.mul(S,B),P=r.add(P,S),j=r.mul(I,$),j=r.add(j,j),S=r.mul(j,B),A=r.sub(A,S),C=r.mul(j,M),C=r.add(C,C),C=r.add(C,C),new d(A,P,C)}add(w){u(w);const{px:v,py:b,pz:E}=this,{px:I,py:$,pz:A}=w;let P=r.ZERO,C=r.ZERO,S=r.ZERO;const M=e.a,j=r.mul(e.b,Rc);let B=r.mul(v,I),q=r.mul(b,$),T=r.mul(E,A),g=r.add(v,b),m=r.add(I,$);g=r.mul(g,m),m=r.add(B,q),g=r.sub(g,m),m=r.add(v,E);let _=r.add(I,A);return m=r.mul(m,_),_=r.add(B,T),m=r.sub(m,_),_=r.add(b,E),P=r.add($,A),_=r.mul(_,P),P=r.add(q,T),_=r.sub(_,P),S=r.mul(M,m),P=r.mul(j,T),S=r.add(P,S),P=r.sub(q,S),S=r.add(q,S),C=r.mul(P,S),q=r.add(B,B),q=r.add(q,B),T=r.mul(M,T),m=r.mul(j,m),q=r.add(q,T),T=r.sub(B,T),T=r.mul(M,T),m=r.add(m,T),B=r.mul(q,m),C=r.add(C,B),B=r.mul(_,m),P=r.mul(g,P),P=r.sub(P,B),B=r.mul(g,q),S=r.mul(_,S),S=r.add(S,B),new d(P,C,S)}subtract(w){return this.add(w.negate())}is0(){return this.equals(d.ZERO)}wNAF(w){return p.wNAFCached(this,w,d.normalizeZ)}multiplyUnsafe(w){const{endo:v,n:b}=e;jt("scalar",w,Ft,b);const E=d.ZERO;if(w===Ft)return E;if(this.is0()||w===we)return this;if(!v||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,w,d.normalizeZ);let{k1neg:I,k1:$,k2neg:A,k2:P}=v.splitScalar(w),C=E,S=E,M=this;for(;$>Ft||P>Ft;)$&we&&(C=C.add(M)),P&we&&(S=S.add(M)),M=M.double(),$>>=we,P>>=we;return I&&(C=C.negate()),A&&(S=S.negate()),S=new d(r.mul(S.px,v.beta),S.py,S.pz),C.add(S)}multiply(w){const{endo:v,n:b}=e;jt("scalar",w,we,b);let E,I;if(v){const{k1neg:$,k1:A,k2neg:P,k2:C}=v.splitScalar(w);let{p:S,f:M}=this.wNAF(A),{p:j,f:B}=this.wNAF(C);S=p.constTimeNegate($,S),j=p.constTimeNegate(P,j),j=new d(r.mul(j.px,v.beta),j.py,j.pz),E=S.add(j),I=M.add(B)}else{const{p:$,f:A}=this.wNAF(w);E=$,I=A}return d.normalizeZ([E,I])[0]}multiplyAndAddUnsafe(w,v,b){const E=d.BASE,I=(A,P)=>P===Ft||P===we||!A.equals(E)?A.multiplyUnsafe(P):A.multiply(P),$=I(this,v).add(I(w,b));return $.is0()?void 0:$}toAffine(w){return l(this,w)}isTorsionFree(){const{h:w,isTorsionFree:v}=e;if(w===we)return!0;if(v)return v(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:v}=e;return w===we?this:v?v(d,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Zr("isCompressed",w),this.assertValidity(),s(d,this,w)}toHex(w=!0){return Zr("isCompressed",w),Qr(this.toRawBytes(w))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const f=e.nBitLength,p=n0(d,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function b0(t){const e=Wh(t);return ai(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function v0(t){const e=b0(t),{Fp:r,n:i}=e,s=r.BYTES+1,n=2*r.BYTES+1;function o(T){return qe(T,i)}function a(T){return uo(T,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=w0({...e,toBytes(T,g,m){const _=g.toAffine(),O=r.toBytes(_.x),D=Ni;return Zr("isCompressed",m),m?D(Uint8Array.from([g.hasEvenY()?2:3]),O):D(Uint8Array.from([4]),O,r.toBytes(_.y))},fromBytes(T){const g=T.length,m=T[0],_=T.subarray(1);if(g===s&&(m===2||m===3)){const O=lr(_);if(!Gs(O,we,r.ORDER))throw new Error("Point is not on curve");const D=l(O);let x;try{x=r.sqrt(D)}catch(k){const z=k instanceof Error?": "+k.message:"";throw new Error("Point is not on curve"+z)}const L=(x&we)===we;return(m&1)===1!==L&&(x=r.neg(x)),{x:O,y:x}}else if(g===n&&m===4){const O=r.fromBytes(_.subarray(0,r.BYTES)),D=r.fromBytes(_.subarray(r.BYTES,2*r.BYTES));return{x:O,y:D}}else{const O=s,D=n;throw new Error("invalid Point, expected length of "+O+", or uncompressed "+D+", got "+g)}}}),d=T=>Qr(ei(T,e.nByteLength));function f(T){const g=i>>we;return T>g}function p(T){return f(T)?o(-T):T}const y=(T,g,m)=>lr(T.slice(g,m));class w{constructor(g,m,_){this.r=g,this.s=m,this.recovery=_,this.assertValidity()}static fromCompact(g){const m=e.nByteLength;return g=Ge("compactSignature",g,m*2),new w(y(g,0,m),y(g,m,2*m))}static fromDER(g){const{r:m,s:_}=Nt.toSig(Ge("DER",g));return new w(m,_)}assertValidity(){jt("r",this.r,we,i),jt("s",this.s,we,i)}addRecoveryBit(g){return new w(this.r,this.s,g)}recoverPublicKey(g){const{r:m,s:_,recovery:O}=this,D=A(Ge("msgHash",g));if(O==null||![0,1,2,3].includes(O))throw new Error("recovery id invalid");const x=O===2||O===3?m+e.n:m;if(x>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=O&1?"03":"02",k=c.fromHex(L+d(x)),z=a(x),U=o(-D*z),H=o(_*z),G=c.BASE.multiplyAndAddUnsafe(k,U,H);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Xr(this.toDERHex())}toDERHex(){return Nt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const v={isValidPrivateKey(T){try{return u(T),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const T=Hh(e.n);return r0(e.randomBytes(T),e.n)},precompute(T=8,g=c.BASE){return g._setWindowSize(T),g.multiply(BigInt(3)),g}};function b(T,g=!0){return c.fromPrivateKey(T).toRawBytes(g)}function E(T){const g=pr(T),m=typeof T=="string",_=(g||m)&&T.length;return g?_===s||_===n:m?_===2*s||_===2*n:T instanceof c}function I(T,g,m=!0){if(E(T))throw new Error("first arg must be private key");if(!E(g))throw new Error("second arg must be public key");return c.fromHex(g).multiply(u(T)).toRawBytes(m)}const $=e.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");const g=lr(T),m=T.length*8-e.nBitLength;return m>0?g>>BigInt(m):g},A=e.bits2int_modN||function(T){return o($(T))},P=Zo(e.nBitLength);function C(T){return jt("num < 2^"+e.nBitLength,T,Ft,P),ei(T,e.nByteLength)}function S(T,g,m=M){if(["recovered","canonical"].some(ee=>ee in m))throw new Error("sign() legacy options not supported");const{hash:_,randomBytes:O}=e;let{lowS:D,prehash:x,extraEntropy:L}=m;D==null&&(D=!0),T=Ge("msgHash",T),Tc(m),x&&(T=Ge("prehashed msgHash",_(T)));const k=A(T),z=u(g),U=[C(z),C(k)];if(L!=null&&L!==!1){const ee=L===!0?O(r.BYTES):L;U.push(Ge("extraEntropy",ee))}const H=Ni(...U),G=k;function ne(ee){const Y=$(ee);if(!h(Y))return;const xe=a(Y),_e=c.BASE.multiply(Y).toAffine(),Re=o(_e.x);if(Re===Ft)return;const tt=o(xe*o(G+Re*z));if(tt===Ft)return;let rt=(_e.x===Re?0:2)|Number(_e.y&we),br=tt;return D&&f(tt)&&(br=p(tt),rt^=1),new w(Re,br,rt)}return{seed:H,k2sig:ne}}const M={lowS:e.lowS,prehash:!1},j={lowS:e.lowS,prehash:!1};function B(T,g,m=M){const{seed:_,k2sig:O}=S(T,g,m),D=e;return Uh(D.hash.outputLen,D.nByteLength,D.hmac)(_,O)}c.BASE._setWindowSize(8);function q(T,g,m,_=j){var tt;const O=T;g=Ge("msgHash",g),m=Ge("publicKey",m);const{lowS:D,prehash:x,format:L}=_;if(Tc(_),"strict"in _)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const k=typeof O=="string"||pr(O),z=!k&&!L&&typeof O=="object"&&O!==null&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!k&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,H;try{if(z&&(U=new w(O.r,O.s)),k){try{L!=="compact"&&(U=w.fromDER(O))}catch(rt){if(!(rt instanceof Nt.Err))throw rt}!U&&L!=="der"&&(U=w.fromCompact(O))}H=c.fromHex(m)}catch{return!1}if(!U||D&&U.hasHighS())return!1;x&&(g=e.hash(g));const{r:G,s:ne}=U,ee=A(g),Y=a(ne),xe=o(ee*Y),_e=o(G*Y),Re=(tt=c.BASE.multiplyAndAddUnsafe(H,xe,_e))==null?void 0:tt.toAffine();return Re?o(Re.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:I,sign:B,verify:q,ProjectivePoint:c,Signature:w,utils:v}}function E0(t){return{hash:t,hmac:(e,...r)=>Hs(t,e,Sb(...r)),randomBytes:oi}}function _0(t,e){const r=i=>v0({...t,...E0(i)});return{...r(e),create:r}}const Gh=qh(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),I0=Gh.create(BigInt("-3")),D0=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),S0=_0({a:I0,b:D0,Fp:Gh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Vi),Yh="base10",Be="base16",gt="base64pad",Ht="base64url",Wi="utf8",Jh=0,Lt=1,Gi=2,O0=0,Nc=1,Si=12,Qo=32;function P0(){const t=ho.utils.randomPrivateKey(),e=ho.getPublicKey(t);return{privateKey:Fe(t,Be),publicKey:Fe(e,Be)}}function po(){const t=oi(Qo);return Fe(t,Be)}function $0(t,e){const r=ho.getSharedSecret(Ze(t,Be),Ze(e,Be)),i=Tv(Vi,r,void 0,void 0,Qo);return Fe(i,Be)}function vs(t){const e=Vi(Ze(t,Be));return Fe(e,Be)}function _t(t){const e=Vi(Ze(t,Wi));return Fe(e,Be)}function Zh(t){return Ze(`${t}`,Yh)}function fr(t){return Number(Fe(t,Yh))}function Qh(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xh(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function A0(t){const e=Zh(typeof t.type<"u"?t.type:Jh);if(fr(e)===Lt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Ze(t.senderPublicKey,Be):void 0,i=typeof t.iv<"u"?Ze(t.iv,Be):oi(Si),s=Ze(t.symKey,Be),n=Bh(s,i).encrypt(Ze(t.message,Wi)),o=ed({type:e,sealed:n,iv:i,senderPublicKey:r});return t.encoding===Ht?Qh(o):o}function x0(t){const e=Ze(t.symKey,Be),{sealed:r,iv:i}=Fi({encoded:t.encoded,encoding:t.encoding}),s=Bh(e,i).decrypt(r);if(s===null)throw new Error("Failed to decrypt");return Fe(s,Wi)}function C0(t,e){const r=Zh(Gi),i=oi(Si),s=Ze(t,Wi),n=ed({type:r,sealed:s,iv:i});return e===Ht?Qh(n):n}function T0(t,e){const{sealed:r}=Fi({encoded:t,encoding:e});return Fe(r,Wi)}function ed(t){if(fr(t.type)===Gi)return Fe(Kr([t.type,t.sealed]),gt);if(fr(t.type)===Lt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Fe(Kr([t.type,t.senderPublicKey,t.iv,t.sealed]),gt)}return Fe(Kr([t.type,t.iv,t.sealed]),gt)}function Fi(t){const e=(t.encoding||gt)===Ht?Xh(t.encoded):t.encoded,r=Ze(e,gt),i=r.slice(O0,Nc),s=Nc;if(fr(i)===Lt){const c=s+Qo,u=c+Si,l=r.slice(s,c),h=r.slice(c,u),d=r.slice(u);return{type:i,sealed:d,iv:h,senderPublicKey:l}}if(fr(i)===Gi){const c=r.slice(s),u=oi(Si);return{type:i,sealed:c,iv:u}}const n=s+Si,o=r.slice(s,n),a=r.slice(n);return{type:i,sealed:a,iv:o}}function R0(t,e){const r=Fi({encoded:t,encoding:e==null?void 0:e.encoding});return td({type:fr(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Fe(r.senderPublicKey,Be):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function td(t){const e=(t==null?void 0:t.type)||Jh;if(e===Lt){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function Fc(t){return t.type===Lt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Bc(t){return t.type===Gi}function N0(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return Kr([new Uint8Array([4]),e,r])}function F0(t,e){const[r,i,s]=t.split("."),n=Buffer.from(Xh(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${r}.${i}`,u=Vi(c),l=N0(e);if(!S0.verify(Kr([o,a]),u,l))throw new Error("Invalid signature");return $s(t).payload}const B0="irn";function Cs(t){return(t==null?void 0:t.relay)||{protocol:B0}}function _i(t){const e=mh[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function j0(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=t[s];r[n]=o}}),r}function jc(t){if(!t.includes("wc:")){const u=Ih(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),s=t.substring(e+1,r).split("@"),n=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(n),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:L0(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:j0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function L0(t){return t.startsWith("//")?t.substring(2):t}function U0(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(s=>{const n=s,o=r+e+n;t[n]&&(i[o]=t[n])}),i}function Lc(t){const e=new URLSearchParams,r=U0(t.relay);Object.keys(r).sort().forEach(s=>{e.set(s,r[s])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const i=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${i}`}function cs(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var k0=Object.defineProperty,M0=Object.defineProperties,q0=Object.getOwnPropertyDescriptors,Uc=Object.getOwnPropertySymbols,z0=Object.prototype.hasOwnProperty,H0=Object.prototype.propertyIsEnumerable,kc=(t,e,r)=>e in t?k0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V0=(t,e)=>{for(var r in e||(e={}))z0.call(e,r)&&kc(t,r,e[r]);if(Uc)for(var r of Uc(e))H0.call(e,r)&&kc(t,r,e[r]);return t},K0=(t,e)=>M0(t,q0(e));function ci(t){const e=[];return t.forEach(r=>{const[i,s]=r.split(":");e.push(`${i}:${s}`)}),e}function W0(t){const e=[];return Object.values(t).forEach(r=>{e.push(...ci(r.accounts))}),e}function G0(t,e){const r=[];return Object.values(t).forEach(i=>{ci(i.accounts).includes(e)&&r.push(...i.methods)}),r}function Y0(t,e){const r=[];return Object.values(t).forEach(i=>{ci(i.accounts).includes(e)&&r.push(...i.events)}),r}function Ys(t){return t.includes(":")}function zr(t){return Ys(t)?t.split(":")[0]:t}function Mc(t){var e,r,i;const s={};if(!Gt(t))return s;for(const[n,o]of Object.entries(t)){const a=Ys(n)?[n]:o.chains,c=o.methods||[],u=o.events||[],l=zr(n);s[l]=K0(V0({},s[l]),{chains:It(a,(e=s[l])==null?void 0:e.chains),methods:It(c,(r=s[l])==null?void 0:r.methods),events:It(u,(i=s[l])==null?void 0:i.events)})}return s}function J0(t){const e={};return t==null||t.forEach(r=>{var i;const[s,n]=r.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(r),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function qc(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=J0(e);for(const[i,s]of Object.entries(r))s.methods?s.methods=It(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return r}function Z0(t,e){var r,i,s,n,o,a;const c=Mc(t),u=Mc(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const d of h)l[d]={chains:It((r=c[d])==null?void 0:r.chains,(i=u[d])==null?void 0:i.chains),methods:It((s=c[d])==null?void 0:s.methods,(n=u[d])==null?void 0:n.methods),events:It((o=c[d])==null?void 0:o.events,(a=u[d])==null?void 0:a.events)};return l}const Q0={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},X0={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function F(t,e){const{message:r,code:i}=X0[t];return{message:e?`${r} ${e}`:r,code:i}}function te(t,e){const{message:r,code:i}=Q0[t];return{message:e?`${r} ${e}`:r,code:i}}function yt(t,e){return!!Array.isArray(t)}function Gt(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Oe(t){return typeof t>"u"}function de(t,e){return e&&Oe(t)?!0:typeof t=="string"&&!!t.trim().length}function Xo(t,e){return e&&Oe(t)?!0:typeof t=="number"&&!isNaN(t)}function e1(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),s=Object.keys(r);let n=!0;return ur(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=ci(a),h=r[o];(!ur(wh(o,h),l)||!ur(h.methods,c)||!ur(h.events,u))&&(n=!1)}),n):!1}function Ts(t){return de(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function t1(t){if(de(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Ts(r)}}return!1}function r1(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(de(t,!1)){if(e(t))return!0;const r=Ih(t);return e(r)}}catch{}return!1}function i1(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function s1(t){return t==null?void 0:t.topic}function n1(t,e){let r=null;return de(t==null?void 0:t.publicKey,!1)||(r=F("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function zc(t){let e=!0;return yt(t)?t.length&&(e=t.every(r=>de(r,!1))):e=!1,e}function o1(t,e,r){let i=null;return yt(e)&&e.length?e.forEach(s=>{i||Ts(s)||(i=te("UNSUPPORTED_CHAINS",`${r}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Ts(t)||(i=te("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function a1(t,e,r){let i=null;return Object.entries(t).forEach(([s,n])=>{if(i)return;const o=o1(s,wh(s,n),`${e} ${r}`);o&&(i=o)}),i}function c1(t,e){let r=null;return yt(t)?t.forEach(i=>{r||t1(i)||(r=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function u1(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=c1(i==null?void 0:i.accounts,`${e} namespace`);s&&(r=s)}),r}function l1(t,e){let r=null;return zc(t==null?void 0:t.methods)?zc(t==null?void 0:t.events)||(r=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function rd(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=l1(i,`${e}, namespace`);s&&(r=s)}),r}function h1(t,e,r){let i=null;if(t&&Gt(t)){const s=rd(t,e);s&&(i=s);const n=a1(t,e,r);n&&(i=n)}else i=F("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function $n(t,e){let r=null;if(t&&Gt(t)){const i=rd(t,e);i&&(r=i);const s=u1(t,e);s&&(r=s)}else r=F("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function id(t){return de(t.protocol,!0)}function d1(t,e){let r=!1;return t?t&&yt(t)&&t.length&&t.forEach(i=>{r=id(i)}):r=!0,r}function p1(t){return typeof t=="number"}function Me(t){return typeof t<"u"&&typeof t!==null}function f1(t){return!(!t||typeof t!="object"||!t.code||!Xo(t.code,!1)||!t.message||!de(t.message,!1))}function g1(t){return!(Oe(t)||!de(t.method,!1))}function y1(t){return!(Oe(t)||Oe(t.result)&&Oe(t.error)||!Xo(t.id,!1)||!de(t.jsonrpc,!1))}function m1(t){return!(Oe(t)||!de(t.name,!1))}function Hc(t,e){return!(!Ts(e)||!W0(t).includes(e))}function w1(t,e,r){return de(r,!1)?G0(t,e).includes(r):!1}function b1(t,e,r){return de(r,!1)?Y0(t,e).includes(r):!1}function Vc(t,e,r){let i=null;const s=v1(t),n=E1(e),o=Object.keys(s),a=Object.keys(n),c=Kc(Object.keys(t)),u=Kc(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(i=F("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
@@ -22,4 +22,4 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Bb(r)).toStr
22
22
  Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const d=ci(e[h].accounts);d.includes(h)||(i=F("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
23
23
  Required: ${h}
24
24
  Approved: ${d.toString()}`))}),o.forEach(h=>{i||(ur(s[h].methods,n[h].methods)?ur(s[h].events,n[h].events)||(i=F("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=F("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function v1(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(s=>{e[s]={methods:t[r].methods,events:t[r].events}})}),e}function Kc(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function E1(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=ci(t[r].accounts);i==null||i.forEach(s=>{e[s]={accounts:t[r].accounts.filter(n=>n.includes(`${s}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function _1(t,e){return Xo(t,!1)&&t<=e.max&&t>=e.min}function Wc(){const t=zi();return new Promise(e=>{switch(t){case Qe.browser:e(I1());break;case Qe.reactNative:e(D1());break;case Qe.node:e(S1());break;default:e(!0)}})}function I1(){return ni()&&(navigator==null?void 0:navigator.onLine)}async function D1(){if(Jt()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function S1(){return!0}function O1(t){switch(zi()){case Qe.browser:P1(t);break;case Qe.reactNative:$1(t);break}}function P1(t){!Jt()&&ni()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function $1(t){Jt()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function A1(){var t;return ni()&&exports.getDocument_1()?((t=exports.getDocument_1())==null?void 0:t.visibilityState)==="visible":!0}const An={};class yi{static get(e){return An[e]}static set(e,r){An[e]=r}static delete(e){delete An[e]}}class Zt{}let x1=class extends Zt{constructor(e){super()}};const Gc=N.FIVE_SECONDS,Qt={pulse:"heartbeat_pulse"};let sd=class nd extends x1{constructor(e){super(e),this.events=new He.EventEmitter,this.interval=Gc,this.interval=(e==null?void 0:e.interval)||Gc}static async init(e){const r=new nd(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),N.toMiliseconds(this.interval))}pulse(){this.events.emit(Qt.pulse)}};const C1=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,T1=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,R1=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function N1(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){F1(t);return}return e}function F1(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Ii(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!R1.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(C1.test(t)||T1.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,N1)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function B1(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function me(t,...e){try{return B1(t(...e))}catch(r){return Promise.reject(r)}}function j1(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function L1(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Es(t){if(j1(t))return String(t);if(L1(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Es(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const fo="base64:";function U1(t){return typeof t=="string"?t:fo+q1(t)}function k1(t){return typeof t!="string"||!t.startsWith(fo)?t:M1(t.slice(fo.length))}function M1(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function q1(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function ke(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function z1(...t){return ke(t.join(":"))}function us(t){return t=ke(t),t?t+":":""}function H1(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function V1(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const K1="memory",W1=()=>{const t=new Map;return{name:K1,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function G1(t={}){const e={mounts:{"":t.driver||W1()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},i=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(u,l)=>{if(e.watching){l=ke(l);for(const h of e.watchListeners)h(u,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Yc(e.mounts[u],s,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const d=new Map,f=p=>{let y=d.get(p.base);return y||(y={driver:p.driver,base:p.base,items:[]},d.set(p.base,y)),y};for(const p of u){const y=typeof p=="string",w=ke(y?p:p.key),v=y?void 0:p.value,b=y||!p.options?l:{...l,...p.options},E=r(w);f(E).items.push({key:w,value:v,relativeKey:E.relativeKey,options:b})}return Promise.all([...d.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return me(d.hasItem,h,l)},getItem(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return me(d.getItem,h,l).then(f=>Ii(f))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?me(h.driver.getItems,h.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(f=>({key:z1(h.base,f.key),value:Ii(f.value)}))):Promise.all(h.items.map(d=>me(h.driver.getItem,d.relativeKey,d.options).then(f=>({key:d.key,value:Ii(f)})))))},getItemRaw(u,l={}){u=ke(u);const{relativeKey:h,driver:d}=r(u);return d.getItemRaw?me(d.getItemRaw,h,l):me(d.getItem,h,l).then(f=>k1(f))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=ke(u);const{relativeKey:d,driver:f}=r(u);f.setItem&&(await me(f.setItem,d,Es(l),h),f.watch||s("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return me(h.driver.setItems,h.items.map(d=>({key:d.relativeKey,value:Es(d.value),options:d.options})),l);h.driver.setItem&&await Promise.all(h.items.map(d=>me(h.driver.setItem,d.relativeKey,Es(d.value),d.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=ke(u);const{relativeKey:d,driver:f}=r(u);if(f.setItemRaw)await me(f.setItemRaw,d,l,h);else if(f.setItem)await me(f.setItem,d,U1(l),h);else return;f.watch||s("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=ke(u);const{relativeKey:h,driver:d}=r(u);d.removeItem&&(await me(d.removeItem,h,l),(l.removeMeta||l.removeMata)&&await me(d.removeItem,h+"$",l),d.watch||s("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=ke(u);const{relativeKey:h,driver:d}=r(u),f=Object.create(null);if(d.getMeta&&Object.assign(f,await me(d.getMeta,h,l)),!l.nativeOnly){const p=await me(d.getItem,h+"$",l).then(y=>Ii(y));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(f,p))}return f},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){var w;u=us(u);const h=i(u,!0);let d=[];const f=[];let p=!0;for(const v of h){(w=v.driver.flags)!=null&&w.maxDepth||(p=!1);const b=await me(v.driver.getKeys,v.relativeBase,l);for(const E of b){const I=v.mountpoint+ke(E);d.some($=>I.startsWith($))||f.push(I)}d=[v.mountpoint,...d.filter(E=>!E.startsWith(v.mountpoint))]}const y=l.maxDepth!==void 0&&!p;return f.filter(v=>(!y||H1(v,l.maxDepth))&&V1(v,u))},async clear(u,l={}){u=us(u),await Promise.all(i(u,!1).map(async h=>{if(h.driver.clear)return me(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const d=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(d.map(f=>h.driver.removeItem(f,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Jc(u)))},async watch(u){return await n(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=us(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,d)=>d.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(Yc(l,s,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){var h,d;u=us(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&((d=(h=e.unwatch)[u])==null||d.call(h),delete e.unwatch[u]),l&&await Jc(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=ke(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=ke(u),i(u,l.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function Yc(t,e,r){return t.watch?t.watch((i,s)=>e(i,r+s)):()=>{}}async function Jc(t){typeof t.dispose=="function"&&await me(t.dispose)}const Y1="idb-keyval";var J1=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=s=>e+s;let i;return t.dbName&&t.storeName&&(i=Ro(t.dbName,t.storeName)),{name:Y1,options:t,async hasItem(s){return!(typeof await qn(r(s),i)>"u")},async getItem(s){return await qn(r(s),i)??null},setItem(s,n){return cl(r(s),n,i)},removeItem(s){return ul(r(s),i)},getKeys(){return hl(i)},clear(){return ll(i)}}};const Z1="WALLET_CONNECT_V2_INDEXED_DB",Q1="keyvaluestorage";let X1=class{constructor(){this.indexedDb=G1({driver:J1({dbName:Z1,storeName:Q1})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,St(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var xn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},_s={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof xn<"u"&&xn.localStorage?_s.exports=xn.localStorage:typeof window<"u"&&window.localStorage?_s.exports=window.localStorage:_s.exports=new e})();function eE(t){var e;return[t[0],Yt((e=t[1])!=null?e:"")]}let tE=class{constructor(){this.localStorage=_s.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(eE)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return Yt(r)}async setItem(e,r){this.localStorage.setItem(e,St(r))}async removeItem(e){this.localStorage.removeItem(e)}};const rE="wc_storage_version",Zc=1,iE=async(t,e,r)=>{const i=rE,s=await e.getItem(i);if(s&&s>=Zc){r(e);return}const n=await t.getKeys();if(!n.length){r(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(i,Zc),r(e),sE(t,o)},sE=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let nE=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new tE;this.storage=e;try{const r=new X1;iE(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};function oE(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var aE=cE;function cE(t,e,r){var i=r&&r.stringify||oE,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=i(t);for(var a=1;a<n;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-s,h=-1,d=t&&t.length||0,f=0;f<d;){if(t.charCodeAt(f)===37&&f+1<d){switch(h=h>-1?h:0,t.charCodeAt(f+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<f&&(u+=t.slice(h,f)),u+=Number(e[l]),h=f+2,f++;break;case 105:if(l>=c||e[l]==null)break;h<f&&(u+=t.slice(h,f)),u+=Math.floor(Number(e[l])),h=f+2,f++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<f&&(u+=t.slice(h,f));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",h=f+2,f++;break}if(p==="function"){u+=e[l].name||"<anonymous>",h=f+2,f++;break}u+=i(e[l]),h=f+2,f++;break;case 115:if(l>=c)break;h<f&&(u+=t.slice(h,f)),u+=String(e[l]),h=f+2,f++;break;case 37:h<f&&(u+=t.slice(h,f)),u+="%",h=f+2,f++,l--;break}++l}++f}return h===-1?t:(h<d&&(u+=t.slice(h)),u)}const Qc=aE;var kr=Dt;const Bi=wE().console||{},uE={mapHttpRequest:ls,mapHttpResponse:ls,wrapRequestSerializer:Cn,wrapResponseSerializer:Cn,wrapErrorSerializer:Cn,req:ls,res:ls,err:fE};function lE(t,e){return Array.isArray(t)?t.filter(function(i){return i!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Dt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||Bi;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},s=lE(t.browser.serialize,i);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=ji),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:d});const u={transmit:e,serialize:s,asObject:t.browser.asObject,levels:o,timestamp:gE(t)};c.levels=Dt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=ji,c.serializers=i,c._serialize=s,c._stdErrSerialize=n,c.child=f,e&&(c._logEvent=go());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function d(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,Sr(u,c,"error","log"),Sr(u,c,"fatal","error"),Sr(u,c,"warn","error"),Sr(u,c,"info","log"),Sr(u,c,"debug","log"),Sr(u,c,"trace","log")}function f(p,y){if(!p)throw new Error("missing bindings for child Pino");y=y||{},s&&p.serializers&&(y.serializers=p.serializers);const w=y.serializers;if(s&&w){var v=Object.assign({},i,w),b=t.browser.serialize===!0?Object.keys(v):s;delete p.serializers,Js([p],b,v,this._stdErrSerialize)}function E(I){this._childLevel=(I._childLevel|0)+1,this.error=Or(I,p,"error"),this.fatal=Or(I,p,"fatal"),this.warn=Or(I,p,"warn"),this.info=Or(I,p,"info"),this.debug=Or(I,p,"debug"),this.trace=Or(I,p,"trace"),v&&(this.serializers=v,this._serialize=b),e&&(this._logEvent=go([].concat(I._logEvent.bindings,p)))}return E.prototype=this,new E(this)}return c}Dt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Dt.stdSerializers=uE;Dt.stdTimeFunctions=Object.assign({},{nullTime:od,epochTime:ad,unixTime:yE,isoTime:mE});function Sr(t,e,r,i){const s=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?ji:s[r]?s[r]:Bi[r]||Bi[i]||ji,hE(t,e,r)}function hE(t,e,r){!t.transmit&&e[r]===ji||(e[r]=function(i){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Bi?Bi:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Js(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?i.call(a,dE(this,r,o,n)):i.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Dt.levels.values[u],h=Dt.levels.values[r];if(h<l)return;pE(this,{ts:n,methodLevel:r,methodValue:h,transmitValue:Dt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function dE(t,e,r,i){t._serialize&&Js(r,t._serialize,t.serializers,t._stdErrSerialize);const s=r.slice();let n=s[0];const o={};i&&(o.time=i),o.level=Dt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof s[0]=="object";)Object.assign(o,s.shift());n=s.length?Qc(s.shift(),s):void 0}else typeof n=="string"&&(n=Qc(s.shift(),s));return n!==void 0&&(o.msg=n),o}function Js(t,e,r,i){for(const s in t)if(i&&t[s]instanceof Error)t[s]=Dt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s]))for(const n in t[s])e&&e.indexOf(n)>-1&&n in r&&(t[s][n]=r[n](t[s][n]))}function Or(t,e,r){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var s=1;s<i.length;s++)i[s]=arguments[s-1];return t[r].apply(this,i)}}function pE(t,e,r){const i=e.send,s=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Js(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=r.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=n,t._logEvent.level.value=o,i(n,t._logEvent,a),t._logEvent=go(c)}function go(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function fE(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function gE(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?od:ad}function ls(){return{}}function Cn(t){return t}function ji(){}function od(){return!1}function ad(){return Date.now()}function yE(){return Math.round(Date.now()/1e3)}function mE(){return new Date(Date.now()).toISOString()}function wE(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const ui=ze.getDefaultExportFromCjs(kr),bE={level:"info"},Yi="custom_context",ea=1e3*1024;let vE=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Xc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new vE(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}},cd=class{constructor(e,r=ea){this.level=e??"error",this.levelValue=kr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new Xc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===kr.levels.values.error?console.error(e):r===kr.levels.values.warn?console.warn(e):r===kr.levels.values.debug?console.debug(e):r===kr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(St({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new Xc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(St({extraMetadata:e})),new Blob(r,{type:"application/json"})}},EE=class{constructor(e,r=ea){this.baseChunkLogger=new cd(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}},_E=class{constructor(e,r=ea){this.baseChunkLogger=new cd(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var IE=Object.defineProperty,DE=Object.defineProperties,SE=Object.getOwnPropertyDescriptors,eu=Object.getOwnPropertySymbols,OE=Object.prototype.hasOwnProperty,PE=Object.prototype.propertyIsEnumerable,tu=(t,e,r)=>e in t?IE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rs=(t,e)=>{for(var r in e||(e={}))OE.call(e,r)&&tu(t,r,e[r]);if(eu)for(var r of eu(e))PE.call(e,r)&&tu(t,r,e[r]);return t},Ns=(t,e)=>DE(t,SE(e));function Ji(t){return Ns(Rs({},t),{level:(t==null?void 0:t.level)||bE.level})}function $E(t,e=Yi){return t[e]||""}function AE(t,e,r=Yi){return t[r]=e,t}function je(t,e=Yi){let r="";return typeof t.bindings>"u"?r=$E(t,e):r=t.bindings().context||"",r}function xE(t,e,r=Yi){const i=je(t,r);return i.trim()?`${i}/${e}`:e}function Te(t,e,r=Yi){const i=xE(t,e,r),s=t.child({context:i});return AE(s,i,r)}function CE(t){var e,r;const i=new EE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ui(Ns(Rs({},t.opts),{level:"trace",browser:Ns(Rs({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function TE(t){var e;const r=new _E((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ui(Ns(Rs({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function ud(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?CE(t):TE(t)}var RE=Object.defineProperty,NE=(t,e,r)=>e in t?RE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ru=(t,e,r)=>NE(t,typeof e!="symbol"?e+"":e,r);let FE=class extends Zt{constructor(e){super(),this.opts=e,ru(this,"protocol","wc"),ru(this,"version",2)}};var BE=Object.defineProperty,jE=(t,e,r)=>e in t?BE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,LE=(t,e,r)=>jE(t,e+"",r);let UE=class extends Zt{constructor(e,r){super(),this.core=e,this.logger=r,LE(this,"records",new Map)}},kE=class{constructor(e,r){this.logger=e,this.core=r}};class ME extends Zt{constructor(e,r){super(),this.relayer=e,this.logger=r}}let qE=class extends Zt{constructor(e){super()}},zE=class{constructor(e,r,i,s){this.core=e,this.logger=r,this.name=i}},HE=class extends Zt{constructor(e,r){super(),this.relayer=e,this.logger=r}},VE=class extends Zt{constructor(e,r){super(),this.core=e,this.logger=r}},KE=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},WE=class{constructor(e,r){this.projectId=e,this.logger=r}},GE=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var YE=Object.defineProperty,JE=(t,e,r)=>e in t?YE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,iu=(t,e,r)=>JE(t,typeof e!="symbol"?e+"":e,r);let ZE=class{constructor(e){this.opts=e,iu(this,"protocol","wc"),iu(this,"version",2)}},QE=class{constructor(e){this.client=e}};const XE="PARSE_ERROR",e_="INVALID_REQUEST",t_="METHOD_NOT_FOUND",r_="INVALID_PARAMS",ld="INTERNAL_ERROR",ta="SERVER_ERROR",i_=[-32700,-32600,-32601,-32602,-32603],Oi={[XE]:{code:-32700,message:"Parse error"},[e_]:{code:-32600,message:"Invalid Request"},[t_]:{code:-32601,message:"Method not found"},[r_]:{code:-32602,message:"Invalid params"},[ld]:{code:-32603,message:"Internal error"},[ta]:{code:-32e3,message:"Server error"}},hd=ta;function s_(t){return i_.includes(t)}function su(t){return Object.keys(Oi).includes(t)?Oi[t]:Oi[hd]}function n_(t){const e=Object.values(Oi).find(r=>r.code===t);return e||Oi[hd]}function dd(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var pd={},Ct={},nu;function o_(){if(nu)return Ct;nu=1,Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.isBrowserCryptoAvailable=Ct.getSubtleCrypto=Ct.getBrowerCrypto=void 0;function t(){return(ze.commonjsGlobal===null||ze.commonjsGlobal===void 0?void 0:ze.commonjsGlobal.crypto)||(ze.commonjsGlobal===null||ze.commonjsGlobal===void 0?void 0:ze.commonjsGlobal.msCrypto)||{}}Ct.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ct.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ct.isBrowserCryptoAvailable=r,Ct}var Tt={},ou;function a_(){if(ou)return Tt;ou=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.isBrowser=Tt.isNode=Tt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Tt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Tt.isNode=e;function r(){return!t()&&!e()}return Tt.isBrowser=r,Tt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ui;e.__exportStar(o_(),t),e.__exportStar(a_(),t)})(pd);function pt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Kt(t=6){return BigInt(pt(t))}function Bt(t,e,r){return{id:r||pt(),jsonrpc:"2.0",method:t,params:e}}function Zi(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Qi(t,e,r){return{id:t,jsonrpc:"2.0",error:c_(e)}}function c_(t,e){return typeof t>"u"?su(ld):(typeof t=="string"&&(t=Object.assign(Object.assign({},su(ta)),{message:t})),s_(t.code)&&(t=n_(t.code)),t)}class u_{}class l_ extends u_{constructor(){super()}}class h_ extends l_{constructor(e){super()}}const d_="^https?:",p_="^wss?:";function f_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function fd(t,e){const r=f_(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function au(t){return fd(t,d_)}function cu(t){return fd(t,p_)}function g_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function gd(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Zs(t){return gd(t)&&"method"in t}function Xi(t){return gd(t)&&(ft(t)||Ye(t))}function ft(t){return"result"in t}function Ye(t){return"error"in t}let et=class extends h_{constructor(e){super(e),this.events=new He.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Bt(e.method,e.params||[],e.id||Kt().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{Ye(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Xi(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const y_=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),m_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",uu=t=>t.split("?")[0],lu=10,w_=y_();let yd=class{constructor(e){if(this.url=e,this.events=new He.EventEmitter,this.registering=!1,!cu(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(St(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!cu(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=pd.isReactNative()?void 0:{rejectUnauthorized:!g_(e)},n=new w_(e,[],s);m_()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Yt(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Qi(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dd(e,uu(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>lu&&this.events.setMaxListeners(lu)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${uu(this.url)}`));return this.events.emit("register_error",r),r}};const md="wc",wd=2,yo="core",Ot=`${md}@2:${yo}:`,b_={logger:"error"},v_={database:":memory:"},E_="crypto",hu="client_ed25519_seed",__=N.ONE_DAY,I_="keychain",D_="0.3",S_="messages",O_="0.3",du=N.SIX_HOURS,P_="publisher",bd="irn",$_="error",vd="wss://relay.walletconnect.org",A_="relayer",be={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},x_="_subscription",it={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},C_=.1,mo="2.21.1",ce={link_mode:"link_mode",relay:"relay"},Is={inbound:"inbound",outbound:"outbound"},T_="0.3",R_="WALLETCONNECT_CLIENT_ID",pu="WALLETCONNECT_LINK_MODE_APPS",We={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},N_="subscription",F_="0.3",B_="pairing",j_="0.3",mi={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},ar={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ut={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},L_="history",U_="0.3",k_="expirer",nt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},M_="0.3",q_="verify-api",z_="https://verify.walletconnect.com",Ed="https://verify.walletconnect.org",Pi=Ed,H_=`${Pi}/v3`,V_=[z_,Ed],K_="echo",W_="https://echo.walletconnect.com",Et={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Rt={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},lt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},tr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},rr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},wi={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},G_=.1,Y_="event-client",J_=86400,Z_="https://pulse.walletconnect.org/batch";function Q_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var $=p[v],A=0,P=E-1;($!==0||A<w)&&P!==-1;P--,A++)$+=256*I[P]>>>0,I[P]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var S=c.repeat(y);C<E;++C)S+=t.charAt(I[C]);return S}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*u+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var $=0,A=b-1;(I!==0||$<v)&&A!==-1;A--,$++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=$,y++}if(p[y]!==" "){for(var P=b-v;P!==b&&E[P]===0;)P++;for(var C=new Uint8Array(w+(b-P)),S=w;P!==b;)C[S++]=E[P++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var X_=Q_,e2=X_;const _d=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},t2=t=>new TextEncoder().encode(t),r2=t=>new TextDecoder().decode(t);class i2{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class s2{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Id(this,e)}}class n2{constructor(e){this.decoders=e}or(e){return Id(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Id=(t,e)=>new n2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class o2{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new i2(e,r,i),this.decoder=new s2(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Qs=({name:t,prefix:e,encode:r,decode:i})=>new o2(t,e,r,i),es=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=e2(r,e);return Qs({prefix:t,name:e,encode:i,decode:n=>_d(s(n))})},a2=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},c2=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Ae=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Qs({prefix:e,name:t,encode(s){return c2(s,i,r)},decode(s){return a2(s,i,r,t)}}),u2=Qs({prefix:"\0",name:"identity",encode:t=>r2(t),decode:t=>t2(t)});var l2=Object.freeze({__proto__:null,identity:u2});const h2=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var d2=Object.freeze({__proto__:null,base2:h2});const p2=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var f2=Object.freeze({__proto__:null,base8:p2});const g2=es({prefix:"9",name:"base10",alphabet:"0123456789"});var y2=Object.freeze({__proto__:null,base10:g2});const m2=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),w2=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var b2=Object.freeze({__proto__:null,base16:m2,base16upper:w2});const v2=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),E2=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_2=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),I2=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),D2=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S2=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),O2=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),P2=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$2=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var A2=Object.freeze({__proto__:null,base32:v2,base32upper:E2,base32pad:_2,base32padupper:I2,base32hex:D2,base32hexupper:S2,base32hexpad:O2,base32hexpadupper:P2,base32z:$2});const x2=es({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),C2=es({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var T2=Object.freeze({__proto__:null,base36:x2,base36upper:C2});const R2=es({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),N2=es({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var F2=Object.freeze({__proto__:null,base58btc:R2,base58flickr:N2});const B2=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),j2=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),L2=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U2=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var k2=Object.freeze({__proto__:null,base64:B2,base64pad:j2,base64url:L2,base64urlpad:U2});const Dd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),M2=Dd.reduce((t,e,r)=>(t[r]=e,t),[]),q2=Dd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function z2(t){return t.reduce((e,r)=>(e+=M2[r],e),"")}function H2(t){const e=[];for(const r of t){const i=q2[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const V2=Qs({prefix:"🚀",name:"base256emoji",encode:z2,decode:H2});var K2=Object.freeze({__proto__:null,base256emoji:V2}),W2=Sd,fu=128,G2=-128,Y2=Math.pow(2,31);function Sd(t,e,r){e=e||[],r=r||0;for(var i=r;t>=Y2;)e[r++]=t&255|fu,t/=128;for(;t&G2;)e[r++]=t&255|fu,t>>>=7;return e[r]=t|0,Sd.bytes=r-i+1,e}var J2=wo,Z2=128,gu=127;function wo(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw wo.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&gu)<<s:(o&gu)*Math.pow(2,s),s+=7}while(o>=Z2);return wo.bytes=n-i,r}var Q2=Math.pow(2,7),X2=Math.pow(2,14),eI=Math.pow(2,21),tI=Math.pow(2,28),rI=Math.pow(2,35),iI=Math.pow(2,42),sI=Math.pow(2,49),nI=Math.pow(2,56),oI=Math.pow(2,63),aI=function(t){return t<Q2?1:t<X2?2:t<eI?3:t<tI?4:t<rI?5:t<iI?6:t<sI?7:t<nI?8:t<oI?9:10},cI={encode:W2,decode:J2,encodingLength:aI},Od=cI;const yu=(t,e,r=0)=>(Od.encode(t,e,r),e),mu=t=>Od.encodingLength(t),bo=(t,e)=>{const r=e.byteLength,i=mu(t),s=i+mu(r),n=new Uint8Array(s+r);return yu(t,n,0),yu(r,n,i),n.set(e,s),new uI(t,r,e,n)};class uI{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const Pd=({name:t,code:e,encode:r})=>new lI(t,e,r);class lI{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?bo(this.code,r):r.then(i=>bo(this.code,i))}else throw Error("Unknown type, must be binary type")}}const $d=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),hI=Pd({name:"sha2-256",code:18,encode:$d("SHA-256")}),dI=Pd({name:"sha2-512",code:19,encode:$d("SHA-512")});var pI=Object.freeze({__proto__:null,sha256:hI,sha512:dI});const Ad=0,fI="identity",xd=_d,gI=t=>bo(Ad,xd(t)),yI={code:Ad,name:fI,encode:xd,digest:gI};var mI=Object.freeze({__proto__:null,identity:yI});new TextEncoder,new TextDecoder;const wu={...l2,...d2,...f2,...y2,...b2,...A2,...T2,...F2,...k2,...K2};({...pI,...mI});function wI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Cd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const bu=Cd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Tn=Cd("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=wI(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),bI={utf8:bu,"utf-8":bu,hex:wu.base16,latin1:Tn,ascii:Tn,binary:Tn,...wu};function vI(t,e="utf8"){const r=bI[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bt=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);class II{constructor(e,r){this.core=e,this.logger=r,bt(this,"keychain",new Map),bt(this,"name",I_),bt(this,"version",D_),bt(this,"initialized",!1),bt(this,"storagePrefix",Ot),bt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),bt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),bt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),bt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=F("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),bt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Te(r,this.name)}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,to(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ro(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var DI=Object.defineProperty,SI=(t,e,r)=>e in t?DI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,De=(t,e,r)=>SI(t,typeof e!="symbol"?e+"":e,r);class OI{constructor(e,r,i){this.core=e,this.logger=r,De(this,"name",E_),De(this,"keychain"),De(this,"randomSessionIdentifier",po()),De(this,"initialized",!1),De(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),De(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),De(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=eo(s);return Vo(n.publicKey)}),De(this,"generateKeyPair",()=>{this.isInitialized();const s=P0();return this.setPrivateKey(s.publicKey,s.privateKey)}),De(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=eo(n),a=this.randomSessionIdentifier;return await hh(a,s,__,o)}),De(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=$0(a,n);return this.setSymKey(c,o)}),De(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||vs(s);return await this.keychain.set(o,s),o}),De(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),De(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),De(this,"encode",async(s,n,o)=>{this.isInitialized();const a=td(o),c=St(n);if(Bc(a))return C0(c,o==null?void 0:o.encoding);if(Fc(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;s=await this.generateSharedKey(d,f)}const u=this.getSymKey(s),{type:l,senderPublicKey:h}=a;return A0({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),De(this,"decode",async(s,n,o)=>{this.isInitialized();const a=R0(n,o);if(Bc(a)){const c=T0(n,o==null?void 0:o.encoding);return Yt(c)}if(Fc(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;s=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(s),u=x0({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return Yt(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),De(this,"getPayloadType",(s,n=gt)=>{const o=Fi({encoded:s,encoding:n});return fr(o.type)}),De(this,"getPayloadSenderPublicKey",(s,n=gt)=>{const o=Fi({encoded:s,encoding:n});return o.senderPublicKey?Fe(o.senderPublicKey,Be):void 0}),this.core=e,this.logger=Te(r,this.name),this.keychain=i||new II(this.core,this.logger)}get context(){return je(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(hu)}catch{e=po(),await this.keychain.set(hu,e)}return vI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PI=Object.defineProperty,$I=Object.defineProperties,AI=Object.getOwnPropertyDescriptors,vu=Object.getOwnPropertySymbols,xI=Object.prototype.hasOwnProperty,CI=Object.prototype.propertyIsEnumerable,vo=(t,e,r)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,TI=(t,e)=>{for(var r in e||(e={}))xI.call(e,r)&&vo(t,r,e[r]);if(vu)for(var r of vu(e))CI.call(e,r)&&vo(t,r,e[r]);return t},RI=(t,e)=>$I(t,AI(e)),Ve=(t,e,r)=>vo(t,typeof e!="symbol"?e+"":e,r);class NI extends kE{constructor(e,r){super(e,r),this.logger=e,this.core=r,Ve(this,"messages",new Map),Ve(this,"messagesWithoutClientAck",new Map),Ve(this,"name",S_),Ve(this,"version",O_),Ve(this,"initialized",!1),Ve(this,"storagePrefix",Ot),Ve(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Ve(this,"set",async(i,s,n)=>{this.isInitialized();const o=_t(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===Is.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,RI(TI({},c),{[o]:s}))}return await this.persist(),o}),Ve(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),Ve(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Ve(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=_t(s);return typeof n[o]<"u"}),Ve(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=_t(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),Ve(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Te(e,this.name),this.core=r}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,to(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,to(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ro(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?ro(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var FI=Object.defineProperty,BI=Object.defineProperties,jI=Object.getOwnPropertyDescriptors,Eu=Object.getOwnPropertySymbols,LI=Object.prototype.hasOwnProperty,UI=Object.prototype.propertyIsEnumerable,Eo=(t,e,r)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hs=(t,e)=>{for(var r in e||(e={}))LI.call(e,r)&&Eo(t,r,e[r]);if(Eu)for(var r of Eu(e))UI.call(e,r)&&Eo(t,r,e[r]);return t},Rn=(t,e)=>BI(t,jI(e)),ht=(t,e,r)=>Eo(t,typeof e!="symbol"?e+"":e,r);class kI extends ME{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ht(this,"events",new He.EventEmitter),ht(this,"name",P_),ht(this,"queue",new Map),ht(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),ht(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),ht(this,"needsTransportRestart",!1),ht(this,"publish",async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||du,c=Cs(n),u=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,h=(n==null?void 0:n.id)||Kt().toString(),d={topic:i,message:s,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const p=new Promise(async y=>{const w=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(be.publish,w),y(d))};this.relayer.events.on(be.publish,w);const v=Vt(new Promise((b,E)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:u,tag:l,id:h,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),E(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await v,this.events.removeListener(be.publish,w)}catch(b){this.queue.set(h,Rn(hs({},d),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:i,message:s,opts:n}}),await Vt(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(h)}}),ht(this,"on",(i,s)=>{this.events.on(i,s)}),ht(this,"once",(i,s)=>{this.events.once(i,s)}),ht(this,"off",(i,s)=>{this.events.off(i,s)}),ht(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=Te(r,this.name),this.registerEventListeners()}get context(){return je(this.logger)}async rpcPublish(e){var r,i,s,n;const{topic:o,message:a,ttl:c=du,prompt:u,tag:l,id:h,attestation:d,tvf:f}=e,p={method:_i(Cs().protocol).publish,params:hs({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},f),id:h};Oe((r=p.params)==null?void 0:r.prompt)&&((i=p.params)==null||delete i.prompt),Oe((s=p.params)==null?void 0:s.tag)&&((n=p.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const y=await this.relayer.request(p);return this.relayer.events.emit(be.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,Rn(hs({},e),{attempt:i}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(Rn(hs({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Qt.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(be.connection_stalled);return}this.checkQueue()}),this.relayer.on(be.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var MI=Object.defineProperty,qI=(t,e,r)=>e in t?MI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pr=(t,e,r)=>qI(t,typeof e!="symbol"?e+"":e,r);class zI{constructor(){Pr(this,"map",new Map),Pr(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Pr(this,"get",e=>this.map.get(e)||[]),Pr(this,"exists",(e,r)=>this.get(e).includes(r)),Pr(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Pr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var HI=Object.defineProperty,VI=Object.defineProperties,KI=Object.getOwnPropertyDescriptors,_u=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,_o=(t,e,r)=>e in t?HI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bi=(t,e)=>{for(var r in e||(e={}))WI.call(e,r)&&_o(t,r,e[r]);if(_u)for(var r of _u(e))GI.call(e,r)&&_o(t,r,e[r]);return t},Nn=(t,e)=>VI(t,KI(e)),ie=(t,e,r)=>_o(t,typeof e!="symbol"?e+"":e,r);class YI extends HE{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ie(this,"subscriptions",new Map),ie(this,"topicMap",new zI),ie(this,"events",new He.EventEmitter),ie(this,"name",N_),ie(this,"version",F_),ie(this,"pending",new Map),ie(this,"cached",[]),ie(this,"initialized",!1),ie(this,"storagePrefix",Ot),ie(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),ie(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),ie(this,"clientId"),ie(this,"batchSubscribeTopicsLimit",500),ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ie(this,"subscribe",async(i,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=Cs(s),o={topic:i,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ie(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ie(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ie(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ie(this,"on",(i,s)=>{this.events.on(i,s)}),ie(this,"once",(i,s)=>{this.events.once(i,s)}),ie(this,"off",(i,s)=>{this.events.off(i,s)}),ie(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ie(this,"start",async()=>{await this.onConnect()}),ie(this,"stop",async()=>{await this.onDisconnect()}),ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ie(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Qt.pulse,async()=>{await this.checkPending()}),this.events.on(We.created,async i=>{const s=We.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(We.deleted,async i=>{const s=We.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=Te(r,this.name),this.clientId=""}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const s=Cs(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s;(!i||(i==null?void 0:i.transportType)===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const n={method:_i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},N.toMiliseconds(N.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(We.created,h),l(d.id))};this.events.on(We.created,h);try{const d=await Vt(new Promise((f,p)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),p(y)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(We.created,h),l(d)}catch{}}),u=await Vt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(be.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Vt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(be.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await Vt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(be.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:_i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,Nn(bi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,bi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,bi({},r)),this.topicMap.set(r.topic,e),this.events.emit(We.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(We.deleted,Nn(bi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(We.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(We.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Nn(bi({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await fb(N.toMiliseconds(N.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return _t(e+await this.getClientId())}}var JI=Object.defineProperty,Iu=Object.getOwnPropertySymbols,ZI=Object.prototype.hasOwnProperty,QI=Object.prototype.propertyIsEnumerable,Io=(t,e,r)=>e in t?JI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Du=(t,e)=>{for(var r in e||(e={}))ZI.call(e,r)&&Io(t,r,e[r]);if(Iu)for(var r of Iu(e))QI.call(e,r)&&Io(t,r,e[r]);return t},Z=(t,e,r)=>Io(t,typeof e!="symbol"?e+"":e,r);class XI extends qE{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new He.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",A_),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Z(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const n=r.id||Kt().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Z(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(be.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(be.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(it.payload,this.onPayloadHandler),this.provider.on(it.connect,this.onConnectHandler),this.provider.on(it.disconnect,this.onDisconnectHandler),this.provider.on(it.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Te(e.logger,this.name):ui(Ji({level:e.logger||$_})),this.messages=new NI(this.logger,e.core),this.subscriber=new YI(this,this.logger),this.publisher=new kI(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||vd,this.projectId=e.projectId,Qw()?this.packageName=nc():Xw()&&(this.bundleId=nc()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return je(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:ce.relay},Is.outbound)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(We.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(We.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Du({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Vt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Wc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=pe(N.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(be.message,e),await this.recordMessageEvent(e,Is.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(it.disconnect,n),await Vt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(it.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(it.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(it.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,N.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new et(new yd(sb({sdkVersion:mo,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:s}=e;await this.messages.set(i,s,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Zs(e)){if(!e.method.endsWith(x_))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Du({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Xi(e)&&this.events.emit(be.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Is.inbound),this.events.emit(be.message,e))}async acknowledgePayload(e){const r=Zi(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(it.payload,this.onPayloadHandler),this.provider.off(it.connect,this.onConnectHandler),this.provider.off(it.disconnect,this.onDisconnectHandler),this.provider.off(it.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Wc();O1(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Qt.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&A1())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(be.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},N.toMiliseconds(C_)))))}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function eD(){}function Su(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function Ou(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Pu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const tD="[object RegExp]",rD="[object String]",iD="[object Number]",sD="[object Boolean]",$u="[object Arguments]",nD="[object Symbol]",oD="[object Date]",aD="[object Map]",cD="[object Set]",uD="[object Array]",lD="[object Function]",hD="[object ArrayBuffer]",Fn="[object Object]",dD="[object Error]",pD="[object DataView]",fD="[object Uint8Array]",gD="[object Uint8ClampedArray]",yD="[object Uint16Array]",mD="[object Uint32Array]",wD="[object BigUint64Array]",bD="[object Int8Array]",vD="[object Int16Array]",ED="[object Int32Array]",_D="[object BigInt64Array]",ID="[object Float32Array]",DD="[object Float64Array]";function SD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function OD(t,e,r){return Di(t,e,void 0,void 0,void 0,void 0,r)}function Di(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return $i(t,e,n,o)}return $i(t,e,n,o)}function $i(t,e,r,i){if(Object.is(t,e))return!0;let s=Pu(t),n=Pu(e);if(s===$u&&(s=Fn),n===$u&&(n=Fn),s!==n)return!1;switch(s){case rD:return t.toString()===e.toString();case iD:{const c=t.valueOf(),u=e.valueOf();return SD(c,u)}case sD:case oD:case nD:return Object.is(t.valueOf(),e.valueOf());case tD:return t.source===e.source&&t.flags===e.flags;case lD:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(s){case aD:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Di(u,e.get(c),c,t,e,r,i))return!1;return!0}case cD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],d=u.findIndex(f=>Di(h,f,void 0,t,e,r,i));if(d===-1)return!1;u.splice(d,1)}return!0}case uD:case fD:case gD:case yD:case mD:case wD:case bD:case vD:case ED:case _D:case ID:case DD:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Di(t[c],e[c],c,t,e,r,i))return!1;return!0}case hD:return t.byteLength!==e.byteLength?!1:$i(new Uint8Array(t),new Uint8Array(e),r,i);case pD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:$i(new Uint8Array(t),new Uint8Array(e),r,i);case dD:return t.name===e.name&&t.message===e.message;case Fn:{if(!($i(t.constructor,e.constructor,r,i)||Su(t)&&Su(e)))return!1;const c=[...Object.keys(t),...Ou(t)],u=[...Object.keys(e),...Ou(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const f=e[h];if(!Di(d,f,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function PD(t,e){return OD(t,e,eD)}var $D=Object.defineProperty,Au=Object.getOwnPropertySymbols,AD=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,Do=(t,e,r)=>e in t?$D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xu=(t,e)=>{for(var r in e||(e={}))AD.call(e,r)&&Do(t,r,e[r]);if(Au)for(var r of Au(e))xD.call(e,r)&&Do(t,r,e[r]);return t},Ue=(t,e,r)=>Do(t,typeof e!="symbol"?e+"":e,r);class mr extends zE{constructor(e,r,i,s=Ot,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,Ue(this,"map",new Map),Ue(this,"version",T_),Ue(this,"cached",[]),Ue(this,"initialized",!1),Ue(this,"getKey"),Ue(this,"storagePrefix",Ot),Ue(this,"recentlyDeleted",[]),Ue(this,"recentlyDeletedLimit",200),Ue(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Oe(o)?this.map.set(this.getKey(o),o):i1(o)?this.map.set(o.id,o):s1(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ue(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Ue(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ue(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>PD(a[c],o[c]))):this.values)),Ue(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=xu(xu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ue(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Te(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var CD=Object.defineProperty,TD=(t,e,r)=>e in t?CD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,K=(t,e,r)=>TD(t,typeof e!="symbol"?e+"":e,r);class RD{constructor(e,r){this.core=e,this.logger=r,K(this,"name",B_),K(this,"version",j_),K(this,"events",new Us),K(this,"pairings"),K(this,"initialized",!1),K(this,"storagePrefix",Ot),K(this,"ignoredPayloadTypes",[Lt]),K(this,"registeredMethods",[]),K(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),K(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),K(this,"create",async i=>{this.isInitialized();const s=po(),n=await this.core.crypto.setSymKey(s),o=pe(N.FIVE_MINUTES),a={protocol:bd},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=Lc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(ar.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:u}}),K(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Et.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:u}=jc(i.uri);s.props.properties.topic=n,s.addTrace(Et.pairing_uri_validation_success),s.addTrace(Et.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),s.addTrace(Et.existing_pairing),l.active)throw s.setError(Rt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(Et.pairing_not_expired)}const h=c||pe(N.FIVE_MINUTES),d={topic:n,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(n,h),await this.pairings.set(n,d),s.addTrace(Et.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(ar.create,d),s.addTrace(Et.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(Et.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Rt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw s.setError(Rt.subscribe_pairing_topic_failure),f}return s.addTrace(Et.subscribe_pairing_topic_success),d}),K(this,"activate",async({topic:i})=>{this.isInitialized();const s=pe(N.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),K(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=ir();this.events.once(X("pairing_ping",n),({error:u})=>{u?c(u):a()}),await o()}}),K(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),K(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),K(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),K(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))}),K(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return Lc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),K(this,"sendRequest",async(i,s,n)=>{const o=Bt(s,n),a=await this.core.crypto.encode(i,o),c=mi[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),K(this,"sendResult",async(i,s,n)=>{const o=Zi(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=mi[c].res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),K(this,"sendError",async(i,s,n)=>{const o=Qi(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=mi[c]?mi[c].res:mi.unregistered_method.res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),K(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),K(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>zt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),K(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),K(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),K(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(ar.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),K(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{ft(s)?this.events.emit(X("pairing_ping",n),{}):Ye(s)&&this.events.emit(X("pairing_ping",n),{error:s.error})},500)}),K(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(ar.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),K(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),K(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),K(this,"isValidPair",(i,s)=>{var n;if(!Me(i)){const{message:a}=F("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(!r1(i.uri)){const{message:a}=F("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(Rt.malformed_pairing_uri),new Error(a)}const o=jc(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(Rt.pairing_expired);const{message:a}=F("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),K(this,"isValidPing",async i=>{if(!Me(i)){const{message:n}=F("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),K(this,"isValidDisconnect",async i=>{if(!Me(i)){const{message:n}=F("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),K(this,"isValidPairingTopic",async i=>{if(!de(i,!1)){const{message:s}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(zt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=F("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=Te(r,this.name),this.pairings=new mr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return je(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(be.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);Zs(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):Xi(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(nt.expired,async e=>{const{topic:r}=_h(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(ar.expire,{topic:r}))})}}var ND=Object.defineProperty,FD=(t,e,r)=>e in t?ND(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>FD(t,typeof e!="symbol"?e+"":e,r);class BD extends UE{constructor(e,r){super(e,r),this.core=e,this.logger=r,Se(this,"records",new Map),Se(this,"events",new He.EventEmitter),Se(this,"name",L_),Se(this,"version",U_),Se(this,"cached",[]),Se(this,"initialized",!1),Se(this,"storagePrefix",Ot),Se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Se(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:pe(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ut.created,o)}),Se(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=Ye(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(ut.updated,s))}),Se(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),Se(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(ut.deleted,n)}}),this.persist()}),Se(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),Se(this,"on",(i,s)=>{this.events.on(i,s)}),Se(this,"once",(i,s)=>{this.events.once(i,s)}),Se(this,"off",(i,s)=>{this.events.off(i,s)}),Se(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Te(r,this.name)}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Bt(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ut.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ut.created,e=>{const r=ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ut.updated,e=>{const r=ut.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ut.deleted,e=>{const r=ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Qt.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{N.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ut.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jD=Object.defineProperty,LD=(t,e,r)=>e in t?jD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ce=(t,e,r)=>LD(t,typeof e!="symbol"?e+"":e,r);class UD extends VE{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ce(this,"expirations",new Map),Ce(this,"events",new He.EventEmitter),Ce(this,"name",k_),Ce(this,"version",M_),Ce(this,"cached",[]),Ce(this,"initialized",!1),Ce(this,"storagePrefix",Ot),Ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ce(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Ce(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(nt.created,{target:n,expiration:o})}),Ce(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Ce(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(nt.deleted,{target:s,expiration:n})}}),Ce(this,"on",(i,s)=>{this.events.on(i,s)}),Ce(this,"once",(i,s)=>{this.events.once(i,s)}),Ce(this,"off",(i,s)=>{this.events.off(i,s)}),Ce(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Te(r,this.name)}get context(){return je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return nb(e);if(typeof e=="number")return ob(e);const{message:r}=F("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(nt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;N.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(nt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Qt.pulse,()=>this.checkExpirations()),this.events.on(nt.created,e=>{const r=nt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(nt.expired,e=>{const r=nt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(nt.deleted,e=>{const r=nt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kD=Object.defineProperty,MD=(t,e,r)=>e in t?kD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,he=(t,e,r)=>MD(t,typeof e!="symbol"?e+"":e,r);class qD extends KE{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,he(this,"name",q_),he(this,"abortController"),he(this,"isDevEnv"),he(this,"verifyUrlV3",H_),he(this,"storagePrefix",Ot),he(this,"version",wd),he(this,"publicKey"),he(this,"fetchPromise"),he(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),he(this,"register",async s=>{if(!ni()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const u=exports.getDocument_1(),l=this.startAbortTimer(N.ONE_SECOND*5),h=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(y),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",p,{signal:this.abortController.signal});const w=v=>{if(v.data&&typeof v.data=="string")try{const b=JSON.parse(v.data);if(b.type==="verify_attestation"){if($s(b.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};u.body.appendChild(y),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),he(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if($s(n).payload.id!==a)return;const u=await this.isValidJwtAttestation(n);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),he(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(N.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),he(this,"getVerifyUrl",s=>{let n=s||Pi;return V_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Pi}`),n=Pi),n}),he(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(N.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),he(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),he(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),he(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),he(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),he(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),he(this,"validateAttestation",(s,n)=>{const o=F0(s,n.publicKey),a={hasExpired:N.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Te(r,this.name),this.abortController=new AbortController,this.isDevEnv=Ko(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return je(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}}var zD=Object.defineProperty,HD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cu=(t,e,r)=>HD(t,typeof e!="symbol"?e+"":e,r);class VD extends WE{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Cu(this,"context",K_),Cu(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${W_}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=Te(r,this.context)}}var KD=Object.defineProperty,Tu=Object.getOwnPropertySymbols,WD=Object.prototype.hasOwnProperty,GD=Object.prototype.propertyIsEnumerable,So=(t,e,r)=>e in t?KD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vi=(t,e)=>{for(var r in e||(e={}))WD.call(e,r)&&So(t,r,e[r]);if(Tu)for(var r of Tu(e))GD.call(e,r)&&So(t,r,e[r]);return t},ge=(t,e,r)=>So(t,typeof e!="symbol"?e+"":e,r);class YD extends GE{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,ge(this,"context",Y_),ge(this,"storagePrefix",Ot),ge(this,"storageVersion",G_),ge(this,"events",new Map),ge(this,"shouldPersist",!1),ge(this,"init",async()=>{if(!Ko())try{const s={eventId:ac(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:vh(this.core.relayer.protocol,this.core.relayer.version,mo)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),ge(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,u=ac(),l=this.core.projectId||"",h=Date.now(),d=vi({eventId:u,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,d),this.shouldPersist=!0),d}),ge(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return vi(vi({},a),this.setMethods(a.eventId))}),ge(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),ge(this,"setEventListeners",()=>{this.core.heartbeat.on(Qt.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(s.timestamp)>J_&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),ge(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),ge(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),ge(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),ge(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ge(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,vi(vi({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),ge(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),ge(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Z_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${mo}${n}`,{method:"POST",body:JSON.stringify(s)})}),ge(this,"getAppDomain",()=>bh().url),this.logger=Te(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var JD=Object.defineProperty,Ru=Object.getOwnPropertySymbols,ZD=Object.prototype.hasOwnProperty,QD=Object.prototype.propertyIsEnumerable,Oo=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nu=(t,e)=>{for(var r in e||(e={}))ZD.call(e,r)&&Oo(t,r,e[r]);if(Ru)for(var r of Ru(e))QD.call(e,r)&&Oo(t,r,e[r]);return t},oe=(t,e,r)=>Oo(t,typeof e!="symbol"?e+"":e,r);let XD=class Td extends FE{constructor(e){var r;super(e),oe(this,"protocol",md),oe(this,"version",wd),oe(this,"name",yo),oe(this,"relayUrl"),oe(this,"projectId"),oe(this,"customStoragePrefix"),oe(this,"events",new He.EventEmitter),oe(this,"logger"),oe(this,"heartbeat"),oe(this,"relayer"),oe(this,"crypto"),oe(this,"storage"),oe(this,"history"),oe(this,"expirer"),oe(this,"pairing"),oe(this,"verify"),oe(this,"echoClient"),oe(this,"linkModeSupportedApps"),oe(this,"eventClient"),oe(this,"initialized",!1),oe(this,"logChunkController"),oe(this,"on",(a,c)=>this.events.on(a,c)),oe(this,"once",(a,c)=>this.events.once(a,c)),oe(this,"off",(a,c)=>this.events.off(a,c)),oe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),oe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ce.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||vd,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Ji({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:b_.logger,name:yo}),{logger:n,chunkLoggerController:o}=ud({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Te(n,this.name),this.heartbeat=new sd,this.crypto=new OI(this,this.logger,e==null?void 0:e.keychain),this.history=new BD(this,this.logger),this.expirer=new UD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new nE(Nu(Nu({},v_),e==null?void 0:e.storageOptions)),this.relayer=new XI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new RD(this,this.logger),this.verify=new qD(this,this.logger,this.storage),this.echoClient=new VD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new YD(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Td(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(R_,i),r}get context(){return je(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(pu,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(pu)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const eS=XD,Rd="wc",Nd=2,Fd="client",ra=`${Rd}@${Nd}:${Fd}:`,Bn={name:Fd,logger:"error"},Fu="WALLETCONNECT_DEEPLINK_CHOICE",tS="proposal",Bu="Proposal expired",rS="session",$r=N.SEVEN_DAYS,iS="engine",ye={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},jn={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},vt={idle:"IDLE",active:"ACTIVE"},ju={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},sS="request",nS=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],oS="wc",aS="auth",cS="authKeys",uS="pairingTopics",lS="requests",Xs=`${oS}@${1.5}:${aS}:`,Ds=`${Xs}:PUB_KEY`;var hS=Object.defineProperty,dS=Object.defineProperties,pS=Object.getOwnPropertyDescriptors,Lu=Object.getOwnPropertySymbols,fS=Object.prototype.hasOwnProperty,gS=Object.prototype.propertyIsEnumerable,Po=(t,e,r)=>e in t?hS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e)=>{for(var r in e||(e={}))fS.call(e,r)&&Po(t,r,e[r]);if(Lu)for(var r of Lu(e))gS.call(e,r)&&Po(t,r,e[r]);return t},Ne=(t,e)=>dS(t,pS(e)),R=(t,e,r)=>Po(t,typeof e!="symbol"?e+"":e,r);class yS extends QE{constructor(e){super(e),R(this,"name",iS),R(this,"events",new Us),R(this,"initialized",!1),R(this,"requestQueue",{state:vt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:vt.idle,queue:[]}),R(this,"requestQueueDelay",N.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(ye)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Ne(se({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=Z0(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=i;let l=s,h,d=!1;try{if(l){const A=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),A}if(!l||!d){const{topic:A,uri:P}=await this.client.core.pairing.create();l=A,h=P}if(!l){const{message:A}=F("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(A)}const f=await this.client.core.crypto.generateKeyPair(),p=ye.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,y=pe(p),w=Ne(se(se({requiredNamespaces:n,optionalNamespaces:o,relays:u??[{protocol:bd}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:pt()}),v=X("session_connect",w.id),{reject:b,resolve:E,done:I}=ir(p,Bu),$=({id:A})=>{A===w.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(w.id),this.events.emit(v,{error:{message:Bu,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(v,({error:A,session:P})=>{this.client.events.off("proposal_expire",$),A?b(A):P&&E(P)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:h,approval:I}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),R(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[lt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(S){throw o.setError(tr.no_internet_connection),S}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(S){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(tr.proposal_not_found),S}try{await this.isValidApprove(r)}catch(S){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(tr.session_approve_namespace_validation_failure),S}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:y,requiredNamespaces:w,optionalNamespaces:v}=f;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:lt.session_approve_started,properties:{topic:p,trace:[lt.session_approve_started,lt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),I=y.publicKey,$=await this.client.core.crypto.generateSharedKey(E,I),A=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:pe($r)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),P=ce.relay;b.addTrace(lt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:P})}catch(S){throw b.setError(tr.subscribe_session_topic_failure),S}b.addTrace(lt.subscribe_session_topic_success);const C=Ne(se({},A),{topic:$,requiredNamespaces:w,optionalNamespaces:v,pairingTopic:p,acknowledged:!1,self:A.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:ce.relay});await this.client.session.set($,C),b.addTrace(lt.store_session);try{b.addTrace(lt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:A,throwOnFailedPublish:!0}).catch(S=>{throw b==null||b.setError(tr.session_settle_publish_failure),S}),b.addTrace(lt.session_settle_publish_success),b.addTrace(lt.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(S=>{throw b==null||b.setError(tr.session_approve_publish_failure),S}),b.addTrace(lt.session_approve_publish_success)}catch(S){throw this.client.logger.error(S),this.client.session.delete($,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),S}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:y.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry($,pe($r)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:s,rpcOpts:ye.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:s}=r,{done:n,resolve:o,reject:a}=ir(),c=pt(),u=Kt().toString(),l=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:n}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,s=pt(),{done:n,resolve:o,reject:a}=ir();return this.events.once(X("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,pe($r)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:i,request:s,topic:n,expiry:o=ye.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ce.relay&&await this.confirmOnlineStateOrThrow();const c=pt(),u=Kt().toString(),{done:l,resolve:h,reject:d}=ir(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:v,result:b})=>{v?d(v):h(b)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:f,params:{request:Ne(se({},s),{expiryTimestamp:pe(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(v=>d(v)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await l();const y={request:Ne(se({},s),{expiryTimestamp:pe(o)}),chainId:i},w=this.shouldSetTVF(f,y);return await Promise.all([new Promise(async v=>{await this.sendRequest(se({clientRpcId:c,relayRpcId:u,topic:n,method:f,params:y,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,y)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),v()}),new Promise(async v=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const E=await lb(this.client.core.storage,Fu);await ab({id:c,topic:n,wcDeepLink:E})}v()}),l()]).then(v=>v[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:s}=r,{id:n}=s,o=this.client.session.get(i);o.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);ft(s)?await this.sendResult({id:n,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:a}):Ye(s)&&await this.sendError({id:n,topic:i,error:s.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=pt(),n=Kt().toString(),{done:o,resolve:a,reject:c}=ir();this.events.once(X("session_ping",s),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=Kt().toString(),a=pt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=F("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>e1(i,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:f,nbf:p,methods:y=[],expiry:w}=r,v=[...r.resources||[]],{topic:b,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:E}});const I=await this.client.core.crypto.generateKeyPair(),$=vs(I);if(await Promise.all([this.client.auth.authKeys.set(Ds,{responseTopic:$,publicKey:I}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:b})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),y.length>0){const{namespace:D}=Wr(a[0]);let x=rv(D,"request",y);bs(v)&&(x=sv(x,v.pop())),v.push(x)}const A=w&&w>ye.wc_sessionAuthenticate.req.ttl?w:ye.wc_sessionAuthenticate.req.ttl,P={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:f,nbf:p,resources:v},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:pe(A)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},S={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:pe(ye.wc_sessionPropose.req.ttl),id:pt()},{done:M,resolve:j,reject:B}=ir(A,"Request expired"),q=pt(),T=X("session_connect",S.id),g=X("session_request",q),m=async({error:D,session:x})=>{this.events.off(g,_),D?B(D):x&&j({session:x})},_=async D=>{var x,L,k;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),D.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===Y.code?void 0:(this.events.off(T,m),B(D.error.message))}await this.deleteProposal(S.id),this.events.off(T,m);const{cacaos:z,responder:U}=D.result,H=[],G=[];for(const Y of z){await gc({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),B(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:xe}=Y,_e=bs(xe.resources),Re=[io(xe.iss)],tt=xs(xe.iss);if(_e){const rt=yc(_e),br=mc(_e);H.push(...rt),Re.push(...br)}for(const rt of Re)G.push(`${rt}:${tt}`)}const ne=await this.client.core.crypto.generateSharedKey(I,U.publicKey);let ee;H.length>0&&(ee={topic:ne,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:pe($r),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:qc([...new Set(H)],[...new Set(G)]),transportType:o},await this.client.core.relayer.subscribe(ne,{transportType:o}),await this.client.session.set(ne,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:U.metadata}),ee=this.client.session.get(ne)),(x=this.client.metadata.redirect)!=null&&x.linkMode&&(L=U.metadata.redirect)!=null&&L.linkMode&&(k=U.metadata.redirect)!=null&&k.universal&&i&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(ne,{transportType:ce.link_mode})),j({auths:z,session:ee})};this.events.once(T,m),this.events.once(g,_);let O;try{if(n){const D=Bt("wc_sessionAuthenticate",P,q);this.client.core.history.set(b,D);const x=await this.client.core.crypto.encode("",D,{type:Gi,encoding:Ht});O=cs(i,b,x)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:P,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:S,expiry:ye.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:S.id})])}catch(D){throw this.events.off(T,m),this.events.off(g,_),D}return await this.setProposal(S.id,S),await this.setAuthRequest(q,{request:Ne(se({},P),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:O??E,response:M}}),R(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[rr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw n.setError(wi.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(wi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=vs(c),h={type:Lt,receiverPublicKey:c,senderPublicKey:u},d=[],f=[];for(const w of s){if(!await gc({cacao:w,projectId:this.client.core.projectId})){n.setError(wi.invalid_cacao);const $=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:$,encodeOpts:h}),new Error($.message)}n.addTrace(rr.cacaos_verified);const{p:v}=w,b=bs(v.resources),E=[io(v.iss)],I=xs(v.iss);if(b){const $=yc(b),A=mc(b);d.push(...$),E.push(...A)}for(const $ of E)f.push(`${$}:${I}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);n.addTrace(rr.create_authenticated_session_topic);let y;if((d==null?void 0:d.length)>0){y={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:pe($r),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:qc([...new Set(d)],[...new Set(f)]),transportType:a},n.addTrace(rr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw n.setError(wi.subscribe_authenticated_session_topic_failure),w}n.addTrace(rr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,y),n.addTrace(rr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(rr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:s,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw n.setError(wi.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=vs(o),u={type:Lt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:u,rpcOpts:ye.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return Ch(i,s)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),R(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(Fu).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===s&&this.deletePendingSessionRequest(u.id,te("USER_DISCONNECTED"))}),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=vt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),R(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(tr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=vt.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),R(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,pe(ye.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),R(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=ce.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||pe(ye.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=Bt(s,n,c);let f;const p=!!l;try{const v=p?Ht:gt;f=await this.client.core.crypto.encode(i,d,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),v}let y;if(nS.includes(s)){const v=_t(JSON.stringify(d)),b=_t(f);y=await this.client.core.verify.register({id:b,decryptedId:v})}const w=ye[s].req;if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(i,d),p){const v=cs(l,i,f);await global.Linking.openURL(v,this.client.name)}else{const v=ye[s].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Ne(se({},h),{correlationId:d.id}),u?(v.internal=Ne(se({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,v)):this.client.core.relayer.publish(i,f,v).catch(b=>this.client.logger.error(b))}return d.id}),R(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=Zi(i,n);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Ht:gt;l=await this.client.core.crypto.encode(s,u,Ne(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,f;try{d=await this.client.core.history.get(s,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(i,p.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),p}if(h){const p=cs(c,s,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,y=ye[p].res;y.tvf=Ne(se({},f),{correlationId:i}),o?(y.internal=Ne(se({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,l,y)):this.client.core.relayer.publish(s,l,y).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=Qi(i,n);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?Ht:gt;l=await this.client.core.crypto.encode(s,u,Ne(se({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),f}let d;try{d=await this.client.core.history.get(s,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),f}if(h){const f=cs(c,s,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||ye[f].res;this.client.core.relayer.publish(s,l,p)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;zt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{zt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===vt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=vt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=vt.idle}),R(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=F("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(Rt.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const l=a.expiryTimestamp||pe(ye.wc_sessionPropose.req.ttl),h=se({id:c,pairingTopic:i,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:n,hash:_t(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});u==null||u.addTrace(Et.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:ye.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(ft(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:r,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(Ye(i)){await this.client.proposal.delete(n,te("USER_DISCONNECTED"));const o=X("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),R(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=i.params,f=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(f.proposalId),y=Ne(se(se(se({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(X("session_connect",f.proposalId),{session:y}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;ft(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(X("session_approve",s),{})):Ye(i)&&(await this.client.session.delete(r,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",s),{error:i.error}))}),R(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=yi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:r},s));try{yi.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw yi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=X("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ft(i)?this.events.emit(X("session_update",s),{}):Ye(i)&&this.events.emit(X("session_update",s),{error:i.error})}),R(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,pe($r)),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),R(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=X("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ft(i)?this.events.emit(X("session_extend",s),{}):Ye(i)&&this.events.emit(X("session_extend",s),{error:i.error})}),R(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),R(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=X("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);ft(i)?this.events.emit(X("session_ping",s),{}):Ye(i)&&this.events.emit(X("session_ping",s),{error:i.error})},500)}),R(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(be.publish,async()=>{n(await this.deleteSession({topic:r,id:s}))})}),this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),R(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(se({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:_t(JSON.stringify(Bt("wc_sessionRequest",d,h))),encryptedId:u,metadata:f.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(y),l===ce.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=f.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(f){await this.sendError({id:h,topic:o,error:f}),this.client.logger.error(f)}}),R(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=X("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);ft(i)?this.events.emit(X("session_request",s),{result:i.result}):Ye(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=yi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),yi.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),ft(i)?this.events.emit(X("session_request",s),{result:i.result}):Ye(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=n.params,d=await this.getVerifyContext({attestationId:o,hash:_t(JSON.stringify(n)),encryptedId:a,metadata:u.metadata,transportType:c}),f={requester:u,pairingTopic:s,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:f,pairingTopic:s,transportType:c}),c===ce.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:Lt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:u,encodeOpts:f,rpcOpts:ye.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=vt.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",n.request.id),{error:i})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===vt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=vt.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Bt("wc_sessionPropose",Ne(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),R(this,"isValidConnect",async r=>{if(!Me(r)){const{message:u}=F("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Oe(i)||await this.isValidPairingTopic(i),!d1(c)){const{message:u}=F("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Oe(s)&&Gt(s)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(s,"requiredNamespaces")}if(!Oe(n)&&Gt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,i)=>{const s=h1(r,"connect()",i);if(s)throw new Error(s.message)}),R(this,"isValidApprove",async r=>{if(!Me(r))throw new Error(F("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=$n(s,"approve()");if(u)throw new Error(u.message);const l=Vc(c.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!de(n,!0)){const{message:h}=F("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Me(r)){const{message:n}=F("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!f1(s)){const{message:n}=F("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Me(r)){const{message:u}=F("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!id(i)){const{message:u}=F("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=n1(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=$n(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(zt(o)){const{message:u}=F("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Me(r)){const{message:c}=F("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=$n(s,"update()");if(o)throw new Error(o.message);const a=Vc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Me(r)){const{message:s}=F("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),R(this,"isValidRequest",async r=>{if(!Me(r)){const{message:c}=F("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!Hc(a,n)){const{message:c}=F("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!g1(s)){const{message:c}=F("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!w1(a,n,s.method)){const{message:c}=F("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!_1(o,jn)){const{message:c}=F("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${jn.min} and ${jn.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var i;if(!Me(r)){const{message:o}=F("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(o){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),o}if(!y1(n)){const{message:o}=F("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Me(r)){const{message:s}=F("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidEmit",async r=>{if(!Me(r)){const{message:a}=F("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!Hc(o,n)){const{message:a}=F("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!m1(s)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!b1(o,n,s.name)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Me(r)){const{message:s}=F("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!de(s,!1))throw new Error("uri is required parameter");if(!de(n,!1))throw new Error("domain is required parameter");if(!de(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Wr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Wr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Pi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=F("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),R(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),R(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,u,l,h,d;return!r||i!==ce.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r==null?void 0:r.redirect)==null?void 0:l.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((d=r==null?void 0:r.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r==null?void 0:r.redirect)==null?void 0:s.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=oc(r,"topic")||"",s=decodeURIComponent(oc(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),R(this,"registerLinkModeListeners",async()=>{var r;if(Ko()||Jt()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),R(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:s}=i;return Object.keys(ju).includes(s.method)}),R(this,"getTVFParams",(r,i,s)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,s);return Ne(se({correlationId:r,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,i)=>{try{const s=ju[r];if(typeof i=="string")return[i];const n=i[s.key];if(yt(n))return r==="solana_signAllTransactions"?n.map(o=>qb(o)):n;if(typeof n=="string")return[n]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(be.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Ds)?this.client.auth.authKeys.get(Ds):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===ce.link_mode?Ht:gt});Zs(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:_t(i)})):Xi(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(nt.expired,async e=>{const{topic:r,id:i}=_h(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,F("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,F("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(ar.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ar.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!de(e,!1)){const{message:r}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(zt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=F("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!de(e,!1)){const{message:r}=F("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=F("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(zt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=F("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=F("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(de(e,!1)){const{message:r}=F("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=F("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!p1(e)){const{message:r}=F("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=F("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(zt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=F("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class mS extends mr{constructor(e,r){super(e,r,tS,ra),this.core=e,this.logger=r}}let wS=class extends mr{constructor(e,r){super(e,r,rS,ra),this.core=e,this.logger=r}};class bS extends mr{constructor(e,r){super(e,r,sS,ra,i=>i.id),this.core=e,this.logger=r}}class vS extends mr{constructor(e,r){super(e,r,cS,Xs,()=>Ds),this.core=e,this.logger=r}}class ES extends mr{constructor(e,r){super(e,r,uS,Xs),this.core=e,this.logger=r}}class _S extends mr{constructor(e,r){super(e,r,lS,Xs,i=>i.id),this.core=e,this.logger=r}}var IS=Object.defineProperty,DS=(t,e,r)=>e in t?IS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ln=(t,e,r)=>DS(t,typeof e!="symbol"?e+"":e,r);class SS{constructor(e,r){this.core=e,this.logger=r,Ln(this,"authKeys"),Ln(this,"pairingTopics"),Ln(this,"requests"),this.authKeys=new vS(this.core,this.logger),this.pairingTopics=new ES(this.core,this.logger),this.requests=new _S(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var OS=Object.defineProperty,PS=(t,e,r)=>e in t?OS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>PS(t,typeof e!="symbol"?e+"":e,r);let $S=class Bd extends ZE{constructor(e){super(e),W(this,"protocol",Rd),W(this,"version",Nd),W(this,"name",Bn.name),W(this,"metadata"),W(this,"core"),W(this,"logger"),W(this,"events",new He.EventEmitter),W(this,"engine"),W(this,"session"),W(this,"proposal"),W(this,"pendingRequest"),W(this,"auth"),W(this,"signConfig"),W(this,"on",(i,s)=>this.events.on(i,s)),W(this,"once",(i,s)=>this.events.once(i,s)),W(this,"off",(i,s)=>this.events.off(i,s)),W(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),W(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),W(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),W(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),W(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||Bn.name,this.metadata=tb(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:ui(Ji({level:(e==null?void 0:e.logger)||Bn.logger}));this.core=(e==null?void 0:e.core)||new eS(e),this.logger=Te(r,this.name),this.session=new wS(this.core,this.logger),this.proposal=new mS(this.core,this.logger),this.pendingRequest=new bS(this.core,this.logger),this.engine=new yS(this),this.auth=new SS(this.core,this.logger)}static async init(e){const r=new Bd(e);return await r.initialize(),r}get context(){return je(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var $o={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof ze.commonjsGlobal<"u"&&ze.commonjsGlobal,i=function(){function n(){this.fetch=!1,this.DOMException=r.DOMException}return n.prototype=r,new n}();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof ze.commonjsGlobal<"u"&&ze.commonjsGlobal||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function u(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(g){return g&&l.indexOf(Object.prototype.toString.call(g))>-1};function d(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function f(g){return typeof g!="string"&&(g=String(g)),g}function p(g){var m={next:function(){var _=g.shift();return{done:_===void 0,value:_}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function y(g){this.map={},g instanceof y?g.forEach(function(m,_){this.append(_,m)},this):Array.isArray(g)?g.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(m){this.append(m,g[m])},this)}y.prototype.append=function(g,m){g=d(g),m=f(m);var _=this.map[g];this.map[g]=_?_+", "+m:m},y.prototype.delete=function(g){delete this.map[d(g)]},y.prototype.get=function(g){return g=d(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(d(g))},y.prototype.set=function(g,m){this.map[d(g)]=f(m)},y.prototype.forEach=function(g,m){for(var _ in this.map)this.map.hasOwnProperty(_)&&g.call(m,this.map[_],_,this)},y.prototype.keys=function(){var g=[];return this.forEach(function(m,_){g.push(_)}),p(g)},y.prototype.values=function(){var g=[];return this.forEach(function(m){g.push(m)}),p(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(m,_){g.push([_,m])}),p(g)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function w(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function v(g){return new Promise(function(m,_){g.onload=function(){m(g.result)},g.onerror=function(){_(g.error)}})}function b(g){var m=new FileReader,_=v(m);return m.readAsArrayBuffer(g),_}function E(g){var m=new FileReader,_=v(m),O=/charset=([A-Za-z0-9_-]+)/.exec(g.type),D=O?O[1]:"utf-8";return m.readAsText(g,D),_}function I(g){for(var m=new Uint8Array(g),_=new Array(m.length),O=0;O<m.length;O++)_[O]=String.fromCharCode(m[O]);return _.join("")}function $(g){if(g.slice)return g.slice(0);var m=new Uint8Array(g.byteLength);return m.set(new Uint8Array(g)),m.buffer}function A(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&u(g)?(this._bodyArrayBuffer=$(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=$(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var g=w(this);return g||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(b);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(I(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var P=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function C(g){var m=g.toUpperCase();return P.indexOf(m)>-1?m:g}function S(g,m){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var _=m.body;if(g instanceof S){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,m.headers||(this.headers=new y(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!_&&g._bodyInit!=null&&(_=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new y(m.headers)),this.method=C(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var x=new AbortController;return x.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var O=/([?&])_=[^&]*/;if(O.test(this.url))this.url=this.url.replace(O,"$1_="+new Date().getTime());else{var D=/\?/;this.url+=(D.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}S.prototype.clone=function(){return new S(this,{body:this._bodyInit})};function M(g){var m=new FormData;return g.trim().split("&").forEach(function(_){if(_){var O=_.split("="),D=O.shift().replace(/\+/g," "),x=O.join("=").replace(/\+/g," ");m.append(decodeURIComponent(D),decodeURIComponent(x))}}),m}function j(g){var m=new y,_=g.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function(O){return O.indexOf(`
25
- `)===0?O.substr(1,O.length):O}).forEach(function(O){var D=O.split(":"),x=D.shift().trim();if(x){var L=D.join(":").trim();try{m.append(x,L)}catch(k){console.warn("Response "+k.message)}}}),m}A.call(S.prototype);function B(g,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new y(m.headers),this.url=m.url||"",this._initBody(g)}A.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},B.error=function(){var g=new B(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];B.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var O=Error(m);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function T(g,m){return new Promise(function(_,O){var D=new S(g,m);if(D.signal&&D.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function L(){x.abort()}x.onload=function(){var U={statusText:x.statusText,headers:j(x.getAllResponseHeaders()||"")};D.url.indexOf("file://")===0&&(x.status<200||x.status>599)?U.status=200:U.status=x.status,U.url="responseURL"in x?x.responseURL:U.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new B(H,U))},0)},x.onerror=function(){setTimeout(function(){O(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){O(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){O(new o.DOMException("Aborted","AbortError"))},0)};function k(U){try{return U===""&&a.location.href?a.location.href:U}catch{return U}}if(x.open(D.method,k(D.url),!0),D.credentials==="include"?x.withCredentials=!0:D.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(U){z.push(d(U)),x.setRequestHeader(U,f(m.headers[U]))}),D.headers.forEach(function(U,H){z.indexOf(H)===-1&&x.setRequestHeader(H,U)})}else D.headers.forEach(function(U,H){x.setRequestHeader(H,U)});D.signal&&(D.signal.addEventListener("abort",L),x.onreadystatechange=function(){x.readyState===4&&D.signal.removeEventListener("abort",L)}),x.send(typeof D._bodyInit>"u"?null:D._bodyInit)})}return T.polyfill=!0,a.fetch||(a.fetch=T,a.Headers=y,a.Request=S,a.Response=B),o.Headers=y,o.Request=S,o.Response=B,o.fetch=T,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})($o,$o.exports);var AS=$o.exports;const Uu=ze.getDefaultExportFromCjs(AS);var xS=Object.defineProperty,CS=Object.defineProperties,TS=Object.getOwnPropertyDescriptors,ku=Object.getOwnPropertySymbols,RS=Object.prototype.hasOwnProperty,NS=Object.prototype.propertyIsEnumerable,Mu=(t,e,r)=>e in t?xS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qu=(t,e)=>{for(var r in e||(e={}))RS.call(e,r)&&Mu(t,r,e[r]);if(ku)for(var r of ku(e))NS.call(e,r)&&Mu(t,r,e[r]);return t},zu=(t,e)=>CS(t,TS(e));const FS={Accept:"application/json","Content-Type":"application/json"},BS="POST",Hu={headers:FS,method:BS},Vu=10;let ot=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new He.EventEmitter,this.isAvailable=!1,this.registering=!1,!au(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=St(e),i=await(await Uu(this.url,zu(qu({},Hu),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!au(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=St({id:1,jsonrpc:"2.0",method:"test",params:[]});await Uu(e,zu(qu({},Hu),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Yt(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Qi(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dd(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Vu&&this.events.setMaxListeners(Vu)}};const Ku="error",jS="wss://relay.walletconnect.org",LS="wc",US="universal_provider",ds=`${LS}@2:${US}:`,jd="https://rpc.walletconnect.org/v1/",Mr="generic",kS=`${jd}bundler`,at={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function MS(){}function ia(t){return t==null||typeof t!="object"&&typeof t!="function"}function sa(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function qS(t){if(ia(t))return t;if(Array.isArray(t)||sa(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Wu(t){return typeof t=="object"&&t!==null}function Ld(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ud(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const zS="[object RegExp]",kd="[object String]",Md="[object Number]",qd="[object Boolean]",zd="[object Arguments]",HS="[object Symbol]",VS="[object Date]",KS="[object Map]",WS="[object Set]",GS="[object Array]",YS="[object ArrayBuffer]",JS="[object Object]",ZS="[object DataView]",QS="[object Uint8Array]",XS="[object Uint8ClampedArray]",eO="[object Uint16Array]",tO="[object Uint32Array]",rO="[object Int8Array]",iO="[object Int16Array]",sO="[object Int32Array]",nO="[object Float32Array]",oO="[object Float64Array]";function aO(t,e){return Hr(t,void 0,t,new Map,e)}function Hr(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(ia(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Hr(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Hr(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(sa(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),cr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),cr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),cr(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,cr(o,t,r,i,s),o}if(typeof t=="object"&&cO(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),cr(o,t,r,i,s),o}return t}function cr(t,e,r=t,i,s){const n=[...Object.keys(e),...Ld(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Hr(e[a],a,r,i,s))}}function cO(t){switch(Ud(t)){case zd:case GS:case YS:case ZS:case qd:case VS:case nO:case oO:case rO:case iO:case sO:case KS:case Md:case JS:case zS:case WS:case kd:case HS:case QS:case XS:case eO:case tO:return!0;default:return!1}}function uO(t,e){return aO(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Md:case kd:case qd:{const o=new t.constructor(t==null?void 0:t.valueOf());return cr(o,t),o}case zd:{const o={};return cr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Gu(t){return uO(t)}function Yu(t){return t!==null&&typeof t=="object"&&Ud(t)==="[object Arguments]"}function lO(t){return sa(t)}function hO(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function dO(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Ao(s,o,i,new Map)}return s}function Ao(t,e,r,i){if(ia(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return qS(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...Ld(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(Yu(a)&&(a={...a}),Yu(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Gu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const f=h[d];l[f]=c[f]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||Wu(c)&&Wu(a)?t[o]=Ao(c,a,r,i):c==null&&hO(a)?t[o]=Ao({},a,r,i):c==null&&lO(a)?t[o]=Gu(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function pO(t,...e){return dO(t,...e,MS)}var fO=Object.defineProperty,gO=Object.defineProperties,yO=Object.getOwnPropertyDescriptors,Ju=Object.getOwnPropertySymbols,mO=Object.prototype.hasOwnProperty,wO=Object.prototype.propertyIsEnumerable,Zu=(t,e,r)=>e in t?fO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ps=(t,e)=>{for(var r in e||(e={}))mO.call(e,r)&&Zu(t,r,e[r]);if(Ju)for(var r of Ju(e))wO.call(e,r)&&Zu(t,r,e[r]);return t},bO=(t,e)=>gO(t,yO(e));function Xe(t,e,r){var i;const s=Wr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${jd}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function wr(t){return t.includes(":")?t.split(":")[1]:t}function Hd(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function vO(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function fs(t={},e={}){const r=Qu(t),i=Qu(e);return pO(r,i)}function Qu(t){var e,r,i,s,n;const o={};if(!Gt(t))return o;for(const[a,c]of Object.entries(t)){const u=Ys(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},f=zr(a);o[f]=bO(ps(ps({},o[f]),c),{chains:It(u,(e=o[f])==null?void 0:e.chains),methods:It(l,(r=o[f])==null?void 0:r.methods),events:It(h,(i=o[f])==null?void 0:i.events)}),(Gt(d)||Gt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=ps(ps({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Xu(t){return t.includes(":")?t.split(":")[2]:t}function el(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ys(r)?[r]:i.chains?i.chains:Hd(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Un(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const Vd={},Q=t=>Vd[t],kn=(t,e)=>{Vd[t]=e};var EO=Object.defineProperty,_O=(t,e,r)=>e in t?EO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e,r)=>_O(t,typeof e!="symbol"?e+"":e,r);class IO{constructor(e){Ar(this,"name","polkadot"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var DO=Object.defineProperty,SO=Object.defineProperties,OO=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,PO=Object.prototype.hasOwnProperty,$O=Object.prototype.propertyIsEnumerable,xo=(t,e,r)=>e in t?DO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rl=(t,e)=>{for(var r in e||(e={}))PO.call(e,r)&&xo(t,r,e[r]);if(tl)for(var r of tl(e))$O.call(e,r)&&xo(t,r,e[r]);return t},il=(t,e)=>SO(t,OO(e)),xr=(t,e,r)=>xo(t,typeof e!="symbol"?e+"":e,r);class AO{constructor(e){xr(this,"name","eip155"),xr(this,"client"),xr(this,"chainId"),xr(this,"namespace"),xr(this,"httpProviders"),xr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(wr(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h==null?void 0:h[u];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:il(rl({},l.sessionProperties||{}),{capabilities:il(rl({},h||{}),{[u]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const s=this.client.session.get(e.topic),n=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Bt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${kS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var xO=Object.defineProperty,CO=(t,e,r)=>e in t?xO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cr=(t,e,r)=>CO(t,typeof e!="symbol"?e+"":e,r);class TO{constructor(e){Cr(this,"name","solana"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var RO=Object.defineProperty,NO=(t,e,r)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>NO(t,typeof e!="symbol"?e+"":e,r);class FO{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var BO=Object.defineProperty,jO=(t,e,r)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>jO(t,typeof e!="symbol"?e+"":e,r);class LO{constructor(e){Rr(this,"name","algorand"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new et(new ot(i,Q("disableProviderPing")))}}var UO=Object.defineProperty,kO=(t,e,r)=>e in t?UO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>kO(t,typeof e!="symbol"?e+"":e,r);class MO{constructor(e){Nr(this,"name","cip34"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),s=wr(r);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var qO=Object.defineProperty,zO=(t,e,r)=>e in t?qO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>zO(t,typeof e!="symbol"?e+"":e,r);class HO{constructor(e){Fr(this,"name","elrond"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var VO=Object.defineProperty,KO=(t,e,r)=>e in t?VO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>KO(t,typeof e!="symbol"?e+"":e,r);class WO{constructor(e){Br(this,"name","multiversx"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var GO=Object.defineProperty,YO=(t,e,r)=>e in t?GO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>YO(t,typeof e!="symbol"?e+"":e,r);class JO{constructor(e){jr(this,"name","near"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new et(new ot(i,Q("disableProviderPing")))}}var ZO=Object.defineProperty,QO=(t,e,r)=>e in t?ZO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>QO(t,typeof e!="symbol"?e+"":e,r);class XO{constructor(e){Lr(this,"name","tezos"),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new et(new ot(i))}}var eP=Object.defineProperty,tP=(t,e,r)=>e in t?eP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>tP(t,typeof e!="symbol"?e+"":e,r);class rP{constructor(e){Ur(this,"name",Mr),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{const n=Wr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var iP=Object.defineProperty,sP=Object.defineProperties,nP=Object.getOwnPropertyDescriptors,sl=Object.getOwnPropertySymbols,oP=Object.prototype.hasOwnProperty,aP=Object.prototype.propertyIsEnumerable,Co=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gs=(t,e)=>{for(var r in e||(e={}))oP.call(e,r)&&Co(t,r,e[r]);if(sl)for(var r of sl(e))aP.call(e,r)&&Co(t,r,e[r]);return t},Mn=(t,e)=>sP(t,nP(e)),st=(t,e,r)=>Co(t,typeof e!="symbol"?e+"":e,r);let cP=class Kd{constructor(e){st(this,"client"),st(this,"namespaces"),st(this,"optionalNamespaces"),st(this,"sessionProperties"),st(this,"scopedProperties"),st(this,"events",new Us),st(this,"rpcProviders",{}),st(this,"session"),st(this,"providerOpts"),st(this,"logger"),st(this,"uri"),st(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:ui(Ji({level:(e==null?void 0:e.logger)||Ku})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new Kd(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:gs({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,Zi(n,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=el(this.session.namespaces);this.namespaces=fs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();this.session=s;const n=el(s.namespaces);return this.namespaces=fs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Mr?n.setDefaultChain(`${i}:${s}`,r):n.setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(yt(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,r;if(this.client=this.providerOpts.client||await $S.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ku,relayUrl:this.providerOpts.relayUrl||jS,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>zr(r)))];kn("client",this.client),kn("events",this.events),kn("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=vO(r,this.session),s=Hd(i),n=fs(this.namespaces,this.optionalNamespaces),o=Mn(gs({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new AO({namespace:o});break;case"algorand":this.rpcProviders[r]=new LO({namespace:o});break;case"solana":this.rpcProviders[r]=new TO({namespace:o});break;case"cosmos":this.rpcProviders[r]=new FO({namespace:o});break;case"polkadot":this.rpcProviders[r]=new IO({namespace:o});break;case"cip34":this.rpcProviders[r]=new MO({namespace:o});break;case"elrond":this.rpcProviders[r]=new HO({namespace:o});break;case"multiversx":this.rpcProviders[r]=new WO({namespace:o});break;case"near":this.rpcProviders[r]=new JO({namespace:o});break;case"tezos":this.rpcProviders[r]=new XO({namespace:o});break;default:this.rpcProviders[Mr]?this.rpcProviders[Mr].updateNamespace(o):this.rpcProviders[Mr]=new rP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&yt(o)&&this.events.emit("accountsChanged",o.map(Xu))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=zr(o),u=Un(o)!==Un(a)?`${c}:${Un(a)}`:o;this.onChainChanged(u)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Mn(gs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Mn(gs({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(at.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Mr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=fs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>zr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=zr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var s,n;try{if(r===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Xu);if(!yt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ds}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ds}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ds}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ds)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const uP=cP,lP="wc",hP="ethereum_provider",dP=`${lP}@2:${hP}:`,pP="https://rpc.walletconnect.org/v1/",Fs=["eth_sendTransaction","personal_sign"],Wd=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Bs=["chainChanged","accountsChanged"],Gd=["chainChanged","accountsChanged","message","disconnect","connect"],fP=async()=>{const{createAppKit:t}=await Promise.resolve().then(()=>require("./core-BdUBRviB.js")).then(e=>e.core);return t};var gP=Object.defineProperty,yP=Object.defineProperties,mP=Object.getOwnPropertyDescriptors,nl=Object.getOwnPropertySymbols,wP=Object.prototype.hasOwnProperty,bP=Object.prototype.propertyIsEnumerable,To=(t,e,r)=>e in t?gP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sr=(t,e)=>{for(var r in e||(e={}))wP.call(e,r)&&To(t,r,e[r]);if(nl)for(var r of nl(e))bP.call(e,r)&&To(t,r,e[r]);return t},Ei=(t,e)=>yP(t,mP(e)),Ke=(t,e,r)=>To(t,typeof e!="symbol"?e+"":e,r);function js(t){return Number(t[0].split(":")[1])}function ys(t){return`0x${t.toString(16)}`}function vP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!yt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Fs,events:n||Bs,rpcMap:sr({},e.length?{[js(e)]:a[js(e)]}:{})},u=n==null?void 0:n.filter(f=>!Bs.includes(f)),l=i==null?void 0:i.filter(f=>!Fs.includes(f));if(!r&&!o&&!s&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!r,d={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Wd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Gd))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class en{constructor(){Ke(this,"events",new He.EventEmitter),Ke(this,"namespace","eip155"),Ke(this,"accounts",[]),Ke(this,"signer"),Ke(this,"chainId",1),Ke(this,"modal"),Ke(this,"rpc"),Ke(this,"STORAGE_KEY",dP),Ke(this,"on",(e,r)=>(this.events.on(e,r),this)),Ke(this,"once",(e,r)=>(this.events.once(e,r),this)),Ke(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Ke(this,"off",(e,r)=>(this.events.off(e,r),this)),Ke(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new en;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=vP(this.rpc);try{const n=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Ei(sr({namespaces:sr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=tc(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ys(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Ei(sr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=tc(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ys(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ys(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ei(sr({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ys(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Fs:[],c=s.length?(e==null?void 0:e.events)||Bs:[],u=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?js(this.rpc.chains):js(this.rpc.optionalChains),this.signer=await uP.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const i=await fP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return CP}),n=s(Ei(sr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");r=i(Ei(sr({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&yt(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&yt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${pP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const EP=en;var _P=Object.defineProperty,IP=Object.defineProperties,DP=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertySymbols,SP=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,al=(t,e,r)=>e in t?_P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yd=(t,e)=>{for(var r in e||(e={}))SP.call(e,r)&&al(t,r,e[r]);if(ol)for(var r of ol(e))OP.call(e,r)&&al(t,r,e[r]);return t},PP=(t,e)=>IP(t,DP(e));function $P(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const AP=t=>{const[e,r]=t.split(":");return Jd({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function xP(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(AP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:$P(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:PP(Yd({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=h.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function Jd(t){return Yd({formatters:void 0,fees:void 0,serializers:void 0},t)}var CP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:xP,defineChain:Jd});const TP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:EP,OPTIONAL_EVENTS:Gd,OPTIONAL_METHODS:Wd,REQUIRED_EVENTS:Bs,REQUIRED_METHODS:Fs,default:en},Symbol.toStringTag,{value:"Module"}));exports.A=ud;exports.C=mh;exports.E=Te;exports.Hash=Cl;exports.IEvents=Zt;exports.Nt=Us;exports.Ot=ui;exports.Po=eo;exports.Qe=Vo;exports.Qo=hh;exports.abytes=ki;exports.aexists=Gn;exports.ahash=Df;exports.aoutput=xl;exports.cjs=N;exports.clear=ll;exports.concat=Kr;exports.concatBytes=Bf;exports.createStore=Ro;exports.createView=Tf;exports.del=ul;exports.destr=Ii;exports.detect=vl;exports.eventsExports=He;exports.f=yd;exports.f$1=ot;exports.formatJsonRpcError=Qi;exports.formatJsonRpcRequest=Bt;exports.formatJsonRpcResult=Zi;exports.fromString=Ze;exports.get=qn;exports.getBigIntRpcId=Kt;exports.i=sd;exports.index_es=TP;exports.isJsonRpcError=Ye;exports.isJsonRpcRequest=Zs;exports.isJsonRpcResponse=Xi;exports.isJsonRpcResult=ft;exports.k=Ji;exports.keys=hl;exports.o=et;exports.payloadId=pt;exports.r=Qt;exports.randomBytes=jf;exports.rotr=Rf;exports.safeJsonParse=Yt;exports.safeJsonStringify=St;exports.set=cl;exports.sn=$s;exports.toBytes=Bo;exports.toString=Fe;exports.wrapConstructor=Tl;exports.y=je;
25
+ `)===0?O.substr(1,O.length):O}).forEach(function(O){var D=O.split(":"),x=D.shift().trim();if(x){var L=D.join(":").trim();try{m.append(x,L)}catch(k){console.warn("Response "+k.message)}}}),m}A.call(S.prototype);function B(g,m){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new y(m.headers),this.url=m.url||"",this._initBody(g)}A.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},B.error=function(){var g=new B(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];B.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new B(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var O=Error(m);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function T(g,m){return new Promise(function(_,O){var D=new S(g,m);if(D.signal&&D.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function L(){x.abort()}x.onload=function(){var U={statusText:x.statusText,headers:j(x.getAllResponseHeaders()||"")};D.url.indexOf("file://")===0&&(x.status<200||x.status>599)?U.status=200:U.status=x.status,U.url="responseURL"in x?x.responseURL:U.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new B(H,U))},0)},x.onerror=function(){setTimeout(function(){O(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){O(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){O(new o.DOMException("Aborted","AbortError"))},0)};function k(U){try{return U===""&&a.location.href?a.location.href:U}catch{return U}}if(x.open(D.method,k(D.url),!0),D.credentials==="include"?x.withCredentials=!0:D.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(U){z.push(d(U)),x.setRequestHeader(U,f(m.headers[U]))}),D.headers.forEach(function(U,H){z.indexOf(H)===-1&&x.setRequestHeader(H,U)})}else D.headers.forEach(function(U,H){x.setRequestHeader(H,U)});D.signal&&(D.signal.addEventListener("abort",L),x.onreadystatechange=function(){x.readyState===4&&D.signal.removeEventListener("abort",L)}),x.send(typeof D._bodyInit>"u"?null:D._bodyInit)})}return T.polyfill=!0,a.fetch||(a.fetch=T,a.Headers=y,a.Request=S,a.Response=B),o.Headers=y,o.Request=S,o.Response=B,o.fetch=T,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})($o,$o.exports);var AS=$o.exports;const Uu=ze.getDefaultExportFromCjs(AS);var xS=Object.defineProperty,CS=Object.defineProperties,TS=Object.getOwnPropertyDescriptors,ku=Object.getOwnPropertySymbols,RS=Object.prototype.hasOwnProperty,NS=Object.prototype.propertyIsEnumerable,Mu=(t,e,r)=>e in t?xS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qu=(t,e)=>{for(var r in e||(e={}))RS.call(e,r)&&Mu(t,r,e[r]);if(ku)for(var r of ku(e))NS.call(e,r)&&Mu(t,r,e[r]);return t},zu=(t,e)=>CS(t,TS(e));const FS={Accept:"application/json","Content-Type":"application/json"},BS="POST",Hu={headers:FS,method:BS},Vu=10;let ot=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new He.EventEmitter,this.isAvailable=!1,this.registering=!1,!au(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=St(e),i=await(await Uu(this.url,zu(qu({},Hu),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!au(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=St({id:1,jsonrpc:"2.0",method:"test",params:[]});await Uu(e,zu(qu({},Hu),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Yt(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Qi(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dd(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Vu&&this.events.setMaxListeners(Vu)}};const Ku="error",jS="wss://relay.walletconnect.org",LS="wc",US="universal_provider",ds=`${LS}@2:${US}:`,jd="https://rpc.walletconnect.org/v1/",Mr="generic",kS=`${jd}bundler`,at={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function MS(){}function ia(t){return t==null||typeof t!="object"&&typeof t!="function"}function sa(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function qS(t){if(ia(t))return t;if(Array.isArray(t)||sa(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Wu(t){return typeof t=="object"&&t!==null}function Ld(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ud(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const zS="[object RegExp]",kd="[object String]",Md="[object Number]",qd="[object Boolean]",zd="[object Arguments]",HS="[object Symbol]",VS="[object Date]",KS="[object Map]",WS="[object Set]",GS="[object Array]",YS="[object ArrayBuffer]",JS="[object Object]",ZS="[object DataView]",QS="[object Uint8Array]",XS="[object Uint8ClampedArray]",eO="[object Uint16Array]",tO="[object Uint32Array]",rO="[object Int8Array]",iO="[object Int16Array]",sO="[object Int32Array]",nO="[object Float32Array]",oO="[object Float64Array]";function aO(t,e){return Hr(t,void 0,t,new Map,e)}function Hr(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(ia(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Hr(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Hr(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(sa(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),cr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),cr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),cr(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,cr(o,t,r,i,s),o}if(typeof t=="object"&&cO(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),cr(o,t,r,i,s),o}return t}function cr(t,e,r=t,i,s){const n=[...Object.keys(e),...Ld(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Hr(e[a],a,r,i,s))}}function cO(t){switch(Ud(t)){case zd:case GS:case YS:case ZS:case qd:case VS:case nO:case oO:case rO:case iO:case sO:case KS:case Md:case JS:case zS:case WS:case kd:case HS:case QS:case XS:case eO:case tO:return!0;default:return!1}}function uO(t,e){return aO(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Md:case kd:case qd:{const o=new t.constructor(t==null?void 0:t.valueOf());return cr(o,t),o}case zd:{const o={};return cr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Gu(t){return uO(t)}function Yu(t){return t!==null&&typeof t=="object"&&Ud(t)==="[object Arguments]"}function lO(t){return sa(t)}function hO(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function dO(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Ao(s,o,i,new Map)}return s}function Ao(t,e,r,i){if(ia(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return qS(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...Ld(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(Yu(a)&&(a={...a}),Yu(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Gu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const f=h[d];l[f]=c[f]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||Wu(c)&&Wu(a)?t[o]=Ao(c,a,r,i):c==null&&hO(a)?t[o]=Ao({},a,r,i):c==null&&lO(a)?t[o]=Gu(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function pO(t,...e){return dO(t,...e,MS)}var fO=Object.defineProperty,gO=Object.defineProperties,yO=Object.getOwnPropertyDescriptors,Ju=Object.getOwnPropertySymbols,mO=Object.prototype.hasOwnProperty,wO=Object.prototype.propertyIsEnumerable,Zu=(t,e,r)=>e in t?fO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ps=(t,e)=>{for(var r in e||(e={}))mO.call(e,r)&&Zu(t,r,e[r]);if(Ju)for(var r of Ju(e))wO.call(e,r)&&Zu(t,r,e[r]);return t},bO=(t,e)=>gO(t,yO(e));function Xe(t,e,r){var i;const s=Wr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${jd}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function wr(t){return t.includes(":")?t.split(":")[1]:t}function Hd(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function vO(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function fs(t={},e={}){const r=Qu(t),i=Qu(e);return pO(r,i)}function Qu(t){var e,r,i,s,n;const o={};if(!Gt(t))return o;for(const[a,c]of Object.entries(t)){const u=Ys(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],d=c.rpcMap||{},f=zr(a);o[f]=bO(ps(ps({},o[f]),c),{chains:It(u,(e=o[f])==null?void 0:e.chains),methods:It(l,(r=o[f])==null?void 0:r.methods),events:It(h,(i=o[f])==null?void 0:i.events)}),(Gt(d)||Gt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=ps(ps({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Xu(t){return t.includes(":")?t.split(":")[2]:t}function el(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ys(r)?[r]:i.chains?i.chains:Hd(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Un(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const Vd={},Q=t=>Vd[t],kn=(t,e)=>{Vd[t]=e};var EO=Object.defineProperty,_O=(t,e,r)=>e in t?EO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e,r)=>_O(t,typeof e!="symbol"?e+"":e,r);class IO{constructor(e){Ar(this,"name","polkadot"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var DO=Object.defineProperty,SO=Object.defineProperties,OO=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,PO=Object.prototype.hasOwnProperty,$O=Object.prototype.propertyIsEnumerable,xo=(t,e,r)=>e in t?DO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rl=(t,e)=>{for(var r in e||(e={}))PO.call(e,r)&&xo(t,r,e[r]);if(tl)for(var r of tl(e))$O.call(e,r)&&xo(t,r,e[r]);return t},il=(t,e)=>SO(t,OO(e)),xr=(t,e,r)=>xo(t,typeof e!="symbol"?e+"":e,r);class AO{constructor(e){xr(this,"name","eip155"),xr(this,"client"),xr(this,"chainId"),xr(this,"namespace"),xr(this,"httpProviders"),xr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(wr(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],u=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),h=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[u])return h==null?void 0:h[u];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:il(rl({},l.sessionProperties||{}),{capabilities:il(rl({},h||{}),{[u]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const s=this.client.session.get(e.topic),n=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Bt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${kS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var xO=Object.defineProperty,CO=(t,e,r)=>e in t?xO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cr=(t,e,r)=>CO(t,typeof e!="symbol"?e+"":e,r);class TO{constructor(e){Cr(this,"name","solana"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var RO=Object.defineProperty,NO=(t,e,r)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>NO(t,typeof e!="symbol"?e+"":e,r);class FO{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var BO=Object.defineProperty,jO=(t,e,r)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>jO(t,typeof e!="symbol"?e+"":e,r);class LO{constructor(e){Rr(this,"name","algorand"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new et(new ot(i,Q("disableProviderPing")))}}var UO=Object.defineProperty,kO=(t,e,r)=>e in t?UO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>kO(t,typeof e!="symbol"?e+"":e,r);class MO{constructor(e){Nr(this,"name","cip34"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),s=wr(r);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var qO=Object.defineProperty,zO=(t,e,r)=>e in t?qO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>zO(t,typeof e!="symbol"?e+"":e,r);class HO{constructor(e){Fr(this,"name","elrond"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var VO=Object.defineProperty,KO=(t,e,r)=>e in t?VO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>KO(t,typeof e!="symbol"?e+"":e,r);class WO{constructor(e){Br(this,"name","multiversx"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var GO=Object.defineProperty,YO=(t,e,r)=>e in t?GO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>YO(t,typeof e!="symbol"?e+"":e,r);class JO{constructor(e){jr(this,"name","near"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new et(new ot(i,Q("disableProviderPing")))}}var ZO=Object.defineProperty,QO=(t,e,r)=>e in t?ZO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>QO(t,typeof e!="symbol"?e+"":e,r);class XO{constructor(e){Lr(this,"name","tezos"),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Xe(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace);return typeof i>"u"?void 0:new et(new ot(i))}}var eP=Object.defineProperty,tP=(t,e,r)=>e in t?eP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>tP(t,typeof e!="symbol"?e+"":e,r);class rP{constructor(e){Ur(this,"name",Mr),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(at.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{const n=Wr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Xe(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new et(new ot(i,Q("disableProviderPing")))}}var iP=Object.defineProperty,sP=Object.defineProperties,nP=Object.getOwnPropertyDescriptors,sl=Object.getOwnPropertySymbols,oP=Object.prototype.hasOwnProperty,aP=Object.prototype.propertyIsEnumerable,Co=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gs=(t,e)=>{for(var r in e||(e={}))oP.call(e,r)&&Co(t,r,e[r]);if(sl)for(var r of sl(e))aP.call(e,r)&&Co(t,r,e[r]);return t},Mn=(t,e)=>sP(t,nP(e)),st=(t,e,r)=>Co(t,typeof e!="symbol"?e+"":e,r);let cP=class Kd{constructor(e){st(this,"client"),st(this,"namespaces"),st(this,"optionalNamespaces"),st(this,"sessionProperties"),st(this,"scopedProperties"),st(this,"events",new Us),st(this,"rpcProviders",{}),st(this,"session"),st(this,"providerOpts"),st(this,"logger"),st(this,"uri"),st(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:ui(Ji({level:(e==null?void 0:e.logger)||Ku})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new Kd(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:gs({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,Zi(n,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=el(this.session.namespaces);this.namespaces=fs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();this.session=s;const n=el(s.namespaces);return this.namespaces=fs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Mr?n.setDefaultChain(`${i}:${s}`,r):n.setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(yt(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,r;if(this.client=this.providerOpts.client||await $S.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ku,relayUrl:this.providerOpts.relayUrl||jS,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>zr(r)))];kn("client",this.client),kn("events",this.events),kn("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=vO(r,this.session),s=Hd(i),n=fs(this.namespaces,this.optionalNamespaces),o=Mn(gs({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new AO({namespace:o});break;case"algorand":this.rpcProviders[r]=new LO({namespace:o});break;case"solana":this.rpcProviders[r]=new TO({namespace:o});break;case"cosmos":this.rpcProviders[r]=new FO({namespace:o});break;case"polkadot":this.rpcProviders[r]=new IO({namespace:o});break;case"cip34":this.rpcProviders[r]=new MO({namespace:o});break;case"elrond":this.rpcProviders[r]=new HO({namespace:o});break;case"multiversx":this.rpcProviders[r]=new WO({namespace:o});break;case"near":this.rpcProviders[r]=new JO({namespace:o});break;case"tezos":this.rpcProviders[r]=new XO({namespace:o});break;default:this.rpcProviders[Mr]?this.rpcProviders[Mr].updateNamespace(o):this.rpcProviders[Mr]=new rP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&yt(o)&&this.events.emit("accountsChanged",o.map(Xu))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=zr(o),u=Un(o)!==Un(a)?`${c}:${Un(a)}`:o;this.onChainChanged(u)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Mn(gs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Mn(gs({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(at.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Mr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=fs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>zr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=zr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var s,n;try{if(r===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Xu);if(!yt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ds}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ds}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ds}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ds)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const uP=cP,lP="wc",hP="ethereum_provider",dP=`${lP}@2:${hP}:`,pP="https://rpc.walletconnect.org/v1/",Fs=["eth_sendTransaction","personal_sign"],Wd=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Bs=["chainChanged","accountsChanged"],Gd=["chainChanged","accountsChanged","message","disconnect","connect"],fP=async()=>{const{createAppKit:t}=await Promise.resolve().then(()=>require("./core-CKEBRqJG.js")).then(e=>e.core);return t};var gP=Object.defineProperty,yP=Object.defineProperties,mP=Object.getOwnPropertyDescriptors,nl=Object.getOwnPropertySymbols,wP=Object.prototype.hasOwnProperty,bP=Object.prototype.propertyIsEnumerable,To=(t,e,r)=>e in t?gP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sr=(t,e)=>{for(var r in e||(e={}))wP.call(e,r)&&To(t,r,e[r]);if(nl)for(var r of nl(e))bP.call(e,r)&&To(t,r,e[r]);return t},Ei=(t,e)=>yP(t,mP(e)),Ke=(t,e,r)=>To(t,typeof e!="symbol"?e+"":e,r);function js(t){return Number(t[0].split(":")[1])}function ys(t){return`0x${t.toString(16)}`}function vP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!yt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Fs,events:n||Bs,rpcMap:sr({},e.length?{[js(e)]:a[js(e)]}:{})},u=n==null?void 0:n.filter(f=>!Bs.includes(f)),l=i==null?void 0:i.filter(f=>!Fs.includes(f));if(!r&&!o&&!s&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!r,d={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Wd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Gd))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class en{constructor(){Ke(this,"events",new He.EventEmitter),Ke(this,"namespace","eip155"),Ke(this,"accounts",[]),Ke(this,"signer"),Ke(this,"chainId",1),Ke(this,"modal"),Ke(this,"rpc"),Ke(this,"STORAGE_KEY",dP),Ke(this,"on",(e,r)=>(this.events.on(e,r),this)),Ke(this,"once",(e,r)=>(this.events.once(e,r),this)),Ke(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),Ke(this,"off",(e,r)=>(this.events.off(e,r),this)),Ke(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new en;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=vP(this.rpc);try{const n=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Ei(sr({namespaces:sr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=tc(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ys(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Ei(sr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=tc(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ys(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ys(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",Ei(sr({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ys(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Fs:[],c=s.length?(e==null?void 0:e.events)||Bs:[],u=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?js(this.rpc.chains):js(this.rpc.optionalChains),this.signer=await uP.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const i=await fP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return CP}),n=s(Ei(sr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");r=i(Ei(sr({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&yt(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&yt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${pP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const EP=en;var _P=Object.defineProperty,IP=Object.defineProperties,DP=Object.getOwnPropertyDescriptors,ol=Object.getOwnPropertySymbols,SP=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,al=(t,e,r)=>e in t?_P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yd=(t,e)=>{for(var r in e||(e={}))SP.call(e,r)&&al(t,r,e[r]);if(ol)for(var r of ol(e))OP.call(e,r)&&al(t,r,e[r]);return t},PP=(t,e)=>IP(t,DP(e));function $P(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const AP=t=>{const[e,r]=t.split(":");return Jd({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function xP(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(AP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var d;return h.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:$P(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:PP(Yd({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=h.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function Jd(t){return Yd({formatters:void 0,fees:void 0,serializers:void 0},t)}var CP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:xP,defineChain:Jd});const TP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:EP,OPTIONAL_EVENTS:Gd,OPTIONAL_METHODS:Wd,REQUIRED_EVENTS:Bs,REQUIRED_METHODS:Fs,default:en},Symbol.toStringTag,{value:"Module"}));exports.A=ud;exports.C=mh;exports.E=Te;exports.Hash=Cl;exports.IEvents=Zt;exports.Nt=Us;exports.Ot=ui;exports.Po=eo;exports.Qe=Vo;exports.Qo=hh;exports.abytes=ki;exports.aexists=Gn;exports.ahash=Df;exports.aoutput=xl;exports.cjs=N;exports.clear=ll;exports.concat=Kr;exports.concatBytes=Bf;exports.createStore=Ro;exports.createView=Tf;exports.del=ul;exports.destr=Ii;exports.detect=vl;exports.eventsExports=He;exports.f=yd;exports.f$1=ot;exports.formatJsonRpcError=Qi;exports.formatJsonRpcRequest=Bt;exports.formatJsonRpcResult=Zi;exports.fromString=Ze;exports.get=qn;exports.getBigIntRpcId=Kt;exports.i=sd;exports.index_es=TP;exports.isJsonRpcError=Ye;exports.isJsonRpcRequest=Zs;exports.isJsonRpcResponse=Xi;exports.isJsonRpcResult=ft;exports.k=Ji;exports.keys=hl;exports.o=et;exports.payloadId=pt;exports.r=Qt;exports.randomBytes=jf;exports.rotr=Rf;exports.safeJsonParse=Yt;exports.safeJsonStringify=St;exports.set=cl;exports.sn=$s;exports.toBytes=Bo;exports.toString=Fe;exports.wrapConstructor=Tl;exports.y=je;