@dodoex/wallet-web3 0.6.4 → 0.6.5
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.
- package/dist/PhArrowCircleDown-4a08ae8e.js +14 -0
- package/dist/PhArrowClockwise-401ea1c0.js +14 -0
- package/dist/PhArrowDown-789ae7d2.js +14 -0
- package/dist/PhArrowLeft-2e6d4940.js +14 -0
- package/dist/PhArrowRight-2928b0dc.js +14 -0
- package/dist/PhArrowSquareOut-17d61d08.js +14 -0
- package/dist/PhArrowUp-1cfcf9df.js +14 -0
- package/dist/PhArrowUpRight-552c41cb.js +14 -0
- package/dist/PhArrowsClockwise-92a70162.js +14 -0
- package/dist/PhArrowsDownUp-ce27c8a7.js +14 -0
- package/dist/PhArrowsLeftRight-ed549dc7.js +14 -0
- package/dist/PhBank-92a1a1df.js +14 -0
- package/dist/PhBrowser-495dc3ce.js +14 -0
- package/dist/PhCaretDown-610f20fc.js +14 -0
- package/dist/PhCaretLeft-2a86ee53.js +14 -0
- package/dist/PhCaretRight-f3057f58.js +14 -0
- package/dist/PhCaretUp-7b74b8cb.js +14 -0
- package/dist/PhCheck-c514f32c.js +14 -0
- package/dist/PhCircleHalf-3bfd24c9.js +14 -0
- package/dist/PhClock-29284ead.js +14 -0
- package/dist/PhCompass-101d3241.js +14 -0
- package/dist/PhCopy-d92dcd27.js +14 -0
- package/dist/PhCreditCard-d8d77fc2.js +14 -0
- package/dist/PhCurrencyDollar-6553df79.js +14 -0
- package/dist/PhDesktop-91653c8e.js +14 -0
- package/dist/PhDeviceMobile-0f3d8fa2.js +14 -0
- package/dist/PhDotsThree-67debca2.js +14 -0
- package/dist/PhEnvelope-f83faab2.js +14 -0
- package/dist/PhFunnelSimple-5058af43.js +14 -0
- package/dist/PhGlobe-c4653621.js +14 -0
- package/dist/PhIdentificationCard-848bf9a1.js +14 -0
- package/dist/PhImage-de71fc6b.js +14 -0
- package/dist/PhInfo-9614a766.js +14 -0
- package/dist/PhLightbulb-7d582ae7.js +14 -0
- package/dist/PhMagnifyingGlass-c926bd63.js +14 -0
- package/dist/PhPaperPlaneRight-76b25832.js +14 -0
- package/dist/PhPlus-767ddc55.js +14 -0
- package/dist/PhPower-95f188dd.js +14 -0
- package/dist/PhPuzzlePiece-f016afe5.js +14 -0
- package/dist/PhQrCode-e9b7ab93.js +14 -0
- package/dist/PhQuestion-ea0e639d.js +14 -0
- package/dist/PhQuestionMark-13d6338e.js +14 -0
- package/dist/PhSealCheck-45bb7b9c.js +14 -0
- package/dist/PhSignOut-6b91c59c.js +14 -0
- package/dist/PhSpinner-eb9b7ac1.js +14 -0
- package/dist/PhTrash-758cc3b3.js +14 -0
- package/dist/PhUser-0834861d.js +14 -0
- package/dist/PhVault-e4d6f9af.js +14 -0
- package/dist/PhWallet-5e257abe.js +14 -0
- package/dist/PhWarning-6af3740e.js +14 -0
- package/dist/PhWarningCircle-a78fd8e8.js +14 -0
- package/dist/PhX-60c46532.js +14 -0
- package/dist/{__tslib-83c7dd77.js → __tslib-6d6a586c.js} +1 -1
- package/dist/{alchemy-provider-5870b6fa-ef26112b.js → alchemy-provider-5870b6fa-a9fe5aa5.js} +1 -1
- package/dist/{alchemy-websocket-provider-213da986-2d698146.js → alchemy-websocket-provider-213da986-16164c2e.js} +1 -1
- package/dist/basic-77fe1b96.js +1320 -0
- package/dist/{blocto-05d7faf5.js → blocto-ab8ba330.js} +1 -1
- package/dist/{ccip-ea7099a8.js → ccip-e246f9cf.js} +1 -1
- package/dist/cjs/PhArrowCircleDown-df23d036.cjs +14 -0
- package/dist/cjs/PhArrowClockwise-440d23dc.cjs +14 -0
- package/dist/cjs/PhArrowDown-252590ed.cjs +14 -0
- package/dist/cjs/PhArrowLeft-d480faa4.cjs +14 -0
- package/dist/cjs/PhArrowRight-969dbdd8.cjs +14 -0
- package/dist/cjs/PhArrowSquareOut-eabfdecb.cjs +14 -0
- package/dist/cjs/PhArrowUp-66bd5f15.cjs +14 -0
- package/dist/cjs/PhArrowUpRight-6df3b31b.cjs +14 -0
- package/dist/cjs/PhArrowsClockwise-3a9d2dc6.cjs +14 -0
- package/dist/cjs/PhArrowsDownUp-47a7788f.cjs +14 -0
- package/dist/cjs/PhArrowsLeftRight-f90368dd.cjs +14 -0
- package/dist/cjs/PhBank-670a2708.cjs +14 -0
- package/dist/cjs/PhBrowser-b9c35fd1.cjs +14 -0
- package/dist/cjs/PhCaretDown-11a46455.cjs +14 -0
- package/dist/cjs/PhCaretLeft-04f11ca7.cjs +14 -0
- package/dist/cjs/PhCaretRight-391111c1.cjs +14 -0
- package/dist/cjs/PhCaretUp-b17dccf6.cjs +14 -0
- package/dist/cjs/PhCheck-08bf36b0.cjs +14 -0
- package/dist/cjs/PhCircleHalf-0a9eac35.cjs +14 -0
- package/dist/cjs/PhClock-cf1cc2cb.cjs +14 -0
- package/dist/cjs/PhCompass-e9671b30.cjs +14 -0
- package/dist/cjs/PhCopy-9132cbc5.cjs +14 -0
- package/dist/cjs/PhCreditCard-853e1556.cjs +14 -0
- package/dist/cjs/PhCurrencyDollar-34eea829.cjs +14 -0
- package/dist/cjs/PhDesktop-c02b883b.cjs +14 -0
- package/dist/cjs/PhDeviceMobile-93c2088c.cjs +14 -0
- package/dist/cjs/PhDotsThree-69beaba7.cjs +14 -0
- package/dist/cjs/PhEnvelope-86ee730e.cjs +14 -0
- package/dist/cjs/PhFunnelSimple-056c2f76.cjs +14 -0
- package/dist/cjs/PhGlobe-64c4ee8e.cjs +14 -0
- package/dist/cjs/PhIdentificationCard-ec7a98e0.cjs +14 -0
- package/dist/cjs/PhImage-07904cbb.cjs +14 -0
- package/dist/cjs/PhInfo-34eeeace.cjs +14 -0
- package/dist/cjs/PhLightbulb-39ebe854.cjs +14 -0
- package/dist/cjs/PhMagnifyingGlass-2fbe4400.cjs +14 -0
- package/dist/cjs/PhPaperPlaneRight-e06c210f.cjs +14 -0
- package/dist/cjs/PhPlus-03a04ed3.cjs +14 -0
- package/dist/cjs/PhPower-4cc2ecb8.cjs +14 -0
- package/dist/cjs/PhPuzzlePiece-035d561e.cjs +14 -0
- package/dist/cjs/PhQrCode-37e23b36.cjs +14 -0
- package/dist/cjs/PhQuestion-bfba435e.cjs +14 -0
- package/dist/cjs/PhQuestionMark-8ef38ecf.cjs +14 -0
- package/dist/cjs/PhSealCheck-5458de15.cjs +14 -0
- package/dist/cjs/PhSignOut-2d177ea1.cjs +14 -0
- package/dist/cjs/PhSpinner-e7c590df.cjs +14 -0
- package/dist/cjs/PhTrash-1920f5dc.cjs +14 -0
- package/dist/cjs/PhUser-84a1a685.cjs +14 -0
- package/dist/cjs/PhVault-1493c03f.cjs +14 -0
- package/dist/cjs/PhWallet-f0502f03.cjs +14 -0
- package/dist/cjs/PhWarning-1bf637ba.cjs +14 -0
- package/dist/cjs/PhWarningCircle-b1747661.cjs +14 -0
- package/dist/cjs/PhX-f864d86c.cjs +14 -0
- package/dist/cjs/{__tslib-12e41834.cjs → __tslib-a9f27ba6.cjs} +1 -1
- package/dist/cjs/{alchemy-provider-5870b6fa-683a7f2e.cjs → alchemy-provider-5870b6fa-bb1c607e.cjs} +1 -1
- package/dist/cjs/{alchemy-websocket-provider-213da986-5c9807c6.cjs → alchemy-websocket-provider-213da986-521569b5.cjs} +1 -1
- package/dist/cjs/basic-b777d2b1.cjs +1320 -0
- package/dist/cjs/{blocto-4db38a28.cjs → blocto-09e0d574.cjs} +1 -1
- package/dist/cjs/{ccip-82e883e4.cjs → ccip-6ebee1cf.cjs} +1 -1
- package/dist/cjs/core-78a709db.cjs +210 -0
- package/dist/cjs/{draggabilly-308ac2a9.cjs → draggabilly-76af6217.cjs} +1 -1
- package/dist/cjs/features-fa5c5622.cjs +1 -0
- package/dist/cjs/id-c0538166.cjs +1 -0
- package/dist/cjs/{index-2c097978.cjs → index-07e81389.cjs} +1 -1
- package/dist/cjs/{index-eae76bd0.cjs → index-093cef5a.cjs} +2 -2
- package/dist/cjs/{index-362be9fb.cjs → index-208df3f3.cjs} +1 -1
- package/dist/cjs/{index-c8fa7932.cjs → index-253e7cce.cjs} +1 -1
- package/dist/cjs/index-2e8e7a50.cjs +4 -0
- package/dist/cjs/index-395b933d.cjs +2 -0
- package/dist/cjs/{index-281d00df.cjs → index-54d7fc75.cjs} +1 -1
- package/dist/cjs/{index-3714da35.cjs → index-5d28acf4.cjs} +2 -2
- package/dist/cjs/{index-85a2526e.cjs → index-5dac528b.cjs} +7 -7
- package/dist/cjs/index-702e8f89.cjs +15 -0
- package/dist/cjs/{index-ceda42fb.cjs → index-823e17e6.cjs} +1 -1
- package/dist/cjs/{index-9325806f.cjs → index-916994aa.cjs} +1 -1
- package/dist/cjs/{index-00b0ab99.cjs → index-a2b665f4.cjs} +1 -1
- package/dist/cjs/{index-c6b53b3f.cjs → index-b099293c.cjs} +1 -1
- package/dist/cjs/index-d72ddbc1.cjs +17 -0
- package/dist/cjs/index-ef4ef0cc.cjs +1449 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/{interface-10b0ba33.cjs → interface-4947cfa6.cjs} +1 -1
- package/dist/cjs/{lib-typedarrays-012f607a.cjs → lib-typedarrays-a9baf142.cjs} +1 -1
- package/dist/cjs/native-55bb141d.cjs +1 -0
- package/dist/cjs/{portis-2144bb98.cjs → portis-08d9d731.cjs} +1 -1
- package/dist/cjs/property-29e6f732.cjs +29 -0
- package/dist/cjs/providers/connector/safeGnosis/query.d.ts +2 -1
- package/dist/cjs/providers/connector/types.d.ts +1 -1
- package/dist/cjs/providers/wallets/index.d.ts +1 -0
- package/dist/cjs/rainbow-6e84bcfa.cjs +1 -0
- package/dist/cjs/sha224-b46bc3e6.cjs +1 -0
- package/dist/cjs/sha256-ccd47519.cjs +1 -0
- package/dist/cjs/{typed-data-e878587d.cjs → typed-data-5176b792.cjs} +1 -1
- package/dist/cjs/uAuth-b29d2670.cjs +1 -0
- package/dist/cjs/w3m-modal-70bcf6d8.cjs +2380 -0
- package/dist/cjs/walletConnect-20d477a9.cjs +1 -0
- package/dist/cjs/{walletLink-8e49b6d5.cjs → walletLink-08b8da20.cjs} +2 -2
- package/dist/core-4d7ad6f2.js +210 -0
- package/dist/{draggabilly-c6f65920.js → draggabilly-daf3b444.js} +1 -1
- package/dist/features-d8d1c9ce.js +1 -0
- package/dist/id-d4d22b29.js +1 -0
- package/dist/{index-227927b5.js → index-09298bd0.js} +7 -7
- package/dist/{index-f360d801.js → index-244a8189.js} +1 -1
- package/dist/{index-f4727f94.js → index-2ad0fb2a.js} +1 -1
- package/dist/index-35d87b79.js +17 -0
- package/dist/{index-eb473b84.js → index-587ff998.js} +1 -1
- package/dist/{index-a6b10e09.js → index-750a7dfe.js} +1 -1
- package/dist/{index-abb4eaf1.js → index-8bd12de1.js} +1 -1
- package/dist/{index-1e0435b6.js → index-938686fb.js} +1 -1
- package/dist/{index-1db47472.js → index-9d7fee1e.js} +2 -2
- package/dist/{index-af823ebd.js → index-aa744ca0.js} +1 -1
- package/dist/{index-cfa6ef57.js → index-b7d25e8a.js} +2 -2
- package/dist/index-bb1a0019.js +15 -0
- package/dist/index-c5ca8a4e.js +4 -0
- package/dist/{index-1cf97dd7.js → index-cddbc8e8.js} +1 -1
- package/dist/index-f095c09e.js +2 -0
- package/dist/index-ffdf981b.js +1449 -0
- package/dist/index.js +1 -1
- package/dist/{interface-ec064b7d.js → interface-0c535796.js} +1 -1
- package/dist/{lib-typedarrays-ecebfb2c.js → lib-typedarrays-979d2723.js} +1 -1
- package/dist/native-029c50f7.js +1 -0
- package/dist/{portis-e3d3d420.js → portis-9602ac9f.js} +1 -1
- package/dist/property-8eb37909.js +35 -0
- package/dist/providers/connector/safeGnosis/query.d.ts +2 -1
- package/dist/providers/connector/types.d.ts +1 -1
- package/dist/providers/wallets/index.d.ts +1 -0
- package/dist/rainbow-ccab7a95.js +1 -0
- package/dist/sha224-fe98e1bf.js +1 -0
- package/dist/sha256-5a24dfd5.js +1 -0
- package/dist/{typed-data-0f706378.js → typed-data-3a3d44dc.js} +1 -1
- package/dist/uAuth-27f5728d.js +1 -0
- package/dist/w3m-modal-49add722.js +2380 -0
- package/dist/walletConnect-a541881e.js +1 -0
- package/dist/{walletLink-68441960.js → walletLink-67264328.js} +2 -2
- package/package.json +3 -3
- package/dist/_commonjs-dynamic-modules-7cfc9805.js +0 -1
- package/dist/cjs/_commonjs-dynamic-modules-f09a98c7.cjs +0 -1
- package/dist/cjs/id-ea22b6ce.cjs +0 -1
- package/dist/cjs/index-35edc6a0.cjs +0 -60
- package/dist/cjs/index-8a25465c.cjs +0 -6
- package/dist/cjs/index-9f2a69d5.cjs +0 -1
- package/dist/cjs/index-fdda1836.cjs +0 -17
- package/dist/cjs/index.es-80622213.cjs +0 -9
- package/dist/cjs/rainbow-18d05876.cjs +0 -1
- package/dist/cjs/sha224-1c092a15.cjs +0 -1
- package/dist/cjs/sha256-9e1680c1.cjs +0 -1
- package/dist/cjs/uAuth-b89f7081.cjs +0 -1
- package/dist/cjs/walletConnect-b79e1e97.cjs +0 -1
- package/dist/id-397f0303.js +0 -1
- package/dist/index-02e42cd2.js +0 -17
- package/dist/index-65d96278.js +0 -60
- package/dist/index-89717995.js +0 -6
- package/dist/index-f08d6a6b.js +0 -1
- package/dist/index.es-7adbb6c0.js +0 -9
- package/dist/rainbow-73b82cd7.js +0 -1
- package/dist/sha224-51e5e6a9.js +0 -1
- package/dist/sha256-549e482b.js +0 -1
- package/dist/uAuth-ce19d386.js +0 -1
- package/dist/walletConnect-b0b635de.js +0 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var e=require("events"),t=require("./__tslib-a9f27ba6.cjs"),i=require("./index-5dac528b.cjs");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=s(e),n=function(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r<n;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},o=function(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"},a=function(e){this.version=e,this.type="node",this.name="node",this.os=process.platform},c=function(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"},h=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},l=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},u=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,d=3,f=[["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",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],p=[["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 g(e){return e?y(e):"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new l:"undefined"!=typeof navigator?y(navigator.userAgent):"undefined"!=typeof process&&process.version?new a(process.version.slice(1)):null}function y(e){var t=function(e){return""!==e&&f.reduce((function(t,i){var s=i[0],r=i[1];if(t)return t;var n=r.exec(e);return!!n&&[s,n]}),!1)}(e);if(!t)return null;var i=t[0],s=t[1];if("searchbot"===i)return new h;var r=s[1]&&s[1].split(".").join("_").split("_").slice(0,3);r?r.length<d&&(r=n(n([],r,!0),function(e){for(var t=[],i=0;i<e;i++)t.push("0");return t}(d-r.length),!0)):r=[];var a=r.join("."),l=function(e){for(var t=0,i=p.length;t<i;t++){var s=p[t],r=s[0];if(s[1].exec(e))return r}return null}(e),g=u.exec(e);return g&&g[1]?new c(i,a,l,g[1]):new o(i,a,l)}var w,m={},b={},v={};var E,x={},I={},S={};var _,O,A,P,T={};function R(){return O||(O=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const i=t.require$$0;i.__exportStar((E||(E=1,Object.defineProperty(S,"__esModule",{value:!0}),S.ONE_THOUSAND=S.ONE_HUNDRED=void 0,S.ONE_HUNDRED=100,S.ONE_THOUSAND=1e3),S),e),i.__exportStar((_||(_=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ONE_YEAR=e.FOUR_WEEKS=e.THREE_WEEKS=e.TWO_WEEKS=e.ONE_WEEK=e.THIRTY_DAYS=e.SEVEN_DAYS=e.FIVE_DAYS=e.THREE_DAYS=e.ONE_DAY=e.TWENTY_FOUR_HOURS=e.TWELVE_HOURS=e.SIX_HOURS=e.THREE_HOURS=e.ONE_HOUR=e.SIXTY_MINUTES=e.THIRTY_MINUTES=e.TEN_MINUTES=e.FIVE_MINUTES=e.ONE_MINUTE=e.SIXTY_SECONDS=e.THIRTY_SECONDS=e.TEN_SECONDS=e.FIVE_SECONDS=e.ONE_SECOND=void 0,e.ONE_SECOND=1,e.FIVE_SECONDS=5,e.TEN_SECONDS=10,e.THIRTY_SECONDS=30,e.SIXTY_SECONDS=60,e.ONE_MINUTE=e.SIXTY_SECONDS,e.FIVE_MINUTES=5*e.ONE_MINUTE,e.TEN_MINUTES=10*e.ONE_MINUTE,e.THIRTY_MINUTES=30*e.ONE_MINUTE,e.SIXTY_MINUTES=60*e.ONE_MINUTE,e.ONE_HOUR=e.SIXTY_MINUTES,e.THREE_HOURS=3*e.ONE_HOUR,e.SIX_HOURS=6*e.ONE_HOUR,e.TWELVE_HOURS=12*e.ONE_HOUR,e.TWENTY_FOUR_HOURS=24*e.ONE_HOUR,e.ONE_DAY=e.TWENTY_FOUR_HOURS,e.THREE_DAYS=3*e.ONE_DAY,e.FIVE_DAYS=5*e.ONE_DAY,e.SEVEN_DAYS=7*e.ONE_DAY,e.THIRTY_DAYS=30*e.ONE_DAY,e.ONE_WEEK=e.SEVEN_DAYS,e.TWO_WEEKS=2*e.ONE_WEEK,e.THREE_WEEKS=3*e.ONE_WEEK,e.FOUR_WEEKS=4*e.ONE_WEEK,e.ONE_YEAR=365*e.ONE_DAY}(T)),T),e)}(I)),I}function B(){return P||(P=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const i=t.require$$0;i.__exportStar((w||(w=1,Object.defineProperty(v,"__esModule",{value:!0}),v.delay=void 0,v.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(!0)}),e)}))}),v),e),i.__exportStar(function(){if(A)return x;A=1,Object.defineProperty(x,"__esModule",{value:!0}),x.fromMiliseconds=x.toMiliseconds=void 0;const e=R();return x.toMiliseconds=function(t){return t*e.ONE_THOUSAND},x.fromMiliseconds=function(t){return Math.floor(t/e.ONE_THOUSAND)},x}(),e)}(b)),b}var N,C={};var U,k,L={},q={};function D(){return k||(k=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});t.require$$0.__exportStar((U||(U=1,Object.defineProperty(q,"__esModule",{value:!0}),q.IWatch=void 0,q.IWatch=class{}),q),e)}(L)),L}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const i=t.require$$0;i.__exportStar(B(),e),i.__exportStar(function(){if(N)return C;N=1,Object.defineProperty(C,"__esModule",{value:!0}),C.Watch=void 0;class e{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){const t=this.get(e);if(void 0!==t.elapsed)throw new Error(`Watch already stopped for label: ${e}`);const i=Date.now()-t.started;this.timestamps.set(e,{started:t.started,elapsed:i})}get(e){const t=this.timestamps.get(e);if(void 0===t)throw new Error(`No timestamp found for label: ${e}`);return t}elapsed(e){const t=this.get(e);return t.elapsed||Date.now()-t.started}}return C.Watch=e,C.default=e,C}(),e),i.__exportStar(D(),e),i.__exportStar(R(),e)}(m);var M={};function $(e){let t;return"undefined"!=typeof window&&void 0!==window[e]&&(t=window[e]),t}function j(e){const t=$(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Object.defineProperty(M,"__esModule",{value:!0}),M.getLocalStorage=M.getLocalStorageOrThrow=M.getCrypto=M.getCryptoOrThrow=exports.getLocation_1=M.getLocation=M.getLocationOrThrow=exports.getNavigator_1=M.getNavigator=M.getNavigatorOrThrow=exports.getDocument_1=M.getDocument=M.getDocumentOrThrow=M.getFromWindowOrThrow=M.getFromWindow=void 0,M.getFromWindow=$,M.getFromWindowOrThrow=j,M.getDocumentOrThrow=function(){return j("document")},exports.getDocument_1=M.getDocument=function(){return $("document")},M.getNavigatorOrThrow=function(){return j("navigator")},exports.getNavigator_1=M.getNavigator=function(){return $("navigator")},M.getLocationOrThrow=function(){return j("location")},exports.getLocation_1=M.getLocation=function(){return $("location")},M.getCryptoOrThrow=function(){return j("crypto")},M.getCrypto=function(){return $("crypto")},M.getLocalStorageOrThrow=function(){return j("localStorage")},M.getLocalStorage=function(){return $("localStorage")};var z={};Object.defineProperty(z,"__esModule",{value:!0}),exports.getWindowMetadata_1=z.getWindowMetadata=void 0;const F=M;exports.getWindowMetadata_1=z.getWindowMetadata=function(){let e,t;try{e=F.getDocumentOrThrow(),t=F.getLocationOrThrow()}catch(e){return null}function i(...t){const i=e.getElementsByTagName("meta");for(let e=0;e<i.length;e++){const s=i[e],r=["itemprop","property","name"].map((e=>s.getAttribute(e))).filter((e=>!!e&&t.includes(e)));if(r.length&&r){const e=s.getAttribute("content");if(e)return e}}return""}const s=function(){let t=i("name","og:site_name","og:title","twitter:title");return t||(t=e.title),t}(),r=i("description","og:description","twitter:description","keywords"),n=t.origin,o=function(){const i=e.getElementsByTagName("link"),s=[];for(let e=0;e<i.length;e++){const r=i[e],n=r.getAttribute("rel");if(n&&n.toLowerCase().indexOf("icon")>-1){const e=r.getAttribute("href");if(e)if(-1===e.toLowerCase().indexOf("https:")&&-1===e.toLowerCase().indexOf("http:")&&0!==e.indexOf("//")){let i=t.protocol+"//"+t.host;if(0===e.indexOf("/"))i+=e;else{const s=t.pathname.split("/");s.pop();i+=s.join("/")+"/"+e}s.push(i)}else if(0===e.indexOf("//")){const i=t.protocol+e;s.push(i)}else s.push(e)}}return s}();return{description:r,url:n,icons:o,name:s}};const K=BigInt(2**32-1),V=BigInt(32);function H(e,t=!1){return t?{h:Number(e&K),l:Number(e>>V&K)}:{h:0|Number(e>>V&K),l:0|Number(e&K)}}function W(e,t=!1){const i=e.length;let s=new Uint32Array(i),r=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:o}=H(e[n],t);[s[n],r[n]]=[i,o]}return[s,r]}const G=(e,t,i)=>e>>>i,Y=(e,t,i)=>e<<32-i|t>>>i,Z=(e,t,i)=>e>>>i|t<<32-i,J=(e,t,i)=>e<<32-i|t>>>i,X=(e,t,i)=>e<<64-i|t>>>i-32,Q=(e,t,i)=>e>>>i-32|t<<64-i,ee=(e,t)=>t,te=(e,t)=>e;function ie(e,t,i,s){const r=(t>>>0)+(s>>>0);return{h:e+i+(r/2**32|0)|0,l:0|r}}const se=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),re=(e,t,i,s)=>t+i+s+(e/2**32|0)|0,ne=(e,t,i,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),oe=(e,t,i,s,r)=>t+i+s+r+(e/2**32|0)|0,ae=(e,t,i,s,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0)+(r>>>0),ce=(e,t,i,s,r,n)=>t+i+s+r+n+(e/2**32|0)|0,he="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function le(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ue(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function de(e,...t){if(!le(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function fe(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ue(e.outputLen),ue(e.blockLen)}function pe(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ge(e,t){de(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function ye(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function we(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function me(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function be(e,t){return e<<32-t|e>>>t}const ve=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Ee(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const xe=ve?e=>e:e=>Ee(e);const Ie=ve?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Ee(e[t]);return e},Se=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),_e=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Oe(e){if(de(e),Se)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=_e[e[i]];return t}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Pe(e){return e>=Ae._0&&e<=Ae._9?e-Ae._0:e>=Ae.A&&e<=Ae.F?e-(Ae.A-10):e>=Ae.a&&e<=Ae.f?e-(Ae.a-10):void 0}function Te(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Se)return Uint8Array.fromHex(e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=Pe(e.charCodeAt(r)),n=Pe(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function Re(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),de(e),e}function Be(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];de(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}class Ne{}function Ce(e){const t=t=>e().update(Re(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function Ue(e){const t=(t,i)=>e(i).update(Re(t)).digest(),i=e({});return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}function ke(e=32){if(he&&"function"==typeof he.getRandomValues)return he.getRandomValues(new Uint8Array(e));if(he&&"function"==typeof he.randomBytes)return Uint8Array.from(he.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const Le=BigInt(0),qe=BigInt(1),De=BigInt(2),Me=BigInt(7),$e=BigInt(256),je=BigInt(113),ze=[],Fe=[],Ke=[];for(let e=0,t=qe,i=1,s=0;e<24;e++){[i,s]=[s,(2*i+3*s)%5],ze.push(2*(5*s+i)),Fe.push((e+1)*(e+2)/2%64);let r=Le;for(let e=0;e<7;e++)t=(t<<qe^(t>>Me)*je)%$e,t&De&&(r^=qe<<(qe<<BigInt(e))-qe);Ke.push(r)}const Ve=W(Ke,!0),He=Ve[0],We=Ve[1],Ge=(e,t,i)=>i>32?((e,t,i)=>t<<i-32|e>>>64-i)(e,t,i):((e,t,i)=>e<<i|t>>>32-i)(e,t,i),Ye=(e,t,i)=>i>32?((e,t,i)=>e<<i-32|t>>>64-i)(e,t,i):((e,t,i)=>t<<i|e>>>32-i)(e,t,i);class Ze extends Ne{constructor(e,t,i,s=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=r,ue(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ye(this.state)}clone(){return this._cloneInto()}keccak(){Ie(this.state32),function(e,t=24){const i=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,r=(t+2)%10,n=i[r],o=i[r+1],a=Ge(n,o,1)^i[s],c=Ye(n,o,1)^i[s+1];for(let i=0;i<50;i+=10)e[t+i]^=a,e[t+i+1]^=c}let t=e[2],r=e[3];for(let i=0;i<24;i++){const s=Fe[i],n=Ge(t,r,s),o=Ye(t,r,s),a=ze[i];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)i[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~i[(s+2)%10]&i[(s+4)%10]}e[0]^=He[s],e[1]^=We[s]}we(i)}(this.state32,this.rounds),Ie(this.state32),this.posOut=0,this.pos=0}update(e){pe(this),de(e=Re(e));const{blockLen:t,state:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(t-this.pos,s-r);for(let t=0;t<n;t++)i[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,0!=(128&t)&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){pe(this,!1),de(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,r=e.length;s<r;){this.posOut>=i&&this.keccak();const n=Math.min(i-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ge(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,we(this.state)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:r,enableXOF:n}=this;return e||(e=new Ze(t,i,s,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=i,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Je=(()=>{return e=1,t=136,i=32,Ce((()=>new Ze(t,e,i)));var e,t,i})();class Xe extends Error{constructor(e,t={}){const i=(()=>{if(t.cause instanceof Xe){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&"string"==typeof t.cause.details?t.cause.details:t.cause?.message?t.cause.message:t.details})(),s=t.cause instanceof Xe&&t.cause.docsPath||t.docsPath,r=`https://oxlib.sh${s??""}`,n=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${r}`:void 0]:[]].filter((e=>"string"==typeof e)).join("\n");super(n,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{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,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"ox@0.1.1"}),this.cause=t.cause,this.details=i,this.docs=r,this.docsPath=s,this.shortMessage=e}walk(e){return Qe(this,e)}}function Qe(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&e.cause?Qe(e.cause,t):t?null:e}const et="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function tt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function it(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function st(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function rt(e,t){it(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function nt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ot(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function at(e,t){return e<<32-t|e>>>t}const ct=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let i=0;i<e.length;i++)e[i]=(t=e[i])<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var t;return e};function ht(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),it(e),e}class lt{}function ut(e){const t=t=>e().update(ht(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function dt(e=32){if(et&&"function"==typeof et.getRandomValues)return et.getRandomValues(new Uint8Array(e));if(et&&"function"==typeof et.randomBytes)return Uint8Array.from(et.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ft(e,t,i){return e&t^~e&i}function pt(e,t,i){return e&t^e&i^t&i}class gt extends lt{constructor(e,t,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ot(this.buffer)}update(e){st(this),it(e=ht(e));const{view:t,buffer:i,blockLen:s}=this,r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=ot(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){st(this),rt(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,nt(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=ot(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.destroyed=n,e.finished=r,e.length=s,e.pos=o,s%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const yt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wt=BigInt(2**32-1),mt=BigInt(32);function bt(e,t=!1){return t?{h:Number(e&wt),l:Number(e>>mt&wt)}:{h:0|Number(e>>mt&wt),l:0|Number(e&wt)}}function vt(e,t=!1){const i=e.length;let s=new Uint32Array(i),r=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:o}=bt(e[n],t);[s[n],r[n]]=[i,o]}return[s,r]}const Et=BigInt(0),xt=BigInt(1),It=BigInt(2),St=BigInt(7),_t=BigInt(256),Ot=BigInt(113),At=[],Pt=[],Tt=[];for(let e=0,t=xt,i=1,s=0;e<24;e++){[i,s]=[s,(2*i+3*s)%5],At.push(2*(5*s+i)),Pt.push((e+1)*(e+2)/2%64);let r=Et;for(let e=0;e<7;e++)t=(t<<xt^(t>>St)*Ot)%_t,t&It&&(r^=xt<<(xt<<BigInt(e))-xt);Tt.push(r)}const Rt=vt(Tt,!0),Bt=Rt[0],Nt=Rt[1],Ct=(e,t,i)=>i>32?((e,t,i)=>t<<i-32|e>>>64-i)(e,t,i):((e,t,i)=>e<<i|t>>>32-i)(e,t,i),Ut=(e,t,i)=>i>32?((e,t,i)=>e<<i-32|t>>>64-i)(e,t,i):((e,t,i)=>t<<i|e>>>32-i)(e,t,i);class kt extends lt{constructor(e,t,i,s=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=r,tt(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}clone(){return this._cloneInto()}keccak(){ct(this.state32),function(e,t=24){const i=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,r=(t+2)%10,n=i[r],o=i[r+1],a=Ct(n,o,1)^i[s],c=Ut(n,o,1)^i[s+1];for(let i=0;i<50;i+=10)e[t+i]^=a,e[t+i+1]^=c}let t=e[2],r=e[3];for(let i=0;i<24;i++){const s=Pt[i],n=Ct(t,r,s),o=Ut(t,r,s),a=At[i];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)i[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~i[(s+2)%10]&i[(s+4)%10]}e[0]^=Bt[s],e[1]^=Nt[s]}nt(i)}(this.state32,this.rounds),ct(this.state32),this.posOut=0,this.pos=0}update(e){st(this),it(e=ht(e));const{blockLen:t,state:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(t-this.pos,s-r);for(let t=0;t<n;t++)i[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,0!=(128&t)&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){st(this,!1),it(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,r=e.length;s<r;){this.posOut>=i&&this.keccak();const n=Math.min(i-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return tt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(rt(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,nt(this.state)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:r,enableXOF:n}=this;return e||(e=new kt(t,i,s,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=i,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const Lt=(()=>{return e=1,t=136,i=32,ut((()=>new kt(t,e,i)));var e,t,i})(),qt=Uint32Array.from([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]),Dt=new Uint32Array(64);class Mt extends gt{constructor(e=32){super(64,e,8,!1),this.A=0|yt[0],this.B=0|yt[1],this.C=0|yt[2],this.D=0|yt[3],this.E=0|yt[4],this.F=0|yt[5],this.G=0|yt[6],this.H=0|yt[7]}get(){const{A:e,B:t,C:i,D:s,E:r,F:n,G:o,H:a}=this;return[e,t,i,s,r,n,o,a]}set(e,t,i,s,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|s,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let i=0;i<16;i++,t+=4)Dt[i]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Dt[e-15],i=Dt[e-2],s=at(t,7)^at(t,18)^t>>>3,r=at(i,17)^at(i,19)^i>>>10;Dt[e]=r+Dt[e-7]+s+Dt[e-16]|0}let{A:i,B:s,C:r,D:n,E:o,F:a,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(at(o,6)^at(o,11)^at(o,25))+ft(o,a,c)+qt[e]+Dt[e]|0,l=(at(i,2)^at(i,13)^at(i,22))+pt(i,s,r)|0;h=c,c=a,a=o,o=n+t|0,n=r,r=s,s=i,i=t+l|0}i=i+this.A|0,s=s+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,s,r,n,o,a,c,h)}roundClean(){nt(Dt)}destroy(){this.set(0,0,0,0,0,0,0,0),nt(this.buffer)}}const $t=ut((()=>new Mt)),jt=BigInt(0),zt=BigInt(1);
|
|
2
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ft(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Kt(e){if(!Ft(e))throw new Error("Uint8Array expected")}function Vt(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Ht(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Wt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?jt:BigInt("0x"+e)}const Gt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,Yt=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Zt(e){if(Kt(e),Gt)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=Yt[e[i]];return t}const Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xt(e){return e>=Jt._0&&e<=Jt._9?e-Jt._0:e>=Jt.A&&e<=Jt.F?e-(Jt.A-10):e>=Jt.a&&e<=Jt.f?e-(Jt.a-10):void 0}function Qt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Gt)return Uint8Array.fromHex(e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=Xt(e.charCodeAt(r)),n=Xt(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function ei(e){return Wt(Zt(e))}function ti(e){return Kt(e),Wt(Zt(Uint8Array.from(e).reverse()))}function ii(e,t){return Qt(e.toString(16).padStart(2*t,"0"))}function si(e,t){return ii(e,t).reverse()}function ri(e,t,i){let s;if("string"==typeof t)try{s=Qt(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Ft(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function ni(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Kt(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}const oi=e=>"bigint"==typeof e&&jt<=e;function ai(e,t,i){return oi(e)&&oi(t)&&oi(i)&&t<=e&&e<i}function ci(e,t,i,s){if(!ai(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}const hi=e=>(zt<<BigInt(e))-zt,li=e=>new Uint8Array(e),ui=e=>Uint8Array.from(e);const di={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Ft(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function fi(e,t,i={}){const s=(t,i,s)=>{const r=di[i];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+i+", got "+n)};for(const[e,i]of Object.entries(t))s(e,i,!1);for(const[e,t]of Object.entries(i))s(e,t,!0);return e}function pi(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}function gi(e,t){if(Di(e)>t)throw new ji({givenSize:Di(e),maxSize:t})}const yi={zero:48,nine:57,A:65,F:70,a:97,f:102};function wi(e){return e>=yi.zero&&e<=yi.nine?e-yi.zero:e>=yi.A&&e<=yi.F?e-(yi.A-10):e>=yi.a&&e<=yi.f?e-(yi.a-10):void 0}function mi(e,t){if(Ai(e)>t)throw new Ni({givenSize:Ai(e),maxSize:t})}function bi(e,t={}){const{dir:i,size:s=32}=t;if(0===s)return e;const r=e.replace("0x","");if(r.length>2*s)throw new Ui({size:Math.ceil(r.length/2),targetSize:s,type:"Hex"});return`0x${r["right"===i?"padEnd":"padStart"](2*s,"0")}`}function vi(e,t,i){return JSON.stringify(e,((e,i)=>"function"==typeof t?t(e,i):"bigint"==typeof i?i.toString()+"#__bigint":i),i)}const Ei=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function xi(e){return e instanceof Uint8Array?Ii(e):Array.isArray(e)?Ii(new Uint8Array(e)):e}function Ii(e,t={}){let i="";for(let t=0;t<e.length;t++)i+=Ei[e[t]];const s=`0x${i}`;return"number"==typeof t.size?(mi(s,t.size),_i(s,t.size)):s}function Si(e,t={}){const{signed:i,size:s}=t,r=BigInt(e);let n;s?n=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof n&&i?-n-1n:0;if(n&&r>n||r<o){const t="bigint"==typeof e?"n":"";throw new Ti({max:n?`${n}${t}`:void 0,min:`${o}${t}`,signed:i,size:s,value:`${e}${t}`})}const a=`0x${(i&&r<0?(1n<<BigInt(8*s))+BigInt(r):r).toString(16)}`;return s?function(e,t){return bi(e,{dir:"left",size:t})}(a,s):a}function _i(e,t){return bi(e,{dir:"right",size:t})}function Oi(e,t,i,s={}){const{strict:r}=s;!function(e,t){if("number"==typeof t&&t>0&&t>Ai(e)-1)throw new Ci({offset:t,position:"start",size:Ai(e)})}(e,t);const n=`0x${e.replace("0x","").slice(2*(t??0),2*(i??e.length))}`;return r&&function(e,t,i){if("number"==typeof t&&"number"==typeof i&&Ai(e)!==i-t)throw new Ci({offset:i,position:"end",size:Ai(e)})}(n,t,i),n}function Ai(e){return Math.ceil((e.length-2)/2)}function Pi(e,t={}){const{strict:i=!1}=t;try{return function(e,t={}){const{strict:i=!1}=t;if(!e)throw new Ri(e);if("string"!=typeof e)throw new Ri(e);if(i&&!/^0x[0-9a-fA-F]*$/.test(e))throw new Bi(e);if(!e.startsWith("0x"))throw new Bi(e)}(e,{strict:i}),!0}catch{return!1}}class Ti extends Xe{constructor({max:e,min:t,signed:i,size:s,value:r}){super(`Number \`${r}\` is not in safe${s?` ${8*s}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Ri extends Xe{constructor(e){super(`Value \`${"object"==typeof e?vi(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Bi extends Xe{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class Ni extends Xe{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class Ci extends Xe{constructor({offset:e,position:t,size:i}){super(`Slice ${"start"===t?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class Ui extends Xe{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const ki=new TextEncoder;function Li(e){return e instanceof Uint8Array?e:"string"==typeof e?function(e,t={}){const{size:i}=t;let s=e;i&&(mi(e,i),s=_i(e,i));let r=s.slice(2);r.length%2&&(r=`0${r}`);const n=r.length/2,o=new Uint8Array(n);for(let e=0,t=0;e<n;e++){const i=wi(r.charCodeAt(t++)),s=wi(r.charCodeAt(t++));if(void 0===i||void 0===s)throw new Xe(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);o[e]=16*i+s}return o}(e):function(e){return e instanceof Uint8Array?e:new Uint8Array(e)}(e)}function qi(e,t={}){const{size:i}=t,s=ki.encode(e);return"number"==typeof i?(gi(s,i),function(e,t){return function(e,t={}){const{dir:i,size:s=32}=t;if(0===s)return e;if(e.length>s)throw new zi({size:e.length,targetSize:s,type:"Bytes"});const r=new Uint8Array(s);for(let t=0;t<s;t++){const n="right"===i;r[n?t:s-t-1]=e[n?t:e.length-t-1]}return r}(e,{dir:"right",size:t})}(s,i)):s}function Di(e){return e.length}function Mi(e){try{return function(e){if(!(e instanceof Uint8Array)){if(!e)throw new $i(e);if("object"!=typeof e)throw new $i(e);if(!("BYTES_PER_ELEMENT"in e))throw new $i(e);if(1!==e.BYTES_PER_ELEMENT||"Uint8Array"!==e.constructor.name)throw new $i(e)}}(e),!0}catch{return!1}}class $i extends Xe{constructor(e){super(`Value \`${"object"==typeof e?vi(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class ji extends Xe{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class zi extends Xe{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Fi(e,t={}){const{as:i=("string"==typeof e?"Hex":"Bytes")}=t,s=Lt(Li(e));return"Bytes"===i?s:Ii(s)}class Ki extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const Vi={checksum:new Ki(8192)}.checksum;function Hi(e,t={}){const{compressed:i}=t,{prefix:s,x:r,y:n}=e;if(!1===i||"bigint"==typeof r&&"bigint"==typeof n){if(4!==s)throw new Zi({prefix:s,cause:new Xi})}else{if(!0!==i&&("bigint"!=typeof r||void 0!==n))throw new Yi({publicKey:e});if(3!==s&&2!==s)throw new Zi({prefix:s,cause:new Ji})}}function Wi(e){const t=(()=>{if(Pi(e))return Gi(e);if(Mi(e))return function(e){return Gi(Ii(e))}(e);const{prefix:t,x:i,y:s}=e;return"bigint"==typeof i&&"bigint"==typeof s?{prefix:t??4,x:i,y:s}:{prefix:t,x:i}})();return Hi(t),t}function Gi(e){if(132!==e.length&&130!==e.length&&68!==e.length)throw new Qi({publicKey:e});if(130===e.length){return{prefix:4,x:BigInt(Oi(e,0,32)),y:BigInt(Oi(e,32,64))}}if(132===e.length){return{prefix:Number(Oi(e,0,1)),x:BigInt(Oi(e,1,33)),y:BigInt(Oi(e,33,65))}}return{prefix:Number(Oi(e,0,1)),x:BigInt(Oi(e,1,33))}}class Yi extends Xe{constructor({publicKey:e}){super(`Value \`${vi(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Zi extends Xe{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Ji extends Xe{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Xi extends Xe{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class Qi extends Xe{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Ai(xi(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const es=/^0x[a-fA-F0-9]{40}$/;function ts(e,t={}){const{strict:i=!0}=t;if(!es.test(e))throw new rs({address:e,cause:new ns});if(i){if(e.toLowerCase()===e)return;if(is(e)!==e)throw new rs({address:e,cause:new os})}}function is(e){if(Vi.has(e))return Vi.get(e);ts(e,{strict:!1});const t=e.substring(2).toLowerCase(),i=Fi(qi(t),{as:"Bytes"}),s=t.split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&i[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());const r=`0x${s.join("")}`;return Vi.set(e,r),r}function ss(e,t={}){const i=Fi(`0x${function(e,t={}){Hi(e);const{prefix:i,x:s,y:r}=e,{includePrefix:n=!0}=t,o=function(...e){return`0x${e.reduce(((e,t)=>e+t.replace("0x","")),"")}`}(n?Si(i,{size:1}):"0x",Si(s,{size:32}),"bigint"==typeof r?Si(r,{size:32}):"0x");return o}(e).slice(4)}`).substring(26);return function(e,t={}){const{checksum:i=!1}=t;return ts(e),i?is(e):e}(`0x${i}`,t)}class rs extends Xe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class ns extends Xe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class os extends Xe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class as extends lt{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");tt(e.outputLen),tt(e.blockLen)}(e);const i=ht(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(i.length>s?e.create().update(i).digest():i);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),nt(r)}update(e){return st(this),this.iHash.update(e),this}digestInto(e){st(this),it(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:t,iHash:i,finished:s,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const cs=(e,t,i)=>new as(e,t).update(i).digest();cs.create=(e,t)=>new as(e,t);const hs=BigInt(0),ls=BigInt(1),us=BigInt(2),ds=BigInt(3),fs=BigInt(4),ps=BigInt(5),gs=BigInt(8);function ys(e,t){const i=e%t;return i>=hs?i:t+i}function ws(e,t,i){let s=e;for(;t-- >hs;)s*=s,s%=i;return s}function ms(e,t){if(e===hs)throw new Error("invert: expected non-zero number");if(t<=hs)throw new Error("invert: expected positive modulus, got "+t);let i=ys(e,t),s=t,r=hs,n=ls;for(;i!==hs;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==ls)throw new Error("invert: does not exist");return ys(r,t)}function bs(e,t){const i=(e.ORDER+ls)/fs,s=e.pow(t,i);if(!e.eql(e.sqr(s),t))throw new Error("Cannot find square root");return s}function vs(e,t){const i=(e.ORDER-ps)/gs,s=e.mul(t,us),r=e.pow(s,i),n=e.mul(t,r),o=e.mul(e.mul(n,us),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function Es(e){return e%fs===ds?bs:e%gs===ps?vs:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-ls,i=0;for(;t%us===hs;)t/=us,i++;let s=us;const r=Os(e);for(;1===Ss(r,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===i)return bs;let n=r.pow(s,t);const o=(t+ls)/us;return function(e,s){if(e.is0(s))return s;if(1!==Ss(e,s))throw new Error("Cannot find square root");let r=i,a=e.mul(e.ONE,n),c=e.pow(s,t),h=e.pow(s,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,i=e.sqr(c);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===r)throw new Error("Cannot find square root");const s=ls<<BigInt(r-t-1),n=e.pow(a,s);r=t,a=e.sqr(n),c=e.mul(c,a),h=e.mul(h,n)}return h}}(e)}const xs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Is(e,t,i=!1){const s=new Array(t.length).fill(i?e.ZERO:void 0),r=t.reduce(((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i))),e.ONE),n=e.inv(r);return t.reduceRight(((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i))),n),s}function Ss(e,t){const i=(e.ORDER-ls)/us,s=e.pow(t,i),r=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!r&&!n&&!o)throw new Error("invalid Legendre symbol result");return r?1:n?0:-1}function _s(e,t){void 0!==t&&tt(t);const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function Os(e,t,i=!1,s={}){if(e<=hs)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=_s(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:i,BITS:r,BYTES:n,MASK:hi(r),ZERO:hs,ONE:ls,create:t=>ys(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return hs<=t&&t<e},is0:e=>e===hs,isOdd:e=>(e&ls)===ls,neg:t=>ys(-t,e),eql:(e,t)=>e===t,sqr:t=>ys(t*t,e),add:(t,i)=>ys(t+i,e),sub:(t,i)=>ys(t-i,e),mul:(t,i)=>ys(t*i,e),pow:(e,t)=>function(e,t,i){if(i<hs)throw new Error("invalid exponent, negatives unsupported");if(i===hs)return e.ONE;if(i===ls)return t;let s=e.ONE,r=t;for(;i>hs;)i&ls&&(s=e.mul(s,r)),r=e.sqr(r),i>>=ls;return s}(a,e,t),div:(t,i)=>ys(t*ms(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ms(t,e),sqrt:s.sqrt||(t=>(o||(o=Es(e)),o(a,t))),toBytes:e=>i?si(e,n):ii(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return i?ti(e):ei(e)},invertBatch:e=>Is(a,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(a)}function As(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ps(e){const t=As(e);return t+Math.ceil(t/2)}const Ts=BigInt(0),Rs=BigInt(1);function Bs(e,t){const i=t.negate();return e?i:t}function Ns(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Cs(e,t){Ns(e,t);const i=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:hi(e),maxNumber:i,shiftBy:BigInt(e)}}function Us(e,t,i){const{windowSize:s,mask:r,maxNumber:n,shiftBy:o}=i;let a=Number(e&r),c=e>>o;a>s&&(a-=n,c+=Rs);const h=t*s;return{nextN:c,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:h}}const ks=new WeakMap,Ls=new WeakMap;function qs(e){return Ls.get(e)||1}function Ds(e,t,i,s){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t);const r=i.length,n=s.length;if(r!==n)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=function(e){let t;for(t=0;e>jt;e>>=zt,t+=1);return t}(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=hi(c),l=new Array(Number(h)+1).fill(o);let u=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(o);for(let t=0;t<n;t++){const r=s[t],n=Number(r>>BigInt(e)&h);l[n]=l[n].add(i[t])}let t=o;for(let e=l.length-1,i=o;e>0;e--)i=i.add(l[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<c;e++)u=u.double()}return u}function Ms(e){return fi(e.Fp,xs.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),fi(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({..._s(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}function $s(e){void 0!==e.lowS&&Vt("lowS",e.lowS),void 0!==e.prehash&&Vt("prehash",e.prehash)}class js extends Error{constructor(e=""){super(e)}}const zs={Err:js,_tlv:{encode:(e,t)=>{const{Err:i}=zs;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");const s=t.length/2,r=Ht(s);if(r.length/2&128)throw new i("tlv.encode: long form length too big");const n=s>127?Ht(r.length/2|128):"";return Ht(e)+n+r+t},decode(e,t){const{Err:i}=zs;let s=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new i("tlv.decode: wrong tlv");const r=t[s++];let n=0;if(!!(128&r)){const e=127&r;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===o[0])throw new i("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(s+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(s,s+n);if(o.length!==n)throw new i("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=zs;if(e<Ks)throw new t("integer: negative integers are not allowed");let i=Ht(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){const{Err:t}=zs;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ei(e)}},toSig(e){const{Err:t,_int:i,_tlv:s}=zs,r=ri("signature",e),{v:n,l:o}=s.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(h)}},hexFromSig(e){const{_tlv:t,_int:i}=zs,s=t.encode(2,i.encode(e.r))+t.encode(2,i.encode(e.s));return t.encode(48,s)}};function Fs(e,t){return Zt(ii(e,t))}const Ks=BigInt(0),Vs=BigInt(1);BigInt(2);const Hs=BigInt(3),Ws=BigInt(4);function Gs(e){const t=function(e){const t=Ms(e);fi(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:i,Fp:s,a:r}=t;if(i){if(!s.eql(r,s.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if("object"!=typeof i||"bigint"!=typeof i.beta||"function"!=typeof i.splitScalar)throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}(e),{Fp:i}=t,s=Os(t.n,t.nBitLength),r=t.toBytes||((e,t,s)=>{const r=t.toAffine();return ni(Uint8Array.from([4]),i.toBytes(r.x),i.toBytes(r.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:i.fromBytes(t.subarray(0,i.BYTES)),y:i.fromBytes(t.subarray(i.BYTES,2*i.BYTES))}});function o(e){const{a:s,b:r}=t,n=i.sqr(e),o=i.mul(n,e);return i.add(i.add(o,i.mul(e,s)),r)}function a(e,t){const s=i.sqr(t),r=o(e);return i.eql(s,r)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const c=i.mul(i.pow(t.a,Hs),Ws),h=i.mul(i.sqr(t.b),BigInt(27));if(i.is0(i.add(c,h)))throw new Error("bad curve params: a or b");function l(e){const{allowedPrivateKeyLengths:i,nByteLength:s,wrapPrivateKey:r,n:n}=t;if(i&&"bigint"!=typeof e){if(Ft(e)&&(e=Zt(e)),"string"!=typeof e||!i.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let o;try{o="bigint"==typeof e?e:ei(ri("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return r&&(o=ys(o,n)),ci("private key",o,Vs,n),o}function u(e){if(!(e instanceof p))throw new Error("ProjectivePoint expected")}const d=pi(((e,t)=>{const{px:s,py:r,pz:n}=e;if(i.eql(n,i.ONE))return{x:s,y:r};const o=e.is0();null==t&&(t=o?i.ONE:i.inv(n));const a=i.mul(s,t),c=i.mul(r,t),h=i.mul(n,t);if(o)return{x:i.ZERO,y:i.ZERO};if(!i.eql(h,i.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),f=pi((e=>{if(e.is0()){if(t.allowInfinityPoint&&!i.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:r}=e.toAffine();if(!i.isValid(s)||!i.isValid(r))throw new Error("bad point: x or y not FE");if(!a(s,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class p{constructor(e,t,s){if(null==e||!i.isValid(e))throw new Error("x required");if(null==t||!i.isValid(t)||i.is0(t))throw new Error("y required");if(null==s||!i.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!i.isValid(t)||!i.isValid(s))throw new Error("invalid affine point");if(e instanceof p)throw new Error("projective point not allowed");const r=e=>i.eql(e,i.ZERO);return r(t)&&r(s)?p.ZERO:new p(t,s,i.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=Is(i,e.map((e=>e.pz)));return e.map(((e,i)=>e.toAffine(t[i]))).map(p.fromAffine)}static fromHex(e){const t=p.fromAffine(n(ri("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return p.BASE.multiply(l(e))}static msm(e,t){return Ds(p,s,e,t)}_setWindowSize(e){w.setWindowSize(this,e)}assertValidity(){f(this)}hasEvenY(){const{y:e}=this.toAffine();if(i.isOdd)return!i.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:s,pz:r}=this,{px:n,py:o,pz:a}=e,c=i.eql(i.mul(t,a),i.mul(n,r)),h=i.eql(i.mul(s,a),i.mul(o,r));return c&&h}negate(){return new p(this.px,i.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,r=i.mul(s,Hs),{px:n,py:o,pz:a}=this;let c=i.ZERO,h=i.ZERO,l=i.ZERO,u=i.mul(n,n),d=i.mul(o,o),f=i.mul(a,a),g=i.mul(n,o);return g=i.add(g,g),l=i.mul(n,a),l=i.add(l,l),c=i.mul(e,l),h=i.mul(r,f),h=i.add(c,h),c=i.sub(d,h),h=i.add(d,h),h=i.mul(c,h),c=i.mul(g,c),l=i.mul(r,l),f=i.mul(e,f),g=i.sub(u,f),g=i.mul(e,g),g=i.add(g,l),l=i.add(u,u),u=i.add(l,u),u=i.add(u,f),u=i.mul(u,g),h=i.add(h,u),f=i.mul(o,a),f=i.add(f,f),u=i.mul(f,g),c=i.sub(c,u),l=i.mul(f,d),l=i.add(l,l),l=i.add(l,l),new p(c,h,l)}add(e){u(e);const{px:s,py:r,pz:n}=this,{px:o,py:a,pz:c}=e;let h=i.ZERO,l=i.ZERO,d=i.ZERO;const f=t.a,g=i.mul(t.b,Hs);let y=i.mul(s,o),w=i.mul(r,a),m=i.mul(n,c),b=i.add(s,r),v=i.add(o,a);b=i.mul(b,v),v=i.add(y,w),b=i.sub(b,v),v=i.add(s,n);let E=i.add(o,c);return v=i.mul(v,E),E=i.add(y,m),v=i.sub(v,E),E=i.add(r,n),h=i.add(a,c),E=i.mul(E,h),h=i.add(w,m),E=i.sub(E,h),d=i.mul(f,v),h=i.mul(g,m),d=i.add(h,d),h=i.sub(w,d),d=i.add(w,d),l=i.mul(h,d),w=i.add(y,y),w=i.add(w,y),m=i.mul(f,m),v=i.mul(g,v),w=i.add(w,m),m=i.sub(y,m),m=i.mul(f,m),v=i.add(v,m),y=i.mul(w,v),l=i.add(l,y),y=i.mul(E,v),h=i.mul(b,h),h=i.sub(h,y),y=i.mul(b,w),d=i.mul(E,d),d=i.add(d,y),new p(h,l,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(p.ZERO)}wNAF(e){return w.wNAFCached(this,e,p.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:r}=t;ci("scalar",e,Ks,r);const n=p.ZERO;if(e===Ks)return n;if(this.is0()||e===Vs)return this;if(!s||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,e,p.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:h}=s.splitScalar(e),l=n,u=n,d=this;for(;a>Ks||h>Ks;)a&Vs&&(l=l.add(d)),h&Vs&&(u=u.add(d)),d=d.double(),a>>=Vs,h>>=Vs;return o&&(l=l.negate()),c&&(u=u.negate()),u=new p(i.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:s,n:r}=t;let n,o;if(ci("scalar",e,Vs,r),s){const{k1neg:t,k1:r,k2neg:a,k2:c}=s.splitScalar(e);let{p:h,f:l}=this.wNAF(r),{p:u,f:d}=this.wNAF(c);h=w.constTimeNegate(t,h),u=w.constTimeNegate(a,u),u=new p(i.mul(u.px,s.beta),u.py,u.pz),n=h.add(u),o=l.add(d)}else{const{p:t,f:i}=this.wNAF(e);n=t,o=i}return p.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,i){const s=p.BASE,r=(e,t)=>t!==Ks&&t!==Vs&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=r(this,t).add(r(e,i));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:i}=t;if(e===Vs)return!0;if(i)return i(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:i}=t;return e===Vs?this:i?i(p,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Vt("isCompressed",e),this.assertValidity(),r(p,this,e)}toHex(e=!0){return Vt("isCompressed",e),Zt(this.toRawBytes(e))}}p.BASE=new p(t.Gx,t.Gy,i.ONE),p.ZERO=new p(i.ZERO,i.ONE,i.ZERO);const{endo:g,nBitLength:y}=t,w=function(e,t){return{constTimeNegate:Bs,hasPrecomputes:e=>1!==qs(e),unsafeLadder(t,i,s=e.ZERO){let r=t;for(;i>Ts;)i&Rs&&(s=s.add(r)),r=r.double(),i>>=Rs;return s},precomputeWindow(e,i){const{windows:s,windowSize:r}=Cs(i,t),n=[];let o=e,a=o;for(let e=0;e<s;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(i,s,r){let n=e.ZERO,o=e.BASE;const a=Cs(i,t);for(let e=0;e<a.windows;e++){const{nextN:t,offset:i,isZero:c,isNeg:h,isNegF:l,offsetF:u}=Us(r,e,a);r=t,c?o=o.add(Bs(l,s[u])):n=n.add(Bs(h,s[i]))}return{p:n,f:o}},wNAFUnsafe(i,s,r,n=e.ZERO){const o=Cs(i,t);for(let e=0;e<o.windows&&r!==Ts;e++){const{nextN:t,offset:i,isZero:a,isNeg:c}=Us(r,e,o);if(r=t,!a){const e=s[i];n=n.add(c?e.negate():e)}}return n},getPrecomputes(e,t,i){let s=ks.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&ks.set(t,i(s))),s},wNAFCached(e,t,i){const s=qs(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)},wNAFCachedUnsafe(e,t,i,s){const r=qs(e);return 1===r?this.unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)},setWindowSize(e,i){Ns(i,t),Ls.set(e,i),ks.delete(e)}}}(p,g?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:p,normPrivateKeyToScalar:l,weierstrassEquation:o,isWithinCurveOrder:function(e){return ai(e,Vs,t.n)}}}function Ys(e){const t=function(e){const t=Ms(e);return fi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:i,n:s,nByteLength:r,nBitLength:n}=t,o=i.BYTES+1,a=2*i.BYTES+1;function c(e){return ys(e,s)}function h(e){return ms(e,s)}const{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:d,isWithinCurveOrder:f}=Gs({...t,toBytes(e,t,s){const r=t.toAffine(),n=i.toBytes(r.x),o=ni;return Vt("isCompressed",s),s?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,i.toBytes(r.y))},fromBytes(e){const t=e.length,s=e[0],r=e.subarray(1);if(t!==o||2!==s&&3!==s){if(t===a&&4===s){return{x:i.fromBytes(r.subarray(0,i.BYTES)),y:i.fromBytes(r.subarray(i.BYTES,2*i.BYTES))}}throw new Error("invalid Point, expected length of "+o+", or uncompressed "+a+", got "+t)}{const e=ei(r);if(!ai(e,Vs,i.ORDER))throw new Error("Point is not on curve");const t=d(e);let n;try{n=i.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return 1==(1&s)!==((n&Vs)===Vs)&&(n=i.neg(n)),{x:e,y:n}}}});function p(e){return e>s>>Vs}const g=(e,t,i)=>ei(e.slice(t,i));class y{constructor(e,t,i){ci("r",e,Vs,s),ci("s",t,Vs,s),this.r=e,this.s=t,null!=i&&(this.recovery=i),Object.freeze(this)}static fromCompact(e){const t=r;return e=ri("compactSignature",e,2*t),new y(g(e,0,t),g(e,t,2*t))}static fromDER(e){const{r:t,s:i}=zs.toSig(ri("DER",e));return new y(t,i)}assertValidity(){}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:r,recovery:n}=this,o=v(ri("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const a=2===n||3===n?s+t.n:s;if(a>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");const u=0==(1&n)?"02":"03",d=l.fromHex(u+Fs(a,i.BYTES)),f=h(a),p=c(-o*f),g=c(r*f),y=l.BASE.multiplyAndAddUnsafe(d,p,g);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Qt(this.toDERHex())}toDERHex(){return zs.hexFromSig(this)}toCompactRawBytes(){return Qt(this.toCompactHex())}toCompactHex(){const e=r;return Fs(this.r,e)+Fs(this.s,e)}}const w={isValidPrivateKey(e){try{return u(e),!0}catch(e){return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const e=Ps(t.n);return function(e,t,i=!1){const s=e.length,r=As(t),n=Ps(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=ys(i?ti(e):ei(e),t-ls)+ls;return i?si(o,r):ii(o,r)}(t.randomBytes(e),t.n)},precompute:(e=8,t=l.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){if("bigint"==typeof e)return!1;if(e instanceof l)return!0;const s=ri("key",e).length,n=i.BYTES,o=n+1,a=2*n+1;return t.allowedPrivateKeyLengths||r===o?void 0:s===o||s===a}const b=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ei(e),i=8*e.length-n;return i>0?t>>BigInt(i):t},v=t.bits2int_modN||function(e){return c(b(e))},E=hi(n);function x(e){return ci("num < 2^"+n,e,Ks,E),ii(e,r)}function I(e,s,r=S){if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:o}=t;let{lowS:a,prehash:d,extraEntropy:g}=r;null==a&&(a=!0),e=ri("msgHash",e),$s(r),d&&(e=ri("prehashed msgHash",n(e)));const w=v(e),m=u(s),E=[x(m),x(w)];if(null!=g&&!1!==g){const e=!0===g?o(i.BYTES):g;E.push(ri("extraEntropy",e))}const I=ni(...E),_=w;return{seed:I,k2sig:function(e){const t=b(e);if(!f(t))return;const i=h(t),s=l.BASE.multiply(t).toAffine(),r=c(s.x);if(r===Ks)return;const n=c(i*c(_+r*m));if(n===Ks)return;let o=(s.x===r?0:2)|Number(s.y&Vs),u=n;return a&&p(n)&&(u=function(e){return p(e)?c(-e):e}(n),o^=1),new y(r,u,o)}}}const S={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};return l.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return l.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,i=!0){if(!0===m(e))throw new Error("first arg must be private key");if(!1===m(t))throw new Error("second arg must be public key");return l.fromHex(t).multiply(u(e)).toRawBytes(i)},sign:function(e,i,s=S){const{seed:r,k2sig:n}=I(e,i,s),o=t,a=function(e,t,i){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof i)throw new Error("hmacFn must be a function");let s=li(e),r=li(e),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...e)=>i(r,s,...e),c=(e=li(0))=>{r=a(ui([0]),e),s=a(),0!==e.length&&(r=a(ui([1]),e),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const i=[];for(;e<t;){s=a();const t=s.slice();i.push(t),e+=s.length}return ni(...i)};return(e,t)=>{let i;for(o(),c(e);!(i=t(h()));)c();return o(),i}}(o.hash.outputLen,o.nByteLength,o.hmac);return a(r,n)},verify:function(e,i,s,r=_){const n=e;i=ri("msgHash",i),s=ri("publicKey",s);const{lowS:o,prehash:a,format:u}=r;if($s(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");const d="string"==typeof n||Ft(n),f=!d&&!u&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!d&&!f)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let p,g;try{if(f&&(p=new y(n.r,n.s)),d){try{"compact"!==u&&(p=y.fromDER(n))}catch(e){if(!(e instanceof zs.Err))throw e}p||"der"===u||(p=y.fromCompact(n))}g=l.fromHex(s)}catch(e){return!1}if(!p)return!1;if(o&&p.hasHighS())return!1;a&&(i=t.hash(i));const{r:w,s:m}=p,b=v(i),E=h(m),x=c(b*E),I=c(w*E),S=l.BASE.multiplyAndAddUnsafe(g,x,I)?.toAffine();return!!S&&c(S.x)===w},ProjectivePoint:l,Signature:y,utils:w}}function Zs(e){return{hash:e,hmac:(t,...i)=>cs(e,t,function(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];it(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(...i)),randomBytes:dt}}const Js=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xs=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Qs=BigInt(0),er=BigInt(1),tr=BigInt(2),ir=(e,t)=>(e+t/tr)/t;const sr=Os(Js,void 0,void 0,{sqrt:function(e){const t=Js,i=BigInt(3),s=BigInt(6),r=BigInt(11),n=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=e*e*e%t,l=h*h*e%t,u=ws(l,i,t)*l%t,d=ws(u,i,t)*l%t,f=ws(d,tr,t)*h%t,p=ws(f,r,t)*f%t,g=ws(p,n,t)*p%t,y=ws(g,a,t)*g%t,w=ws(y,c,t)*y%t,m=ws(w,a,t)*g%t,b=ws(m,i,t)*l%t,v=ws(b,o,t)*p%t,E=ws(v,s,t)*h%t,x=ws(E,tr,t);if(!sr.eql(sr.sqr(x),e))throw new Error("Cannot find square root");return x}}),rr=function(e,t){const i=t=>Ys({...e,...Zs(t)});return{...i(t),create:i}}({a:Qs,b:BigInt(7),Fp:sr,n:Xs,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Xs,i=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-er*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=i,o=BigInt("0x100000000000000000000000000000000"),a=ir(n*e,t),c=ir(-s*e,t);let h=ys(e-a*i-c*r,t),l=ys(-a*s-c*n,t);const u=h>o,d=l>o;if(u&&(h=t-h),d&&(l=t-l),h>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:h,k2neg:d,k2:l}}}},$t);function nr(e){if(130!==e.length&&132!==e.length)throw new or({signature:e});const t=BigInt(Oi(e,0,32)),i=BigInt(Oi(e,32,64)),s=(()=>{const t=Number(`0x${e.slice(130)}`);if(!Number.isNaN(t))try{return function(e){if(0===e||27===e)return 0;if(1===e||28===e)return 1;if(e>=35)return e%2==0?1:0;throw new cr({value:e})}(t)}catch{throw new ar({value:t})}})();return void 0===s?{r:t,s:i}:{r:t,s:i,yParity:s}}class or extends Xe{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Ai(xi(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class ar extends Xe{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class cr extends Xe{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function hr(e){return ss(function(e){const{payload:t,signature:i}=e,{r:s,s:r,yParity:n}=i,o=new rr.Signature(BigInt(s),BigInt(r)).addRecoveryBit(n);return Wi(o.recoverPublicKey(xi(t).substring(2)))}
|
|
3
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */(e))}function lr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ur(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function dr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function fr(e,...t){if(!lr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function pr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function gr(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function yr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const wr=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function mr(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!lr(e))throw new Error("Uint8Array expected, got "+typeof e);e=Ir(e)}return e}const br=(e,t)=>{function i(i,...s){if(fr(i),!wr)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=s[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?fr(t):fr(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==s[1]&&fr(s[1]);const n=t(i,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");fr(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,fr(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(fr(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(n.decrypt.length,t),n.decrypt(e,t)}}}return Object.assign(i,e),i};function vr(e,t,i=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(i&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function Er(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}function xr(e,t,i){ur(i);const s=new Uint8Array(16),r=(n=s,new DataView(n.buffer,n.byteOffset,n.byteLength));var n;return Er(r,0,BigInt(t),i),Er(r,8,BigInt(e),i),s}function Ir(e){return Uint8Array.from(e)}function Sr(e,t,i){return e&t^~e&i}function _r(e,t,i){return e&t^e&i^t&i}class Or extends Ne{constructor(e,t,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=me(this.buffer)}update(e){pe(this),de(e=Re(e));const{view:t,buffer:i,blockLen:s}=this,r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=me(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){pe(this),ge(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,we(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=me(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.destroyed=n,e.finished=r,e.length=s,e.pos=o,s%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const Ar=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Tr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rr=Uint32Array.from([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]),Br=new Uint32Array(64);class Nr extends Or{constructor(e=32){super(64,e,8,!1),this.A=0|Ar[0],this.B=0|Ar[1],this.C=0|Ar[2],this.D=0|Ar[3],this.E=0|Ar[4],this.F=0|Ar[5],this.G=0|Ar[6],this.H=0|Ar[7]}get(){const{A:e,B:t,C:i,D:s,E:r,F:n,G:o,H:a}=this;return[e,t,i,s,r,n,o,a]}set(e,t,i,s,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|s,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let i=0;i<16;i++,t+=4)Br[i]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Br[e-15],i=Br[e-2],s=be(t,7)^be(t,18)^t>>>3,r=be(i,17)^be(i,19)^i>>>10;Br[e]=r+Br[e-7]+s+Br[e-16]|0}let{A:i,B:s,C:r,D:n,E:o,F:a,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(be(o,6)^be(o,11)^be(o,25))+Sr(o,a,c)+Rr[e]+Br[e]|0,l=(be(i,2)^be(i,13)^be(i,22))+_r(i,s,r)|0;h=c,c=a,a=o,o=n+t|0,n=r,r=s,s=i,i=t+l|0}i=i+this.A|0,s=s+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,s,r,n,o,a,c,h)}roundClean(){we(Br)}destroy(){this.set(0,0,0,0,0,0,0,0),we(this.buffer)}}const Cr=(()=>W(["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((e=>BigInt(e)))))(),Ur=(()=>Cr[0])(),kr=(()=>Cr[1])(),Lr=new Uint32Array(80),qr=new Uint32Array(80);class Dr extends Or{constructor(e=64){super(128,e,16,!1),this.Ah=0|Tr[0],this.Al=0|Tr[1],this.Bh=0|Tr[2],this.Bl=0|Tr[3],this.Ch=0|Tr[4],this.Cl=0|Tr[5],this.Dh=0|Tr[6],this.Dl=0|Tr[7],this.Eh=0|Tr[8],this.El=0|Tr[9],this.Fh=0|Tr[10],this.Fl=0|Tr[11],this.Gh=0|Tr[12],this.Gl=0|Tr[13],this.Hh=0|Tr[14],this.Hl=0|Tr[15]}get(){const{Ah:e,Al:t,Bh:i,Bl:s,Ch:r,Cl:n,Dh:o,Dl:a,Eh:c,El:h,Fh:l,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|s,this.Ch=0|r,this.Cl=0|n,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|h,this.Fh=0|l,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=4)Lr[i]=e.getUint32(t),qr[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Lr[e-15],i=0|qr[e-15],s=Z(t,i,1)^Z(t,i,8)^G(t,0,7),r=J(t,i,1)^J(t,i,8)^Y(t,i,7),n=0|Lr[e-2],o=0|qr[e-2],a=Z(n,o,19)^X(n,o,61)^G(n,0,6),c=J(n,o,19)^Q(n,o,61)^Y(n,o,6),h=ne(r,c,qr[e-7],qr[e-16]),l=oe(h,s,a,Lr[e-7],Lr[e-16]);Lr[e]=0|l,qr[e]=0|h}let{Ah:i,Al:s,Bh:r,Bl:n,Ch:o,Cl:a,Dh:c,Dl:h,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:y,Hl:w}=this;for(let e=0;e<80;e++){const t=Z(l,u,14)^Z(l,u,18)^X(l,u,41),m=J(l,u,14)^J(l,u,18)^Q(l,u,41),b=l&d^~l&p,v=ae(w,m,u&f^~u&g,kr[e],qr[e]),E=ce(v,y,t,b,Ur[e],Lr[e]),x=0|v,I=Z(i,s,28)^X(i,s,34)^X(i,s,39),S=J(i,s,28)^Q(i,s,34)^Q(i,s,39),_=i&r^i&o^r&o,O=s&n^s&a^n&a;y=0|p,w=0|g,p=0|d,g=0|f,d=0|l,f=0|u,({h:l,l:u}=ie(0|c,0|h,0|E,0|x)),c=0|o,h=0|a,o=0|r,a=0|n,r=0|i,n=0|s;const A=se(x,S,O);i=re(A,E,I,_),s=0|A}({h:i,l:s}=ie(0|this.Ah,0|this.Al,0|i,0|s)),({h:r,l:n}=ie(0|this.Bh,0|this.Bl,0|r,0|n)),({h:o,l:a}=ie(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:h}=ie(0|this.Dh,0|this.Dl,0|c,0|h)),({h:l,l:u}=ie(0|this.Eh,0|this.El,0|l,0|u)),({h:d,l:f}=ie(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=ie(0|this.Gh,0|this.Gl,0|p,0|g)),({h:y,l:w}=ie(0|this.Hh,0|this.Hl,0|y,0|w)),this.set(i,s,r,n,o,a,c,h,l,u,d,f,p,g,y,w)}roundClean(){we(Lr,qr)}destroy(){we(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Mr extends Dr{constructor(){super(48),this.Ah=0|Pr[0],this.Al=0|Pr[1],this.Bh=0|Pr[2],this.Bl=0|Pr[3],this.Ch=0|Pr[4],this.Cl=0|Pr[5],this.Dh=0|Pr[6],this.Dl=0|Pr[7],this.Eh=0|Pr[8],this.El=0|Pr[9],this.Fh=0|Pr[10],this.Fl=0|Pr[11],this.Gh=0|Pr[12],this.Gl=0|Pr[13],this.Hh=0|Pr[14],this.Hl=0|Pr[15]}}const $r=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class jr extends Dr{constructor(){super(32),this.Ah=0|$r[0],this.Al=0|$r[1],this.Bh=0|$r[2],this.Bl=0|$r[3],this.Ch=0|$r[4],this.Cl=0|$r[5],this.Dh=0|$r[6],this.Dl=0|$r[7],this.Eh=0|$r[8],this.El=0|$r[9],this.Fh=0|$r[10],this.Fl=0|$r[11],this.Gh=0|$r[12],this.Gl=0|$r[13],this.Hh=0|$r[14],this.Hl=0|$r[15]}}const zr=Ce((()=>new Nr)),Fr=Ce((()=>new Dr)),Kr=Ce((()=>new Mr)),Vr=Ce((()=>new jr)),Hr=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Wr=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Gr=new Uint32Array(32);function Yr(e,t,i,s,r,n){const o=r[n],a=r[n+1];let c=Gr[2*e],h=Gr[2*e+1],l=Gr[2*t],u=Gr[2*t+1],d=Gr[2*i],f=Gr[2*i+1],p=Gr[2*s],g=Gr[2*s+1],y=se(c,l,o);h=re(y,h,u,a),c=0|y,({Dh:g,Dl:p}={Dh:g^h,Dl:p^c}),({Dh:g,Dl:p}={Dh:ee(0,p),Dl:te(g)}),({h:f,l:d}=ie(f,d,g,p)),({Bh:u,Bl:l}={Bh:u^f,Bl:l^d}),({Bh:u,Bl:l}={Bh:Z(u,l,24),Bl:J(u,l,24)}),Gr[2*e]=c,Gr[2*e+1]=h,Gr[2*t]=l,Gr[2*t+1]=u,Gr[2*i]=d,Gr[2*i+1]=f,Gr[2*s]=p,Gr[2*s+1]=g}function Zr(e,t,i,s,r,n){const o=r[n],a=r[n+1];let c=Gr[2*e],h=Gr[2*e+1],l=Gr[2*t],u=Gr[2*t+1],d=Gr[2*i],f=Gr[2*i+1],p=Gr[2*s],g=Gr[2*s+1],y=se(c,l,o);h=re(y,h,u,a),c=0|y,({Dh:g,Dl:p}={Dh:g^h,Dl:p^c}),({Dh:g,Dl:p}={Dh:Z(g,p,16),Dl:J(g,p,16)}),({h:f,l:d}=ie(f,d,g,p)),({Bh:u,Bl:l}={Bh:u^f,Bl:l^d}),({Bh:u,Bl:l}={Bh:X(u,l,63),Bl:Q(u,l,63)}),Gr[2*e]=c,Gr[2*e+1]=h,Gr[2*t]=l,Gr[2*t+1]=u,Gr[2*i]=d,Gr[2*i+1]=f,Gr[2*s]=p,Gr[2*s+1]=g}class Jr extends Ne{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ue(e),ue(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ye(this.buffer)}update(e){pe(this),de(e=Re(e));const{blockLen:t,buffer:i,buffer32:s}=this,r=e.length,n=e.byteOffset,o=e.buffer;for(let a=0;a<r;){this.pos===t&&(Ie(s),this.compress(s,0,!1),Ie(s),this.pos=0);const c=Math.min(t-this.pos,r-a),h=n+a;if(c!==t||h%4||!(a+c<r))i.set(e.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const e=new Uint32Array(o,h,Math.floor((r-a)/4));Ie(e);for(let i=0;a+t<r;i+=s.length,a+=t)this.length+=t,this.compress(e,i,!1);Ie(e)}}return this}digestInto(e){pe(this),ge(e,this);const{pos:t,buffer32:i}=this;this.finished=!0,we(this.buffer.subarray(t)),Ie(i),this.compress(i,0,!0),Ie(i);const s=ye(e);this.get().forEach(((e,t)=>s[t]=xe(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){const{buffer:t,length:i,finished:s,destroyed:r,outputLen:n,pos:o}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=r,e.finished=s,e.length=i,e.pos=o,e.outputLen=n,e}clone(){return this._cloneInto()}}class Xr extends Jr{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|Wr[0],this.v0h=0|Wr[1],this.v1l=0|Wr[2],this.v1h=0|Wr[3],this.v2l=0|Wr[4],this.v2h=0|Wr[5],this.v3l=0|Wr[6],this.v3h=0|Wr[7],this.v4l=0|Wr[8],this.v4h=0|Wr[9],this.v5l=0|Wr[10],this.v5h=0|Wr[11],this.v6l=0|Wr[12],this.v6h=0|Wr[13],this.v7l=0|Wr[14],this.v7h=0|Wr[15],function(e,t={},i,s,r){if(ue(i),e<0||e>i)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=t;if(void 0!==n&&(n.length<1||n.length>i))throw new Error("key length must be undefined or 1.."+i);if(void 0!==o&&o.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==a&&a.length!==r)throw new Error("personalization must be undefined or "+r)}(t,e,64,16,16);let{key:i,personalization:s,salt:r}=e,n=0;if(void 0!==i&&(i=Re(i),n=i.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==r){r=Re(r);const e=ye(r);this.v4l^=xe(e[0]),this.v4h^=xe(e[1]),this.v5l^=xe(e[2]),this.v5h^=xe(e[3])}if(void 0!==s){s=Re(s);const e=ye(s);this.v6l^=xe(e[0]),this.v6h^=xe(e[1]),this.v7l^=xe(e[2]),this.v7h^=xe(e[3])}if(void 0!==i){const e=new Uint8Array(this.blockLen);e.set(i),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:s,v2l:r,v2h:n,v3l:o,v3h:a,v4l:c,v4h:h,v5l:l,v5h:u,v6l:d,v6h:f,v7l:p,v7h:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|i,this.v1h=0|s,this.v2l=0|r,this.v2h=0|n,this.v3l=0|o,this.v3h=0|a,this.v4l=0|c,this.v4h=0|h,this.v5l=0|l,this.v5h=0|u,this.v6l=0|d,this.v6h=0|f,this.v7l=0|p,this.v7h=0|g}compress(e,t,i){this.get().forEach(((e,t)=>Gr[t]=e)),Gr.set(Wr,16);let{h:s,l:r}=H(BigInt(this.length));Gr[24]=Wr[8]^r,Gr[25]=Wr[9]^s,i&&(Gr[28]=~Gr[28],Gr[29]=~Gr[29]);let n=0;const o=Hr;for(let i=0;i<12;i++)Yr(0,4,8,12,e,t+2*o[n++]),Zr(0,4,8,12,e,t+2*o[n++]),Yr(1,5,9,13,e,t+2*o[n++]),Zr(1,5,9,13,e,t+2*o[n++]),Yr(2,6,10,14,e,t+2*o[n++]),Zr(2,6,10,14,e,t+2*o[n++]),Yr(3,7,11,15,e,t+2*o[n++]),Zr(3,7,11,15,e,t+2*o[n++]),Yr(0,5,10,15,e,t+2*o[n++]),Zr(0,5,10,15,e,t+2*o[n++]),Yr(1,6,11,12,e,t+2*o[n++]),Zr(1,6,11,12,e,t+2*o[n++]),Yr(2,7,8,13,e,t+2*o[n++]),Zr(2,7,8,13,e,t+2*o[n++]),Yr(3,4,9,14,e,t+2*o[n++]),Zr(3,4,9,14,e,t+2*o[n++]);this.v0l^=Gr[0]^Gr[16],this.v0h^=Gr[1]^Gr[17],this.v1l^=Gr[2]^Gr[18],this.v1h^=Gr[3]^Gr[19],this.v2l^=Gr[4]^Gr[20],this.v2h^=Gr[5]^Gr[21],this.v3l^=Gr[6]^Gr[22],this.v3h^=Gr[7]^Gr[23],this.v4l^=Gr[8]^Gr[24],this.v4h^=Gr[9]^Gr[25],this.v5l^=Gr[10]^Gr[26],this.v5h^=Gr[11]^Gr[27],this.v6l^=Gr[12]^Gr[28],this.v6h^=Gr[13]^Gr[29],this.v7l^=Gr[14]^Gr[30],this.v7h^=Gr[15]^Gr[31],we(Gr)}destroy(){this.destroyed=!0,we(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Qr=Ue((e=>new Xr(e)));const en=new TextEncoder;function tn(e,t,i){e.length>50?function(e,t,i){en.encodeInto(e,t.subarray(i))}(e,t,i):function(e,t,i){const s=e.length;let r=i,n=0;for(;n<s;){let i=e.charCodeAt(n++);if(0!=(4294967168&i)){if(0==(4294965248&i))t[r++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&n<s){const t=e.charCodeAt(n);56320==(64512&t)&&(++n,i=((1023&i)<<10)+(1023&t)+65536)}0==(4294901760&i)?(t[r++]=i>>12&15|224,t[r++]=i>>6&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128)}t[r++]=63&i|128}else t[r++]=i}}(e,t,i)}const sn=4096;function rn(e,t,i){let s=t;const r=s+i,n=[];let o="";for(;s<r;){const t=e[s++];if(0==(128&t))n.push(t);else if(192==(224&t)){const i=63&e[s++];n.push((31&t)<<6|i)}else if(224==(240&t)){const i=63&e[s++],r=63&e[s++];n.push((31&t)<<12|i<<6|r)}else if(240==(248&t)){let i=(7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++];i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i)}else n.push(t);n.length>=sn&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const nn=new TextDecoder;function on(e,t,i){return i>200?function(e,t,i){const s=e.subarray(t,t+i);return nn.decode(s)}(e,t,i):rn(e,t,i)}class an{type;data;constructor(e,t){this.type=e,this.data=t}}class cn extends Error{constructor(e){super(e);const t=Object.create(cn.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:cn.name})}}const hn=4294967295;function ln(e,t,i){const s=Math.floor(i/4294967296),r=i;e.setUint32(t,s),e.setUint32(t+4,r)}function un(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const dn=4294967295,fn=17179869183;const pn={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=fn){if(0===t&&e<=dn){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const i=e/4294967296,s=4294967295&e,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,t<<2|3&i),n.setUint32(4,s),r}}{const i=new Uint8Array(12),s=new DataView(i.buffer);return s.setUint32(0,t),ln(s,4,e),i}}(function(e){const t=e.getTime(),i=Math.floor(t/1e3),s=1e6*(t-1e3*i),r=Math.floor(s/1e9);return{sec:i+r,nsec:s-1e9*r}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:un(t,4),nsec:t.getUint32(0)};default:throw new cn(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class gn{static defaultCodec=new gn;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(pn)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(null!=s){const r=s(e,t);if(null!=r){return new an(-1-i,r)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(null!=s){const r=s(e,t);if(null!=r){return new an(i,r)}}}return e instanceof an?e:null}decode(e,t,i){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,i):new an(t,e)}}function yn(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}class wn{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??gn.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new wn({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),s=new DataView(t);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let i=0,s=0;for(;s<t;){let r=e.charCodeAt(s++);if(0!=(4294967168&r))if(0==(4294965248&r))i+=2;else{if(r>=55296&&r<=56319&&s<t){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,r=((1023&r)<<10)+(1023&t)+65536)}i+=0==(4294901760&r)?3:4}else i++}return i}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),tn(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(null!=i)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const i=yn(e);this.writeU8a(i)}encodeArray(e,t){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large array: ${i}`);this.writeU8(221),this.writeU32(i)}for(const i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let i=0;for(const s of t)void 0!==e[s]&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large map object: ${s}`);this.writeU8(223),this.writeU32(s)}for(const s of i){const i=e[s];this.ignoreUndefined&&void 0===i||(this.encodeString(s),this.doEncode(i,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),i=t.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);return this.writeU8(201),this.writeU32(i),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,i){const s=i/4294967296,r=i;e.setUint32(t,s),e.setUint32(t+4,r)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ln(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function mn(e,t){return new wn(t).encodeSharedRef(e)}function bn(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const vn="array",En="map_key",xn="map_value",In=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new cn("The type of key must be string or number but "+typeof e)};class Sn{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=vn,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=En,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===vn){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===En||e.type===xn){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const _n=new DataView(new ArrayBuffer(0)),On=new Uint8Array(_n.buffer);try{_n.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const An=new RangeError("Insufficient data"),Pn=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const s=this.caches[i-1];e:for(const r of s){const s=r.bytes;for(let r=0;r<i;r++)if(s[r]!==e[t+r])continue e;return r.str}return null}store(e,t){const i=this.caches[e.length-1],s={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,t,i){const s=this.find(e,t,i);if(null!=s)return this.hit++,s;this.miss++;const r=rn(e,t,i),n=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(n,r),r}};class Tn{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=_n;bytes=On;headByte=-1;stack=new Sn;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??gn.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??hn,this.maxBinLength=e?.maxBinLength??hn,this.maxArrayLength=e?.maxArrayLength??hn,this.maxMapLength=e?.maxMapLength??hn,this.maxExtLength=e?.maxExtLength??hn,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:Pn,this.mapKeyConverter=e?.mapKeyConverter??In}clone(){return new Tn({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=yn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),i=yn(e),s=new Uint8Array(t.length+i.length);s.set(t),s.set(i,t.length),this.setBuffer(s)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,i=!1;for await(const s of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{t=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:s,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${bn(s)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const i=this.clone();yield*i.decodeMultiAsync(e,t)}else try{this.entered=!0;let i=t,s=-1;for await(const r of e){if(t&&0===s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),0!=--s;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const i=e-128;if(0!==i){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){const i=e-144;if(0!==i){this.pushArrayState(i),this.complete();continue e}t=[]}else{const i=e-160;t=this.decodeString(i,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new cn(`Unrecognized type byte: ${bn(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const i=this.stack;for(;i.length>0;){const e=i.top();if(e.type===vn){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,i.release(e)}else{if(e.type===En){if("__proto__"===t)throw new cn("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=xn;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=En;continue e}t=e.map,i.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new cn(`Unrecognized array type byte: ${bn(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new cn(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new cn(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new cn(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw An;const i=this.pos+t;let s;return s=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,i,e):on(this.bytes,i,e),this.pos+=t+e,s}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===En}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new cn(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw An;const i=this.pos+t,s=this.bytes.subarray(i,i+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new cn(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,i=this.pos,4294967296*t.getUint32(i)+t.getUint32(i+4));var t,i;return this.pos+=8,e}readI64(){const e=un(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Rn(e,t){return new Tn(t).decode(e)}
|
|
4
|
+
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Bn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Nn(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function Cn(e){if("function"!=typeof e)throw new Error("function expected");return!0}function Un(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function kn(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function Ln(e){if(!Array.isArray(e))throw new Error("array expected")}function qn(e,t){if(!Nn(!0,t))throw new Error(`${e}: array of strings expected`)}function Dn(e,t){if(!Nn(!1,t))throw new Error(`${e}: array of numbers expected`)}function Mn(...e){const t=e=>e,i=(e,t)=>i=>e(t(i)),s=e.map((e=>e.encode)).reduceRight(i,t),r=e.map((e=>e.decode)).reduce(i,t);return{encode:s,decode:r}}function $n(e){const t="string"==typeof e?e.split(""):e,i=t.length;qn("alphabet",t);const s=new Map(t.map(((e,t)=>[e,t])));return{encode:s=>(Ln(s),s.map((s=>{if(!Number.isSafeInteger(s)||s<0||s>=i)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]}))),decode:t=>(Ln(t),t.map((t=>{Un("alphabet.decode",t);const i=s.get(t);if(void 0===i)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return i})))}}function jn(e=""){return Un("join",e),{encode:t=>(qn("join.decode",t),t.join(e)),decode:t=>(Un("join.decode",t),t.split(e))}}function zn(e,t="="){return kn(e),Un("padding",t),{encode(i){for(qn("padding.encode",i);i.length*e%8;)i.push(t);return i},decode(i){qn("padding.decode",i);let s=i.length;if(s*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;s>0&&i[s-1]===t;s--){if((s-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return i.slice(0,s)}}}function Fn(e){return Cn(e),{encode:e=>e,decode:t=>e(t)}}function Kn(e,t,i){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(i<2)throw new Error(`convertRadix: invalid to=${i}, base cannot be less than 2`);if(Ln(e),!e.length)return[];let s=0;const r=[],n=Array.from(e,(e=>{if(kn(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e})),o=n.length;for(;;){let e=0,a=!0;for(let r=s;r<o;r++){const o=n[r],c=t*e,h=c+o;if(!Number.isSafeInteger(h)||c/t!==e||h-o!==c)throw new Error("convertRadix: carry overflow");const l=h/i;e=h%i;const u=Math.floor(l);if(n[r]=u,!Number.isSafeInteger(u)||u*i+e!==h)throw new Error("convertRadix: carry overflow");a&&(u?a=!1:s=r)}if(r.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)r.push(0);return r.reverse()}const Vn=(e,t)=>0===t?e:Vn(t,e%t),Hn=(e,t)=>e+(t-Vn(e,t)),Wn=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Gn(e,t,i,s){if(Ln(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(i<=0||i>32)throw new Error(`convertRadix2: wrong to=${i}`);if(Hn(t,i)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${i} carryBits=${Hn(t,i)}`);let r=0,n=0;const o=Wn[t],a=Wn[i]-1,c=[];for(const s of e){if(kn(s),s>=o)throw new Error(`convertRadix2: invalid data word=${s} from=${t}`);if(r=r<<t|s,n+t>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${t}`);for(n+=t;n>=i;n-=i)c.push((r>>n-i&a)>>>0);const e=Wn[n];if(void 0===e)throw new Error("invalid carry");r&=e-1}if(r=r<<i-n&a,!s&&n>=t)throw new Error("Excess padding");if(!s&&r>0)throw new Error(`Non-zero padding: ${r}`);return s&&n>0&&c.push(r>>>0),c}function Yn(e,t=!1){if(kn(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Hn(8,e)>32||Hn(e,8)>32)throw new Error("radix2: carry overflow");return{encode:i=>{if(!Bn(i))throw new Error("radix2.encode input should be Uint8Array");return Gn(Array.from(i),8,e,!t)},decode:i=>(Dn("radix2.decode",i),Uint8Array.from(Gn(i,e,8,t)))}}function Zn(e){return Cn(e),function(...t){try{return e.apply(null,t)}catch(e){}}}Mn(Yn(4),$n("0123456789ABCDEF"),jn(""));const Jn=Mn(Yn(5),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),zn(5),jn(""));Mn(Yn(5),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),jn("")),Mn(Yn(5),$n("0123456789ABCDEFGHIJKLMNOPQRSTUV"),zn(5),jn("")),Mn(Yn(5),$n("0123456789ABCDEFGHIJKLMNOPQRSTUV"),jn("")),Mn(Yn(5),$n("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),jn(""),Fn((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))));const Xn=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();Xn||Mn(Yn(6),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),zn(6),jn("")),Mn(Yn(6),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),jn("")),Xn||Mn(Yn(6),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),zn(6),jn("")),Mn(Yn(6),$n("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),jn(""));const Qn=e=>{return Mn((kn(t=58),{encode:e=>{if(!Bn(e))throw new Error("radix.encode input should be Uint8Array");return Kn(Array.from(e),256,t)},decode:e=>(Dn("radix.decode",e),Uint8Array.from(Kn(e,t,256)))}),$n(e),jn(""));var t},eo=Qn("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");Qn("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Qn("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const to=Mn($n("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),jn("")),io=[996825010,642813549,513874426,1027748829,705979059];function so(e){const t=e>>25;let i=(33554431&e)<<5;for(let e=0;e<io.length;e++)1==(t>>e&1)&&(i^=io[e]);return i}function ro(e,t,i=1){const s=e.length;let r=1;for(let t=0;t<s;t++){const i=e.charCodeAt(t);if(i<33||i>126)throw new Error(`Invalid prefix (${e})`);r=so(r)^i>>5}r=so(r);for(let t=0;t<s;t++)r=so(r)^31&e.charCodeAt(t);for(let e of t)r=so(r)^e;for(let e=0;e<6;e++)r=so(r);return r^=i,to.encode(Gn([r%Wn[30]],30,5,!1))}function no(e){const t="bech32"===e?1:734539939,i=Yn(5),s=i.decode,r=i.encode,n=Zn(s);function o(e,i,s=90){Un("bech32.encode prefix",e),Bn(i)&&(i=Array.from(i)),Dn("bech32.encode",i);const r=e.length;if(0===r)throw new TypeError(`Invalid prefix length ${r}`);const n=r+7+i.length;if(!1!==s&&n>s)throw new TypeError(`Length ${n} exceeds limit ${s}`);const o=e.toLowerCase(),a=ro(o,i,t);return`${o}1${to.encode(i)}${a}`}function a(e,i=90){Un("bech32.decode input",e);const s=e.length;if(s<8||!1!==i&&s>i)throw new TypeError(`invalid string length: ${s} (${e}). Expected (8..${i})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const n=r.lastIndexOf("1");if(0===n||-1===n)throw new Error('Letter "1" must be present between prefix and data only');const o=r.slice(0,n),a=r.slice(n+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const c=to.decode(a).slice(0,-6),h=ro(o,c,t);if(!a.endsWith(h))throw new Error(`Invalid checksum in ${e}: expected "${h}"`);return{prefix:o,words:c}}return{encode:o,decode:a,encodeFromBytes:function(e,t){return o(e,r(t))},decodeToBytes:function(e){const{prefix:t,words:i}=a(e,!1);return{prefix:t,words:i,bytes:s(i)}},decodeUnsafe:Zn(a),fromWords:s,fromWordsUnsafe:n,toWords:r}}no("bech32"),no("bech32m");function oo(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function ao(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?oo(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function co(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const i=ao(t);let s=0;for(const t of e)i.set(t,s),s+=t.length;return oo(i)}(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||Mn(Yn(4),$n("0123456789abcdef"),jn(""),Fn((e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));var ho=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var f=n-r;f!==n&&0===o[f];)f++;for(var p=new Uint8Array(s+(n-f)),g=s;f!==n;)p[g++]=o[f++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,f=o-1;(0!==u||d<s)&&-1!==f;f--,d++)u+=256*h[f]>>>0,h[f]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var p=o-s;p!==o&&0===h[p];)p++;for(var g=c.repeat(i);p<o;++p)g+=e.charAt(h[p]);return g},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},lo=ho;const uo=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class fo{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class po{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return yo(this,e)}}class go{constructor(e){this.decoders=e}or(e){return yo(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 yo=(e,t)=>new go({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class wo{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new fo(e,t,i),this.decoder=new po(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const mo=({name:e,prefix:t,encode:i,decode:s})=>new wo(e,t,i,s),bo=({prefix:e,name:t,alphabet:i})=>{const{encode:s,decode:r}=lo(i,t);return mo({prefix:e,name:t,encode:s,decode:e=>uo(r(e))})},vo=({name:e,prefix:t,bitsPerChar:i,alphabet:s})=>mo({prefix:t,name:e,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let s=0;s<e.length;++s)for(a=a<<8|e[s],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,s,i),decode:t=>((e,t,i,s)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${s} character`);c=c<<i|n,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,s,i,e)}),Eo=mo({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var xo=Object.freeze({__proto__:null,identity:Eo});const Io=vo({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var So=Object.freeze({__proto__:null,base2:Io});const _o=vo({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Oo=Object.freeze({__proto__:null,base8:_o});const Ao=bo({prefix:"9",name:"base10",alphabet:"0123456789"});var Po=Object.freeze({__proto__:null,base10:Ao});const To=vo({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ro=vo({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Bo=Object.freeze({__proto__:null,base16:To,base16upper:Ro});const No=vo({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Co=vo({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Uo=vo({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ko=vo({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Lo=vo({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),qo=vo({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Do=vo({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Mo=vo({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$o=vo({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jo=Object.freeze({__proto__:null,base32:No,base32upper:Co,base32pad:Uo,base32padupper:ko,base32hex:Lo,base32hexupper:qo,base32hexpad:Do,base32hexpadupper:Mo,base32z:$o});const zo=bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fo=bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ko=Object.freeze({__proto__:null,base36:zo,base36upper:Fo});const Vo=bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ho=bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wo=Object.freeze({__proto__:null,base58btc:Vo,base58flickr:Ho});const Go=vo({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yo=vo({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zo=vo({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Jo=vo({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xo=Object.freeze({__proto__:null,base64:Go,base64pad:Yo,base64url:Zo,base64urlpad:Jo});const Qo=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ea=Qo.reduce(((e,t,i)=>(e[i]=t,e)),[]),ta=Qo.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const ia=mo({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=ea[t]),"")},decode:function(e){const t=[];for(const i of e){const e=ta[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var sa=Object.freeze({__proto__:null,base256emoji:ia}),ra=function e(t,i,s){i=i||[];var r=s=s||0;for(;t>=aa;)i[s++]=255&t|na,t/=128;for(;t&oa;)i[s++]=255&t|na,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},na=128,oa=-128,aa=Math.pow(2,31);var ca=function e(t,i){var s,r=0,n=0,o=i=i||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&la)<<n:(s&la)*Math.pow(2,n),n+=7}while(s>=ha);return e.bytes=o-i,r},ha=128,la=127;var ua=Math.pow(2,7),da=Math.pow(2,14),fa=Math.pow(2,21),pa=Math.pow(2,28),ga=Math.pow(2,35),ya=Math.pow(2,42),wa=Math.pow(2,49),ma=Math.pow(2,56),ba=Math.pow(2,63),va={encode:ra,decode:ca,encodingLength:function(e){return e<ua?1:e<da?2:e<fa?3:e<pa?4:e<ga?5:e<ya?6:e<wa?7:e<ma?8:e<ba?9:10}};const Ea=(e,t,i=0)=>(va.encode(e,t,i),t),xa=e=>va.encodingLength(e),Ia=(e,t)=>{const i=t.byteLength,s=xa(e),r=s+xa(i),n=new Uint8Array(r+i);return Ea(e,n,0),Ea(i,n,s),n.set(t,r),new Sa(e,i,t,n)};class Sa{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const _a=({name:e,code:t,encode:i})=>new Oa(e,t,i);class Oa{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Ia(this.code,t):t.then((e=>Ia(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Aa=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t));_a({name:"sha2-256",code:18,encode:Aa("SHA-256")}),_a({name:"sha2-512",code:19,encode:Aa("SHA-512")});new TextEncoder,new TextDecoder;const Pa={...xo,...So,...Oo,...Po,...Bo,...jo,...Ko,...Wo,...Xo,...sa};function Ta(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ra=Ta("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ba=Ta("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=ao((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Na={utf8:Ra,"utf-8":Ra,hex:Pa.base16,latin1:Ba,ascii:Ba,binary:Ba,...Pa};function Ca(e,t="utf8"){const i=Na[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):oo(globalThis.Buffer.from(e,"utf-8"))}function Ua(e,t="utf8"){const i=Na[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}const ka=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),La=ka("expand 16-byte k"),qa=ka("expand 32-byte k"),Da=gr(La),Ma=gr(qa);function $a(e,t){return e<<t|e>>>32-t}function ja(e){return e.byteOffset%4==0}const za=64,Fa=16,Ka=2**32-1,Va=new Uint32Array;function Ha(e,t){const{allowShortKeys:i,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return dr(r),dr(o),ur(n),ur(i),(t,a,c,h,l=0)=>{fr(t),fr(a),fr(c);const u=c.length;if(void 0===h&&(h=new Uint8Array(u)),fr(h),dr(l),l<0||l>=Ka)throw new Error("arx: counter overflow");if(h.length<u)throw new Error(`arx: output (${h.length}) is shorter than data (${u})`);const d=[];let f,p,g=t.length;if(32===g)d.push(f=Ir(t)),p=Ma;else{if(16!==g||!i)throw new Error(`arx: invalid 32-byte key, got length=${g}`);f=new Uint8Array(32),f.set(t),f.set(t,16),p=Da,d.push(f)}ja(a)||d.push(a=Ir(a));const y=gr(f);if(s){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");s(p,y,gr(a.subarray(0,16)),y),a=a.subarray(16)}const w=16-r;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,n?0:12-a.length),a=e,d.push(a)}const m=gr(a);return function(e,t,i,s,r,n,o,a){const c=r.length,h=new Uint8Array(za),l=gr(h),u=ja(r)&&ja(n),d=u?gr(r):Va,f=u?gr(n):Va;for(let p=0;p<c;o++){if(e(t,i,s,l,o,a),o>=Ka)throw new Error("arx: counter overflow");const g=Math.min(za,c-p);if(u&&g===za){const e=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let t,i=0;i<Fa;i++)t=e+i,f[t]=d[t]^l[i];p+=za}else{for(let e,t=0;t<g;t++)e=p+t,n[e]=r[e]^h[t];p+=g}}}(e,p,y,m,c,h,l,o),yr(...d),h}}const Wa=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Ga{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,fr(e=mr(e),32);const t=Wa(e,0),i=Wa(e,2),s=Wa(e,4),r=Wa(e,6),n=Wa(e,8),o=Wa(e,10),a=Wa(e,12),c=Wa(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|i<<3),this.r[2]=7939&(i>>>10|s<<6),this.r[3]=8191&(s>>>7|r<<9),this.r[4]=255&(r>>>4|n<<12),this.r[5]=n>>>1&8190,this.r[6]=8191&(n>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Wa(e,16+2*t)}process(e,t,i=!1){const s=i?0:2048,{h:r,r:n}=this,o=n[0],a=n[1],c=n[2],h=n[3],l=n[4],u=n[5],d=n[6],f=n[7],p=n[8],g=n[9],y=Wa(e,t+0),w=Wa(e,t+2),m=Wa(e,t+4),b=Wa(e,t+6),v=Wa(e,t+8),E=Wa(e,t+10),x=Wa(e,t+12),I=Wa(e,t+14);let S=r[0]+(8191&y),_=r[1]+(8191&(y>>>13|w<<3)),O=r[2]+(8191&(w>>>10|m<<6)),A=r[3]+(8191&(m>>>7|b<<9)),P=r[4]+(8191&(b>>>4|v<<12)),T=r[5]+(v>>>1&8191),R=r[6]+(8191&(v>>>14|E<<2)),B=r[7]+(8191&(E>>>11|x<<5)),N=r[8]+(8191&(x>>>8|I<<8)),C=r[9]+(I>>>5|s),U=0,k=U+S*o+_*(5*g)+O*(5*p)+A*(5*f)+P*(5*d);U=k>>>13,k&=8191,k+=T*(5*u)+R*(5*l)+B*(5*h)+N*(5*c)+C*(5*a),U+=k>>>13,k&=8191;let L=U+S*a+_*o+O*(5*g)+A*(5*p)+P*(5*f);U=L>>>13,L&=8191,L+=T*(5*d)+R*(5*u)+B*(5*l)+N*(5*h)+C*(5*c),U+=L>>>13,L&=8191;let q=U+S*c+_*a+O*o+A*(5*g)+P*(5*p);U=q>>>13,q&=8191,q+=T*(5*f)+R*(5*d)+B*(5*u)+N*(5*l)+C*(5*h),U+=q>>>13,q&=8191;let D=U+S*h+_*c+O*a+A*o+P*(5*g);U=D>>>13,D&=8191,D+=T*(5*p)+R*(5*f)+B*(5*d)+N*(5*u)+C*(5*l),U+=D>>>13,D&=8191;let M=U+S*l+_*h+O*c+A*a+P*o;U=M>>>13,M&=8191,M+=T*(5*g)+R*(5*p)+B*(5*f)+N*(5*d)+C*(5*u),U+=M>>>13,M&=8191;let $=U+S*u+_*l+O*h+A*c+P*a;U=$>>>13,$&=8191,$+=T*o+R*(5*g)+B*(5*p)+N*(5*f)+C*(5*d),U+=$>>>13,$&=8191;let j=U+S*d+_*u+O*l+A*h+P*c;U=j>>>13,j&=8191,j+=T*a+R*o+B*(5*g)+N*(5*p)+C*(5*f),U+=j>>>13,j&=8191;let z=U+S*f+_*d+O*u+A*l+P*h;U=z>>>13,z&=8191,z+=T*c+R*a+B*o+N*(5*g)+C*(5*p),U+=z>>>13,z&=8191;let F=U+S*p+_*f+O*d+A*u+P*l;U=F>>>13,F&=8191,F+=T*h+R*c+B*a+N*o+C*(5*g),U+=F>>>13,F&=8191;let K=U+S*g+_*p+O*f+A*d+P*u;U=K>>>13,K&=8191,K+=T*l+R*h+B*c+N*a+C*o,U+=K>>>13,K&=8191,U=(U<<2)+U|0,U=U+k|0,k=8191&U,U>>>=13,L+=U,r[0]=k,r[1]=L,r[2]=q,r[3]=D,r[4]=M,r[5]=$,r[6]=j,r[7]=z,r[8]=F,r[9]=K}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=s,s=e[t]>>>13,e[t]&=8191;e[0]+=5*s,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 t=1;t<10;t++)i[t]=e[t]+s,s=i[t]>>>13,i[t]&=8191;i[9]-=8192;let r=(1^s)-1;for(let e=0;e<10;e++)i[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|i[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let n=e[0]+t[0];e[0]=65535&n;for(let i=1;i<8;i++)n=(e[i]+t[i]|0)+(n>>>16)|0,e[i]=65535&n;yr(i)}update(e){pr(this),fr(e=mr(e));const{buffer:t,blockLen:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(i-this.pos,s-r);if(n!==i)t.set(e.subarray(r,r+n),this.pos),this.pos+=n,r+=n,this.pos===i&&(this.process(t,0,!1),this.pos=0);else for(;i<=s-r;r+=i)this.process(e,r)}return this}destroy(){yr(this.h,this.r,this.buffer,this.pad)}digestInto(e){pr(this),function(e,t){fr(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=i[t]>>>0,e[r++]=i[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}}const Ya=function(e){const t=(t,i)=>e(i).update(mr(t)).digest(),i=e(new Uint8Array(32));return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}((e=>new Ga(e)));function Za(e,t,i,s,r,n=20){let o=e[0],a=e[1],c=e[2],h=e[3],l=t[0],u=t[1],d=t[2],f=t[3],p=t[4],g=t[5],y=t[6],w=t[7],m=r,b=i[0],v=i[1],E=i[2],x=o,I=a,S=c,_=h,O=l,A=u,P=d,T=f,R=p,B=g,N=y,C=w,U=m,k=b,L=v,q=E;for(let e=0;e<n;e+=2)x=x+O|0,U=$a(U^x,16),R=R+U|0,O=$a(O^R,12),x=x+O|0,U=$a(U^x,8),R=R+U|0,O=$a(O^R,7),I=I+A|0,k=$a(k^I,16),B=B+k|0,A=$a(A^B,12),I=I+A|0,k=$a(k^I,8),B=B+k|0,A=$a(A^B,7),S=S+P|0,L=$a(L^S,16),N=N+L|0,P=$a(P^N,12),S=S+P|0,L=$a(L^S,8),N=N+L|0,P=$a(P^N,7),_=_+T|0,q=$a(q^_,16),C=C+q|0,T=$a(T^C,12),_=_+T|0,q=$a(q^_,8),C=C+q|0,T=$a(T^C,7),x=x+A|0,q=$a(q^x,16),N=N+q|0,A=$a(A^N,12),x=x+A|0,q=$a(q^x,8),N=N+q|0,A=$a(A^N,7),I=I+P|0,U=$a(U^I,16),C=C+U|0,P=$a(P^C,12),I=I+P|0,U=$a(U^I,8),C=C+U|0,P=$a(P^C,7),S=S+T|0,k=$a(k^S,16),R=R+k|0,T=$a(T^R,12),S=S+T|0,k=$a(k^S,8),R=R+k|0,T=$a(T^R,7),_=_+O|0,L=$a(L^_,16),B=B+L|0,O=$a(O^B,12),_=_+O|0,L=$a(L^_,8),B=B+L|0,O=$a(O^B,7);let D=0;s[D++]=o+x|0,s[D++]=a+I|0,s[D++]=c+S|0,s[D++]=h+_|0,s[D++]=l+O|0,s[D++]=u+A|0,s[D++]=d+P|0,s[D++]=f+T|0,s[D++]=p+R|0,s[D++]=g+B|0,s[D++]=y+N|0,s[D++]=w+C|0,s[D++]=m+U|0,s[D++]=b+k|0,s[D++]=v+L|0,s[D++]=E+q|0}const Ja=Ha(Za,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Xa=new Uint8Array(16),Qa=(e,t)=>{e.update(t);const i=t.length%16;i&&e.update(Xa.subarray(i))},ec=new Uint8Array(32);function tc(e,t,i,s,r){const n=e(t,i,ec),o=Ya.create(n);r&&Qa(o,r),Qa(o,s);const a=xr(s.length,r?r.length:0,!0);o.update(a);const c=o.digest();return yr(n,a),c}const ic=br({blockSize:64,nonceLength:12,tagLength:16},(sc=Ja,(e,t,i)=>{const s=16;return{encrypt(r,n){const o=r.length;(n=vr(o+s,n,!1)).set(r);const a=n.subarray(0,-16);sc(e,t,a,a,1);const c=tc(sc,e,t,a,i);return n.set(c,o),yr(c),n},decrypt(r,n){n=vr(r.length-s,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=tc(sc,e,t,o,i);if(!function(e,t){if(e.length!==t.length)return!1;let i=0;for(let s=0;s<e.length;s++)i|=e[s]^t[s];return 0===i}(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),sc(e,t,n,n,1),yr(c),n}}}));var sc;class rc extends Ne{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,fe(e);const i=Re(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(i.length>s?e.create().update(i).digest():i);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),we(r)}update(e){return pe(this),this.iHash.update(e),this}digestInto(e){pe(this),de(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:t,iHash:i,finished:s,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const nc=(e,t,i)=>new rc(e,t).update(i).digest();nc.create=(e,t)=>new rc(e,t);const oc=Uint8Array.from([0]),ac=Uint8Array.of();const cc=(e,t,i,s,r)=>function(e,t,i,s=32){fe(e),ue(s);const r=e.outputLen;if(s>255*r)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(s/r);void 0===i&&(i=ac);const o=new Uint8Array(n*r),a=nc.create(e,t),c=a._cloneInto(),h=new Uint8Array(a.outputLen);for(let e=0;e<n;e++)oc[0]=e+1,c.update(0===e?ac:h).update(i).update(oc).digestInto(h),o.set(h,r*e),a._cloneInto(c);return a.destroy(),c.destroy(),we(h,oc),o.slice(0,s)}(e,function(e,t,i){return fe(e),void 0===i&&(i=new Uint8Array(e.outputLen)),nc(e,Re(i),Re(t))}(e,t,i),s,r),hc=zr,lc=BigInt(0),uc=BigInt(1);function dc(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function fc(e,t,i=""){const s=le(e),r=e?.length,n=void 0!==t;if(!s||n&&r!==t){throw new Error((i&&`"${i}" `)+"expected Uint8Array"+(n?` of length ${t}`:"")+", got "+(s?`length=${r}`:"type="+typeof e))}return e}function pc(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function gc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?lc:BigInt("0x"+e)}function yc(e){return gc(Oe(e))}function wc(e){return de(e),gc(Oe(Uint8Array.from(e).reverse()))}function mc(e,t){return Te(e.toString(16).padStart(2*t,"0"))}function bc(e,t){return mc(e,t).reverse()}function vc(e,t,i){let s;if("string"==typeof t)try{s=Te(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!le(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function Ec(e){return Uint8Array.from(e)}const xc=e=>"bigint"==typeof e&&lc<=e;function Ic(e,t,i,s){if(!function(e,t,i){return xc(e)&&xc(t)&&xc(i)&&t<=e&&e<i}(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}function Sc(e){let t;for(t=0;e>lc;e>>=uc,t+=1);return t}const _c=e=>(uc<<BigInt(e))-uc;function Oc(e,t,i={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function s(t,i,s){const r=e[t];if(s&&void 0===r)return;const n=typeof r;if(n!==i||null===r)throw new Error(`param "${t}" is invalid: expected ${i}, got ${n}`)}Object.entries(t).forEach((([e,t])=>s(e,t,!1))),Object.entries(i).forEach((([e,t])=>s(e,t,!0)))}const Ac=()=>{throw new Error("not implemented")};function Pc(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}const Tc=BigInt(0),Rc=BigInt(1),Bc=BigInt(2),Nc=BigInt(3),Cc=BigInt(4),Uc=BigInt(5),kc=BigInt(7),Lc=BigInt(8),qc=BigInt(9),Dc=BigInt(16);function Mc(e,t){const i=e%t;return i>=Tc?i:t+i}function $c(e,t,i){let s=e;for(;t-- >Tc;)s*=s,s%=i;return s}function jc(e,t){if(e===Tc)throw new Error("invert: expected non-zero number");if(t<=Tc)throw new Error("invert: expected positive modulus, got "+t);let i=Mc(e,t),s=t,r=Tc,n=Rc;for(;i!==Tc;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==Rc)throw new Error("invert: does not exist");return Mc(r,t)}function zc(e,t,i){if(!e.eql(e.sqr(t),i))throw new Error("Cannot find square root")}function Fc(e,t){const i=(e.ORDER+Rc)/Cc,s=e.pow(t,i);return zc(e,s,t),s}function Kc(e,t){const i=(e.ORDER-Uc)/Lc,s=e.mul(t,Bc),r=e.pow(s,i),n=e.mul(t,r),o=e.mul(e.mul(n,Bc),r),a=e.mul(n,e.sub(o,e.ONE));return zc(e,a,t),a}function Vc(e){if(e<Nc)throw new Error("sqrt is not defined for small field");let t=e-Rc,i=0;for(;t%Bc===Tc;)t/=Bc,i++;let s=Bc;const r=Xc(e);for(;1===Zc(r,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===i)return Fc;let n=r.pow(s,t);const o=(t+Rc)/Bc;return function(e,s){if(e.is0(s))return s;if(1!==Zc(e,s))throw new Error("Cannot find square root");let r=i,a=e.mul(e.ONE,n),c=e.pow(s,t),h=e.pow(s,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,i=e.sqr(c);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===r)throw new Error("Cannot find square root");const s=Rc<<BigInt(r-t-1),n=e.pow(a,s);r=t,a=e.sqr(n),c=e.mul(c,a),h=e.mul(h,n)}return h}}function Hc(e){return e%Cc===Nc?Fc:e%Lc===Uc?Kc:e%Dc===qc?function(e){const t=Xc(e),i=Vc(e),s=i(t,t.neg(t.ONE)),r=i(t,s),n=i(t,t.neg(s)),o=(e+kc)/Dc;return(e,t)=>{let i=e.pow(t,o),a=e.mul(i,s);const c=e.mul(i,r),h=e.mul(i,n),l=e.eql(e.sqr(a),t),u=e.eql(e.sqr(c),t);i=e.cmov(i,a,l),a=e.cmov(h,c,u);const d=e.eql(e.sqr(a),t),f=e.cmov(i,a,d);return zc(e,f,t),f}}(e):Vc(e)}const Wc=(e,t)=>(Mc(e,t)&Rc)===Rc,Gc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yc(e,t,i=!1){const s=new Array(t.length).fill(i?e.ZERO:void 0),r=t.reduce(((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i))),e.ONE),n=e.inv(r);return t.reduceRight(((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i))),n),s}function Zc(e,t){const i=(e.ORDER-Rc)/Bc,s=e.pow(t,i),r=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!r&&!n&&!o)throw new Error("invalid Legendre symbol result");return r?1:n?0:-1}function Jc(e,t){void 0!==t&&ue(t);const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function Xc(e,t,i=!1,s={}){if(e<=Tc)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,n,o,a=!1;if("object"==typeof t&&null!=t){if(s.sqrt||i)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(r=e.BITS),e.sqrt&&(n=e.sqrt),"boolean"==typeof e.isLE&&(i=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(r=t),s.sqrt&&(n=s.sqrt);const{nBitLength:c,nByteLength:h}=Jc(e,r);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const u=Object.freeze({ORDER:e,isLE:i,BITS:c,BYTES:h,MASK:_c(c),ZERO:Tc,ONE:Rc,allowedLengths:o,create:t=>Mc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Tc<=t&&t<e},is0:e=>e===Tc,isValidNot0:e=>!u.is0(e)&&u.isValid(e),isOdd:e=>(e&Rc)===Rc,neg:t=>Mc(-t,e),eql:(e,t)=>e===t,sqr:t=>Mc(t*t,e),add:(t,i)=>Mc(t+i,e),sub:(t,i)=>Mc(t-i,e),mul:(t,i)=>Mc(t*i,e),pow:(e,t)=>function(e,t,i){if(i<Tc)throw new Error("invalid exponent, negatives unsupported");if(i===Tc)return e.ONE;if(i===Rc)return t;let s=e.ONE,r=t;for(;i>Tc;)i&Rc&&(s=e.mul(s,r)),r=e.sqr(r),i>>=Rc;return s}(u,e,t),div:(t,i)=>Mc(t*jc(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>jc(t,e),sqrt:n||(t=>(l||(l=Hc(e)),l(u,t))),toBytes:e=>i?bc(e,h):mc(e,h),fromBytes:(t,s=!0)=>{if(o){if(!o.includes(t.length)||t.length>h)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(h);e.set(t,i?0:e.length-t.length),t=e}if(t.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+t.length);let r=i?wc(t):yc(t);if(a&&(r=Mc(r,e)),!s&&!u.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>Yc(u,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(u)}function Qc(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function eh(e){const t=Qc(e);return t+Math.ceil(t/2)}const th=BigInt(0),ih=BigInt(1);function sh(e,t){const i=t.negate();return e?i:t}function rh(e,t){const i=Yc(e.Fp,t.map((e=>e.Z)));return t.map(((t,s)=>e.fromAffine(t.toAffine(i[s]))))}function nh(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function oh(e,t){nh(e,t);const i=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:_c(e),maxNumber:i,shiftBy:BigInt(e)}}function ah(e,t,i){const{windowSize:s,mask:r,maxNumber:n,shiftBy:o}=i;let a=Number(e&r),c=e>>o;a>s&&(a-=n,c+=ih);const h=t*s;return{nextN:c,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:h}}const ch=new WeakMap,hh=new WeakMap;function lh(e){return hh.get(e)||1}function uh(e){if(e!==th)throw new Error("invalid wNAF")}class dh{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,i=this.ZERO){let s=e;for(;t>th;)t&ih&&(i=i.add(s)),s=s.double(),t>>=ih;return i}precomputeWindow(e,t){const{windows:i,windowSize:s}=oh(t,this.bits),r=[];let n=e,o=n;for(let e=0;e<i;e++){o=n,r.push(o);for(let e=1;e<s;e++)o=o.add(n),r.push(o);n=o.double()}return r}wNAF(e,t,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let s=this.ZERO,r=this.BASE;const n=oh(e,this.bits);for(let e=0;e<n.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:h,isNegF:l,offsetF:u}=ah(i,e,n);i=o,c?r=r.add(sh(l,t[u])):s=s.add(sh(h,t[a]))}return uh(i),{p:s,f:r}}wNAFUnsafe(e,t,i,s=this.ZERO){const r=oh(e,this.bits);for(let e=0;e<r.windows&&i!==th;e++){const{nextN:n,offset:o,isZero:a,isNeg:c}=ah(i,e,r);if(i=n,!a){const e=t[o];s=s.add(c?e.negate():e)}}return uh(i),s}getPrecomputes(e,t,i){let s=ch.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&("function"==typeof i&&(s=i(s)),ch.set(t,s))),s}cached(e,t,i){const s=lh(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)}unsafe(e,t,i,s){const r=lh(e);return 1===r?this._unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)}createCache(e,t){nh(t,this.bits),hh.set(e,t),ch.delete(e)}hasCache(e){return 1!==lh(e)}}function fh(e,t,i,s){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t);const r=i.length,n=s.length;if(r!==n)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Sc(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=_c(c),l=new Array(Number(h)+1).fill(o);let u=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(o);for(let t=0;t<n;t++){const r=s[t],n=Number(r>>BigInt(e)&h);l[n]=l[n].add(i[t])}let t=o;for(let e=l.length-1,i=o;e>0;e--)i=i.add(l[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<c;e++)u=u.double()}return u}function ph(e,t,i){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Oc(e,Gc.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Xc(e,{isLE:i})}function gh(e,t,i={},s){if(void 0===s&&(s="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const i=t[e];if(!("bigint"==typeof i&&i>th))throw new Error(`CURVE.${e} must be positive bigint`)}const r=ph(t.p,i.Fp,s),n=ph(t.n,i.Fn,s),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:r,Fn:n}}const yh=BigInt(0),wh=BigInt(1),mh=BigInt(2),bh=BigInt(8);class vh{constructor(e){this.ep=e}static fromBytes(e){Ac()}static fromHex(e){Ac()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Oe(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}}function Eh(e,t,i={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Oc(i,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:s}=i,{BASE:r,Fp:n,Fn:o}=e,a=i.randomBytes||ke,c=i.adjustScalarBytes||(e=>e),h=i.domain||((e,t,i)=>{if(dc(i,"phflag"),t.length||i)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return o.create(wc(e))}function u(e){const{head:i,prefix:s,scalar:n}=function(e){const i=y.secretKey;e=vc("private key",e,i);const s=vc("hashed private key",t(e),2*i),r=c(s.slice(0,i));return{head:r,prefix:s.slice(i,2*i),scalar:l(r)}}(e),o=r.multiply(n),a=o.toBytes();return{head:i,prefix:s,scalar:n,point:o,pointBytes:a}}function d(e){return u(e).pointBytes}function f(e=Uint8Array.of(),...i){const r=Be(...i);return l(t(h(r,vc("context",e),!!s)))}const p={zip215:!0};const g=n.BYTES,y={secretKey:g,publicKey:g,signature:2*g,seed:g};function w(e=a(y.seed)){return fc(e,y.seed,"seed")}const m={getExtendedPublicKey:u,randomSecretKey:w,isValidSecretKey:function(e){return le(e)&&e.length===o.BYTES},isValidPublicKey:function(t,i){try{return!!e.fromBytes(t,i)}catch(e){return!1}},toMontgomery(t){const{y:i}=e.fromBytes(t),s=y.publicKey,r=32===s;if(!r&&57!==s)throw new Error("only defined for 25519 and 448");const o=r?n.div(wh+i,wh-i):n.div(i-wh,i+wh);return n.toBytes(o)},toMontgomerySecret(e){const i=y.secretKey;fc(e,i);const s=t(e.subarray(0,i));return c(s).subarray(0,i)},randomPrivateKey:w,precompute:(t=8,i=e.BASE)=>i.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=m.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,i={}){e=vc("message",e),s&&(e=s(e));const{prefix:n,scalar:a,pointBytes:c}=u(t),h=f(i.context,n,e),l=r.multiply(h).toBytes(),d=f(i.context,l,c,e),p=o.create(h+d*a);if(!o.isValid(p))throw new Error("sign failed: invalid s");return fc(Be(l,o.toBytes(p)),y.signature,"result")},verify:function(t,i,n,o=p){const{context:a,zip215:c}=o,h=y.signature;t=vc("signature",t,h),i=vc("message",i),n=vc("publicKey",n,y.publicKey),void 0!==c&&dc(c,"zip215"),s&&(i=s(i));const l=h/2,u=t.subarray(0,l),d=wc(t.subarray(l,h));let g,w,m;try{g=e.fromBytes(n,c),w=e.fromBytes(u,c),m=r.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const b=f(a,w.toBytes(),g.toBytes(),i);return w.add(g.multiplyUnsafe(b)).subtract(m).clearCofactor().is0()},utils:m,Point:e,lengths:y})}function xh(e){const{CURVE:t,curveOpts:i,hash:s,eddsaOpts:r}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},i={Fp:e.Fp,Fn:Xc(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:i,hash:e.hash,eddsaOpts:s}}(e),n=function(e,t={}){const i=gh("edwards",e,t,t.FpFnLE),{Fp:s,Fn:r}=i;let n=i.CURVE;const{h:o}=n;Oc(t,{},{uvRatio:"function"});const a=mh<<BigInt(8*r.BYTES)-wh,c=e=>s.create(e),h=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:s.sqrt(s.div(e,t))}}catch(e){return{isValid:!1,value:yh}}});if(!function(e,t,i,s){const r=e.sqr(i),n=e.sqr(s),o=e.add(e.mul(t.a,r),n),a=e.add(e.ONE,e.mul(t.d,e.mul(r,n)));return e.eql(o,a)}(s,n,n.Gx,n.Gy))throw new Error("bad curve params: generator point");function l(e,t,i=!1){return Ic("coordinate "+e,t,i?wh:yh,a),t}function u(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=Pc(((e,t)=>{const{X:i,Y:r,Z:n}=e,o=e.is0();null==t&&(t=o?bh:s.inv(n));const a=c(i*t),h=c(r*t),l=s.mul(n,t);if(o)return{x:yh,y:wh};if(l!==wh)throw new Error("invZ was invalid");return{x:a,y:h}})),f=Pc((e=>{const{a:t,d:i}=n;if(e.is0())throw new Error("bad point: ZERO");const{X:s,Y:r,Z:o,T:a}=e,h=c(s*s),l=c(r*r),u=c(o*o),d=c(u*u),f=c(h*t);if(c(u*c(f+l))!==c(d+c(i*c(h*l))))throw new Error("bad point: equation left != right (1)");if(c(s*r)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0}));class p{constructor(e,t,i,s){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",i,!0),this.T=l("t",s),Object.freeze(this)}static CURVE(){return n}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:i}=e||{};return l("x",t),l("y",i),new p(t,i,wh,c(t*i))}static fromBytes(e,t=!1){const i=s.BYTES,{a:r,d:o}=n;e=Ec(fc(e,i,"point")),dc(t,"zip215");const l=Ec(e),u=e[i-1];l[i-1]=-129&u;const d=wc(l),f=t?a:s.ORDER;Ic("point.y",d,yh,f);const g=c(d*d),y=c(g-wh),w=c(o*g-r);let{isValid:m,value:b}=h(y,w);if(!m)throw new Error("bad point: invalid y coordinate");const v=(b&wh)===wh,E=0!=(128&u);if(!t&&b===yh&&E)throw new Error("bad point: x=0 and x_0=1");return E!==v&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(vc("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(mh),this}assertValidity(){f(this)}equals(e){u(e);const{X:t,Y:i,Z:s}=this,{X:r,Y:n,Z:o}=e,a=c(t*o),h=c(r*s),l=c(i*o),d=c(n*s);return a===h&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=n,{X:t,Y:i,Z:s}=this,r=c(t*t),o=c(i*i),a=c(mh*c(s*s)),h=c(e*r),l=t+i,u=c(c(l*l)-r-o),d=h+o,f=d-a,g=h-o,y=c(u*f),w=c(d*g),m=c(u*g),b=c(f*d);return new p(y,w,b,m)}add(e){u(e);const{a:t,d:i}=n,{X:s,Y:r,Z:o,T:a}=this,{X:h,Y:l,Z:d,T:f}=e,g=c(s*h),y=c(r*l),w=c(a*i*f),m=c(o*d),b=c((s+r)*(h+l)-g-y),v=m-w,E=m+w,x=c(y-t*g),I=c(b*v),S=c(E*x),_=c(b*x),O=c(v*E);return new p(I,S,O,_)}subtract(e){return this.add(e.negate())}multiply(e){if(!r.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:i}=g.cached(this,e,(e=>rh(p,e)));return rh(p,[t,i])[0]}multiplyUnsafe(e,t=p.ZERO){if(!r.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===yh?p.ZERO:this.is0()||e===wh?this:g.unsafe(this,e,(e=>rh(p,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,n.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===wh?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),i=s.toBytes(t);return i[i.length-1]|=e&wh?128:0,i}toHex(){return Oe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return rh(p,e)}static msm(e,t){return fh(p,r,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(n.Gx,n.Gy,wh,c(n.Gx*n.Gy)),p.ZERO=new p(yh,wh,wh,yh),p.Fp=s,p.Fn=r;const g=new dh(p,r.BITS);return p.BASE.precompute(8),p}(t,i);return function(e,t){const i=t.Point;return Object.assign({},t,{ExtendedPoint:i,CURVE:e,nBitLength:i.Fn.BITS,nByteLength:i.Fn.BYTES})}(e,Eh(n,s,r))}const Ih=BigInt(0),Sh=BigInt(1),_h=BigInt(2);function Oh(e){const t=(Oc(i=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...i}));var i;const{P:s,type:r,adjustScalarBytes:n,powPminus2:o,randomBytes:a}=t,c="x25519"===r;if(!c&&"x448"!==r)throw new Error("invalid type");const h=a||ke,l=c?255:448,u=c?32:56,d=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?_h**BigInt(254):_h**BigInt(447),g=c?BigInt(8)*_h**BigInt(251)-Sh:BigInt(4)*_h**BigInt(445)-Sh,y=p+g+Sh,w=e=>Mc(e,s),m=b(d);function b(e){return bc(w(e),u)}function v(e,t){const i=function(e,t){Ic("u",e,Ih,s),Ic("scalar",t,p,y);const i=t,r=e;let n=Sh,a=Ih,c=e,h=Sh,u=Ih;for(let e=BigInt(l-1);e>=Ih;e--){const t=i>>e&Sh;u^=t,({x_2:n,x_3:c}=x(u,n,c)),({x_2:a,x_3:h}=x(u,a,h)),u=t;const s=n+a,o=w(s*s),l=n-a,d=w(l*l),p=o-d,g=c+h,y=w((c-h)*s),m=w(g*l),b=y+m,v=y-m;c=w(b*b),h=w(r*w(v*v)),n=w(o*d),a=w(p*(o+w(f*p)))}({x_2:n,x_3:c}=x(u,n,c)),({x_2:a,x_3:h}=x(u,a,h));const d=o(a);return w(n*d)}(function(e){const t=vc("u coordinate",e,u);return c&&(t[31]&=127),w(wc(t))}(t),function(e){return wc(n(vc("scalar",e,u)))}(e));if(i===Ih)throw new Error("invalid private or public key received");return b(i)}function E(e){return v(e,m)}function x(e,t,i){const s=w(e*(t-i));return{x_2:t=w(t-s),x_3:i=w(i+s)}}const I={secretKey:u,publicKey:u,seed:u},S=(e=h(u))=>(de(e,I.seed),e);return{keygen:function(e){const t=S(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:{randomSecretKey:S,randomPrivateKey:S},GuBytes:m.slice(),lengths:I}}const Ah=BigInt(0),Ph=BigInt(1),Th=BigInt(2),Rh=BigInt(3),Bh=BigInt(5),Nh=BigInt(8),Ch=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Uh=(()=>({p:Ch,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Nh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function kh(e){const t=BigInt(10),i=BigInt(20),s=BigInt(40),r=BigInt(80),n=Ch,o=e*e%n*e%n,a=$c(o,Th,n)*o%n,c=$c(a,Ph,n)*e%n,h=$c(c,Bh,n)*c%n,l=$c(h,t,n)*h%n,u=$c(l,i,n)*l%n,d=$c(u,s,n)*u%n,f=$c(d,r,n)*d%n,p=$c(f,r,n)*d%n,g=$c(p,t,n)*h%n;return{pow_p_5_8:$c(g,Th,n)*e%n,b2:o}}function Lh(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const qh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Dh(e,t){const i=Ch,s=Mc(t*t*t,i),r=Mc(s*s*t,i);let n=Mc(e*s*kh(e*r).pow_p_5_8,i);const o=Mc(t*n*n,i),a=n,c=Mc(n*qh,i),h=o===e,l=o===Mc(-e,i),u=o===Mc(-e*qh,i);return h&&(n=a),(l||u)&&(n=c),Wc(n,i)&&(n=Mc(-n,i)),{isValid:h||l,value:n}}const Mh=(()=>Xc(Uh.p,{isLE:!0}))(),$h=(()=>Xc(Uh.n,{isLE:!0}))(),jh=(()=>({...Uh,Fp:Mh,hash:Fr,adjustScalarBytes:Lh,uvRatio:Dh}))(),zh=(()=>xh(jh))(),Fh=(()=>{const e=Mh.ORDER;return Oh({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:i,b2:s}=kh(t);return Mc($c(i,Rh,e)*s,e)},adjustScalarBytes:Lh})})(),Kh=qh,Vh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Hh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Wh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Gh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Yh=e=>Dh(Ph,e),Zh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Jh=e=>zh.Point.Fp.create(wc(e)&Zh);function Xh(e){const{d:t}=Uh,i=Ch,s=e=>Mh.create(e),r=s(Kh*e*e),n=s((r+Ph)*Wh);let o=BigInt(-1);const a=s((o-t*r)*s(r+t));let{isValid:c,value:h}=Dh(n,a),l=s(h*e);Wc(l,i)||(l=s(-l)),c||(h=l),c||(o=r);const u=s(o*(r-Ph)*Gh-a),d=h*h,f=s((h+h)*a),p=s(u*Vh),g=s(Ph-d),y=s(Ph+d);return new zh.Point(s(f*y),s(g*p),s(p*y),s(f*g))}class Qh extends vh{constructor(e){super(e)}static fromAffine(e){return new Qh(zh.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Qh))throw new Error("RistrettoPoint expected")}init(e){return new Qh(e)}static hashToCurve(e){return function(e){de(e,64);const t=Xh(Jh(e.subarray(0,32))),i=Xh(Jh(e.subarray(32,64)));return new Qh(t.add(i))}(vc("ristrettoHash",e,64))}static fromBytes(e){de(e,32);const{a:t,d:i}=Uh,s=Ch,r=e=>Mh.create(e),n=Jh(e);if(!function(e,t){if(e.length!==t.length)return!1;let i=0;for(let s=0;s<e.length;s++)i|=e[s]^t[s];return 0===i}(Mh.toBytes(n),e)||Wc(n,s))throw new Error("invalid ristretto255 encoding 1");const o=r(n*n),a=r(Ph+t*o),c=r(Ph-t*o),h=r(a*a),l=r(c*c),u=r(t*i*h-l),{isValid:d,value:f}=Yh(r(u*l)),p=r(f*c),g=r(f*p*u);let y=r((n+n)*p);Wc(y,s)&&(y=r(-y));const w=r(a*g),m=r(y*w);if(!d||Wc(m,s)||w===Ah)throw new Error("invalid ristretto255 encoding 2");return new Qh(new zh.Point(y,w,Ph,m))}static fromHex(e){return Qh.fromBytes(vc("ristrettoHex",e,32))}static msm(e,t){return fh(Qh,zh.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:i,T:s}=this.ep;const r=Ch,n=e=>Mh.create(e),o=n(n(i+t)*n(i-t)),a=n(e*t),c=n(a*a),{value:h}=Yh(n(o*c)),l=n(h*o),u=n(h*a),d=n(l*u*s);let f;if(Wc(s*d,r)){let i=n(t*Kh),s=n(e*Kh);e=i,t=s,f=n(l*Hh)}else f=u;Wc(e*d,r)&&(t=n(-t));let p=n((i-t)*f);return Wc(p,r)&&(p=n(-p)),Mh.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:i}=this.ep,{X:s,Y:r}=e.ep,n=e=>Mh.create(e),o=n(t*r)===n(i*s),a=n(i*r)===n(t*s);return o||a}is0(){return this.equals(Qh.ZERO)}}Qh.BASE=(()=>new Qh(zh.Point.BASE))(),Qh.ZERO=(()=>new Qh(zh.Point.ZERO))(),Qh.Fp=(()=>Mh)(),Qh.Fn=(()=>$h)();const el=(e,t)=>(e+(e>=0?t:-t)/al)/t;function tl(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function il(e,t){const i={};for(let s of Object.keys(t))i[s]=void 0===e[s]?t[s]:e[s];return dc(i.lowS,"lowS"),dc(i.prehash,"prehash"),void 0!==i.format&&tl(i.format),i}class sl extends Error{constructor(e=""){super(e)}}const rl={Err:sl,_tlv:{encode:(e,t)=>{const{Err:i}=rl;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");const s=t.length/2,r=pc(s);if(r.length/2&128)throw new i("tlv.encode: long form length too big");const n=s>127?pc(r.length/2|128):"";return pc(e)+n+r+t},decode(e,t){const{Err:i}=rl;let s=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new i("tlv.decode: wrong tlv");const r=t[s++];let n=0;if(!!(128&r)){const e=127&r;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===o[0])throw new i("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(s+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(s,s+n);if(o.length!==n)throw new i("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=rl;if(e<nl)throw new t("integer: negative integers are not allowed");let i=pc(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){const{Err:t}=rl;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return yc(e)}},toSig(e){const{Err:t,_int:i,_tlv:s}=rl,r=vc("signature",e),{v:n,l:o}=s.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(h)}},hexFromSig(e){const{_tlv:t,_int:i}=rl,s=t.encode(2,i.encode(e.r))+t.encode(2,i.encode(e.s));return t.encode(48,s)}},nl=BigInt(0),ol=BigInt(1),al=BigInt(2),cl=BigInt(3),hl=BigInt(4);function ll(e,t){const{BYTES:i}=e;let s;if("bigint"==typeof t)s=t;else{let r=vc("private key",t);try{s=e.fromBytes(r)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${i}, got ${typeof t}`)}}if(!e.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function ul(e,t={}){const i=gh("weierstrass",e,t),{Fp:s,Fn:r}=i;let n=i.CURVE;const{h:o,n:a}=n;Oc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!s.is0(n.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const h=fl(s,r);function l(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const u=t.toBytes||function(e,t,i){const{x:r,y:n}=t.toAffine(),o=s.toBytes(r);if(dc(i,"isCompressed"),i){l();return Be(dl(!s.isOdd(n)),o)}return Be(Uint8Array.of(4),o,s.toBytes(n))},d=t.fromBytes||function(e){fc(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:i}=h,r=e.length,n=e[0],o=e.subarray(1);if(r!==t||2!==n&&3!==n){if(r===i&&4===n){const e=s.BYTES,t=s.fromBytes(o.subarray(0,e)),i=s.fromBytes(o.subarray(e,2*e));if(!p(t,i))throw new Error("bad point: is not on curve");return{x:t,y:i}}throw new Error(`bad point: got length ${r}, expected compressed=${t} or uncompressed=${i}`)}{const e=s.fromBytes(o);if(!s.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=f(e);let i;try{i=s.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}l();return 1==(1&n)!==s.isOdd(i)&&(i=s.neg(i)),{x:e,y:i}}};function f(e){const t=s.sqr(e),i=s.mul(t,e);return s.add(s.add(i,s.mul(e,n.a)),n.b)}function p(e,t){const i=s.sqr(t),r=f(e);return s.eql(i,r)}if(!p(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const g=s.mul(s.pow(n.a,cl),hl),y=s.mul(s.sqr(n.b),BigInt(27));if(s.is0(s.add(g,y)))throw new Error("bad curve params: a or b");function w(e,t,i=!1){if(!s.isValid(t)||i&&s.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function m(e){if(!(e instanceof I))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,i){const[[s,r],[n,o]]=t,a=el(o*e,i),c=el(-r*e,i);let h=e-a*s-c*n,l=-a*r-c*o;const u=h<nl,d=l<nl;u&&(h=-h),d&&(l=-l);const f=_c(Math.ceil(Sc(i)/2))+ol;if(h<nl||h>=f||l<nl||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:h,k2neg:d,k2:l}}(e,c.basises,r.ORDER)}const v=Pc(((e,t)=>{const{X:i,Y:r,Z:n}=e;if(s.eql(n,s.ONE))return{x:i,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(n));const a=s.mul(i,t),c=s.mul(r,t),h=s.mul(n,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(h,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),E=Pc((e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:i,y:r}=e.toAffine();if(!s.isValid(i)||!s.isValid(r))throw new Error("bad point: x or y not field elements");if(!p(i,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));function x(e,t,i,r,n){return i=new I(s.mul(i.X,e),i.Y,i.Z),t=sh(r,t),i=sh(n,i),t.add(i)}class I{constructor(e,t,i){this.X=w("x",e),this.Y=w("y",t,!0),this.Z=w("z",i),Object.freeze(this)}static CURVE(){return n}static fromAffine(e){const{x:t,y:i}=e||{};if(!e||!s.isValid(t)||!s.isValid(i))throw new Error("invalid affine point");if(e instanceof I)throw new Error("projective point not allowed");return s.is0(t)&&s.is0(i)?I.ZERO:new I(t,i,s.ONE)}static fromBytes(e){const t=I.fromAffine(d(fc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return I.fromBytes(vc("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return _.createCache(this,e),t||this.multiply(cl),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(e)}equals(e){m(e);const{X:t,Y:i,Z:r}=this,{X:n,Y:o,Z:a}=e,c=s.eql(s.mul(t,a),s.mul(n,r)),h=s.eql(s.mul(i,a),s.mul(o,r));return c&&h}negate(){return new I(this.X,s.neg(this.Y),this.Z)}double(){const{a:e,b:t}=n,i=s.mul(t,cl),{X:r,Y:o,Z:a}=this;let c=s.ZERO,h=s.ZERO,l=s.ZERO,u=s.mul(r,r),d=s.mul(o,o),f=s.mul(a,a),p=s.mul(r,o);return p=s.add(p,p),l=s.mul(r,a),l=s.add(l,l),c=s.mul(e,l),h=s.mul(i,f),h=s.add(c,h),c=s.sub(d,h),h=s.add(d,h),h=s.mul(c,h),c=s.mul(p,c),l=s.mul(i,l),f=s.mul(e,f),p=s.sub(u,f),p=s.mul(e,p),p=s.add(p,l),l=s.add(u,u),u=s.add(l,u),u=s.add(u,f),u=s.mul(u,p),h=s.add(h,u),f=s.mul(o,a),f=s.add(f,f),u=s.mul(f,p),c=s.sub(c,u),l=s.mul(f,d),l=s.add(l,l),l=s.add(l,l),new I(c,h,l)}add(e){m(e);const{X:t,Y:i,Z:r}=this,{X:o,Y:a,Z:c}=e;let h=s.ZERO,l=s.ZERO,u=s.ZERO;const d=n.a,f=s.mul(n.b,cl);let p=s.mul(t,o),g=s.mul(i,a),y=s.mul(r,c),w=s.add(t,i),b=s.add(o,a);w=s.mul(w,b),b=s.add(p,g),w=s.sub(w,b),b=s.add(t,r);let v=s.add(o,c);return b=s.mul(b,v),v=s.add(p,y),b=s.sub(b,v),v=s.add(i,r),h=s.add(a,c),v=s.mul(v,h),h=s.add(g,y),v=s.sub(v,h),u=s.mul(d,b),h=s.mul(f,y),u=s.add(h,u),h=s.sub(g,u),u=s.add(g,u),l=s.mul(h,u),g=s.add(p,p),g=s.add(g,p),y=s.mul(d,y),b=s.mul(f,b),g=s.add(g,y),y=s.sub(p,y),y=s.mul(d,y),b=s.add(b,y),p=s.mul(g,b),l=s.add(l,p),p=s.mul(v,b),h=s.mul(w,h),h=s.sub(h,p),p=s.mul(w,g),u=s.mul(v,u),u=s.add(u,p),new I(h,l,u)}subtract(e){return this.add(e.negate())}is0(){return this.equals(I.ZERO)}multiply(e){const{endo:i}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,n;const o=e=>_.cached(this,e,(e=>rh(I,e)));if(i){const{k1neg:t,k1:r,k2neg:a,k2:c}=b(e),{p:h,f:l}=o(r),{p:u,f:d}=o(c);n=l.add(d),s=x(i.beta,h,u,t,a)}else{const{p:t,f:i}=o(e);s=t,n=i}return rh(I,[s,n])[0]}multiplyUnsafe(e){const{endo:i}=t,s=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===nl||s.is0())return I.ZERO;if(e===ol)return s;if(_.hasCache(this))return this.multiply(e);if(i){const{k1neg:t,k1:r,k2neg:n,k2:o}=b(e),{p1:a,p2:c}=function(e,t,i,s){let r=t,n=e.ZERO,o=e.ZERO;for(;i>th||s>th;)i&ih&&(n=n.add(r)),s&ih&&(o=o.add(r)),r=r.double(),i>>=ih,s>>=ih;return{p1:n,p2:o}}(I,s,r,o);return x(i.beta,a,c,t,n)}return _.unsafe(s,e)}multiplyAndAddUnsafe(e,t,i){const s=this.multiplyUnsafe(t).add(e.multiplyUnsafe(i));return s.is0()?void 0:s}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===ol||(e?e(I,this):_.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===ol?this:e?e(I,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return dc(e,"isCompressed"),this.assertValidity(),u(I,this,e)}toHex(e=!0){return Oe(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return rh(I,e)}static msm(e,t){return fh(I,r,e,t)}static fromPrivateKey(e){return I.BASE.multiply(ll(r,e))}}I.BASE=new I(n.Gx,n.Gy,s.ONE),I.ZERO=new I(s.ZERO,s.ONE,s.ZERO),I.Fp=s,I.Fn=r;const S=r.BITS,_=new dh(I,t.endo?Math.ceil(S/2):S);return I.BASE.precompute(8),I}function dl(e){return Uint8Array.of(e?2:3)}function fl(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function pl(e,t={}){const{Fn:i}=e,s=t.randomBytes||ke,r=Object.assign(fl(e.Fp,i),{seed:eh(i.ORDER)});function n(e){try{return!!ll(i,e)}catch(e){return!1}}function o(e=s(r.seed)){return function(e,t,i=!1){const s=e.length,r=Qc(t),n=eh(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=Mc(i?wc(e):yc(e),t-Rc)+Rc;return i?bc(o,r):mc(o,r)}(fc(e,r.seed,"seed"),i.ORDER)}function a(t,s=!0){return e.BASE.multiply(ll(i,t)).toBytes(s)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:s,publicKey:n,publicKeyUncompressed:o}=r;if(i.allowedLengths||s===n)return;const a=vc("key",t).length;return a===n||a===o}const h={isValidSecretKey:n,isValidPublicKey:function(t,i){const{publicKey:s,publicKeyUncompressed:n}=r;try{const r=t.length;return(!0!==i||r===s)&&((!1!==i||r===n)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:n,randomPrivateKey:o,normPrivateKeyToScalar:e=>ll(i,e),precompute:(t=8,i=e.BASE)=>i.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,s,r=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(s))throw new Error("second arg must be public key");const n=ll(i,t);return e.fromHex(s).multiply(n).toBytes(r)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:h,lengths:r})}function gl(e,t,i={}){fe(t),Oc(i,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const s=i.randomBytes||ke,r=i.hmac||((e,...i)=>nc(t,e,Be(...i))),{Fp:n,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f}=pl(e,i),p={prehash:!1,lowS:"boolean"==typeof i.lowS&&i.lowS,format:void 0,extraEntropy:!1},g="compact";function y(e){return e>a>>ol}function w(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class m{constructor(e,t,i){this.r=w("r",e),this.s=w("s",t),null!=i&&(this.recovery=i),Object.freeze(this)}static fromBytes(e,t=g){let i;if(function(e,t){tl(t);const i=f.signature;fc(e,"compact"===t?i:"recovered"===t?i+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:i}=rl.toSig(fc(e));return new m(t,i)}"recovered"===t&&(i=e[0],t="compact",e=e.subarray(1));const s=o.BYTES,r=e.subarray(0,s),n=e.subarray(s,2*s);return new m(o.fromBytes(r),o.fromBytes(n),i)}static fromHex(e,t){return this.fromBytes(Te(e),t)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(t){const i=n.ORDER,{r:s,s:r,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*al<i&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const h=2===c||3===c?s+a:s;if(!n.isValid(h))throw new Error("recovery id 2 or 3 invalid");const l=n.toBytes(h),u=e.fromBytes(Be(dl(0==(1&c)),l)),d=o.inv(h),f=v(vc("msgHash",t)),p=o.create(-f*d),g=o.create(r*d),y=e.BASE.multiplyUnsafe(p).add(u.multiplyUnsafe(g));if(y.is0())throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return y(this.s)}toBytes(e=g){if(tl(e),"der"===e)return Te(rl.hexFromSig(this));const t=o.toBytes(this.r),i=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return Be(Uint8Array.of(this.recovery),t,i)}return Be(t,i)}toHex(e){return Oe(this.toBytes(e))}assertValidity(){}static fromCompact(e){return m.fromBytes(vc("sig",e),"compact")}static fromDER(e){return m.fromBytes(vc("sig",e),"der")}normalizeS(){return this.hasHighS()?new m(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Oe(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Oe(this.toBytes("compact"))}}const b=i.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=yc(e),i=8*e.length-c;return i>0?t>>BigInt(i):t},v=i.bits2int_modN||function(e){return o.create(b(e))},E=_c(c);function x(e){return Ic("num < 2^"+c,e,nl,E),o.toBytes(e)}function I(e,i){return fc(e,void 0,"message"),i?fc(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f,Point:e,sign:function(i,n,a={}){i=vc("message",i);const{seed:c,k2sig:h}=function(t,i,r){if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");const{lowS:n,prehash:a,extraEntropy:c}=il(r,p);t=I(t,a);const h=v(t),l=ll(o,i),u=[x(l),x(h)];if(null!=c&&!1!==c){const e=!0===c?s(f.secretKey):c;u.push(vc("extraEntropy",e))}const d=Be(...u),g=h;return{seed:d,k2sig:function(t){const i=b(t);if(!o.isValidNot0(i))return;const s=o.inv(i),r=e.BASE.multiply(i).toAffine(),a=o.create(r.x);if(a===nl)return;const c=o.create(s*o.create(g+a*l));if(c===nl)return;let h=(r.x===a?0:2)|Number(r.y&ol),u=c;return n&&y(c)&&(u=o.neg(c),h^=1),new m(a,u,h)}}}(i,n,a),l=function(e,t,i){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof i)throw new Error("hmacFn must be a function");const s=e=>new Uint8Array(e),r=e=>Uint8Array.of(e);let n=s(e),o=s(e),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},h=(...e)=>i(o,n,...e),l=(e=s(0))=>{o=h(r(0),e),n=h(),0!==e.length&&(o=h(r(1),e),n=h())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const i=[];for(;e<t;){n=h();const t=n.slice();i.push(t),e+=n.length}return Be(...i)};return(e,t)=>{let i;for(c(),l(e);!(i=t(u()));)l();return c(),i}}(t.outputLen,o.BYTES,r);return l(c,h)},verify:function(t,i,s,r={}){const{lowS:n,prehash:a,format:c}=il(r,p);if(s=vc("publicKey",s),i=I(vc("message",i),a),"strict"in r)throw new Error("options.strict was renamed to lowS");const h=void 0===c?function(e){let t;const i="string"==typeof e||le(e),s=!i&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!i&&!s)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(s)t=new m(e.r,e.s);else if(i){try{t=m.fromBytes(vc("sig",e),"der")}catch(e){if(!(e instanceof rl.Err))throw e}if(!t)try{t=m.fromBytes(vc("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):m.fromBytes(vc("sig",t),c);if(!1===h)return!1;try{const t=e.fromBytes(s);if(n&&h.hasHighS())return!1;const{r:r,s:a}=h,c=v(i),l=o.inv(a),u=o.create(c*l),d=o.create(r*l),f=e.BASE.multiplyUnsafe(u).add(t.multiplyUnsafe(d));if(f.is0())return!1;return o.create(f.x)===r}catch(e){return!1}},recoverPublicKey:function(e,t,i={}){const{prehash:s}=il(i,p);return t=I(t,s),m.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:m,hash:t})}function yl(e){const{CURVE:t,curveOpts:i}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},i=e.Fp;let s=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:i,Fn:Xc(t.n,{BITS:e.nBitLength,allowedLengths:s,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),s={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:i,hash:e.hash,ecdsaOpts:s}}function wl(e){const{CURVE:t,curveOpts:i,hash:s,ecdsaOpts:r}=yl(e);return function(e,t){const i=t.Point;return Object.assign({},t,{ProjectivePoint:i,CURVE:Object.assign({},e,Jc(i.Fn.ORDER,i.Fn.BITS))})}(e,gl(ul(t,i),s,r))}function ml(e,t){const i=t=>wl({...e,hash:t});return{...i(t),create:i}}const bl={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},vl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},El={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},xl=Xc(bl.p),Il=Xc(vl.p),Sl=Xc(El.p),_l=ml({...bl,Fp:xl,lowS:!1},zr);ml({...vl,Fp:Il,lowS:!1},Kr),ml({...El,Fp:Sl,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Fr);const Ol=_l,Al=e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)),Pl=e=>{const t=e.replace(/([\[:])?(\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,'$1"$2n"$3');return JSON.parse(t,((e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t))};function Tl(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return Pl(e)}catch(t){return e}}function Rl(e){return"string"==typeof e?e:Al(e)||""}function Bl(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Nl(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Cl="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Ul=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kl(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),Bl(e),e}class Ll{clone(){return this._cloneInto()}}function ql(e=32){if(Cl&&"function"==typeof Cl.getRandomValues)return Cl.getRandomValues(new Uint8Array(e));if(Cl&&"function"==typeof Cl.randomBytes)return Cl.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}class Dl extends Ll{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,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=Ul(this.buffer)}update(e){Nl(this);const{view:t,buffer:i,blockLen:s}=this,r=(e=kl(e)).length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Ul(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nl(this),function(e,t){Bl(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,this.buffer.subarray(n).fill(0),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;(function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)})(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=Ul(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=n,s%t&&e.buffer.set(i),e}}const Ml=BigInt(2**32-1),$l=BigInt(32);function jl(e,t=!1){return t?{h:Number(e&Ml),l:Number(e>>$l&Ml)}:{h:0|Number(e>>$l&Ml),l:0|Number(e&Ml)}}const zl={fromBig:jl,split:function(e,t=!1){let i=new Uint32Array(e.length),s=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=jl(e[r],t);[i[r],s[r]]=[n,o]}return[i,s]},toBig:(e,t)=>BigInt(e>>>0)<<$l|BigInt(t>>>0),shrSH:(e,t,i)=>e>>>i,shrSL:(e,t,i)=>e<<32-i|t>>>i,rotrSH:(e,t,i)=>e>>>i|t<<32-i,rotrSL:(e,t,i)=>e<<32-i|t>>>i,rotrBH:(e,t,i)=>e<<64-i|t>>>i-32,rotrBL:(e,t,i)=>e>>>i-32|t<<64-i,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,i)=>e<<i|t>>>32-i,rotlSL:(e,t,i)=>t<<i|e>>>32-i,rotlBH:(e,t,i)=>t<<i-32|e>>>64-i,rotlBL:(e,t,i)=>e<<i-32|t>>>64-i,add:function(e,t,i,s){const r=(t>>>0)+(s>>>0);return{h:e+i+(r/2**32|0)|0,l:0|r}},add3L:(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),add3H:(e,t,i,s)=>t+i+s+(e/2**32|0)|0,add4L:(e,t,i,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),add4H:(e,t,i,s,r)=>t+i+s+r+(e/2**32|0)|0,add5H:(e,t,i,s,r,n)=>t+i+s+r+n+(e/2**32|0)|0,add5L:(e,t,i,s,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0)+(r>>>0)},[Fl,Kl]=zl.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((e=>BigInt(e)))),Vl=new Uint32Array(80),Hl=new Uint32Array(80);class Wl extends Dl{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:t,Bh:i,Bl:s,Ch:r,Cl:n,Dh:o,Dl:a,Eh:c,El:h,Fh:l,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|s,this.Ch=0|r,this.Cl=0|n,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|h,this.Fh=0|l,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=4)Vl[i]=e.getUint32(t),Hl[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Vl[e-15],i=0|Hl[e-15],s=zl.rotrSH(t,i,1)^zl.rotrSH(t,i,8)^zl.shrSH(t,i,7),r=zl.rotrSL(t,i,1)^zl.rotrSL(t,i,8)^zl.shrSL(t,i,7),n=0|Vl[e-2],o=0|Hl[e-2],a=zl.rotrSH(n,o,19)^zl.rotrBH(n,o,61)^zl.shrSH(n,o,6),c=zl.rotrSL(n,o,19)^zl.rotrBL(n,o,61)^zl.shrSL(n,o,6),h=zl.add4L(r,c,Hl[e-7],Hl[e-16]),l=zl.add4H(h,s,a,Vl[e-7],Vl[e-16]);Vl[e]=0|l,Hl[e]=0|h}let{Ah:i,Al:s,Bh:r,Bl:n,Ch:o,Cl:a,Dh:c,Dl:h,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:y,Hl:w}=this;for(let e=0;e<80;e++){const t=zl.rotrSH(l,u,14)^zl.rotrSH(l,u,18)^zl.rotrBH(l,u,41),m=zl.rotrSL(l,u,14)^zl.rotrSL(l,u,18)^zl.rotrBL(l,u,41),b=l&d^~l&p,v=u&f^~u&g,E=zl.add5L(w,m,v,Kl[e],Hl[e]),x=zl.add5H(E,y,t,b,Fl[e],Vl[e]),I=0|E,S=zl.rotrSH(i,s,28)^zl.rotrBH(i,s,34)^zl.rotrBH(i,s,39),_=zl.rotrSL(i,s,28)^zl.rotrBL(i,s,34)^zl.rotrBL(i,s,39),O=i&r^i&o^r&o,A=s&n^s&a^n&a;y=0|p,w=0|g,p=0|d,g=0|f,d=0|l,f=0|u,({h:l,l:u}=zl.add(0|c,0|h,0|x,0|I)),c=0|o,h=0|a,o=0|r,a=0|n,r=0|i,n=0|s;const P=zl.add3L(I,_,A);i=zl.add3H(P,x,S,O),s=0|P}({h:i,l:s}=zl.add(0|this.Ah,0|this.Al,0|i,0|s)),({h:r,l:n}=zl.add(0|this.Bh,0|this.Bl,0|r,0|n)),({h:o,l:a}=zl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:h}=zl.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:l,l:u}=zl.add(0|this.Eh,0|this.El,0|l,0|u)),({h:d,l:f}=zl.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=zl.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:y,l:w}=zl.add(0|this.Hh,0|this.Hl,0|y,0|w)),this.set(i,s,r,n,o,a,c,h,l,u,d,f,p,g,y,w)}roundClean(){Vl.fill(0),Hl.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 Gl=function(e){const t=t=>e().update(kl(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}((()=>new Wl)),Yl=BigInt(0),Zl=BigInt(1),Jl=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Xl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ql(e){if(!Xl(e))throw new Error("Uint8Array expected")}function eu(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const tu=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function iu(e){Ql(e);let t="";for(let i=0;i<e.length;i++)t+=tu[e[i]];return t}function su(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Yl:BigInt("0x"+e)}const ru={_0:48,_9:57,A:65,F:70,a:97,f:102};function nu(e){return e>=ru._0&&e<=ru._9?e-ru._0:e>=ru.A&&e<=ru.F?e-(ru.A-10):e>=ru.a&&e<=ru.f?e-(ru.a-10):void 0}function ou(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=nu(e.charCodeAt(r)),n=nu(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function au(e){return Ql(e),su(iu(Uint8Array.from(e).reverse()))}function cu(e,t){return ou(e.toString(16).padStart(2*t,"0"))}function hu(e,t){return cu(e,t).reverse()}function lu(e,t,i){let s;if("string"==typeof t)try{s=ou(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Xl(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function uu(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Ql(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}const du=e=>"bigint"==typeof e&&Yl<=e;function fu(e,t,i,s){if(!function(e,t,i){return du(e)&&du(t)&&du(i)&&t<=e&&e<i}(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}const pu=e=>(Jl<<BigInt(e-1))-Zl,gu={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Xl(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function yu(e,t,i={}){const s=(t,i,s)=>{const r=gu[i];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+i+", got "+n)};for(const[e,i]of Object.entries(t))s(e,i,!1);for(const[e,t]of Object.entries(i))s(e,t,!0);return e}function wu(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}const mu=BigInt(0),bu=BigInt(1),vu=BigInt(2),Eu=BigInt(3),xu=BigInt(4),Iu=BigInt(5),Su=BigInt(8);function _u(e,t){const i=e%t;return i>=mu?i:t+i}function Ou(e,t,i){if(t<mu)throw new Error("invalid exponent, negatives unsupported");if(i<=mu)throw new Error("invalid modulus");if(i===bu)return mu;let s=bu;for(;t>mu;)t&bu&&(s=s*e%i),e=e*e%i,t>>=bu;return s}function Au(e,t,i){let s=e;for(;t-- >mu;)s*=s,s%=i;return s}function Pu(e,t){if(e===mu)throw new Error("invert: expected non-zero number");if(t<=mu)throw new Error("invert: expected positive modulus, got "+t);let i=_u(e,t),s=t,r=mu,n=bu;for(;i!==mu;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==bu)throw new Error("invert: does not exist");return _u(r,t)}function Tu(e){if(e%xu===Eu){const t=(e+bu)/xu;return function(e,i){const s=e.pow(i,t);if(!e.eql(e.sqr(s),i))throw new Error("Cannot find square root");return s}}if(e%Su===Iu){const t=(e-Iu)/Su;return function(e,i){const s=e.mul(i,vu),r=e.pow(s,t),n=e.mul(i,r),o=e.mul(e.mul(n,vu),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),i))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-bu)/vu;let i,s,r;for(i=e-bu,s=0;i%vu===mu;i/=vu,s++);for(r=vu;r<e&&Ou(r,t,e)!==e-bu;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===s){const t=(e+bu)/xu;return function(e,i){const s=e.pow(i,t);if(!e.eql(e.sqr(s),i))throw new Error("Cannot find square root");return s}}const n=(i+bu)/vu;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=s,c=e.pow(e.mul(e.ONE,r),i),h=e.pow(o,n),l=e.pow(o,i);for(;!e.eql(l,e.ONE);){if(e.eql(l,e.ZERO))return e.ZERO;let t=1;for(let i=e.sqr(l);t<a&&!e.eql(i,e.ONE);t++)i=e.sqr(i);const i=e.pow(c,bu<<BigInt(a-t-1));c=e.sqr(i),h=e.mul(h,i),l=e.mul(l,c),a=t}return h}}(e)}const Ru=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bu(e,t){const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function Nu(e,t,i=!1,s={}){if(e<=mu)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=Bu(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:i,BITS:r,BYTES:n,MASK:pu(r),ZERO:mu,ONE:bu,create:t=>_u(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return mu<=t&&t<e},is0:e=>e===mu,isOdd:e=>(e&bu)===bu,neg:t=>_u(-t,e),eql:(e,t)=>e===t,sqr:t=>_u(t*t,e),add:(t,i)=>_u(t+i,e),sub:(t,i)=>_u(t-i,e),mul:(t,i)=>_u(t*i,e),pow:(e,t)=>function(e,t,i){if(i<mu)throw new Error("invalid exponent, negatives unsupported");if(i===mu)return e.ONE;if(i===bu)return t;let s=e.ONE,r=t;for(;i>mu;)i&bu&&(s=e.mul(s,r)),r=e.sqr(r),i>>=bu;return s}(a,e,t),div:(t,i)=>_u(t*Pu(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Pu(t,e),sqrt:s.sqrt||(t=>(o||(o=Tu(e)),o(a,t))),invertBatch:e=>function(e,t){const i=new Array(t.length),s=t.reduce(((t,s,r)=>e.is0(s)?t:(i[r]=t,e.mul(t,s))),e.ONE),r=e.inv(s);return t.reduceRight(((t,s,r)=>e.is0(s)?t:(i[r]=e.mul(t,i[r]),e.mul(t,s))),r),i}(a,e),cmov:(e,t,i)=>i?t:e,toBytes:e=>i?hu(e,n):cu(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return i?au(e):function(e){return su(iu(e))}(e)}});return Object.freeze(a)}const Cu=BigInt(0),Uu=BigInt(1);function ku(e,t){const i=t.negate();return e?i:t}function Lu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function qu(e,t){Lu(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Du=new WeakMap,Mu=new WeakMap;function $u(e){return Mu.get(e)||1}function ju(e,t,i,s){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t),i.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,n=function(e){let t;for(t=0;e>Yl;e>>=Zl,t+=1);return t}(BigInt(i.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let h=r;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(r);for(let t=0;t<s.length;t++){const r=s[t],n=Number(r>>BigInt(e)&BigInt(a));c[n]=c[n].add(i[t])}let t=r;for(let e=c.length-1,i=r;e>0;e--)i=i.add(c[e]),t=t.add(i);if(h=h.add(t),0!==e)for(let e=0;e<o;e++)h=h.double()}return h}function zu(e){return function(e){const t=Ru.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});yu(e,t)}(e.Fp),yu(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bu(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const Fu=BigInt(0),Ku=BigInt(1),Vu=BigInt(2),Hu=BigInt(8),Wu={zip215:!0};function Gu(e){const t=function(e){const t=zu(e);return yu(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:i,n:s,prehash:r,hash:n,randomBytes:o,nByteLength:a,h:c}=t,h=Vu<<BigInt(8*a)-Ku,l=i.create,u=Nu(t.n,t.nBitLength),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:i.sqrt(e*i.inv(t))}}catch{return{isValid:!1,value:Fu}}}),f=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,i)=>{if(eu("phflag",i),t.length||i)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){fu("coordinate "+e,t,Fu,h)}function y(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const w=wu(((e,t)=>{const{ex:s,ey:r,ez:n}=e,o=e.is0();null==t&&(t=o?Hu:i.inv(n));const a=l(s*t),c=l(r*t),h=l(n*t);if(o)return{x:Fu,y:Ku};if(h!==Ku)throw new Error("invZ was invalid");return{x:a,y:c}})),m=wu((e=>{const{a:i,d:s}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:r,ey:n,ez:o,et:a}=e,c=l(r*r),h=l(n*n),u=l(o*o),d=l(u*u),f=l(c*i);if(l(u*l(f+h))!==l(d+l(s*l(c*h))))throw new Error("bad point: equation left != right (1)");if(l(r*n)!==l(o*a))throw new Error("bad point: equation left != right (2)");return!0}));class b{constructor(e,t,i,s){this.ex=e,this.ey=t,this.ez=i,this.et=s,g("x",e),g("y",t),g("z",i),g("t",s),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw new Error("extended point not allowed");const{x:t,y:i}=e||{};return g("x",t),g("y",i),new b(t,i,Ku,l(t*i))}static normalizeZ(e){const t=i.invertBatch(e.map((e=>e.ez)));return e.map(((e,i)=>e.toAffine(t[i]))).map(b.fromAffine)}static msm(e,t){return ju(b,u,e,t)}_setWindowSize(e){x.setWindowSize(this,e)}assertValidity(){m(this)}equals(e){y(e);const{ex:t,ey:i,ez:s}=this,{ex:r,ey:n,ez:o}=e,a=l(t*o),c=l(r*s),h=l(i*o),u=l(n*s);return a===c&&h===u}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:e}=t,{ex:i,ey:s,ez:r}=this,n=l(i*i),o=l(s*s),a=l(Vu*l(r*r)),c=l(e*n),h=i+s,u=l(l(h*h)-n-o),d=c+o,f=d-a,p=c-o,g=l(u*f),y=l(d*p),w=l(u*p),m=l(f*d);return new b(g,y,m,w)}add(e){y(e);const{a:i,d:s}=t,{ex:r,ey:n,ez:o,et:a}=this,{ex:c,ey:h,ez:u,et:d}=e;if(i===BigInt(-1)){const e=l((n-r)*(h+c)),t=l((n+r)*(h-c)),i=l(t-e);if(i===Fu)return this.double();const s=l(o*Vu*d),f=l(a*Vu*u),p=f+s,g=t+e,y=f-s,w=l(p*i),m=l(g*y),v=l(p*y),E=l(i*g);return new b(w,m,E,v)}const f=l(r*c),p=l(n*h),g=l(a*s*d),w=l(o*u),m=l((r+n)*(c+h)-f-p),v=w-g,E=w+g,x=l(p-i*f),I=l(m*v),S=l(E*x),_=l(m*x),O=l(v*E);return new b(I,S,O,_)}subtract(e){return this.add(e.negate())}wNAF(e){return x.wNAFCached(this,e,b.normalizeZ)}multiply(e){const t=e;fu("scalar",t,Ku,s);const{p:i,f:r}=this.wNAF(t);return b.normalizeZ([i,r])[0]}multiplyUnsafe(e,t=b.ZERO){const i=e;return fu("scalar",i,Fu,s),i===Fu?E:this.is0()||i===Ku?this:x.wNAFCachedUnsafe(this,i,b.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return x.unsafeLadder(this,s).is0()}toAffine(e){return w(this,e)}clearCofactor(){const{h:e}=t;return e===Ku?this:this.multiplyUnsafe(e)}static fromHex(e,s=!1){const{d:r,a:n}=t,o=i.BYTES;e=lu("pointHex",e,o),eu("zip215",s);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const u=au(a),f=s?h:i.ORDER;fu("pointHex.y",u,Fu,f);const p=l(u*u),g=l(p-Ku),y=l(r*p-n);let{isValid:w,value:m}=d(g,y);if(!w)throw new Error("Point.fromHex: invalid y coordinate");const v=(m&Ku)===Ku,E=0!=(128&c);if(!s&&m===Fu&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(m=l(-m)),b.fromAffine({x:m,y:u})}static fromPrivateKey(e){return _(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),s=hu(t,i.BYTES);return s[s.length-1]|=e&Ku?128:0,s}toHex(){return iu(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,Ku,l(t.Gx*t.Gy)),b.ZERO=new b(Fu,Ku,Ku,Fu);const{BASE:v,ZERO:E}=b,x=function(e,t){return{constTimeNegate:ku,hasPrecomputes:e=>1!==$u(e),unsafeLadder(t,i,s=e.ZERO){let r=t;for(;i>Cu;)i&Uu&&(s=s.add(r)),r=r.double(),i>>=Uu;return s},precomputeWindow(e,i){const{windows:s,windowSize:r}=qu(i,t),n=[];let o=e,a=o;for(let e=0;e<s;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(i,s,r){const{windows:n,windowSize:o}=qu(i,t);let a=e.ZERO,c=e.BASE;const h=BigInt(2**i-1),l=2**i,u=BigInt(i);for(let e=0;e<n;e++){const t=e*o;let i=Number(r&h);r>>=u,i>o&&(i-=l,r+=Uu);const n=t,d=t+Math.abs(i)-1,f=e%2!=0,p=i<0;0===i?c=c.add(ku(f,s[n])):a=a.add(ku(p,s[d]))}return{p:a,f:c}},wNAFUnsafe(i,s,r,n=e.ZERO){const{windows:o,windowSize:a}=qu(i,t),c=BigInt(2**i-1),h=2**i,l=BigInt(i);for(let e=0;e<o;e++){const t=e*a;if(r===Cu)break;let i=Number(r&c);if(r>>=l,i>a&&(i-=h,r+=Uu),0===i)continue;let o=s[t+Math.abs(i)-1];i<0&&(o=o.negate()),n=n.add(o)}return n},getPrecomputes(e,t,i){let s=Du.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&Du.set(t,i(s))),s},wNAFCached(e,t,i){const s=$u(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)},wNAFCachedUnsafe(e,t,i,s){const r=$u(e);return 1===r?this.unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)},setWindowSize(e,i){Lu(i,t),Mu.set(e,i),Du.delete(e)}}}(b,8*a);function I(e){return _u(e,s)}function S(e){return I(au(e))}function _(e){const t=i.BYTES;e=lu("private key",e,t);const s=lu("hashed private key",n(e),2*t),r=f(s.slice(0,t)),o=s.slice(t,2*t),a=S(r),c=v.multiply(a),h=c.toRawBytes();return{head:r,prefix:o,scalar:a,point:c,pointBytes:h}}function O(e=new Uint8Array,...t){const i=uu(...t);return S(n(p(i,lu("context",e),!!r)))}const A=Wu;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return _(e).pointBytes},sign:function(e,t,n={}){e=lu("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=_(t),h=O(n.context,o,e),l=v.multiply(h).toRawBytes(),u=I(h+O(n.context,l,c,e)*a);return fu("signature.s",u,Fu,s),lu("result",uu(l,hu(u,i.BYTES)),2*i.BYTES)},verify:function(e,t,s,n=A){const{context:o,zip215:a}=n,c=i.BYTES;e=lu("signature",e,2*c),t=lu("message",t),s=lu("publicKey",s,c),void 0!==a&&eu("zip215",a),r&&(t=r(t));const h=au(e.slice(c,2*c));let l,u,d;try{l=b.fromHex(s,a),u=b.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(h)}catch{return!1}if(!a&&l.isSmallOrder())return!1;const f=O(o,u.toRawBytes(),l.toRawBytes(),t);return u.add(l.multiplyUnsafe(f)).subtract(d).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:_,randomPrivateKey:()=>o(i.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}BigInt(0),BigInt(1);const Yu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Zu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ju=BigInt(1),Xu=BigInt(2);BigInt(3);const Qu=BigInt(5),ed=BigInt(8);function td(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function id(e,t){const i=Yu,s=_u(t*t*t,i),r=function(e){const t=BigInt(10),i=BigInt(20),s=BigInt(40),r=BigInt(80),n=Yu,o=e*e%n*e%n,a=Au(o,Xu,n)*o%n,c=Au(a,Ju,n)*e%n,h=Au(c,Qu,n)*c%n,l=Au(h,t,n)*h%n,u=Au(l,i,n)*l%n,d=Au(u,s,n)*u%n,f=Au(d,r,n)*d%n,p=Au(f,r,n)*d%n,g=Au(p,t,n)*h%n;return{pow_p_5_8:Au(g,Xu,n)*e%n,b2:o}}(e*_u(s*s*t,i)).pow_p_5_8;let n=_u(e*s*r,i);const o=_u(t*n*n,i),a=n,c=_u(n*Zu,i),h=o===e,l=o===_u(-e,i),u=o===_u(-e*Zu,i);return h&&(n=a),(l||u)&&(n=c),((e,t)=>(_u(e,t)&bu)===bu)(n,i)&&(n=_u(-n,i)),{isValid:h||l,value:n}}const sd=Nu(Yu,void 0,!0),rd=Gu({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:sd,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:ed,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Gl,randomBytes:ql,adjustScalarBytes:td,uvRatio:id}),nd=".",od="base64url",ad="utf8",cd="utf8",hd=":",ld="did",ud="key",dd="base58btc",fd="z",pd="K36";function gd(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function yd(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?gd(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function wd(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const i=yd(t);let s=0;for(const t of e)i.set(t,s),s+=t.length;return gd(i)}var md=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var f=n-r;f!==n&&0===o[f];)f++;for(var p=new Uint8Array(s+(n-f)),g=s;f!==n;)p[g++]=o[f++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,f=o-1;(0!==u||d<s)&&-1!==f;f--,d++)u+=256*h[f]>>>0,h[f]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var p=o-s;p!==o&&0===h[p];)p++;for(var g=c.repeat(i);p<o;++p)g+=e.charAt(h[p]);return g},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},bd=md;const vd=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Ed{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class xd{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return Sd(this,e)}}class Id{constructor(e){this.decoders=e}or(e){return Sd(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Sd=(e,t)=>new Id({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class _d{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Ed(e,t,i),this.decoder=new xd(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Od=({name:e,prefix:t,encode:i,decode:s})=>new _d(e,t,i,s),Ad=({prefix:e,name:t,alphabet:i})=>{const{encode:s,decode:r}=bd(i,t);return Od({prefix:e,name:t,encode:s,decode:e=>vd(r(e))})},Pd=({name:e,prefix:t,bitsPerChar:i,alphabet:s})=>Od({prefix:t,name:e,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let s=0;s<e.length;++s)for(a=a<<8|e[s],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,s,i),decode:t=>((e,t,i,s)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${s} character`);c=c<<i|n,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,s,i,e)}),Td=Od({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Rd=Object.freeze({__proto__:null,identity:Td});const Bd=Pd({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Nd=Object.freeze({__proto__:null,base2:Bd});const Cd=Pd({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ud=Object.freeze({__proto__:null,base8:Cd});const kd=Ad({prefix:"9",name:"base10",alphabet:"0123456789"});var Ld=Object.freeze({__proto__:null,base10:kd});const qd=Pd({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Dd=Pd({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Md=Object.freeze({__proto__:null,base16:qd,base16upper:Dd});const $d=Pd({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jd=Pd({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zd=Pd({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Fd=Pd({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Kd=Pd({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vd=Pd({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hd=Pd({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wd=Pd({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gd=Pd({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Yd=Object.freeze({__proto__:null,base32:$d,base32upper:jd,base32pad:zd,base32padupper:Fd,base32hex:Kd,base32hexupper:Vd,base32hexpad:Hd,base32hexpadupper:Wd,base32z:Gd});const Zd=Ad({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jd=Ad({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xd=Object.freeze({__proto__:null,base36:Zd,base36upper:Jd});const Qd=Ad({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ef=Ad({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var tf=Object.freeze({__proto__:null,base58btc:Qd,base58flickr:ef});const sf=Pd({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rf=Pd({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nf=Pd({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),of=Pd({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var af=Object.freeze({__proto__:null,base64:sf,base64pad:rf,base64url:nf,base64urlpad:of});const cf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),hf=cf.reduce(((e,t,i)=>(e[i]=t,e)),[]),lf=cf.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const uf=Od({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=hf[t]),"")},decode:function(e){const t=[];for(const i of e){const e=lf[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var df=Object.freeze({__proto__:null,base256emoji:uf}),ff=function e(t,i,s){i=i||[];for(var r=s=s||0;t>=yf;)i[s++]=255&t|pf,t/=128;for(;t&gf;)i[s++]=255&t|pf,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},pf=128,gf=-128,yf=Math.pow(2,31);var wf=function e(t,i){var s,r=0,n=(i=i||0,0),o=i,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&bf)<<n:(s&bf)*Math.pow(2,n),n+=7}while(s>=mf);return e.bytes=o-i,r},mf=128,bf=127;var vf=Math.pow(2,7),Ef=Math.pow(2,14),xf=Math.pow(2,21),If=Math.pow(2,28),Sf=Math.pow(2,35),_f=Math.pow(2,42),Of=Math.pow(2,49),Af=Math.pow(2,56),Pf=Math.pow(2,63),Tf={encode:ff,decode:wf,encodingLength:function(e){return e<vf?1:e<Ef?2:e<xf?3:e<If?4:e<Sf?5:e<_f?6:e<Of?7:e<Af?8:e<Pf?9:10}};const Rf=(e,t,i=0)=>(Tf.encode(e,t,i),t),Bf=e=>Tf.encodingLength(e),Nf=(e,t)=>{const i=t.byteLength,s=Bf(e),r=s+Bf(i),n=new Uint8Array(r+i);return Rf(e,n,0),Rf(i,n,s),n.set(t,r),new Cf(e,i,t,n)};class Cf{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Uf=({name:e,code:t,encode:i})=>new kf(e,t,i);class kf{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Nf(this.code,t):t.then((e=>Nf(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Lf=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),qf=Uf({name:"sha2-256",code:18,encode:Lf("SHA-256")}),Df=Uf({name:"sha2-512",code:19,encode:Lf("SHA-512")});Object.freeze({__proto__:null,sha256:qf,sha512:Df});const Mf=vd,$f={code:0,name:"identity",encode:Mf,digest:e=>Nf(0,Mf(e))};Object.freeze({__proto__:null,identity:$f});new TextEncoder,new TextDecoder;const jf={...Rd,...Nd,...Ud,...Ld,...Md,...Yd,...Xd,...tf,...af,...df};function zf(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ff=zf("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Kf=zf("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=yd((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Vf={utf8:Ff,"utf-8":Ff,hex:jf.base16,latin1:Kf,ascii:Kf,binary:Kf,...jf};function Hf(e,t="utf8"){const i=Vf[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function Wf(e,t="utf8"){const i=Vf[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):gd(globalThis.Buffer.from(e,"utf-8"))}function Gf(e){return Tl(Hf(Wf(e,od),ad))}function Yf(e){return Hf(Wf(Rl(e),ad),od)}function Zf(e){const t=Wf(pd,dd),i=fd+Hf(wd([t,e]),dd);return[ld,ud,i].join(hd)}function Jf(e){return Hf(e,od)}function Xf(e){const t=e.split(nd),i=Gf(t[0]),s=Gf(t[1]),r=function(e){return Wf(e,od)}(t[2]);return{header:i,payload:s,signature:r,data:Wf(t.slice(0,2).join(nd),cd)}}function Qf(e=ql(32)){const t=rd.getPublicKey(e);return{secretKey:wd([e,t]),publicKey:t}}async function ep(e,t,i,s,r=m.fromMiliseconds(Date.now())){const n={alg:"EdDSA",typ:"JWT"},o={iss:Zf(s.publicKey),sub:e,aud:t,iat:r,exp:r+i},a=function(e){return Wf([Yf(e.header),Yf(e.payload)].join(nd),cd)}({header:n,payload:o});return function(e){return[Yf(e.header),Yf(e.payload),Jf(e.signature)].join(nd)}({header:n,payload:o,signature:rd.sign(a,s.secretKey.slice(0,32))})}const tp={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"}};function ip(e){return(4294967296+e).toString(16).substring(1)}var sp={normalizeInput:function(e){let t;if(e instanceof Uint8Array)t=e;else{if("string"!=typeof e)throw new Error("Input must be an string, Buffer or Uint8Array");t=(new TextEncoder).encode(e)}return t},toHex:function(e){return Array.prototype.map.call(e,(function(e){return(e<16?"0":"")+e.toString(16)})).join("")},debugPrint:function(e,t,i){let s="\n"+e+" = ";for(let r=0;r<t.length;r+=2){if(32===i)s+=ip(t[r]).toUpperCase(),s+=" ",s+=ip(t[r+1]).toUpperCase();else{if(64!==i)throw new Error("Invalid size "+i);s+=ip(t[r+1]).toUpperCase(),s+=ip(t[r]).toUpperCase()}r%6==4?s+="\n"+new Array(e.length+4).join(" "):r<t.length-2&&(s+=" ")}console.log(s)},testSpeed:function(e,t,i){let s=(new Date).getTime();const r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=e%256;const n=(new Date).getTime();console.log("Generated random input in "+(n-s)+"ms"),s=n;for(let n=0;n<i;n++){const i=e(r),n=(new Date).getTime(),o=n-s;s=n,console.log("Hashed in "+o+"ms: "+i.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(o/1e3)*100)/100+" MB PER SECOND")}}};const rp=sp;function np(e,t,i){const s=e[t]+e[i];let r=e[t+1]+e[i+1];s>=4294967296&&r++,e[t]=s,e[t+1]=r}function op(e,t,i,s){let r=e[t]+i;i<0&&(r+=4294967296);let n=e[t+1]+s;r>=4294967296&&n++,e[t]=r,e[t+1]=n}function ap(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function cp(e,t,i,s,r,n){const o=dp[r],a=dp[r+1],c=dp[n],h=dp[n+1];np(up,e,t),op(up,e,o,a);let l=up[s]^up[e],u=up[s+1]^up[e+1];up[s]=u,up[s+1]=l,np(up,i,s),l=up[t]^up[i],u=up[t+1]^up[i+1],up[t]=l>>>24^u<<8,up[t+1]=u>>>24^l<<8,np(up,e,t),op(up,e,c,h),l=up[s]^up[e],u=up[s+1]^up[e+1],up[s]=l>>>16^u<<16,up[s+1]=u>>>16^l<<16,np(up,i,s),l=up[t]^up[i],u=up[t+1]^up[i+1],up[t]=u>>>31^l<<1,up[t+1]=l>>>31^u<<1}const hp=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),lp=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((function(e){return 2*e}))),up=new Uint32Array(32),dp=new Uint32Array(32);function fp(e,t){let i=0;for(i=0;i<16;i++)up[i]=e.h[i],up[i+16]=hp[i];for(up[24]=up[24]^e.t,up[25]=up[25]^e.t/4294967296,t&&(up[28]=~up[28],up[29]=~up[29]),i=0;i<32;i++)dp[i]=ap(e.b,4*i);for(i=0;i<12;i++)cp(0,8,16,24,lp[16*i+0],lp[16*i+1]),cp(2,10,18,26,lp[16*i+2],lp[16*i+3]),cp(4,12,20,28,lp[16*i+4],lp[16*i+5]),cp(6,14,22,30,lp[16*i+6],lp[16*i+7]),cp(0,10,20,30,lp[16*i+8],lp[16*i+9]),cp(2,12,22,24,lp[16*i+10],lp[16*i+11]),cp(4,14,16,26,lp[16*i+12],lp[16*i+13]),cp(6,8,18,28,lp[16*i+14],lp[16*i+15]);for(i=0;i<16;i++)e.h[i]=e.h[i]^up[i]^up[i+16]}const pp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function gp(e,t,i,s){if(0===e||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(i&&16!==i.length)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(s&&16!==s.length)throw new Error("Illegal personal, expected Uint8Array with length is 16");const r={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};pp.fill(0),pp[0]=e,t&&(pp[1]=t.length),pp[2]=1,pp[3]=1,i&&pp.set(i,32),s&&pp.set(s,48);for(let e=0;e<16;e++)r.h[e]=hp[e]^ap(pp,4*e);return t&&(yp(r,t),r.c=128),r}function yp(e,t){for(let i=0;i<t.length;i++)128===e.c&&(e.t+=e.c,fp(e,!1),e.c=0),e.b[e.c++]=t[i]}function wp(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;fp(e,!0);const t=new Uint8Array(e.outlen);for(let i=0;i<e.outlen;i++)t[i]=e.h[i>>2]>>8*(3&i);return t}function mp(e,t,i,s,r){i=i||64,e=rp.normalizeInput(e),s&&(s=rp.normalizeInput(s)),r&&(r=rp.normalizeInput(r));const n=gp(i,t,s,r);return yp(n,e),wp(n)}var bp={blake2b:mp,blake2bHex:function(e,t,i,s,r){const n=mp(e,t,i,s,r);return rp.toHex(n)},blake2bInit:gp,blake2bUpdate:yp,blake2bFinal:wp};const vp=sp;function Ep(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function xp(e,t,i,s,r,n){Op[e]=Op[e]+Op[t]+r,Op[s]=Ip(Op[s]^Op[e],16),Op[i]=Op[i]+Op[s],Op[t]=Ip(Op[t]^Op[i],12),Op[e]=Op[e]+Op[t]+n,Op[s]=Ip(Op[s]^Op[e],8),Op[i]=Op[i]+Op[s],Op[t]=Ip(Op[t]^Op[i],7)}function Ip(e,t){return e>>>t^e<<32-t}const Sp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_p=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),Op=new Uint32Array(16),Ap=new Uint32Array(16);function Pp(e,t){let i=0;for(i=0;i<8;i++)Op[i]=e.h[i],Op[i+8]=Sp[i];for(Op[12]^=e.t,Op[13]^=e.t/4294967296,t&&(Op[14]=~Op[14]),i=0;i<16;i++)Ap[i]=Ep(e.b,4*i);for(i=0;i<10;i++)xp(0,4,8,12,Ap[_p[16*i+0]],Ap[_p[16*i+1]]),xp(1,5,9,13,Ap[_p[16*i+2]],Ap[_p[16*i+3]]),xp(2,6,10,14,Ap[_p[16*i+4]],Ap[_p[16*i+5]]),xp(3,7,11,15,Ap[_p[16*i+6]],Ap[_p[16*i+7]]),xp(0,5,10,15,Ap[_p[16*i+8]],Ap[_p[16*i+9]]),xp(1,6,11,12,Ap[_p[16*i+10]],Ap[_p[16*i+11]]),xp(2,7,8,13,Ap[_p[16*i+12]],Ap[_p[16*i+13]]),xp(3,4,9,14,Ap[_p[16*i+14]],Ap[_p[16*i+15]]);for(i=0;i<8;i++)e.h[i]^=Op[i]^Op[i+8]}function Tp(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const i=t?t.length:0;if(t&&!(i>0&&i<=32))throw new Error("Incorrect key length, should be in [1, 32]");const s={h:new Uint32Array(Sp),b:new Uint8Array(64),c:0,t:0,outlen:e};return s.h[0]^=16842752^i<<8^e,i>0&&(Rp(s,t),s.c=64),s}function Rp(e,t){for(let i=0;i<t.length;i++)64===e.c&&(e.t+=e.c,Pp(e,!1),e.c=0),e.b[e.c++]=t[i]}function Bp(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;Pp(e,!0);const t=new Uint8Array(e.outlen);for(let i=0;i<e.outlen;i++)t[i]=e.h[i>>2]>>8*(3&i)&255;return t}function Np(e,t,i){i=i||32,e=vp.normalizeInput(e);const s=Tp(i,t);return Rp(s,e),Bp(s)}var Cp={blake2s:Np,blake2sHex:function(e,t,i){const s=Np(e,t,i);return vp.toHex(s)},blake2sInit:Tp,blake2sUpdate:Rp,blake2sFinal:Bp};var Up={blake2b:bp.blake2b,blake2bHex:bp.blake2bHex,blake2bInit:bp.blake2bInit,blake2bUpdate:bp.blake2bUpdate,blake2bFinal:bp.blake2bFinal,blake2s:Cp.blake2s,blake2sHex:Cp.blake2sHex,blake2sInit:Cp.blake2sInit,blake2sUpdate:Cp.blake2sUpdate,blake2sFinal:Cp.blake2sFinal},kp={exports:{}};function Lp(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var qp=function(e,t,i){var s=i&&i.stringify||Lp;if("object"==typeof e&&null!==e){var r=t.length+1;if(1===r)return e;var n=new Array(r);n[0]=s(e);for(var o=1;o<r;o++)n[o]=s(t[o]);return n.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",h=0,l=-1,u=e&&e.length||0,d=0;d<u;){if(37===e.charCodeAt(d)&&d+1<u){switch(l=l>-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(h>=a||null==t[h])break;l<d&&(c+=e.slice(l,d)),c+=Number(t[h]),l=d+2,d++;break;case 105:if(h>=a||null==t[h])break;l<d&&(c+=e.slice(l,d)),c+=Math.floor(Number(t[h])),l=d+2,d++;break;case 79:case 111:case 106:if(h>=a||void 0===t[h])break;l<d&&(c+=e.slice(l,d));var f=typeof t[h];if("string"===f){c+="'"+t[h]+"'",l=d+2,d++;break}if("function"===f){c+=t[h].name||"<anonymous>",l=d+2,d++;break}c+=s(t[h]),l=d+2,d++;break;case 115:if(h>=a)break;l<d&&(c+=e.slice(l,d)),c+=String(t[h]),l=d+2,d++;break;case 37:l<d&&(c+=e.slice(l,d)),c+="%",l=d+2,d++,h--}++h}++d}return-1===l?e:(l<u&&(c+=e.slice(l)),c)};const Dp=qp;kp.exports=Hp;const Mp=function(){function e(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 e(self)||e(window)||e(this)||{}}}().console||{},$p={mapHttpRequest:Xp,mapHttpResponse:Xp,wrapRequestSerializer:Qp,wrapResponseSerializer:Qp,wrapErrorSerializer:Qp,req:Xp,res:Xp,err:Zp,errWithCause:Zp};function jp(e,t){return"silent"===e?1/0:t.levels.values[e]}const zp=Symbol("pino.logFuncs"),Fp=Symbol("pino.hierarchy"),Kp={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Vp(e,t){const i={logger:t,parent:e[Fp]};t[Fp]=i}function Hp(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const i=e.browser.write||Mp;e.browser.write&&(e.browser.asObject=!0);const s=e.serializers||{},r=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,s);let n=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof i&&a.forEach((function(e){i[e]=i})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",h=Object.create(i);h.log||(h.log=eg),function(e,t,i){const s={};t.forEach((e=>{s[e]=i[e]?i[e]:Mp[e]||Mp[Kp[e]||"log"]||eg})),e[zp]=s}(h,a,i),Vp({},h),Object.defineProperty(h,"levelVal",{get:function(){return jp(this.level,this)}}),Object.defineProperty(h,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,Wp(this,l,h,"error"),Wp(this,l,h,"fatal"),Wp(this,l,h,"warn"),Wp(this,l,h,"info"),Wp(this,l,h,"debug"),Wp(this,l,h,"trace"),o.forEach((e=>{Wp(this,l,h,e)}))}});const l={transmit:t,serialize:r,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:Jp(e),messageKey:e.messageKey||"msg",onChild:e.onChild||eg};function u(i,n,o){if(!n)throw new Error("missing bindings for child Pino");o=o||{},r&&n.serializers&&(o.serializers=n.serializers);const a=o.serializers;if(r&&a){var c=Object.assign({},s,a),h=!0===e.browser.serialize?Object.keys(c):r;delete n.serializers,Gp([n],h,c,this._stdErrSerialize)}function l(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,c&&(this.serializers=c,this._serialize=h),t&&(this._logEvent=Yp([].concat(e._logEvent.bindings,n)))}l.prototype=this;const d=new l(this);return Vp(this,d),d.child=function(...e){return u.call(this,i,...e)},d.level=o.level||this.level,i.onChild(d),d}return h.levels=function(e){const t=e.customLevels||{},i=Object.assign({},Hp.levels.values,t),s=Object.assign({},Hp.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(i){t[e[i]]=i})),t}(t));return{values:i,labels:s}}(e),h.level=c,h.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=eg,h.serializers=s,h._serialize=r,h._stdErrSerialize=n,h.child=function(...e){return u.call(this,l,...e)},t&&(h._logEvent=Yp()),h}function Wp(e,t,i,s){if(Object.defineProperty(e,s,{value:jp(e.level,i)>jp(s,i)?eg:i[zp][s],writable:!0,enumerable:!0,configurable:!0}),e[s]===eg){if(!t.transmit)return;const r=jp(t.transmit.level||e.level,i);if(jp(s,i)<r)return}e[s]=function(e,t,i,s){return function(r){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Mp?Mp:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var h=!1;if(t.serialize&&(Gp(o,this._serialize,this.serializers,this._stdErrSerialize),h=!0),t.asObject||t.formatters?r.call(a,...function(e,t,i,s,r){const{level:n,log:o=(e=>e)}=r.formatters||{},a=i.slice();let c=a[0];const h={};let l=1+(0|e._childLevel);if(l<1&&(l=1),s&&(h.time=s),n){const i=n(t,e.levels.values[t]);Object.assign(h,i)}else h.level=e.levels.values[t];if(r.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;l--&&"object"==typeof a[0];)Object.assign(h,a.shift());return[o(h),...a]}if(null!==c&&"object"==typeof c){for(;l--&&"object"==typeof a[0];)Object.assign(h,a.shift());c=a.length?Dp(a.shift(),a):void 0}else"string"==typeof c&&(c=Dp(a.shift(),a));return void 0!==c&&(h[r.messageKey]=c),[o(h)]}(this,s,o,n,t)):r.apply(a,o),t.transmit){const r=t.transmit.level||e._level,a=jp(r,i),c=jp(s,i);if(c<a)return;!function(e,t,i,s=!1){const r=t.send,n=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,h=e._logEvent.bindings;s||Gp(i,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=n,e._logEvent.messages=i.filter((function(e){return-1===h.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=a,r(o,e._logEvent,c),e._logEvent=Yp(h)}(this,{ts:n,methodLevel:s,methodValue:c,transmitLevel:r,transmitValue:i.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:jp(e._level,i)},o,h)}}}(e[zp][s])}(e,t,i,s);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let i=e[Fp];for(;i.parent;)i=i.parent,i.logger.bindings&&t.push(i.logger.bindings);return t.reverse()}(e);0!==r.length&&(e[s]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(r,e[s]))}function Gp(e,t,i,s){for(const r in e)if(s&&e[r]instanceof Error)e[r]=Hp.stdSerializers.err(e[r]);else if("object"==typeof e[r]&&!Array.isArray(e[r])&&t)for(const s in e[r])t.indexOf(s)>-1&&s in i&&(e[r][s]=i[s](e[r][s]))}function Yp(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function Zp(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const i in e)void 0===t[i]&&(t[i]=e[i]);return t}function Jp(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?tg:ig}function Xp(){return{}}function Qp(e){return e}function eg(){}function tg(){return!1}function ig(){return Date.now()}Hp.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"}},Hp.stdSerializers=$p,Hp.stdTimeFunctions=Object.assign({},{nullTime:tg,epochTime:ig,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),kp.exports.default=Hp,kp.exports.pino=Hp;const sg="info",rg="custom_context",ng=1024e3;var og=Object.defineProperty,ag=(e,t,i)=>((e,t,i)=>t in e?og(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class cg{constructor(e){ag(this,"nodeValue"),ag(this,"sizeInBytes"),ag(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class hg{constructor(e){ag(this,"lengthInNodes"),ag(this,"sizeInBytes"),ag(this,"head"),ag(this,"tail"),ag(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new cg(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.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 t=this.head;for(;null!==t;)e.push(t.value),t=t.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 t=e.value;return e=e.next,{done:!1,value:t}}}}}function lg(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var ug=Object.defineProperty,dg=(e,t,i)=>((e,t,i)=>t in e?ug(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class fg{constructor(e,t=ng){dg(this,"logs"),dg(this,"level"),dg(this,"levelValue"),dg(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=kp.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new hg(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===kp.exports.levels.values.error?console.error(e):t===kp.exports.levels.values.warn?console.warn(e):t===kp.exports.levels.values.debug?console.debug(e):t===kp.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(lg({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new hg(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(lg({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var pg=Object.defineProperty,gg=(e,t,i)=>((e,t,i)=>t in e?pg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class yg{constructor(e,t=ng){gg(this,"baseChunkLogger"),this.baseChunkLogger=new fg(e,t)}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 t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}}var wg=Object.defineProperty,mg=(e,t,i)=>((e,t,i)=>t in e?wg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class bg{constructor(e,t=ng){mg(this,"baseChunkLogger"),this.baseChunkLogger=new fg(e,t)}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 vg=Object.defineProperty,Eg=Object.defineProperties,xg=Object.getOwnPropertyDescriptors,Ig=Object.getOwnPropertySymbols,Sg=Object.prototype.hasOwnProperty,_g=Object.prototype.propertyIsEnumerable,Og=(e,t,i)=>t in e?vg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Ag=(e,t)=>{for(var i in t||(t={}))Sg.call(t,i)&&Og(e,i,t[i]);if(Ig)for(var i of Ig(t))_g.call(t,i)&&Og(e,i,t[i]);return e},Pg=(e,t)=>Eg(e,xg(t));function Tg(e,t=rg){return e[t]||""}function Rg(e,t,i=rg){const s=function(e,t,i=rg){const s=Tg(e,i);return s.trim()?`${s}/${t}`:t}(e,t,i);return function(e,t,i=rg){return e[i]=t,e}(e.child({context:s}),s,i)}function Bg(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const i=Pg(Ag({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,i;const s=new yg(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:kp.exports(Pg(Ag({},e.opts),{level:"trace",browser:Pg(Ag({},null==(i=e.opts)?void 0:i.browser),{write:e=>s.write(e)})})),chunkLoggerController:s}}(Pg(Ag({},e),{opts:i})):function(e){var t,i;const s=new bg(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:kp.exports(Pg(Ag({},e.opts),{level:"trace",browser:Pg(Ag({},null==(i=e.opts)?void 0:i.browser),{write:e=>s.write(e)})}),s),chunkLoggerController:s}}(Pg(Ag({},e),{opts:i}))}const Ng=":";function Cg(e){const[t,i]=e.split(Ng);return{namespace:t,reference:i}}function Ug(e,t=[]){const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...r.accounts)})),i}function kg(e,t){return e.includes(":")?[e]:t.chains||[]}const Lg={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}},qg={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 Dg(e,t){const{message:i,code:s}=qg[e];return{message:t?`${i} ${t}`:i,code:s}}function Mg(e,t){const{message:i,code:s}=Lg[e];return{message:t?`${i} ${t}`:i,code:s}}const $g="ReactNative",jg={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},zg="js";function Fg(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Kg(){return!exports.getDocument_1()&&!!exports.getNavigator_1()&&navigator.product===$g}function Vg(){return!Fg()&&!!exports.getNavigator_1()&&!!exports.getDocument_1()}function Hg(){return Kg()?jg.reactNative:Fg()?jg.node:Vg()?jg.browser:jg.unknown}function Wg(){try{return Kg()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function Gg(){return exports.getWindowMetadata_1()||{name:"",description:"",url:"",icons:[""]}}function Yg(e,t,i){const s=function(){if(Hg()===jg.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){const{OS:e,Version:t}=global.Platform;return[e,t].join("-")}const e=g();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=function(){const e=Hg();return e===jg.browser?[e,exports.getLocation_1()?.host||"unknown"].join(":"):e}();return[[e,t].join("-"),[zg,i].join("-"),s,r].join("/")}function Zg({protocol:e,version:t,relayUrl:i,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=i.split("?"),l={auth:r,ua:Yg(e,t,s),projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},u=function(e,t){const i=new URLSearchParams(e);return Object.entries(t).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,t])=>{null!=t&&i.set(e,String(t))})),i.toString()}(h[1]||"",l);return h[0]+"?"+u}function Jg(e,t){return e.filter((e=>t.includes(e))).length===e.length}function Xg(e){return Object.fromEntries(e.entries())}function Qg(e){return new Map(Object.entries(e))}function ey(e=m.FIVE_MINUTES,t){const i=m.toMiliseconds(e||m.FIVE_MINUTES);let s,r,n,o;return{resolve:e=>{n&&s&&(clearTimeout(n),s(e),o=Promise.resolve(e))},reject:e=>{n&&r&&(clearTimeout(n),r(e))},done:()=>new Promise(((e,a)=>{if(o)return e(o);n=setTimeout((()=>{const e=Dg("EXPIRED"),i=new Error(t||e.message);i.code=e.code,a(i)}),i),s=e,r=a}))}}function ty(e,t,i){return new Promise((async(s,r)=>{const n=setTimeout((()=>r(new Error(i))),t);try{s(await e)}catch(e){r(e)}clearTimeout(n)}))}function iy(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function sy(e){const[t,i]=e.split(":"),s={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof i)s.topic=i;else{if("id"!==t||!Number.isInteger(Number(i)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${i}`);s.id=Number(i)}return s}function ry(e,t){return m.fromMiliseconds((t||Date.now())+m.toMiliseconds(e))}function ny(e){return Date.now()>=m.toMiliseconds(e)}function oy(e,t){return`${e}${t?`:${t}`:""}`}function ay(e=[],t=[]){return[...new Set([...e,...t])]}async function cy({id:e,topic:t,wcDeepLink:i}){try{if(!i)return;const s=("string"==typeof i?JSON.parse(i):i)?.href;if("string"!=typeof s)return;const r=function(e,t,i){const s=`requestId=${t}&sessionTopic=${i}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;if(e.startsWith("https://t.me")){r=`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const i=(new TextEncoder).encode(e),s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=String.fromCharCode(i[e]);const r=btoa(s.join(""));return t?r.replace(/[=]/g,""):r}(s,!0)}`}else r=`${r}/wc?${s}`;return r}(s,e,t),n=Hg();if(n===jg.browser){if(!exports.getDocument_1()?.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(r)}else n===jg.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(r)}catch(e){console.error(e)}}function hy(e,t){if(!e.includes(t))return null;const i=e.split(/([&,?,=])/),s=i.indexOf(t);return i[s+2]}function ly(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function uy(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function dy(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return(new TextDecoder).decode(s)}class fy{constructor({limit:e}){this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}}const py="https://rpc.walletconnect.org/v1";function gy(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return s}const yy=/^0x[0-9a-fA-F]{64}$/;function wy(e){const t=`Ethereum Signed Message:\n${e.length}`,i=(new TextEncoder).encode(t+e);return"0x"+Ua(Je(i),"base16")}async function my(e,t,i,s,r,n){switch(i.t){case"eip191":return await function(e,t,i){const s=nr(i);return hr({payload:wy(t),signature:s}).toLowerCase()===e.toLowerCase()}(e,t,i.s);case"eip1271":return await async function(e,t,i,s,r,n){const o=Cg(s);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${s}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c=i.substring(2),h=(c.length/2).toString(16).padStart(64,"0"),l=(function(e){return yy.test(e)}(t)?t:wy(t)).substring(2),u=o+l+a+h+c,d=await fetch(`${n||py}/?chainId=${s}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:by(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:u},"latest"]})}),{result:f}=await d.json();return!!f&&f.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,i.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}function by(){return Date.now()+Math.floor(1e3*Math.random())}function vy(e){const t=gy(e),i=(new TextEncoder).encode("TransactionData::"),s=new Uint8Array(i.length+t.length);s.set(i),s.set(t,i.length);const r=Qr(s,{dkLen:32});return eo.encode(r)}function Ey(e){const t=new Uint8Array(zr(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&e?.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return eo.encode(t)}function xy(e){const t=Rn(gy(e)).txn;if(!t)throw new Error("Invalid signed transaction: missing 'txn' field");const i=mn(t),s=co([(new TextEncoder).encode("TX"),new Uint8Array(i)]),r=Vr(s);return Jn.encode(r).replace(/=+$/,"")}function Iy(e){const t=[];let i=BigInt(e);for(;i>=0x80n;)t.push(Number(0x7fn&i|0x80n)),i>>=7n;return t.push(Number(i)),new Uint8Array(t)}function Sy(e){const t=gy(e.signed.bodyBytes),i=gy(e.signed.authInfoBytes),s=gy(e.signature.signature),r=[];r.push(new Uint8Array([10])),r.push(Iy(t.length)),r.push(t),r.push(new Uint8Array([18])),r.push(Iy(i.length)),r.push(i),r.push(new Uint8Array([26])),r.push(Iy(s.length)),r.push(s);const n=co(r);return Ua(zr(n),"base16").toUpperCase()}const _y={pubnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"},Oy=72,Ay=64,Py=20;function Ty(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!1)}function Ry(e,t){const i=gy(e);if(i.length<8)throw new Error("getStellarTransactionHash: envelope too short");const s=Ty(i,0);let r,n;switch(s){case 0:r=2,n=0;break;case 2:r=2,n=4;break;case 5:r=5,n=4;break;default:throw new Error(`getStellarTransactionHash: unsupported envelope type: ${s}`)}const o=function(e){for(let t=Py;t>=0;t--){const i=e.length-4-Oy*t;if(i<4||Ty(e,i)!==t)continue;let s=!0;for(let r=0;r<t;r++)if(Ty(e,i+4+Oy*r+4)!==Ay){s=!1;break}if(s)return i}throw new Error("getStellarTransactionHash: could not locate envelope signature array")}(i),a=t?.split(":").pop()??"pubnet",c=_y[a];if(!c)throw new Error(`getStellarTransactionHash: unknown Stellar network: ${a}`);const h=co([zr((new TextEncoder).encode(c)),new Uint8Array([0,0,0,r]),i.slice(n,o)]);return Ua(zr(h),"base16")}const By="did:pkh:",Ny={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Cy=e=>e?.split(":"),Uy=e=>{const t=e&&Cy(e);if(t)return t[2]+":"+t[3]},ky=e=>{const t=e&&Cy(e);if(t)return t.pop()};async function Ly(e){const{cacao:t,projectId:i}=e,{s:s,p:r}=t;let n;try{n=qy(r,r.iss)}catch{return!1}const o=ky(r.iss);return await my(o,n,s,Uy(r.iss),i)}const qy=(e,t)=>{const i=(e=>{const t=e&&Cy(e);if(t)return e.includes(By)?t[2]:t[0]})(t);if(!i)throw new Error("Invalid issuer: "+t);const s=`${e.domain} wants you to sign in with your ${(e=>e?Ny[e]||e:"")(i)} account:`,r=ky(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${(e=>{const t=e&&Cy(e);if(t)return e.includes(By)?t[3]:t[1]})(t)}`,h=`Nonce: ${e.nonce}`,l=`Issued At: ${e.iat}`,u=e.exp?`Expiration Time: ${e.exp}`:void 0,d=e.nbf?`Not Before: ${e.nbf}`:void 0,f=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map((e=>`\n- ${e}`)).join("")}`:void 0,g=Hy(e.resources);if(g){n=function(e="",t){Dy(t);const i="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(i))return e;const s=[];let r=0;Object.keys(t.att).forEach((e=>{const i=Object.keys(t.att[e]).map((e=>({ability:e.split("/")[0],action:e.split("/")[1]})));i.sort(((e,t)=>e.action.localeCompare(t.action)));const n={};i.forEach((e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)}));const o=Object.keys(n).map((t=>(r++,`(${r}) '${t}': '${n[t].join("', '")}' for '${e}'.`)));s.push(o.join(", ").replace(".,","."))}));const n=s.join(" "),o=`${i}${n}`;return`${e?e+" ":""}${o}`}(n,jy(g))}if(n&&/\r|\n/.test(n))throw new Error("Statement must not contain line breaks (`\\r` or `\\n`)");return[s,r,"",n,"",o,a,c,h,l,u,d,f,p].filter((e=>null!=e)).join("\n")};function Dy(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!t?.length)throw new Error("No resources found in `att` property");t.forEach((t=>{const i=e.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof i)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach((e=>{const t=i[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach((t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)}))}))}))}function My(e,t,i={}){t=t?.sort(((e,t)=>e.localeCompare(t)));const s=t.map((t=>({[`${e}/${t}`]:[i]})));return Object.assign({},...s)}function $y(e){return Dy(e),`urn:recap:${function(e){const t=JSON.stringify(e),i=(new TextEncoder).encode(t),s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=String.fromCharCode(i[e]);return btoa(s.join(""))}(e).replace(/=/g,"")}`}function jy(e){const t=function(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return JSON.parse((new TextDecoder).decode(s))}(e.replace("urn:recap:",""));return Dy(t),t}function zy(e,t,i){const s=function(e,t,i,s={}){return i?.sort(((e,t)=>e.localeCompare(t))),{att:{[e]:My(t,i,s)}}}(e,t,i);return $y(s)}function Fy(e,t){const i=function(e,t){Dy(e),Dy(t);const i=Object.keys(e.att).concat(Object.keys(t.att)).sort(((e,t)=>e.localeCompare(t))),s={att:{}};return i.forEach((i=>{Object.keys(e.att?.[i]||{}).concat(Object.keys(t.att?.[i]||{})).sort(((e,t)=>e.localeCompare(t))).forEach((r=>{s.att[i]={...s.att[i],[r]:e.att[i]?.[r]||t.att[i]?.[r]}}))})),s}(jy(e),jy(t));return $y(i)}function Ky(e){const t=jy(e);Dy(t);const i=t.att?.eip155;return i?Object.keys(i).map((e=>e.split("/")[1])):[]}function Vy(e){const t=jy(e);Dy(t);const i=[];return Object.values(t.att).forEach((e=>{Object.values(e).forEach((e=>{e?.[0]?.chains&&i.push(e[0].chains)}))})),[...new Set(i.flat())]}function Hy(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}const Wy="base10",Gy="base16",Yy="base64pad",Zy="base64url",Jy="utf8",Xy=0,Qy=1,ew=2,tw=0,iw=1,sw=12,rw=32;function nw(){return Ua(ke(rw),Gy)}function ow(e){return Ua(hc(Ca(e,Gy)),Gy)}function aw(e){return Ua(hc(Ca(e,Jy)),Gy)}function cw(e){return Ca(`${e}`,Wy)}function hw(e){return Number(Ua(e,Wy))}function lw(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function uw(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4;return t+"=".repeat(i)}function dw(e){if(hw(e.type)===ew)return Ua(co([e.type,e.sealed]),Yy);if(hw(e.type)===Qy){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ua(co([e.type,e.senderPublicKey,e.iv,e.sealed]),Yy)}return Ua(co([e.type,e.iv,e.sealed]),Yy)}function fw(e){const t=Ca((e.encoding||Yy)===Zy?uw(e.encoded):e.encoded,Yy),i=t.slice(tw,iw),s=iw;if(hw(i)===Qy){const e=s+rw,r=e+sw,n=t.slice(s,e),o=t.slice(e,r);return{type:i,sealed:t.slice(r),iv:o,senderPublicKey:n}}if(hw(i)===ew){return{type:i,sealed:t.slice(s),iv:ke(sw)}}const r=s+sw,n=t.slice(s,r);return{type:i,sealed:t.slice(r),iv:n}}function pw(e){const t=e?.type||Xy;if(t===Qy){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function gw(e){return e.type===Qy&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function yw(e){return e.type===ew}function ww(e,t){const[i,s,r]=e.split("."),n=Ca(uw(r),Yy);if(64!==n.length)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=hc(`${i}.${s}`),h=function(e){const t=Ca(uw(e.x),Yy),i=Ca(uw(e.y),Yy);return co([new Uint8Array([4]),t,i])}(t);if(!Ol.verify(co([o,a]),c,h))throw new Error("Invalid signature");return Xf(e).payload}function mw(e){return e?.relay||{protocol:"irn"}}function bw(e){const t=tp[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function vw(e,t="-"){const i={},s="relay"+t;return Object.keys(e).forEach((t=>{if(t.startsWith(s)){const r=t.replace(s,""),n=e[t];i[r]=n}})),i}function Ew(e){if(!e.includes("wc:")){const t=dy(e);t?.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),i=-1!==e.indexOf("?")?e.indexOf("?"):void 0,s=e.substring(0,t),r=e.substring(t+1,i).split("@"),n=typeof i<"u"?e.substring(i):"",o=new URLSearchParams(n),a=Object.fromEntries(o.entries()),c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:s,topic:xw(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:vw(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function xw(e){return e.startsWith("//")?e.substring(2):e}function Iw(e,t="-"){const i={};return Object.keys(e).forEach((s=>{const r=s,n="relay"+t+r;e[r]&&(i[n]=e[r])})),i}function Sw(e){const t=new URLSearchParams,i={...Iw(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(i).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,i])=>{void 0!==i&&t.append(e,String(i))})),`${e.protocol}:${e.topic}@${e.version}?${t}`}function _w(e,t,i){return`${e}?wc_ev=${i}&topic=${t}`}function Ow(e){const t=[];return e.forEach((e=>{const[i,s]=e.split(":");t.push(`${i}:${s}`)})),t}function Aw(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Ow(e.accounts))})),[...new Set(t)]}function Pw(e){return e.includes(":")}function Tw(e){return Pw(e)?e.split(":")[0]:e}function Rw(e){const t={};if(!Cw(e))return t;for(const[i,s]of Object.entries(e)){const e=Pw(i)?[i]:s.chains,r=s.methods||[],n=s.events||[],o=Tw(i);t[o]={...t[o],chains:ay(e,t[o]?.chains),methods:ay(r,t[o]?.methods),events:ay(n,t[o]?.events)}}return t}function Bw(e,t){t=t.map((e=>e.replace("did:pkh:","")));const i=function(e){const t={};return e?.forEach((e=>{const[i,s]=e.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(e),t[i].chains?.push(`${i}:${s}`)})),t}(t);for(const[t,s]of Object.entries(i))s.methods?s.methods=ay(s.methods,e):s.methods=e,s.events=["chainChanged","accountsChanged"];return i}function Nw(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function Cw(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Uw(e){return typeof e>"u"}function kw(e,t){return!(!t||!Uw(e))||"string"==typeof e&&!!e.trim().length}function Lw(e,t){return!(!t||!Uw(e))||"number"==typeof e&&!isNaN(e)}function qw(e){return!(!kw(e,!1)||!e.includes(":"))&&2===e.split(":").length}function Dw(e){let t=!0;return Nw(e)?e.length&&(t=e.every((e=>kw(e,!1)))):t=!1,t}function Mw(e,t,i){let s=null;return Object.entries(e).forEach((([e,r])=>{if(s)return;const n=function(e,t,i){let s=null;return Nw(t)&&t.length?t.forEach((e=>{s||qw(e)||(s=Mg("UNSUPPORTED_CHAINS",`${i}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):qw(e)||(s=Mg("UNSUPPORTED_CHAINS",`${i}, 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"] }`)),s}(e,kg(e,r),`${t} ${i}`);n&&(s=n)})),s}function $w(e,t){let i=null;return Nw(e)?e.forEach((e=>{i||function(e){if(kw(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&qw(e)}}return!1}(e)||(i=Mg("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):i=Mg("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function jw(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=function(e,t){let i=null;return Dw(e?.methods)?Dw(e?.events)||(i=Mg("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):i=Mg("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),i}(e,`${t}, namespace`);s&&(i=s)})),i}function zw(e,t){let i=null;if(e&&Cw(e)){const s=jw(e,t);s&&(i=s);const r=function(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=$w(e?.accounts,`${t} namespace`);s&&(i=s)})),i}(e,t);r&&(i=r)}else i=Dg("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function Fw(e){return kw(e.protocol,!0)}function Kw(e){return typeof e<"u"&&null!==typeof e}function Vw(e,t){return!(!qw(t)||!Aw(e).includes(t))}function Hw(e,t,i){return!!kw(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Ow(e.accounts).includes(t)&&i.push(...e.methods)})),i}(e,t).includes(i)}function Ww(e,t,i){return!!kw(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Ow(e.accounts).includes(t)&&i.push(...e.events)})),i}(e,t).includes(i)}function Gw(e,t,i){let s=null;const r=function(e){const t={};return Object.keys(e).forEach((i=>{i.includes(":")?t[i]=e[i]:e[i].chains?.forEach((s=>{t[s]={methods:e[i].methods,events:e[i].events}}))})),t}(e),n=function(e){const t={};return Object.keys(e).forEach((i=>{i.includes(":")?t[i]=e[i]:Ow(e[i].accounts)?.forEach((s=>{t[s]={accounts:e[i].accounts.filter((e=>e.includes(`${s}:`))),methods:e[i].methods,events:e[i].events}}))})),t}(t),o=Object.keys(r),a=Object.keys(n),c=Yw(Object.keys(e)),h=Yw(Object.keys(t)),l=c.filter((e=>!h.includes(e)));return l.length&&(s=Dg("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.\n Required: ${l.toString()}\n Received: ${Object.keys(t).toString()}`)),Jg(o,a)||(s=Dg("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||s)return;const r=Ow(t[e].accounts);r.includes(e)||(s=Dg("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))})),o.forEach((e=>{s||(Jg(r[e].methods,n[e].methods)?Jg(r[e].events,n[e].events)||(s=Dg("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):s=Dg("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))})),s}function Yw(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function Zw(){const e=Hg();return new Promise((t=>{switch(e){case jg.browser:t(Vg()&&navigator?.onLine);break;case jg.reactNative:t(async function(){return!(Kg()&&typeof global<"u"&&global?.NetInfo)||(await(global?.NetInfo.fetch()))?.isConnected}());break;case jg.node:default:t(!0)}}))}function Jw(e){switch(Hg()){case jg.browser:!function(e){!Kg()&&Vg()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case jg.reactNative:!function(e){Kg()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e)}}const Xw={};class Qw{static get(e){return Xw[e]}static set(e,t){Xw[e]=t}static delete(e){delete Xw[e]}}function em({publicKey:e,signature:t,payload:i}){const s=tm(i.method),r=128|parseInt(i.version?.toString()||"4"),n=function(e){const t=eo.decode(e)[0];return 42===t?0:60===t?2:1}(i.address),o="00"===i.era?new Uint8Array([0]):tm(i.era);if(1!==o.length&&2!==o.length)throw new Error("Invalid era length");const a=parseInt(i.nonce,16),c=new Uint8Array([255&a,a>>8&255]),h=BigInt(`0x${function(e){return e.startsWith("0x")?e.slice(2):e}(i.tip)}`),l=function(e){if(e<1n<<6n)return new Uint8Array([Number(e<<2n)]);if(e<1n<<14n){const t=e<<2n|0x01n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn)])}if(e<1n<<30n){const t=e<<2n|0x02n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}throw new Error("BigInt compact encoding not supported > 2^30")}(h),u=new Uint8Array([0,...e,n,...t,...o,...c,...l,...s]),d=function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){const t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<1<<30){const t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw new Error("Compact encoding > 2^30 not supported")}(u.length+1);return new Uint8Array([...d,r,...u])}function tm(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map((e=>parseInt(e,16))))}function im(e){const t=tm(e.signature),i=function(e){const t=eo.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address);return function(e){const t=tm(e);return"0x"+Ua(Up.blake2b(t,void 0,32),"base16")}(Ua(em({publicKey:i,signature:t,payload:e.transaction}),"base16"))}const sm=new Set(["TransferFactory_Transfer","DelegateProxy_TransferFactory_Transfer"]);function rm(e,t){const i=t?.payload?.updateId;if(!i)return[];const s=function(e){const t=e?.commands;if(!Array.isArray(t))return[];const i=[];for(const e of t){const t=e?.ExerciseCommand;if(!t||!sm.has(t.choice))continue;const s=t.choiceArgument?.transfer;!s?.amount||!s?.instrumentId?.id||i.push({amount:String(s.amount),instrumentId:String(s.instrumentId.id)})}return i}(e);return 0===s.length?[String(i)]:s.map((e=>`${i}:${e.amount}:${e.instrumentId}`))}function nm({logger:e,name:t}){const i="string"==typeof e?Bg({opts:{level:e,name:t}}).logger:e;return i.level="string"==typeof e?e:e.level,i}class om{}class am extends om{constructor(e){super()}}const cm=m.FIVE_SECONDS,hm="heartbeat_pulse";class lm extends am{constructor(t){super(t),this.events=new e.EventEmitter,this.interval=cm,this.interval=t?.interval||cm}static async init(e){const t=new lm(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval((()=>this.pulse()),m.toMiliseconds(this.interval))}pulse(){this.events.emit(hm)}}const um=/"(?:_|\\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*:/,dm=/"(?: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*:/,fm=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function pm(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function gm(e,t={}){if("string"!=typeof e)return e;const i=e.trim();if('"'===e[0]&&e.endsWith('"')&&!e.includes("\\"))return i.slice(1,-1);if(i.length<=9){const e=i.toLowerCase();if("true"===e)return!0;if("false"===e)return!1;if("undefined"===e)return;if("null"===e)return null;if("nan"===e)return Number.NaN;if("infinity"===e)return Number.POSITIVE_INFINITY;if("-infinity"===e)return Number.NEGATIVE_INFINITY}if(!fm.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(um.test(e)||dm.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,pm)}return JSON.parse(e)}catch(i){if(t.strict)throw i;return e}}function ym(e,...t){try{return(i=e(...t))&&"function"==typeof i.then?i:Promise.resolve(i)}catch(e){return Promise.reject(e)}var i}function wm(e){if(function(e){const t=typeof e;return null===e||"object"!==t&&"function"!==t}(e))return String(e);if(function(e){const t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}(e)||Array.isArray(e))return JSON.stringify(e);if("function"==typeof e.toJSON)return wm(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function mm(){if(void 0===typeof Buffer)throw new TypeError("[unstorage] Buffer is not supported!")}const bm="base64:";function vm(e){return e?e.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Em(...e){return vm(e.join(":"))}function xm(e){return(e=vm(e))?e+":":""}const Im=()=>{const e=new Map;return{name:"memory",options:{},hasItem:t=>e.has(t),getItem:t=>e.get(t)??null,getItemRaw:t=>e.get(t)??null,setItem(t,i){e.set(t,i)},setItemRaw(t,i){e.set(t,i)},removeItem(t){e.delete(t)},getKeys:()=>Array.from(e.keys()),clear(){e.clear()},dispose(){e.clear()}}};function Sm(e={}){const t={mounts:{"":e.driver||Im()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=e=>{for(const i of t.mountpoints)if(e.startsWith(i))return{base:i,relativeKey:e.slice(i.length),driver:t.mounts[i]};return{base:"",relativeKey:e,driver:t.mounts[""]}},s=(e,i)=>t.mountpoints.filter((t=>t.startsWith(e)||i&&e.startsWith(t))).map((i=>({relativeBase:e.length>i.length?e.slice(i.length):void 0,mountpoint:i,driver:t.mounts[i]}))),r=(e,i)=>{if(t.watching){i=vm(i);for(const s of t.watchListeners)s(e,i)}},n=async()=>{if(t.watching){for(const e in t.unwatch)await t.unwatch[e]();t.unwatch={},t.watching=!1}},o=(e,t,s)=>{const r=new Map,n=e=>{let t=r.get(e.base);return t||(t={driver:e.driver,base:e.base,items:[]},r.set(e.base,t)),t};for(const s of e){const e="string"==typeof s,r=vm(e?s:s.key),o=e?void 0:s.value,a=e||!s.options?t:{...t,...s.options},c=i(r);n(c).items.push({key:r,value:o,relativeKey:c.relativeKey,options:a})}return Promise.all([...r.values()].map((e=>s(e)))).then((e=>e.flat()))},a={hasItem(e,t={}){e=vm(e);const{relativeKey:s,driver:r}=i(e);return ym(r.hasItem,s,t)},getItem(e,t={}){e=vm(e);const{relativeKey:s,driver:r}=i(e);return ym(r.getItem,s,t).then((e=>gm(e)))},getItems:(e,t)=>o(e,t,(e=>e.driver.getItems?ym(e.driver.getItems,e.items.map((e=>({key:e.relativeKey,options:e.options}))),t).then((t=>t.map((t=>({key:Em(e.base,t.key),value:gm(t.value)}))))):Promise.all(e.items.map((t=>ym(e.driver.getItem,t.relativeKey,t.options).then((e=>({key:t.key,value:gm(e)})))))))),getItemRaw(e,t={}){e=vm(e);const{relativeKey:s,driver:r}=i(e);return r.getItemRaw?ym(r.getItemRaw,s,t):ym(r.getItem,s,t).then((e=>function(e){return"string"!=typeof e?e:e.startsWith(bm)?(mm(),Buffer.from(e.slice(bm.length),"base64")):e}(e)))},async setItem(e,t,s={}){if(void 0===t)return a.removeItem(e);e=vm(e);const{relativeKey:n,driver:o}=i(e);o.setItem&&(await ym(o.setItem,n,wm(t),s),o.watch||r("update",e))},async setItems(e,t){await o(e,t,(async e=>{e.driver.setItems&&await ym(e.driver.setItems,e.items.map((e=>({key:e.relativeKey,value:wm(e.value),options:e.options}))),t),e.driver.setItem&&await Promise.all(e.items.map((t=>ym(e.driver.setItem,t.relativeKey,wm(t.value),t.options))))}))},async setItemRaw(e,t,s={}){if(void 0===t)return a.removeItem(e,s);e=vm(e);const{relativeKey:n,driver:o}=i(e);if(o.setItemRaw)await ym(o.setItemRaw,n,t,s);else{if(!o.setItem)return;await ym(o.setItem,n,function(e){if("string"==typeof e)return e;mm();const t=Buffer.from(e).toString("base64");return bm+t}(t),s)}o.watch||r("update",e)},async removeItem(e,t={}){"boolean"==typeof t&&(t={removeMeta:t}),e=vm(e);const{relativeKey:s,driver:n}=i(e);n.removeItem&&(await ym(n.removeItem,s,t),(t.removeMeta||t.removeMata)&&await ym(n.removeItem,s+"$",t),n.watch||r("remove",e))},async getMeta(e,t={}){"boolean"==typeof t&&(t={nativeOnly:t}),e=vm(e);const{relativeKey:s,driver:r}=i(e),n=Object.create(null);if(r.getMeta&&Object.assign(n,await ym(r.getMeta,s,t)),!t.nativeOnly){const e=await ym(r.getItem,s+"$",t).then((e=>gm(e)));e&&"object"==typeof e&&("string"==typeof e.atime&&(e.atime=new Date(e.atime)),"string"==typeof e.mtime&&(e.mtime=new Date(e.mtime)),Object.assign(n,e))}return n},setMeta(e,t,i={}){return this.setItem(e+"$",t,i)},removeMeta(e,t={}){return this.removeItem(e+"$",t)},async getKeys(e,t={}){e=xm(e);const i=s(e,!0);let r=[];const n=[];for(const e of i){const i=(await ym(e.driver.getKeys,e.relativeBase,t)).map((t=>e.mountpoint+vm(t))).filter((e=>!r.some((t=>e.startsWith(t)))));n.push(...i),r=[e.mountpoint,...r.filter((t=>!t.startsWith(e.mountpoint)))]}return e?n.filter((t=>t.startsWith(e)&&!t.endsWith("$"))):n.filter((e=>!e.endsWith("$")))},async clear(e,t={}){e=xm(e),await Promise.all(s(e,!1).map((async e=>{if(e.driver.clear)return ym(e.driver.clear,e.relativeBase,t);if(e.driver.removeItem){const i=await e.driver.getKeys(e.relativeBase||"",t);return Promise.all(i.map((i=>e.driver.removeItem(i,t))))}})))},async dispose(){await Promise.all(Object.values(t.mounts).map((e=>Om(e))))},watch:async e=>(await(async()=>{if(!t.watching){t.watching=!0;for(const e in t.mounts)t.unwatch[e]=await _m(t.mounts[e],r,e)}})(),t.watchListeners.push(e),async()=>{t.watchListeners=t.watchListeners.filter((t=>t!==e)),0===t.watchListeners.length&&await n()}),async unwatch(){t.watchListeners=[],await n()},mount(e,i){if((e=xm(e))&&t.mounts[e])throw new Error(`already mounted at ${e}`);return e&&(t.mountpoints.push(e),t.mountpoints.sort(((e,t)=>t.length-e.length))),t.mounts[e]=i,t.watching&&Promise.resolve(_m(i,r,e)).then((i=>{t.unwatch[e]=i})).catch(console.error),a},async unmount(e,i=!0){(e=xm(e))&&t.mounts[e]&&(t.watching&&e in t.unwatch&&(t.unwatch[e](),delete t.unwatch[e]),i&&await Om(t.mounts[e]),t.mountpoints=t.mountpoints.filter((t=>t!==e)),delete t.mounts[e])},getMount(e=""){e=vm(e)+":";const t=i(e);return{driver:t.driver,base:t.base}},getMounts(e="",t={}){e=vm(e);return s(e,t.parents).map((e=>({driver:e.driver,base:e.mountpoint})))}};return a}function _m(e,t,i){return e.watch?e.watch(((e,s)=>t(e,i+s))):()=>{}}async function Om(e){"function"==typeof e.dispose&&await ym(e.dispose)}function Am(e){return new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)}))}function Pm(e,t){const i=indexedDB.open(e);i.onupgradeneeded=()=>i.result.createObjectStore(t);const s=Am(i);return(e,i)=>s.then((s=>i(s.transaction(t,e).objectStore(t))))}let Tm;function Rm(){return Tm||(Tm=Pm("keyval-store","keyval")),Tm}function Bm(e,t=Rm()){return t("readonly",(t=>Am(t.get(e))))}function Nm(e=Rm()){return e("readonly",(e=>{if(e.getAllKeys)return Am(e.getAllKeys());const t=[];return function(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},Am(e.transaction)}(e,(e=>t.push(e.key))).then((()=>t))}))}var Cm=(e={})=>{const t=e.base&&e.base.length>0?`${e.base}:`:"",i=e=>t+e;let s;return e.dbName&&e.storeName&&(s=Pm(e.dbName,e.storeName)),{name:"idb-keyval",options:e,hasItem:async e=>!(typeof await Bm(i(e),s)>"u"),getItem:async e=>await Bm(i(e),s)??null,setItem:(e,t)=>function(e,t,i=Rm()){return i("readwrite",(i=>(i.put(t,e),Am(i.transaction))))}(i(e),t,s),removeItem:e=>function(e,t=Rm()){return t("readwrite",(t=>(t.delete(e),Am(t.transaction))))}(i(e),s),getKeys:()=>Nm(s),clear:()=>function(e=Rm()){return e("readwrite",(e=>(e.clear(),Am(e.transaction))))}(s)}};class Um{constructor(){this.indexedDb=Sm({driver:Cm({dbName:"WALLET_CONNECT_V2_INDEXED_DB",storeName:"keyvaluestorage"})})}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 t=await this.indexedDb.getItem(e);if(null!==t)return t}async setItem(e,t){await this.indexedDb.setItem(e,Rl(t))}async removeItem(e){await this.indexedDb.removeItem(e)}}var km=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Lm={exports:{}};function qm(e){var t;return[e[0],Tl(null!=(t=e[1])?t:"")]}!function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),typeof km<"u"&&km.localStorage?Lm.exports=km.localStorage:typeof window<"u"&&window.localStorage?Lm.exports=window.localStorage:Lm.exports=new t}();class Dm{constructor(){this.localStorage=Lm.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(qm)}async getItem(e){const t=this.localStorage.getItem(e);if(null!==t)return Tl(t)}async setItem(e,t){this.localStorage.setItem(e,Rl(t))}async removeItem(e){this.localStorage.removeItem(e)}}const Mm=async(e,t)=>{t.length&&t.forEach((async t=>{await e.removeItem(t)}))};class $m{constructor(){this.initialized=!1,this.setInitialized=e=>{this.storage=e,this.initialized=!0};const e=new Dm;this.storage=e;try{(async(e,t,i)=>{const s="wc_storage_version",r=await t.getItem(s);if(r&&r>=1)return void i(t);const n=await e.getKeys();if(!n.length)return void i(t);const o=[];for(;n.length;){const i=n.shift();if(!i)continue;const s=i.toLowerCase();if(s.includes("wc@")||s.includes("walletconnect")||s.includes("wc_")||s.includes("wallet_connect")){const s=await e.getItem(i);await t.setItem(i,s),o.push(i)}}await t.setItem(s,1),i(t),Mm(e,o)})(e,new Um,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,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise((e=>{const t=setInterval((()=>{this.initialized&&(clearInterval(t),e())}),20)}))}}class jm extends om{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class zm extends om{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class Fm{constructor(e,t){this.logger=e,this.core=t}}class Km extends om{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Vm extends om{constructor(e){super()}}class Hm{constructor(e,t,i,s){this.core=e,this.logger=t,this.name=i}}class Wm extends om{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Gm extends om{constructor(e,t){super(),this.core=e,this.logger=t}}class Ym{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class Zm{constructor(e,t){this.projectId=e,this.logger=t}}class Jm{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}class Xm{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class Qm{constructor(e){this.client=e}}const eb="INTERNAL_ERROR",tb="SERVER_ERROR",ib=[-32700,-32600,-32601,-32602,-32603],sb={PARSE_ERROR:{code:-32700,message:"Parse error"},INVALID_REQUEST:{code:-32600,message:"Invalid Request"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},[eb]:{code:-32603,message:"Internal error"},[tb]:{code:-32e3,message:"Server error"}},rb=tb;function nb(e){return Object.keys(sb).includes(e)?sb[e]:sb[rb]}function ob(e,t,i){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${t}`):e}var ab,cb={},hb={};var lb,ub={};function db(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function fb(e=6){return BigInt(db(e))}function pb(e,t,i){return{id:i||db(),jsonrpc:"2.0",method:e,params:t}}function gb(e,t){return{id:e,jsonrpc:"2.0",result:t}}function yb(e,t,i){return{id:e,jsonrpc:"2.0",error:wb(t,i)}}function wb(e,t){return void 0===e?nb(eb):("string"==typeof e&&(e=Object.assign(Object.assign({},nb(tb)),{message:e})),void 0!==t&&(e.data=t),function(e){return ib.includes(e)}(e.code)&&(e=function(e){const t=Object.values(sb).find((t=>t.code===e));return t||sb[rb]}(e.code)),e)}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const s=t.require$$0;s.__exportStar(function(){if(ab)return hb;function e(){return(null===i.commonjsGlobal||void 0===i.commonjsGlobal?void 0:i.commonjsGlobal.crypto)||(null===i.commonjsGlobal||void 0===i.commonjsGlobal?void 0:i.commonjsGlobal.msCrypto)||{}}function t(){const t=e();return t.subtle||t.webkitSubtle}return ab=1,Object.defineProperty(hb,"__esModule",{value:!0}),hb.isBrowserCryptoAvailable=hb.getSubtleCrypto=hb.getBrowerCrypto=void 0,hb.getBrowerCrypto=e,hb.getSubtleCrypto=t,hb.isBrowserCryptoAvailable=function(){return!!e()&&!!t()},hb}(),e),s.__exportStar(function(){if(lb)return ub;function e(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function t(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}return lb=1,Object.defineProperty(ub,"__esModule",{value:!0}),ub.isBrowser=ub.isNode=ub.isReactNative=void 0,ub.isReactNative=e,ub.isNode=t,ub.isBrowser=function(){return!e()&&!t()},ub}(),e)}(cb);class mb{}class bb extends mb{constructor(){super()}}class vb extends bb{constructor(e){super()}}function Eb(e,t){const i=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==i&&new RegExp(t).test(i)}function xb(e){return Eb(e,"^https?:")}function Ib(e){return Eb(e,"^wss?:")}function Sb(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function _b(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function Ob(e){return _b(e)&&"method"in e}function Ab(e){return _b(e)&&(Pb(e)||Tb(e))}function Pb(e){return"result"in e}function Tb(e){return"error"in e}class Rb extends vb{constructor(t){super(t),this.events=new e.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(t),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(pb(e.method,e.params||[],e.id||fb().toString()),t)}async requestStrict(e,t){return new Promise((async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(e){s(e)}this.events.on(`${e.id}`,(e=>{Tb(e)?s(e.error):i(e.result)}));try{await this.connection.send(e,t)}catch(e){s(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ab(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&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(),"string"==typeof e&&(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 Bb=e=>e.split("?")[0],Nb=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");class Cb{constructor(t){if(this.url=t,this.events=new e.EventEmitter,this.registering=!1,!Ib(t))throw new Error(`Provided URL is not compatible with WebSocket connection: ${t}`);this.url=t}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise(((e,t)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())}))}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Rl(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Ib(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,i)=>{const s=cb.isReactNative()?void 0:{rejectUnauthorized:!Sb(e)},r=new Nb(e,[],s);typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?r.onerror=e=>{const t=e;i(this.emitError(t.error))}:r.on("error",(e=>{i(this.emitError(e))})),r.onopen=()=>{this.onOpen(r),t(r)}}))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),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 t="string"==typeof e.data?Tl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=yb(e,i.message||i.toString());this.events.emit("payload",s)}parseError(e,t=this.url){return ob(e,Bb(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Bb(this.url)}`));return this.events.emit("register_error",t),t}}function Ub(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function kb(e){return"__proto__"===e}function Lb(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function qb(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function Db(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Mb="[object RegExp]",$b="[object String]",jb="[object Number]",zb="[object Boolean]",Fb="[object Arguments]",Kb="[object Symbol]",Vb="[object Date]",Hb="[object Map]",Wb="[object Set]",Gb="[object Array]",Yb="[object Function]",Zb="[object ArrayBuffer]",Jb="[object Object]",Xb="[object Error]",Qb="[object DataView]",ev="[object Uint8Array]",tv="[object Uint8ClampedArray]",iv="[object Uint16Array]",sv="[object Uint32Array]",rv="[object BigUint64Array]",nv="[object Int8Array]",ov="[object Int16Array]",av="[object Int32Array]",cv="[object BigInt64Array]",hv="[object Float32Array]",lv="[object Float64Array]";function uv(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function dv(e,t,i,s=new Map,r=void 0){const n=r?.(e,t,i,s);if(void 0!==n)return n;if(Lb(e))return e;if(s.has(e))return s.get(e);if(Array.isArray(e)){const t=new Array(e.length);s.set(e,t);for(let n=0;n<e.length;n++)t[n]=dv(e[n],n,i,s,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;s.set(e,t);for(const[n,o]of e)t.set(n,dv(o,n,i,s,r));return t}if(e instanceof Set){const t=new Set;s.set(e,t);for(const n of e)t.add(dv(n,void 0,i,s,r));return t}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e.subarray();if(uv(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);s.set(e,t);for(let n=0;n<e.length;n++)t[n]=dv(e[n],n,i,s,r);return t}if(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return s.set(e,t),fv(t,e,i,s,r),t}if("undefined"!=typeof File&&e instanceof File){const t=new File([e],e.name,{type:e.type});return s.set(e,t),fv(t,e,i,s,r),t}if("undefined"!=typeof Blob&&e instanceof Blob){const t=new Blob([e],{type:e.type});return s.set(e,t),fv(t,e,i,s,r),t}if(e instanceof Error){const t=structuredClone(e);return s.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,t.constructor=e.constructor,fv(t,e,i,s,r),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return s.set(e,t),fv(t,e,i,s,r),t}if(e instanceof Number){const t=new Number(e.valueOf());return s.set(e,t),fv(t,e,i,s,r),t}if(e instanceof String){const t=new String(e.valueOf());return s.set(e,t),fv(t,e,i,s,r),t}if("object"==typeof e&&function(e){switch(Db(e)){case Fb:case Gb:case Zb:case Qb:case zb:case Vb:case hv:case lv:case nv:case ov:case av:case Hb:case jb:case Jb:case Mb:case Wb:case $b:case Kb:case ev:case tv:case iv:case sv:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return s.set(e,t),fv(t,e,i,s,r),t}return e}function fv(e,t,i=e,s,r){const n=[...Object.keys(t),...qb(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=dv(t[a],a,i,s,r))}}function pv(e,t){return function(e,t){return dv(e,void 0,e,new Map,t)}(e,((i,s,r,n)=>{const o=t?.(i,s,r,n);if(void 0!==o)return o;if("object"==typeof e){if(Db(e)===Jb&&"function"!=typeof e.constructor){const t={};return n.set(e,t),fv(t,e,r,n),t}switch(Object.prototype.toString.call(e)){case jb:case $b:case zb:{const t=new e.constructor(e?.valueOf());return fv(t,e),t}case Fb:{const t={};return fv(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}}))}function gv(e){return pv(e)}function yv(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===Db(e)}function wv(e){return"object"==typeof e&&null!==e}function mv(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function bv(e,t,i,s,r,n,o){const a=o(e,t,i,s,r,n);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return vv(e,t,n,o)}return vv(e,t,n,o)}function vv(e,t,i,s){if(Object.is(e,t))return!0;let r=Db(e),n=Db(t);if(r===Fb&&(r=Jb),n===Fb&&(n=Jb),r!==n)return!1;switch(r){case $b:return e.toString()===t.toString();case jb:{const i=e.valueOf(),s=t.valueOf();return(o=i)===(a=s)||Number.isNaN(o)&&Number.isNaN(a)}case zb:case Vb:case Kb:return Object.is(e.valueOf(),t.valueOf());case Mb:return e.source===t.source&&e.flags===t.flags;case Yb:return e===t}var o,a;const c=(i=i??new Map).get(e),h=i.get(t);if(null!=c&&null!=h)return c===t;i.set(e,t),i.set(t,e);try{switch(r){case Hb:if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!bv(n,t.get(r),r,e,t,i,s))return!1;return!0;case Wb:{if(e.size!==t.size)return!1;const r=Array.from(e.values()),n=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=n.findIndex((r=>bv(a,r,void 0,e,t,i,s)));if(-1===c)return!1;n.splice(c,1)}return!0}case Gb:case ev:case tv:case iv:case sv:case rv:case nv:case ov:case av:case cv:case hv:case lv:if("undefined"!=typeof Buffer&&Buffer.isBuffer(e)!==Buffer.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!bv(e[r],t[r],r,e,t,i,s))return!1;return!0;case Zb:return e.byteLength===t.byteLength&&vv(new Uint8Array(e),new Uint8Array(t),i,s);case Qb:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&vv(new Uint8Array(e),new Uint8Array(t),i,s);case Xb:return e.name===t.name&&e.message===t.message;case Jb:{if(!(vv(e.constructor,t.constructor,i,s)||mv(e)&&mv(t)))return!1;const r=[...Object.keys(e),...qb(e)],n=[...Object.keys(t),...qb(t)];if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++){const o=r[n],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!bv(a,t[o],o,e,t,i,s))return!1}return!0}default:return!1}}finally{i.delete(e),i.delete(t)}}function Ev(){}function xv(e,t){return function(e,t,i){return bv(e,t,void 0,void 0,void 0,void 0,i)}(e,t,Ev)}function Iv(e){return uv(e)}function Sv(e){if("object"!=typeof e)return!1;if(null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];if(null==t)return!1;return!!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function _v(e,t,i,s){if(Lb(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(s.has(t))return function(e){if(Lb(e))return e;if(Array.isArray(e)||uv(e)||e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(null==t)return Object.assign(Object.create(t),e);const i=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new i(e);if(e instanceof RegExp){const t=new i(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new i(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new i(e.errors,e.message,{cause:e.cause}):new i(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}if("undefined"!=typeof File&&e instanceof File)return new i([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const i=Object.create(t);return Object.assign(i,e)}return e}(s.get(t));if(s.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),...qb(t)];for(let o=0;o<r.length;o++){const a=r[o];if(kb(a))continue;let c=t[a],h=e[a];if(yv(c)&&(c={...c}),yv(h)&&(h={...h}),"undefined"!=typeof Buffer&&Buffer.isBuffer(c)&&(c=gv(c)),Array.isArray(c))if(Array.isArray(h)){const e=[],t=Reflect.ownKeys(h);for(let i=0;i<t.length;i++){const s=t[i];e[s]=h[s]}h=e}else if(wv(n=h)&&Ub(n)){const e=[];for(let t=0;t<h.length;t++)e[t]=h[t];h=e}else h=[];const l=i(h,c,a,e,t,s);void 0!==l?e[a]=l:Array.isArray(c)||wv(h)&&wv(c)&&(Sv(h)||Sv(c)||Iv(h)||Iv(c))?e[a]=_v(h,c,i,s):null==h&&Sv(c)?e[a]=_v({},c,i,s):null==h&&Iv(c)?e[a]=gv(c):void 0!==h&&void 0===c||(e[a]=c)}var n;return e}function Ov(e,...t){return function(e,...t){const i=t.slice(0,-1),s=t[t.length-1];let r=e;for(let e=0;e<i.length;e++)r=_v(r,i[e],s,new Map);return r}(e,...t,Ev)}const Av="core",Pv=`wc@2:${Av}:`,Tv="error",Rv={database:":memory:"},Bv="client_ed25519_seed",Nv=m.ONE_DAY,Cv=m.SIX_HOURS,Uv="wss://relay.walletconnect.org",kv="relayer_message",Lv="relayer_message_ack",qv="relayer_connect",Dv="relayer_disconnect",Mv="relayer_error",$v="relayer_connection_stalled",jv="relayer_publish",zv="payload",Fv="connect",Kv="disconnect",Vv="error",Hv="2.24.0",Wv={link_mode:"link_mode",relay:"relay"},Gv="inbound",Yv="outbound",Zv="WALLETCONNECT_LINK_MODE_APPS",Jv="subscription_created",Xv="subscription_deleted",Qv="subscription_sync",eE="subscription_resubscribed",tE={wc_pairingDelete:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:m.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:m.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:m.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:m.ONE_DAY,prompt:!1,tag:0},res:{ttl:m.ONE_DAY,prompt:!1,tag:0}}},iE="pairing_create",sE="pairing_expire",rE="pairing_delete",nE="pairing_ping",oE="history_created",aE="history_updated",cE="history_deleted",hE="history_sync",lE="expirer_created",uE="expirer_deleted",dE="expirer_expired",fE="expirer_sync",pE="https://verify.walletconnect.org",gE=pE,yE=`${gE}/v3`,wE=["https://verify.walletconnect.com",pE],mE="pairing_started",bE="pairing_uri_validation_success",vE="pairing_uri_not_expired",EE="store_new_pairing",xE="subscribing_pairing_topic",IE="subscribe_pairing_topic_success",SE="existing_pairing",_E="pairing_not_expired",OE="emit_inactive_pairing",AE="emit_session_proposal",PE="no_internet_connection",TE="malformed_pairing_uri",RE="active_pairing_already_exists",BE="subscribe_pairing_topic_failure",NE="pairing_expired",CE="proposal_listener_not_found",UE="session_approve_started",kE="session_namespaces_validation_success",LE="subscribing_session_topic",qE="subscribe_session_topic_success",DE="session_approve_publish_success",ME="store_session",$E="session_request_response_started",jE="session_request_response_validation_success",zE="session_request_response_publish_started",FE="no_internet_connection",KE="proposal_expired",VE="subscribe_session_topic_failure",HE="session_approve_namespace_validation_failure",WE="proposal_not_found",GE="session_request_response_validation_failure",YE="session_request_response_publish_failure",ZE="authenticated_session_approve_started",JE="create_authenticated_session_topic",XE="cacaos_verified",QE="store_authenticated_session",ex="subscribing_authenticated_session_topic",tx="subscribe_authenticated_session_topic_success",ix="publishing_authenticated_session_approve",sx="no_internet_connection",rx="invalid_cacao",nx="subscribe_authenticated_session_topic_failure",ox="authenticated_session_approve_publish_failure",ax="authenticated_session_pending_request_not_found";class cx{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=Pv,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=Dg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=Rg(t,this.name)}get context(){return Tg(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Xg(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Qg(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class hx{constructor(e,t,i){this.core=e,this.logger=t,this.name="crypto",this.randomSessionIdentifier=nw(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=Zf(Qf(await this.getClientSeed()).publicKey);return this.clientId=e,e},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=Fh.utils.randomPrivateKey(),t=Fh.getPublicKey(e);return{privateKey:Ua(e,Gy),publicKey:Ua(t,Gy)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=Qf(await this.getClientSeed()),i=this.randomSessionIdentifier,s=Nv;return await ep(i,e,s,t)},this.generateSharedKey=(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=Fh.getSharedSecret(Ca(e,Gy),Ca(t,Gy));return Ua(cc(hc,i,void 0,void 0,rw),Gy)}(this.getPrivateKey(e),t);return this.setSymKey(s,i)},this.setSymKey=async(e,t)=>{this.isInitialized();const i=t||ow(e);return await this.keychain.set(i,e),i},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,i)=>{this.isInitialized();const s=pw(i),r=Rl(t);if(yw(s))return function(e,t){const i=cw(ew),s=ke(sw),r=dw({type:i,sealed:Ca(e,Jy),iv:s});return t===Zy?lw(r):r}(r,i?.encoding);if(gw(s)){const t=s.senderPublicKey,i=s.receiverPublicKey;e=await this.generateSharedKey(t,i)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=s;return function(e){const t=cw(typeof e.type<"u"?e.type:Xy);if(hw(t)===Qy&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof e.senderPublicKey<"u"?Ca(e.senderPublicKey,Gy):void 0,s=typeof e.iv<"u"?Ca(e.iv,Gy):ke(sw),r=Ca(e.symKey,Gy),n=dw({type:t,sealed:ic(r,s).encrypt(Ca(e.message,Jy)),iv:s,senderPublicKey:i});return e.encoding===Zy?lw(n):n}({type:o,symKey:n,message:r,senderPublicKey:a,encoding:i?.encoding})},this.decode=async(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=fw({encoded:e,encoding:t?.encoding});return pw({type:hw(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?Ua(i.senderPublicKey,Gy):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,i);if(yw(s)){const e=function(e,t){const{sealed:i}=fw({encoded:e,encoding:t});return Ua(i,Jy)}(t,i?.encoding);return Tl(e)}if(gw(s)){const t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}try{const s=function(e){const t=Ca(e.symKey,Gy),{sealed:i,iv:s}=fw({encoded:e.encoded,encoding:e.encoding}),r=ic(t,s).decrypt(i);if(null===r)throw new Error("Failed to decrypt");return Ua(r,Jy)}({symKey:this.getSymKey(e),encoded:t,encoding:i?.encoding});return Tl(s)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=(e,t=Yy)=>hw(fw({encoded:e,encoding:t}).type),this.getPayloadSenderPublicKey=(e,t=Yy)=>{const i=fw({encoded:e,encoding:t});return i.senderPublicKey?Ua(i.senderPublicKey,Gy):void 0},this.core=e,this.logger=Rg(t,this.name),this.keychain=i||new cx(this.core,this.logger)}get context(){return Tg(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Bv)}catch{e=nw(),await this.keychain.set(Bv,e)}return Ca(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class lx extends Fm{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=Pv,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t,i)=>{this.isInitialized();const s=aw(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[s]<"u")return s;if(r[s]=t,this.messages.set(e,r),i===Gv){const i=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,{...i,[s]:t})}return await this.persist(),s},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.getWithoutAck=e=>{this.isInitialized();const t={};for(const i of e){const e=this.messagesWithoutClientAck.get(i)||{};t[i]=Object.values(e)}return t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[aw(t)]<"u"},this.ack=async(e,t)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(e);if(typeof i>"u")return;delete i[aw(t)],0===Object.keys(i).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,i),await this.persist()},this.del=async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()},this.logger=Rg(e,this.name),this.core=t}get context(){return Tg(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,Xg(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Xg(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Qg(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Qg(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class ux extends Km{constructor(t,i){super(t,i),this.relayer=t,this.logger=i,this.events=new e.EventEmitter,this.name="publisher",this.queue=new Map,this.publishTimeout=m.toMiliseconds(m.ONE_MINUTE),this.initialPublishTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(e,t,i)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});const s=i?.ttl||Cv,r=i?.prompt||!1,n=i?.tag||0,o=i?.id||fb().toString(),a=bw(mw().protocol),c={id:o,method:i?.publishMethod||a.publish,params:{topic:e,message:t,ttl:s,prompt:r,tag:n,attestation:i?.attestation,...i?.tvf}},h=`Failed to publish payload, please try again. id:${o} tag:${n}`;try{Uw(c.params?.prompt)&&delete c.params?.prompt,Uw(c.params?.tag)&&delete c.params?.tag;const s=new Promise((async e=>{const t=({id:i})=>{c.id?.toString()===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(jv,t),e())};this.relayer.events.on(jv,t);const s=ty(new Promise(((e,t)=>{this.rpcPublish(c,i).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${o} tag:${n}`);try{await s,this.events.removeListener(jv,t)}catch(e){this.queue.set(o,{request:c,opts:i,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:o,topic:e,message:t,opts:i}}),await ty(s,this.publishTimeout,h)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),i?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(o)}},this.publishCustom=async e=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});const{payload:t,opts:i={}}=e,{attestation:s,tvf:r,publishMethod:n,prompt:o,tag:a,ttl:c=m.FIVE_MINUTES}=i,h=i.id||fb().toString(),l=bw(mw().protocol),u=n||l.publish,d={id:h,method:u,params:{...t,ttl:c,prompt:o,tag:a,attestation:s,...r}},f=`Failed to publish custom payload, please try again. id:${h} tag:${a}`;try{Uw(d.params?.prompt)&&delete d.params?.prompt,Uw(d.params?.tag)&&delete d.params?.tag;const e=new Promise((async e=>{const t=({id:i})=>{d.id?.toString()===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(jv,t),e())};this.relayer.events.on(jv,t);const s=ty(new Promise(((e,t)=>{this.rpcPublish(d,i).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${u} id:${h} tag:${a}`);try{await s,this.events.removeListener(jv,t)}catch(e){this.queue.set(h,{request:d,opts:i,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:h,payload:t,opts:i}}),await ty(e,this.publishTimeout,f)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),i?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(h)}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=t,this.logger=Rg(i,this.name),this.registerEventListeners()}get context(){return Tg(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(jv,{...e,...t}),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async(e,t)=>{const i=e.attempt+1;this.queue.set(t,{...e,attempt:i}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)}))}registerEventListeners(){this.relayer.core.heartbeat.on(hm,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit($v);this.checkQueue()})),this.relayer.on(Lv,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}class dx{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter((e=>e!==t));s.length?this.map.set(e,s):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}class fx extends Wm{constructor(t,i){super(t,i),this.relayer=t,this.logger=i,this.subscriptions=new Map,this.topicMap=new dx,this.events=new e.EventEmitter,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=Pv,this.subscribeTimeout=m.toMiliseconds(m.ONE_MINUTE),this.initialSubscribeTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const i=mw(t),s={topic:e,relay:i,transportType:t?.transportType};t?.internal?.skipSubscribe||this.pending.set(e,s);const r=await this.rpcSubscribe(e,i,t);return"string"==typeof r&&(this.onSubscribe(r,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=e=>new Promise((t=>{t(this.topicMap.topics.includes(e))})),this.isKnownTopic=e=>new Promise((t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some((t=>t.topic===e)))})),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(hm,(async()=>{await this.checkPending()})),this.events.on(Jv,(async e=>{const t=Jv;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(Xv,(async e=>{const t=Xv;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))},this.relayer=t,this.logger=Rg(i,this.name),this.clientId=""}get context(){return Tg(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,t){let i=!1;try{i=this.getSubscription(e).topic===t}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,t){const i=this.topicMap.get(e);await Promise.all(i.map((async i=>await this.unsubscribeById(e,i,t))))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=Mg("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,s);const r=mw(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,i){const s=await this.getSubscriptionId(e);if(i?.internal?.skipSubscribe)return s;(!i||i?.transportType===Wv.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:bw(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=i?.internal?.throwOnFailedPublish;try{if(i?.transportType===Wv.link_mode)return setTimeout((()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch((e=>this.logger.warn(e)))}),m.toMiliseconds(m.ONE_SECOND)),s;const t=new Promise((async t=>{const i=s=>{s.topic===e&&(this.events.removeListener(Jv,i),t(s.id))};this.events.on(Jv,i);try{const s=await ty(new Promise(((e,t)=>{this.relayer.request(r).catch((e=>{this.logger.warn(e,e?.message),t(e)})).then(e)})),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Jv,i),t(s)}catch{}})),o=await ty(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?s:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit($v),n)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:bw(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await ty(new Promise(((e,i)=>{this.relayer.request(t).then(e).catch((e=>{this.logger.warn(e),i(e)}))})),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit($v),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:bw(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map((e=>e.topic))}};let i;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{i=await await ty(new Promise(((e,i)=>{this.relayer.request(t).catch((e=>{this.logger.warn(e),i(e)})).then(e)})),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit($v)}return i}rpcUnsubscribe(e,t,i){const s={method:bw(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,{...t,id:e}),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,{...e}),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,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,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,{...t}),this.topicMap.set(t.topic,e),this.events.emit(Jv,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=Dg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Xv,{...i,reason:t})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Qv)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(eE)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every((e=>e.topic===this.subscriptions.get(e.id)?.topic))){const{message:e}=Dg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}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){if(e.length){if(!await this.rpcBatchSubscribe(e))return this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),void e.forEach((e=>{this.pending.set(e.topic,e)}));this.onBatchSubscribe(await Promise.all(e.map((async e=>({...e,id:await this.getSubscriptionId(e.topic)})))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);var i;t&&t.messages&&(await(i=m.toMiliseconds(m.ONE_SECOND),new Promise((e=>setTimeout(e,i)))),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=Dg("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 aw(e+await this.getClientId())}}class px extends Vm{constructor(t){super(t),this.protocol="wc",this.version=2,this.events=new e.EventEmitter,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=m.toMiliseconds(m.THIRTY_SECONDS+m.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=m.toMiliseconds(2*m.ONE_SECOND),this.stalledRestartMaxInterval=m.toMiliseconds(m.THIRTY_SECONDS),this.request=async e=>{this.logger.debug("Publishing Request Payload");const t=e.id||fb().toString();await this.toEstablishConnection();try{this.logger.trace({id:t,method:e.method,topic:e.params?.topic},"relayer.request - publishing...");const i=`${t}:${e.params?.tag||""}`;this.requestsInFlight.push(i);const s=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter((e=>e!==i)),s}catch(e){throw this.logger.debug(`Failed to Publish Request: ${t}`),e}},this.resetPingTimeout=()=>{Fg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout((()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(e){this.logger.warn(e,e?.message)}}),this.heartBeatTimeout))},this.onPayloadHandler=e=>{this.onProviderPayload(e),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(qv)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(Mv,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch((e=>this.logger.warn(e)))},this.registerProviderListeners=()=>{this.provider.on(zv,this.onPayloadHandler),this.provider.on(Fv,this.onConnectHandler),this.provider.on(Kv,this.onDisconnectHandler),this.provider.on(Vv,this.onProviderErrorHandler)},this.core=t.core,this.logger=nm({logger:t.logger??"error",name:this.name}),this.messages=new lx(this.logger,t.core),this.subscriber=new fx(this,this.logger),this.publisher=new ux(this,this.logger),this.projectId=t.projectId,this.relayUrl=t.relayUrl||Uv,Kg()&&typeof global<"u"&&typeof global?.Platform<"u"&&"android"===global?.Platform.OS?this.packageName=Wg():Kg()&&typeof global<"u"&&typeof global?.Platform<"u"&&"ios"===global?.Platform.OS&&(this.bundleId=Wg()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch((e=>this.logger.warn(e,e?.message)))}get context(){return Tg(this.logger)}get connected(){return 1===this.provider?.connection?.socket?.readyState}get connecting(){return 0===this.provider?.connection?.socket?.readyState||void 0!==this.connectPromise}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Wv.relay},Yv)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){this.isInitialized(),(!t?.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const i=t?.internal?.throwOnFailedPublish??!0;let s,r=this.subscriber.topicMap.get(e)?.[0]||"";const n=t=>{t.topic===e&&(this.subscriber.off(Jv,n),s())};return await Promise.all([new Promise((e=>{s=e,this.subscriber.on(Jv,n)})),new Promise(((s,n)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:i},...t}).then((e=>{r=e||r,s()})).catch((e=>{i?n(e):s()}))}))]),r}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await ty(this.provider.disconnect(),2e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(this.subscriber.hasAnyTopics){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=this.connect(e).finally((()=>{this.connectPromise=void 0})),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.info("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await Zw())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort(((e,t)=>e.publishedAt-t.publishedAt));this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const e={topic:i,expiry:ry(m.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,e)}this.events.emit(kv,e),await this.recordMessageEvent(e,Gv)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let t=1;try{for(;t<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(((e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(Kv,i),ty(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then((()=>e())).catch(t).finally((()=>{this.provider.off(Kv,i),clearTimeout(this.reconnectTimeout)}))})),await new Promise(((e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Kv,i),this.subscriber.start().then(e).catch(t).finally((()=>{this.provider.off(Kv,i)}))})),this.hasExperiencedNetworkDisruption=!1}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise((e=>setTimeout(e,m.toMiliseconds(1*t)))),t++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Fg())try{this.provider?.connection?.socket?.on("ping",(()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await ty(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Rb(new Cb(Zg({sdkVersion:Hv,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,t){const{topic:i,message:s}=e;await this.messages.set(i,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||0===i.length)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,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}),Ob(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:i,message:s,publishedAt:r,attestation:n}=t.data,o={topic:i,message:s,publishedAt:r,transportType:Wv.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:t.id,...o}),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else Ab(e)&&this.events.emit(Lv,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Gv),this.events.emit(kv,e))}async acknowledgePayload(e){const t=gb(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(zv,this.onPayloadHandler),this.provider.off(Fv,this.onConnectHandler),this.provider.off(Kv,this.onDisconnectHandler),this.provider.off(Vv,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Zw();Jw((async t=>{e!==t&&(e=t,t?await this.transportOpen().catch((e=>this.logger.error(e,e?.message))):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})),this.core.heartbeat.on(hm,(async()=>{if(!(this.transportExplicitlyClosed||this.connected||Vg()&&exports.getDocument_1()&&"visible"!==exports.getDocument_1()?.visibilityState))try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})),this.events.on($v,(()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const e=0===this.stalledRestartBackoff?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${e?` in ${e}ms`:""}...`),this.stalledRestartTimeout=setTimeout((async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(e){this.logger.error(e,e?.message)}finally{this.stalledRestartInProgress=!1}}),e)}))}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(Dv),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed)return void(this.reconnectInProgress=!1);this.reconnectTimeout=setTimeout((async()=>{await this.transportOpen().catch((e=>this.logger.error(e,e?.message))),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}),m.toMiliseconds(.1))}}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;this.connectPromise=this.connect().finally((()=>{this.connectPromise=void 0})),await this.connectPromise}}}class gx extends Hm{constructor(e,t,i,s=Pv,r=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Pv,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Uw(e)?this.map.set(this.getKey(e),e):function(e){return e?.proposer?.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((i=>xv(t[i],e[i]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const i={...this.getData(e),...t};this.map.set(e,i),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())},this.logger=Rg(t,this.name),this.storagePrefix=s,this.getKey=r}get context(){return Tg(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 t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=Dg("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=Dg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}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:e}=Dg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class yx{constructor(e,t){this.core=e,this.logger=t,this.name="pairing",this.version="0.3",this.events=new r.default,this.initialized=!1,this.storagePrefix=Pv,this.ignoredPayloadTypes=[Qy],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async e=>{this.isInitialized();const t=nw(),i=await this.core.crypto.setSymKey(t),s=ry(m.FIVE_MINUTES),r={protocol:"irn"},n={topic:i,expiry:s,relay:r,active:!1,methods:e?.methods},o=Sw({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:t,relay:r,expiryTimestamp:s,methods:e?.methods});return this.events.emit(iE,n),this.core.expirer.set(i,s),await this.pairings.set(i,n),await this.core.relayer.subscribe(i,{transportType:e?.transportType,internal:e?.internal}),{topic:i,uri:o}},this.pair=async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[mE]}});this.isValidPair(e,t);const{topic:i,symKey:s,relay:r,expiryTimestamp:n,methods:o}=Ew(e.uri);let a;if(t.props.properties.topic=i,t.addTrace(bE),t.addTrace(vE),this.pairings.keys.includes(i)){if(a=this.pairings.get(i),t.addTrace(SE),a.active)throw t.setError(RE),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);t.addTrace(_E)}const c=n||ry(m.FIVE_MINUTES),h={topic:i,relay:r,expiry:c,active:!1,methods:o};this.core.expirer.set(i,c),await this.pairings.set(i,h),t.addTrace(EE),e.activatePairing&&await this.activate({topic:i}),this.events.emit(iE,h),t.addTrace(OE),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),t.addTrace(xE);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(PE)}try{await this.core.relayer.subscribe(i,{relay:r})}catch(e){throw t.setError(BE),e}return t.addTrace(IE),h},this.activate=async({topic:e})=>{this.isInitialized();const t=ry(m.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:s,reject:r}=ey();this.events.once(oy("pairing_ping",e),(({error:e})=>{e?r(e):s()})),await i()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Mg("USER_DISCONNECTED")),await this.deletePairing(t))},this.formatUriFromPairing=e=>{this.isInitialized();const{topic:t,relay:i,expiry:s,methods:r}=e,n=this.core.crypto.keychain.get(t);return Sw({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:i,expiryTimestamp:s,methods:r})},this.sendRequest=async(e,t,i)=>{const s=pb(t,i),r=await this.core.crypto.encode(e,s),n=tE[t].req;return this.core.history.set(e,s),this.core.relayer.publish(e,r,n),s.id},this.sendResult=async(e,t,i)=>{const s=gb(e,i),r=await this.core.crypto.encode(t,s),n=(await this.core.history.get(t,e)).request.method,o=tE[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=yb(e,i),r=await this.core.crypto.encode(t,s),n=(await this.core.history.get(t,e)).request.method,o=tE[n]?tE[n].res:tE.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Mg("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>ny(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=async e=>{const{topic:t,payload:i}=e;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,i);default:return await this.onUnknownRpcMethodRequest(t,i)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.core.history.get(t,i.id)).request.method;return"wc_pairingPing"===s?this.onPairingPingResponse(t,i):this.onUnknownRpcMethodResponse(s)},this.onPairingPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit(nE,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Pb(t)?this.events.emit(oy("pairing_ping",i),{}):Tb(t)&&this.events.emit(oy("pairing_ping",i),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(rE,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:i,method:s}=t;try{if(this.registeredMethods.includes(s))return;const t=Mg("WC_METHOD_UNSUPPORTED",s);await this.sendError(i,e,t),this.logger.error(t)}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Mg("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=(e,t)=>{if(!Kw(e)){const{message:i}=Dg("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(TE),new Error(i)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(kw(e,!1))return!!t(e)||t(dy(e))}catch{}return!1}(e.uri)){const{message:i}=Dg("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(TE),new Error(i)}const i=Ew(e?.uri);if(!i?.relay?.protocol){const{message:e}=Dg("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(TE),new Error(e)}if(!i?.symKey){const{message:e}=Dg("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(TE),new Error(e)}if(i?.expiryTimestamp&&m.toMiliseconds(i?.expiryTimestamp)<Date.now()){t.setError(NE);const{message:e}=Dg("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}},this.isValidPing=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!kw(e,!1)){const{message:t}=Dg("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=Dg("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(ny(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=Dg("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=e,this.logger=Rg(t,this.name),this.pairings=new gx(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Tg(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(kv,(async e=>{const{topic:t,message:i,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==Wv.link_mode){try{if(this.core.crypto.getPayloadType(i,Zy)===ew)return void this.logger.warn(`registerRelayerEvents() -> non-link mode TYPE_2 payload ignored: ${i}`)}catch{}if(!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const e=await this.core.crypto.decode(t,i);Ob(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):Ab(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,i)}catch(e){this.logger.error(e)}}}))}registerExpirerEvents(){this.core.expirer.on(dE,(async e=>{const{topic:t}=sy(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(sE,{topic:t}))}))}}class wx extends zm{constructor(t,i){super(t,i),this.core=t,this.logger=i,this.records=new Map,this.events=new e.EventEmitter,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Pv,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;const s={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i,expiry:ry(m.THIRTY_DAYS)};this.records.set(s.id,s),this.persist(),this.events.emit(oE,s)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response<"u"||(t.response=Tb(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(aE,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((i=>{if(i.topic===e){if(typeof t<"u"&&i.id!==t)return;this.records.delete(i.id),this.events.emit(cE,i)}})),this.persist()},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Rg(i,this.name)}get context(){return Tg(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((t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:pb(t.request.method,t.request.params,t.id),chainId:t.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 t=this.records.get(e);if(!t){const{message:t}=Dg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(hE)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=Dg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(oE,(e=>{const t=oE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(aE,(e=>{const t=aE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(cE,(e=>{const t=cE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.core.heartbeat.on(hm,(()=>{this.cleanup()}))}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach((t=>{m.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(cE,t,!1),e=!0)})),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class mx extends Gm{constructor(t,i){super(t,i),this.core=t,this.logger=i,this.expirations=new Map,this.events=new e.EventEmitter,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Pv,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const i=this.formatTarget(e),s={target:i,expiry:t};this.expirations.set(i,s),this.checkExpiry(i,s),this.events.emit(lE,{target:i,expiration:s})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(uE,{target:t,expiration:i})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Rg(i,this.name)}get context(){return Tg(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("string"==typeof e)return iy("topic",e);if("number"==typeof e)return function(e){return iy("id",e)}(e);const{message:t}=Dg("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}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(fE)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=Dg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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 t=this.expirations.get(e);if(!t){const{message:t}=Dg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:i}=t;m.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(dE,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(hm,(()=>this.checkExpirations())),this.events.on(lE,(e=>{const t=lE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(dE,(e=>{const t=dE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(uE,(e=>{const t=uE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class bx extends Ym{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name="verify-api",this.verifyUrlV3=yE,this.storagePrefix=Pv,this.version=2,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&m.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async e=>{if(!Vg()||this.isDevEnv)return;const t=window.location.origin,{id:i,decryptedId:s}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${i}&decryptedId=${s}`;try{const e=exports.getDocument_1(),t=this.startAbortTimer(5*m.ONE_SECOND),s=await new Promise(((s,n)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if(Xf(n.attestation).payload.id!==i)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),s(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})}));return this.logger.debug(s,"jwt attestation"),s}catch(e){this.logger.warn(e)}return""},this.resolve=async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:i,encryptedId:s}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(Xf(t).payload.id!==s)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!i)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(i,r)},this.fetchAttestation=async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const i=this.startAbortTimer(5*m.ONE_SECOND),s=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),200===s.status?await s.json():void 0},this.getVerifyUrl=e=>{let t=e||gE;return wE.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${gE}`),t=gE),t},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(m.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}},this.persistPublicKey=async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(e,i)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise((async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))}));const e=await this.fetchPromise;return this.fetchPromise=void 0,e},this.validateAttestation=(e,t)=>{const i=ww(e,t.publicKey),s={hasExpired:m.toMiliseconds(i.exp)<Date.now(),payload:i};if(s.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:s.payload.origin,isScam:s.payload.isScam,isVerified:s.payload.isVerified}},this.logger=Rg(t,this.name),this.abortController=new AbortController,this.isDevEnv=uy(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Tg(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),m.toMiliseconds(e))}}class vx extends Zm{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context="echo",this.registerDeviceToken=async e=>{const{clientId:t,token:i,notificationType:s,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:s,token:i,always_raw:r})})},this.logger=Rg(t,this.context)}}class Ex extends Jm{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context="event-client",this.storagePrefix=Pv,this.storageVersion=.1,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!uy())try{const e={eventId:ly(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Yg(this.core.relayer.protocol,this.core.relayer.version,Hv)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}},this.createEvent=e=>{const{event:t="ERROR",type:i="",properties:{topic:s,trace:r}}=e,n=ly(),o=this.core.projectId||"",a={eventId:n,timestamp:Date.now(),props:{event:t,type:i,properties:{topic:s,trace:r}},bundleId:o,domain:this.getAppDomain(),...this.setMethods(n)};return this.telemetryEnabled&&(this.events.set(n,a),this.shouldPersist=!0),a},this.getEvent=e=>{const{eventId:t,topic:i}=e;if(t)return this.events.get(t);const s=Array.from(this.events.values()).find((e=>e.props.properties.topic===i));return s?{...s,...this.setMethods(s.eventId)}:void 0},this.deleteEvent=e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(hm,(async()=>{this.shouldPersist&&await this.persist(),this.events.forEach((e=>{m.fromMiliseconds(Date.now())-m.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)}))}))},this.setMethods=e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}),this.addTrace=(e,t)=>{const i=this.events.get(e);i&&(i.props.properties.trace.push(t),this.events.set(e,i),this.shouldPersist=!0)},this.setError=(e,t)=>{const i=this.events.get(e);i&&(i.props.type=t,i.timestamp=Date.now(),this.events.set(e,i),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach((e=>{this.events.set(e.eventId,{...e,...this.setMethods(e.eventId)})}))}catch(e){this.logger.warn(e)}},this.submit=async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,i]of this.events)i.props.type&&e.push(i);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}},this.sendEvent=async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Hv}${t}`,{method:"POST",body:JSON.stringify(e)})},this.getAppDomain=()=>Gg().url,this.logger=Rg(t,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}}const xx=class t extends jm{constructor(t){super(t),this.protocol="wc",this.version=2,this.name=Av,this.events=new e.EventEmitter,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.dispatchEnvelope=({topic:e,message:t,sessionExists:i})=>{if(!e||!t)return;const s={topic:e,message:t,publishedAt:Date.now(),transportType:Wv.link_mode};this.relayer.onLinkMessageEvent(s,{sessionExists:i})};const i=this.getGlobalCore(t?.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(e){console.warn("Failed to copy global core",e)}this.projectId=t?.projectId,this.relayUrl=t?.relayUrl||Uv,this.customStoragePrefix=t?.customStoragePrefix?`:${t.customStoragePrefix}`:"";const s=function(e){return Pg(Ag({},e),{level:e?.level||sg})}({level:"string"==typeof t?.logger&&t.logger?t.logger:Tv,name:Av}),{logger:r,chunkLoggerController:n}=Bg({opts:s,maxSizeInBytes:t?.maxLogBlobSizeInBytes,loggerOverride:t?.logger});this.logChunkController=n,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Rg(r,this.name),this.heartbeat=new lm,this.crypto=new hx(this,this.logger,t?.keychain),this.history=new wx(this,this.logger),this.expirer=new mx(this,this.logger),this.storage=t?.storage?t.storage:new $m({...Rv,...t?.storageOptions}),this.relayer=new px({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yx(this,this.logger),this.verify=new bx(this,this.logger,this.storage),this.echoClient=new vx(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Ex(this,this.logger,t?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new t(e);await i.initialize();const s=await i.crypto.getClientId();return await i.storage.setItem("WALLETCONNECT_CLIENT_ID",s),i}get context(){return Tg(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Zv,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(Zv)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_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[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[t]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===process.env.DISABLE_GLOBAL_CORE}catch{return!0}}},Ix="client",Sx=`wc@2:${Ix}:`,_x=Ix,Ox="error",Ax="WALLETCONNECT_DEEPLINK_CHOICE",Px="Proposal expired",Tx=m.SEVEN_DAYS,Rx={wc_sessionPropose:{req:{ttl:m.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1104},res:{ttl:m.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1106},res:{ttl:m.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:3*m.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*m.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:m.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1112},res:{ttl:m.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1114},res:{ttl:m.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:m.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:m.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1119}}},Bx={min:m.FIVE_MINUTES,max:m.SEVEN_DAYS},Nx="IDLE",Cx="ACTIVE",Ux={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""},canton_prepareSignExecute:{key:""},stellar_signXDR:{key:""},stellar_signAndSubmitXDR:{key:"tx_hash"}},kx=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],Lx="wc@1.5:auth:",qx=`${Lx}:PUB_KEY`;class Dx extends Qm{constructor(e){super(e),this.name="engine",this.events=new r.default,this.initialized=!1,this.requestQueue={state:Nx,queue:[]},this.sessionRequestQueue={state:Nx,queue:[]},this.emittedSessionRequests=new fy({limit:500}),this.requestQueueDelay=m.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Rx)}),this.initialized=!0,setTimeout((async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),m.toMiliseconds(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t={...e,requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}};await this.isValidConnect(t),t.optionalNamespaces=function(e,t){const i=Rw(e),s=Rw(t),r={},n=Object.keys(i).concat(Object.keys(s));for(const e of n)r[e]={chains:ay(i[e]?.chains,s[e]?.chains),methods:ay(i[e]?.methods,s[e]?.methods),events:ay(i[e]?.events,s[e]?.events)};return r}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:r,sessionProperties:n,scopedProperties:o,relays:a,authentication:c,walletPay:h}=t,l=c?.[0]?.ttl||Rx.wc_sessionPropose.req.ttl||m.FIVE_MINUTES;this.validateRequestExpiry(l);let u,d=i,f=!1;try{if(d){const e=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),e}if(!d||!f){const{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=e,u=t}if(!d){const{message:e}=Dg("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(e)}const p=await this.client.core.crypto.generateKeyPair(),g=ry(l),y={requiredNamespaces:s,optionalNamespaces:r,relays:a??[{protocol:"irn"}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:d,...n&&{sessionProperties:n},...o&&{scopedProperties:o},id:db(),...(c||h)&&{requests:{authentication:c?.map((e=>{const{domain:t,chains:i,nonce:s,uri:r,exp:n,nbf:o,type:a,statement:c,requestId:h,resources:l,signatureTypes:u}=e;return{domain:t,chains:i,nonce:s,type:a??"caip122",aud:r,version:"1",iat:(new Date).toISOString(),exp:n,nbf:o,statement:c,requestId:h,resources:l,signatureTypes:u}})),walletPay:h}}},w=oy("session_connect",y.id),{reject:b,resolve:v,done:E}=ey(l,Px),x=({id:e})=>{if(e===y.id){this.client.events.off("proposal_expire",x);const e=this.pendingSessions.get(y.id);if(e){const{sessionTopic:t,publicKey:i}=e;Promise.all([this.client.core.relayer.unsubscribe(t),this.client.core.crypto.keychain.has(t)?this.client.core.crypto.deleteSymKey(t):Promise.resolve(),this.client.core.crypto.keychain.has(i)?this.client.core.crypto.deleteKeyPair(i):Promise.resolve()]).catch((e=>this.client.logger.warn(e)))}this.pendingSessions.delete(y.id),this.events.emit(w,{error:{message:Px,code:0}})}};return this.client.events.on("proposal_expire",x),this.events.once(w,(({error:e,session:t})=>{this.client.events.off("proposal_expire",x),e?b(e):t&&v(t)})),await this.setProposal(y.id,y),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}).catch((e=>{throw this.deleteProposal(y.id),e})),{uri:u,approval:E}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}},this.approve=async e=>{const t=this.client.core.eventClient.createEvent({properties:{topic:e?.id?.toString(),trace:[UE]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw t.setError(FE),e}try{await this.isValidProposalId(e?.id)}catch(i){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),t.setError(WE),i}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),t.setError(HE),e}const{id:i,relayProtocol:s,namespaces:r,sessionProperties:n,scopedProperties:o,sessionConfig:a,proposalRequestsResponses:c}=e,h=this.client.proposal.get(i);this.client.core.eventClient.deleteEvent({eventId:t.eventId});const{pairingTopic:l,proposer:u,requiredNamespaces:d,optionalNamespaces:f}=h;let p=this.client.core.eventClient?.getEvent({topic:l});p||(p=this.client.core.eventClient?.createEvent({type:UE,properties:{topic:l,trace:[UE,kE]}}));const g=await this.client.core.crypto.generateKeyPair(),y=u.publicKey,w=await this.client.core.crypto.generateSharedKey(g,y),m={relay:{protocol:s??"irn"},namespaces:r,controller:{publicKey:g,metadata:this.client.metadata},expiry:ry(Tx),...n&&{sessionProperties:n},...o&&{scopedProperties:o},...a&&{sessionConfig:a},proposalRequestsResponses:c},b=Wv.relay;p.addTrace(LE);try{await this.client.core.relayer.subscribe(w,{transportType:b,internal:{skipSubscribe:!0}})}catch(e){throw p.setError(VE),e}p.addTrace(qE);const v={...m,topic:w,requiredNamespaces:d,optionalNamespaces:f,pairingTopic:l,acknowledged:!1,self:m.controller,peer:{publicKey:u.publicKey,metadata:u.metadata},controller:g,transportType:Wv.relay,authentication:c?.authentication,walletPayResult:c?.walletPay};await this.client.session.set(w,v),p.addTrace(ME);try{await this.sendApproveSession({sessionTopic:w,proposal:h,pairingProposalResponse:{relay:{protocol:s??"irn"},responderPublicKey:g},sessionSettleRequest:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:i,...this.getTVFApproveParams(v)}}}),p.addTrace(DE)}catch(e){throw this.client.logger.error(e),this.client.session.delete(w,Mg("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(w),e}return this.client.core.eventClient.deleteEvent({eventId:p.eventId}),await this.client.core.pairing.updateMetadata({topic:l,metadata:u.metadata}),await this.deleteProposal(i),await this.client.core.pairing.activate({topic:l}),await this.setExpiry(w,ry(Tx)),{topic:w,acknowledged:()=>Promise.resolve(this.client.session.get(w))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:i}=e;let s;try{s=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}s&&await this.sendError({id:t,topic:s,error:i,rpcOpts:Rx.wc_sessionPropose.reject}),await this.deleteProposal(t)},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:i}=e,s=this.client.session.get(t);if(s.self.publicKey!==s.controller){const{message:e}=Mg("UNAUTHORIZED_UPDATE_REQUEST");throw new Error(e)}const{done:r,resolve:n,reject:o}=ey(m.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),a=db(),c=fb().toString(),h=this.client.session.get(t).namespaces;return this.events.once(oy("session_update",a),(({error:e})=>{e?o(e):n()})),await this.client.session.update(t,{namespaces:i}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch((e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:h}),o(e)})),{acknowledged:r}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,i=db(),{done:s,resolve:r,reject:n}=ey(m.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(oy("session_extend",i),(({error:e})=>{e?n(e):r()})),await this.setExpiry(t,ry(Tx)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch((e=>{n(e)})),{acknowledged:s}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:i,topic:s,expiry:r=Rx.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(s);n?.transportType===Wv.relay&&await this.confirmOnlineStateOrThrow();const o=db(),a=fb().toString(),{done:c,resolve:h,reject:l}=ey(r,"Request expired. Please try again.");this.events.once(oy("session_request",o),(({error:e,result:t})=>{e?l(e):h(t)}));const u="wc_sessionRequest",d=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(d)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:s,method:u,params:{request:{...i,expiryTimestamp:ry(r)},chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:d}).catch((e=>l(e))),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:o}),await c();const f={request:{...i,expiryTimestamp:ry(r)},chainId:t};return await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:s,method:u,params:f,expiry:r,throwOnFailedPublish:!0,tvf:this.getTVFParams(o,f)}).catch((e=>l(e))),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:o}),e()})),new Promise((async e=>{if(!n.sessionConfig?.disableDeepLink){const e=await async function(e,t){let i="";try{if(Vg()&&(i=localStorage.getItem(t),i))return i;i=await e.getItem(t)}catch(e){console.error(e)}return i}(this.client.core.storage,Ax);await cy({id:o,topic:s,wcDeepLink:e})}e()})),c()]).then((e=>e[2]))},this.respond=async e=>{this.isInitialized();const t=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||e?.response?.id?.toString(),trace:[$E]}});try{await this.isValidRespond(e)}catch(e){throw t.addTrace(e?.message),t.setError(GE),e}t.addTrace(jE);const{topic:i,response:s}=e,{id:r}=s,n=this.client.session.get(i);n.transportType===Wv.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);try{t.addTrace(zE),Pb(s)?await this.sendResult({id:r,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:o}):Tb(s)&&await this.sendError({id:r,topic:i,error:s.error,appLink:o}),this.cleanupAfterResponse(e)}catch(e){throw t.addTrace(e?.message),t.setError(YE),e}},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=db(),i=fb().toString(),{done:s,resolve:r,reject:n}=ey(m.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(oy("session_ping",e),(({error:e})=>{e?n(e):r()})),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:i}),s()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:i,chainId:s}=e,r=fb().toString(),n=db();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Mg("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=Dg("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:i}=t,s=Object.keys(e.namespaces),r=Object.keys(i);let n=!0;return!!Jg(r,s)&&(s.forEach((t=>{const{accounts:s,methods:r,events:o}=e.namespaces[t],a=Ow(s),c=i[t];Jg(kg(t,c),a)&&Jg(c.methods,r)&&Jg(c.events,o)||(n=!1)})),n)}(t,e)))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&this.client.metadata.redirect?.linkMode,s=i?Wv.link_mode:Wv.relay;s===Wv.relay&&await this.confirmOnlineStateOrThrow();const{chains:r,statement:n="",uri:o,domain:a,nonce:c,type:h,exp:l,nbf:u,methods:d=[],expiry:f}=e,p=[...e.resources||[]],{topic:g,uri:y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:s});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:g,uri:y}}),this.client.auth.authKeys.keys.includes(qx)){const{responseTopic:e,publicKey:t}=this.client.auth.authKeys.get(qx);e&&(await this.client.core.relayer.unsubscribe(e).catch((e=>this.client.logger.warn(e))),await this.client.auth.pairingTopics.delete(e,{message:"replaced",code:0}).catch((e=>this.client.logger.warn(e)))),t&&this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteKeyPair(t)}const w=await this.client.core.crypto.generateKeyPair(),m=ow(w);if(await Promise.all([this.client.auth.authKeys.set(qx,{responseTopic:m,publicKey:w}),this.client.auth.pairingTopics.set(m,{topic:m,pairingTopic:g})]),await this.client.core.relayer.subscribe(m,{transportType:s}),this.client.logger.info(`sending request to new pairing topic: ${g}`),d.length>0){const{namespace:e}=Cg(r[0]);let t=zy(e,"request",d);Hy(p)&&(t=Fy(t,p.pop())),p.push(t)}const b=f&&f>Rx.wc_sessionAuthenticate.req.ttl?f:Rx.wc_sessionAuthenticate.req.ttl,v={authPayload:{type:h??"caip122",chains:r,statement:n,aud:o,domain:a,version:"1",nonce:c,iat:(new Date).toISOString(),exp:l,nbf:u,resources:p},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:ry(b)},E={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:r,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:g,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:ry(Rx.wc_sessionPropose.req.ttl),id:db()},{done:x,resolve:I,reject:S}=ey(b,"Request expired"),_=db(),O=oy("session_connect",E.id),A=oy("session_request",_),P=async({error:e,session:t})=>{this.events.off(A,T),e?S(e):t&&I({session:t})},T=async e=>{if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),e.error){const t=Mg("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(O,P),S(e.error.message))}await this.deleteProposal(E.id),this.events.off(O,P);const{cacaos:i,responder:r}=e.result,n=[],o=[];for(const e of i){await Ly({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),S(Mg("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,i=Hy(t.resources),s=[Uy(t.iss)],r=ky(t.iss);if(i){const e=Ky(i),t=Vy(i);n.push(...e),s.push(...t)}for(const e of s)o.push(`${e}:${r}`)}const a=await this.client.core.crypto.generateSharedKey(w,r.publicKey);let c;n.length>0&&(c={topic:a,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:r,controller:r.publicKey,expiry:ry(Tx),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:g,namespaces:Bw([...new Set(n)],[...new Set(o)]),transportType:s},await this.client.core.relayer.subscribe(a,{transportType:s}),await this.client.session.set(a,c),g&&await this.client.core.pairing.updateMetadata({topic:g,metadata:r.metadata}),c=this.client.session.get(a)),this.client.metadata.redirect?.linkMode&&r.metadata.redirect?.linkMode&&r.metadata.redirect?.universal&&t&&(this.client.core.addLinkModeSupportedApp(r.metadata.redirect.universal),this.client.session.update(a,{transportType:Wv.link_mode})),I({auths:i,session:c})};let R;this.events.once(O,P),this.events.once(A,T);try{if(i){const e=pb("wc_sessionAuthenticate",v,_);this.client.core.history.set(g,e);const i=await this.client.core.crypto.encode("",e,{type:ew,encoding:Zy});R=_w(t,g,i)}else await Promise.all([this.sendRequest({topic:g,method:"wc_sessionAuthenticate",params:v,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:g,method:"wc_sessionPropose",params:E,expiry:Rx.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(e){throw this.events.off(O,P),this.events.off(A,T),e}return await this.setProposal(E.id,E),await this.setAuthRequest(_,{request:{...v,verifyContext:{}},pairingTopic:g,transportType:s}),{uri:R??y,response:x}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:i}=e,s=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[ZE]}});try{this.isInitialized()}catch(e){throw s.setError(sx),e}const r=this.getPendingAuthRequest(t);if(!r)throw s.setError(ax),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||Wv.relay;n===Wv.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ow(o),h={type:Qy,receiverPublicKey:o,senderPublicKey:a},l=[],u=[];for(const e of i){if(!await Ly({cacao:e,projectId:this.client.core.projectId})){s.setError(rx);const e=Mg("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:h}),new Error(e.message)}s.addTrace(XE);const{p:i}=e,r=Hy(i.resources),n=[Uy(i.iss)],o=ky(i.iss);if(r){const e=Ky(r),t=Vy(r);l.push(...e),n.push(...t)}for(const e of n)u.push(`${e}:${o}`)}const d=await this.client.core.crypto.generateSharedKey(a,o);let f;if(s.addTrace(JE),l?.length>0){f={topic:d,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:r.requester.metadata},controller:o,expiry:ry(Tx),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:Bw([...new Set(l)],[...new Set(u)]),transportType:n},s.addTrace(ex);try{await this.client.core.relayer.subscribe(d,{transportType:n})}catch(e){throw s.setError(nx),e}s.addTrace(tx),await this.client.session.set(d,f),s.addTrace(QE),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}s.addTrace(ix);try{await this.sendResult({topic:c,id:t,result:{cacaos:i,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(e){throw s.setError(ox),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:f}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:i}=e,s=this.getPendingAuthRequest(t);if(!s)throw new Error(`Could not find pending auth request with id ${t}`);s.transportType===Wv.relay&&await this.confirmOnlineStateOrThrow();const r=s.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),o=ow(r),a={type:Qy,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:o,error:i,encodeOpts:a,rpcOpts:Rx.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:i}=e;return qy(t,i)},this.processRelayMessageCache=()=>{setTimeout((async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}}),50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter((i=>i.peerMetadata?.url&&i.peerMetadata?.url===e.peer.metadata.url&&i.topic&&i.topic!==t.topic));if(0===i.length)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async e=>{const{topic:t,expirerHasDeleted:i=!1,emitEvent:s=!0,id:r=0}=e,{self:n}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),await this.client.session.delete(t,Mg("USER_DISCONNECTED")),this.addToRecentlyDeleted(t,"session"),this.client.core.crypto.keychain.has(n.publicKey)&&await this.client.core.crypto.deleteKeyPair(n.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),i||this.client.core.expirer.del(t),this.client.core.storage.removeItem(Ax).catch((e=>this.client.logger.warn(e))),t===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=Nx),await Promise.all(this.getPendingSessionRequests().filter((e=>e.topic===t)).map((e=>this.deletePendingSessionRequest(e.id,Mg("USER_DISCONNECTED"))))),s&&this.client.events.emit("session_delete",{id:r,topic:t})},this.deleteProposal=async(e,t)=>{if(t)try{const t=this.client.proposal.get(e);this.client.core.eventClient.getEvent({topic:t.pairingTopic})?.setError(KE)}catch{}await Promise.all([this.client.proposal.delete(e,Mg("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter((t=>t.id!==e)),i&&(this.sessionRequestQueue.state=Nx,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,i=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,ry(Rx.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:i,pairingTopic:s,transportType:r=Wv.relay}=t;this.client.core.expirer.set(e,i.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:e,pairingTopic:s,verifyContext:i.verifyContext,transportType:r})},this.setPendingSessionRequest=async e=>{const{id:t,topic:i,params:s,verifyContext:r}=e,n=s.request.expiryTimestamp||ry(Rx.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:i,params:s,verifyContext:r})},this.sendRequest=async e=>{const{topic:t,method:i,params:s,expiry:r,relayRpcId:n,clientRpcId:o,throwOnFailedPublish:a,appLink:c,tvf:h,publishOpts:l={}}=e,u=pb(i,s,o);let d;const f=!!c;try{const e=f?Zy:Yy;d=await this.client.core.crypto.encode(t,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),e}let p;if(kx.includes(i)){const e=aw(JSON.stringify(u)),t=aw(d);p=await this.client.core.verify.register({id:t,decryptedId:e})}const g={...Rx[i].req,...l};if(g.attestation=p,r&&(g.ttl=r),n&&(g.id=n),this.client.core.history.set(t,u),f){const e=_w(c,t,d);await global.Linking.openURL(e,this.client.name)}else g.tvf={...h,correlationId:u.id},a?(g.internal={...g.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(t,d,g)):this.client.core.relayer.publish(t,d,g).catch((e=>this.client.logger.error(e)));return u.id},this.sendProposeSession=async e=>{const{proposal:t,publishOpts:i}=e,s=pb("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,s);const r=await this.client.core.crypto.encode(t.pairingTopic,s,{encoding:Yy}),n=aw(JSON.stringify(s)),o=aw(r),a=await this.client.core.verify.register({id:o,decryptedId:n});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:r},opts:{...i,publishMethod:"wc_proposeSession",attestation:a}})},this.sendApproveSession=async e=>{const{sessionTopic:t,pairingProposalResponse:i,proposal:s,sessionSettleRequest:r,publishOpts:n}=e,o=gb(s.id,i),a=await this.client.core.crypto.encode(s.pairingTopic,o,{encoding:Yy}),c=pb("wc_sessionSettle",r,n?.id),h=await this.client.core.crypto.encode(t,c,{encoding:Yy});this.client.core.history.set(t,c),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:s.pairingTopic,sessionProposalResponse:a,sessionSettlementRequest:h},opts:{...n,publishMethod:"wc_approveSession"}})},this.sendResult=async e=>{const{id:t,topic:i,result:s,throwOnFailedPublish:r,encodeOpts:n,appLink:o}=e,a=gb(t,s);let c;const h=o&&typeof global?.Linking<"u";try{const e=h?Zy:Yy;c=await this.client.core.crypto.encode(i,a,{...n||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),e}let l,u;try{l=await this.client.core.history.get(i,t);const e=l.request;try{u=this.getTVFParams(t,e.params,s)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${t}) failed`),e}if(h){const e=_w(o,i,c);await global.Linking.openURL(e,this.client.name)}else{const e=l.request.method,s=Rx[e].res;s.tvf={...u,correlationId:t},r?(s.internal={...s.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(i,c,s)):this.client.core.relayer.publish(i,c,s).catch((e=>this.client.logger.error(e)))}await this.client.core.history.resolve(a)},this.sendError=async e=>{const{id:t,topic:i,error:s,encodeOpts:r,rpcOpts:n,appLink:o}=e,a=yb(t,s);let c;const h=o&&typeof global?.Linking<"u";try{const e=h?Zy:Yy;c=await this.client.core.crypto.encode(i,a,{...r||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),e}let l;try{l=await this.client.core.history.get(i,t)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${i}, ${t}) failed`),e}if(h){const e=_w(o,i,c);await global.Linking.openURL(e,this.client.name)}else{const e=l.request.method,t=n||Rx[e].res;this.client.core.relayer.publish(i,c,t)}await this.client.core.history.resolve(a)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{let i=!1;ny(t.expiry)&&(i=!0),this.client.core.crypto.keychain.has(t.topic)||(i=!0),i&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{ny(e.expiryTimestamp)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession({topic:e}))),...t.map((e=>this.deleteProposal(e)))])},this.onProviderMessageEvent=async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==Cx){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Cx;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=Nx}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=async e=>{const{topic:t,payload:i,attestation:s,transportType:r,encryptedId:n}=e,o=i.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:i,attestation:s,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,i);case"wc_sessionPing":return await this.onSessionPingRequest(t,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:i,attestation:s,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:i,attestation:s,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i,transportType:s}=e,r=(await this.client.core.history.get(t,i.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,i);case"wc_sessionExtend":return this.onSessionExtendResponse(t,i);case"wc_sessionPing":return this.onSessionPingResponse(t,i);case"wc_sessionRequest":return this.onSessionRequestResponse(t,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,i);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:i}=Dg("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:i}=e,s=this.expectedPairingMethodMap.get(t);return!(!s||s.includes(i))&&!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r}=e,{params:n,id:o}=i;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(CE)),this.isValidConnect({...i.params});const a={id:o,pairingTopic:t,expiryTimestamp:n.expiryTimestamp||ry(Rx.wc_sessionPropose.req.ttl),attestation:s,encryptedId:r,...n};await this.setProposal(o,a);const c=await this.getVerifyContext({attestationId:s,hash:aw(JSON.stringify(i)),encryptedId:r,metadata:a.proposer.metadata});e?.addTrace(AE),this.client.events.emit("session_proposal",{id:o,params:a,verifyContext:c})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:Rx.wc_sessionPropose.autoReject}),this.client.logger.error(e)}},this.onSessionProposeResponse=async(e,t,i)=>{const{id:s}=t;if(Pb(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const o=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(s,{sessionTopic:c,pairingTopic:e,proposalId:s,publicKey:o});const h=await this.client.core.relayer.subscribe(c,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:e})}else if(Tb(t)){await this.deleteProposal(s);const e=oy("session_connect",s);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidSessionSettleRequest(s);const{relay:i,controller:r,expiry:n,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:h,proposalRequestsResponses:l}=t.params,u=[...this.pendingSessions.values()].find((t=>t.sessionTopic===e));if(!u)return this.client.logger.error(`Pending session not found for topic ${e}`);const d=this.client.proposal.get(u.proposalId),f={topic:e,relay:i,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:u.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:r.publicKey,self:{publicKey:u.publicKey,metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata},...a&&{sessionProperties:a},...c&&{scopedProperties:c},...h&&{sessionConfig:h},transportType:Wv.relay,authentication:l?.authentication,walletPayResult:l?.walletPay};await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:u.pairingTopic,metadata:f.peer.metadata}),this.pendingSessions.delete(u.proposalId),this.deleteProposal(u.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:t.id,topic:e,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:f}),this.events.emit(oy("session_connect",u.proposalId),{session:f})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:i}=t;Pb(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(oy("session_approve",i),{})):Tb(t)&&(await this.deleteSession({topic:e,emitEvent:!1}),this.events.emit(oy("session_approve",i),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:i,id:s}=t;try{const t=`${e}_session_update`,r=Qw.get(t);if(r&&this.isRequestOutOfSync(r,s))return this.client.logger.warn(`Discarding out of sync request - ${s}`),void this.sendError({id:s,topic:e,error:Mg("INVALID_UPDATE_REQUEST")});await this.isValidUpdate({topic:e,...i});const n=this.client.session.get(e);if(n.peer.publicKey!==n.controller)throw Mg("UNAUTHORIZED_UPDATE_REQUEST");try{Qw.set(t,s),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:e,result:!0})}catch(e){throw Qw.delete(t),e}this.client.events.emit("session_update",{id:s,topic:e,params:i})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3),this.onSessionUpdateResponse=(e,t)=>{const{id:i}=t,s=oy("session_update",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Pb(t)?this.events.emit(oy("session_update",i),{}):Tb(t)&&this.events.emit(oy("session_update",i),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:i}=t;try{await this.isValidExtend({topic:e}),await this.setExpiry(e,ry(Tx)),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_extend",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:i}=t,s=oy("session_extend",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Pb(t)?this.events.emit(oy("session_extend",i),{}):Tb(t)&&this.events.emit(oy("session_extend",i),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:i}=t,s=oy("session_ping",i);setTimeout((()=>{if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners 2176`);Pb(t)?this.events.emit(oy("session_ping",i),{}):Tb(t)&&this.events.emit(oy("session_ping",i),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:i}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Mg("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:i})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r,transportType:n}=e,{id:o,params:a}=i;try{await this.isValidRequest({topic:t,...a});const e=this.client.session.get(t),i={id:o,topic:t,params:a,verifyContext:await this.getVerifyContext({attestationId:s,hash:aw(JSON.stringify(pb("wc_sessionRequest",a,o))),encryptedId:r,metadata:e.peer.metadata,transportType:n})};await this.setPendingSessionRequest(i),n===Wv.link_mode&&e.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(i):(this.addSessionRequestToSessionRequestQueue(i),this.processSessionRequestQueue())}catch(e){await this.sendError({id:o,topic:t,error:e}),this.client.logger.error(e)}},this.onSessionRequestResponse=(e,t)=>{const{id:i}=t,s=oy("session_request",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Pb(t)?this.events.emit(oy("session_request",i),{result:t.result}):Tb(t)&&this.events.emit(oy("session_request",i),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:i,params:s}=t;try{const t=`${e}_session_event_${s.event.name}`,r=Qw.get(t);if(r&&this.isRequestOutOfSync(r,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidEmit({topic:e,...s}),this.client.events.emit("session_event",{id:i,topic:e,params:s}),Qw.set(t,i)}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:i}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),Pb(t)?this.events.emit(oy("session_request",i),{result:t.result}):Tb(t)&&this.events.emit(oy("session_request",i),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r,transportType:n}=e;try{const{requester:e,authPayload:o,expiryTimestamp:a}=i.params,c=await this.getVerifyContext({attestationId:s,hash:aw(JSON.stringify(i)),encryptedId:r,metadata:e.metadata,transportType:n}),h={requester:e,pairingTopic:t,id:i.id,authPayload:o,verifyContext:c,expiryTimestamp:a};await this.setAuthRequest(i.id,{request:h,pairingTopic:t,transportType:n}),n===Wv.link_mode&&e.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:t,params:i.params,id:i.id,verifyContext:c})}catch(e){this.client.logger.error(e);const s=i.params.requester.publicKey,r=await this.client.core.crypto.generateKeyPair(),o=this.getAppLinkIfEnabled(i.params.requester.metadata,n),a={type:Qy,receiverPublicKey:s,senderPublicKey:r};await this.sendError({id:i.id,topic:t,error:e,encodeOpts:a,rpcOpts:Rx.wc_sessionAuthenticate.autoReject,appLink:o})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=Nx,this.processSessionRequestQueue()}),m.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const i=this.client.core.history.pending;i.length>0&&i.filter((t=>t.topic===e&&"wc_sessionRequest"===t.request.method)).forEach((e=>{this.events.emit(oy("session_request",e.request.id),{error:t})}))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===Cx)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.emitSessionRequest=e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=Cx,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const e=this.client.core.relayer.subscriber.topics;if(0===e.length)return;const t=new Set(this.client.session.keys),i=new Set(this.client.core.pairing.pairings.keys),s=new Set([...this.pendingSessions.values()].map((e=>e.sessionTopic)));let r;if(this.client.auth.authKeys.keys.includes(qx)){const{responseTopic:e}=this.client.auth.authKeys.get(qx);r=e}for(const n of e)if(!t.has(n)&&!i.has(n)&&!s.has(n)&&n!==r){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${n}`);try{await this.client.core.relayer.subscriber.unsubscribe(n)}catch(e){this.client.logger.warn(e,`Failed to clean up orphaned subscription: ${n}`)}}},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest({topic:e.topic,payload:pb("wc_sessionPropose",{...t,requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties},t.id),attestation:t.attestation,encryptedId:t.encryptedId})},this.isValidConnect=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:r,scopedProperties:n,relays:o}=e;if(Uw(t)||await this.isValidPairingTopic(t),!function(e,t){let i=!1;return t&&!e?i=!0:e&&Nw(e)&&e.length&&e.forEach((e=>{i=Fw(e)})),i}(o,!0)){const{message:e}=Dg("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(i&&!Uw(i)&&0!==Cw(i)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!Uw(s)&&0!==Cw(s)&&this.validateNamespaces(s,"optionalNamespaces"),r&&!Uw(r)&&this.validateSessionProps(r,"sessionProperties"),n&&!Uw(n)){this.validateSessionProps(n,"scopedProperties");const e=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(n).every((t=>e.includes(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(e)}`)}},this.validateNamespaces=(e,t)=>{const i=function(e,t,i){let s=null;if(e&&Cw(e)){const r=jw(e,t);r&&(s=r);const n=Mw(e,t,i);n&&(s=n)}else s=Dg("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return s}(e,"connect()",t);if(i)throw new Error(i.message)},this.isValidApprove=async e=>{if(!Kw(e))throw new Error(Dg("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:i,relayProtocol:s,sessionProperties:r,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=zw(i,"approve()");if(a)throw new Error(a.message);const c=Gw(o.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!kw(s,!0)){const{message:e}=Dg("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(e)}if(r&&!Uw(r)&&this.validateSessionProps(r,"sessionProperties"),n&&!Uw(n)){this.validateSessionProps(n,"scopedProperties");const e=new Set(Object.keys(i));if(!Object.keys(n).every((t=>e.has(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}},this.isValidReject=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:i}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&Lw(e.code,!1)&&e.message&&kw(e.message,!1))}(i)){const{message:e}=Dg("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:i,namespaces:s,expiry:r}=e;if(!Fw(t)){const{message:e}=Dg("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let i=null;return kw(e?.publicKey,!1)||(i=Dg("MISSING_OR_INVALID",`${t} controller public key should be a string`)),i}(i,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=zw(s,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(ny(r)){const{message:e}=Dg("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:i}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const s=this.client.session.get(t),r=zw(i,"update()");if(r)throw new Error(r.message);const n=Gw(s.requiredNamespaces,i,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:i,chainId:s,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!Vw(n,s)){const{message:e}=Dg("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Uw(e)||!kw(e.method,!1))}(i)){const{message:e}=Dg("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(e)}if(!Hw(n,s,i.method)){const{message:e}=Dg("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(e)}this.validateRequestExpiry(r)},this.isValidRespond=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:i}=e;try{await this.isValidSessionTopic(t)}catch(t){throw e?.response?.id&&this.cleanupAfterResponse(e),t}if(!function(e){return!(Uw(e)||Uw(e.result)&&Uw(e.error)||!Lw(e.id,!1)||!kw(e.jsonrpc,!1))}(i)){const{message:e}=Dg("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}const s=this.client.pendingRequest.get(i.id);if(s.topic!==t){const{message:e}=Dg("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${s.topic}, received topic: ${t}`);throw new Error(e)}},this.isValidPing=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:i,chainId:s}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!Vw(r,s)){const{message:e}=Dg("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Uw(e)||!kw(e.name,!1))}(i)){const{message:e}=Dg("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}if(!Ww(r,s,i.name)){const{message:e}=Dg("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!Kw(e)){const{message:t}=Dg("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:i,domain:s,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!kw(i,!1))throw new Error("uri is required parameter");if(!kw(s,!1))throw new Error("domain is required parameter");if(!kw(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map((e=>Cg(e).namespace)))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=Cg(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:i,encryptedId:s,metadata:r,transportType:n}=e,o={verified:{verifyUrl:r.verifyUrl||gE,validation:"UNKNOWN",origin:r.url||""}};try{if(n===Wv.link_mode){const e=this.getAppLinkIfEnabled(r,n);return o.verified.validation=e&&new URL(e).origin===new URL(r.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:i,encryptedId:s,verifyUrl:r.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(e,t)=>{Object.values(e).forEach(((i,s)=>{if(null==i){const{message:r}=Dg("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${i} for key ${Object.keys(e)[s]}`);throw new Error(r)}}))},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const i of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(i)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:i}=Dg("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(i)}},this.isLinkModeEnabled=(e,t)=>!(!e||t!==Wv.link_mode)&&(!0===this.client.metadata?.redirect?.linkMode&&void 0!==this.client.metadata?.redirect?.universal&&""!==this.client.metadata?.redirect?.universal&&void 0!==e?.redirect?.universal&&""!==e?.redirect?.universal&&!0===e?.redirect?.linkMode&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof global?.Linking<"u"),this.getAppLinkIfEnabled=(e,t)=>this.isLinkModeEnabled(e,t)?e?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=hy(e,"topic")||"",i=decodeURIComponent(hy(e,"wc_ev")||""),s=this.client.session.keys.includes(t);s&&this.client.session.update(t,{transportType:Wv.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:i,sessionExists:s})},this.registerLinkModeListeners=async()=>{if(uy()||Kg()&&this.client.metadata.redirect?.linkMode){const e=global?.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout((()=>{this.handleLinkModeMessage({url:t})}),50)}}},this.getTVFApproveParams=e=>{try{const t=Aw(e.namespaces),i=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.methods)})),[...new Set(t)]}(e.namespaces),s=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.events)})),[...new Set(t)]}(e.namespaces),r=e.sessionProperties;return{approvedChains:t,approvedMethods:i,approvedEvents:s,sessionProperties:r,scopedProperties:e.scopedProperties}}catch(e){return this.client.logger.warn(e,"Error getting TVF approve params"),{}}},this.getTVFParams=(e,t,i)=>{if(!t.request?.method)return{};const s={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{const e=this.extractTxHashesFromResult(t.request,i);s.txHashes=e,s.contractAddresses=this.isValidContractData(t.request.params)?[t.request.params?.[0]?.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return s},this.isValidContractData=e=>{if(!e)return!1;try{const t=e?.data||e?.[0]?.data;if(!t.startsWith("0x"))return!1;const i=t.slice(2);return!!/^[0-9a-fA-F]*$/.test(i)&&i.length%2==0}catch{}return!1},this.extractTxHashesFromResult=(e,t)=>{try{if(!t)return[];const i=e.method,s=Ux[i];if("sui_signTransaction"===i)return[vy(t.transactionBytes)];if("near_signTransaction"===i)return[Ey(t)];if("near_signTransactions"===i)return t.map((e=>Ey(e)));if("xrpl_signTransactionFor"===i||"xrpl_signTransaction"===i)return[t.tx_json?.hash];if("polkadot_signTransaction"===i)return[im({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===i)return Nw(t)?t.map((e=>xy(e))):[xy(t)];if("cosmos_signDirect"===i)return[Sy(t)];if("stellar_signXDR"===i)return[Ry(t.signedXDR,e.params?.chain)];if("wallet_sendCalls"===i)return function(e){const t=[];try{if("string"==typeof e)return t.push(e),t;if("object"!=typeof e)return t;e?.id&&t.push(e.id);const i=e?.capabilities?.caip345?.transactionHashes;i&&t.push(...i)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return t}(t);if("canton_prepareSignExecute"===i)return rm(e.params,t);if("string"==typeof t)return[t];const r=t[s.key];if(Nw(r))return"solana_signAllTransactions"===i?r.map((e=>function(e){const t=gy(e),i=t[0];if(0===i)throw new Error("No signatures found");const s=1+64*i;if(t.length<s)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const r=t.slice(1,65);return eo.encode(r)}(e))):r;if("string"==typeof r)return[r]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,i]of Object.entries(t))for(const t of i)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=Dg("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(kv,(e=>{this.onProviderMessageEvent(e)}))}async onRelayMessage(e){const{topic:t,message:i,attestation:s,transportType:r}=e,{publicKey:n}=this.client.auth.authKeys.keys.includes(qx)?this.client.auth.authKeys.get(qx):{publicKey:void 0};try{try{if(r!==Wv.link_mode&&this.client.core.crypto.getPayloadType(i,Zy)===ew)return void this.client.logger.warn(`onRelayMessage() -> non-link mode TYPE_2 payload ignored: ${i}`)}catch{}const e=await this.client.core.crypto.decode(t,i,{receiverPublicKey:n,encoding:r===Wv.link_mode?Zy:Yy});Ob(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:s,transportType:r,encryptedId:aw(i)})):Ab(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:r}),this.client.core.history.delete(t,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:r})),await this.client.core.relayer.messages.ack(t,i)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(e?.message)}}registerExpirerEvents(){this.client.core.expirer.on(dE,(async e=>{const{topic:t,id:i}=sy(e.target);return i&&this.client.pendingRequest.keys.includes(i)?await this.deletePendingSessionRequest(i,Dg("EXPIRED"),!0):i&&this.client.auth.requests.keys.includes(i)?await this.deletePendingAuthRequest(i,Dg("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i})))}))}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",(async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}}))}registerPairingEvents(){this.client.core.pairing.events.on(iE,(e=>this.onPairingCreated(e))),this.client.core.pairing.events.on(rE,(e=>{this.addToRecentlyDeleted(e.topic,"pairing")}))}isValidPairingTopic(e){if(!kw(e,!1)){const{message:t}=Dg("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=Dg("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(ny(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=Dg("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!kw(e,!1)){const{message:t}=Dg("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=Dg("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(ny(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=Dg("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=Dg("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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)){if(kw(e,!1)){const{message:t}=Dg("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=Dg("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if("number"!=typeof e){const{message:t}=Dg("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=Dg("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(ny(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=Dg("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&(i=Bx,!(Lw(t=e,!1)&&t<=i.max&&t>=i.min))){const{message:t}=Dg("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${Bx.min} and ${Bx.max}`);throw new Error(t)}var t,i}}class Mx extends gx{constructor(e,t){super(e,t,"proposal",Sx),this.core=e,this.logger=t}}class $x extends gx{constructor(e,t){super(e,t,"session",Sx),this.core=e,this.logger=t}}class jx extends gx{constructor(e,t){super(e,t,"request",Sx,(e=>e.id)),this.core=e,this.logger=t}}class zx extends gx{constructor(e,t){super(e,t,"authKeys",Lx,(()=>qx)),this.core=e,this.logger=t}}class Fx extends gx{constructor(e,t){super(e,t,"pairingTopics",Lx),this.core=e,this.logger=t}}class Kx extends gx{constructor(e,t){super(e,t,"requests",Lx,(e=>e.id)),this.core=e,this.logger=t}}class Vx{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new zx(this.core,this.logger),this.pairingTopics=new Fx(this.core,this.logger),this.requests=new Kx(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}const Hx=class t extends Xm{constructor(t){super(t),this.protocol="wc",this.version=2,this.name=_x,this.events=new e.EventEmitter,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.authenticate=async(e,t)=>{try{return console.warn("[WalletConnect] `authenticate` is deprecated and will be removed in a future release. Use `connect()`'s `authentication` instead to establish an authenticated session."),await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSessionAuthenticate=async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSessionAuthenticate=async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.name=t?.name||_x,this.metadata=function(e){const t=Gg();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter((e=>""!==e))),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(i){return console.warn("Error populating app metadata",i),e||t}}(t?.metadata),this.signConfig=t?.signConfig;const i=nm({logger:t?.logger||Ox,name:this.name});this.logger=i,this.core=t?.core||new xx(t),this.session=new $x(this.core,this.logger),this.proposal=new Mx(this.core,this.logger),this.pendingRequest=new jx(this.core,this.logger),this.engine=new Dx(this),this.auth=new Vx(this.core,this.logger)}static async init(e){const i=new t(e);return await i.initialize(),i}get context(){return Tg(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")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Wx=Object.defineProperty,Gx=Object.defineProperties,Yx=Object.getOwnPropertyDescriptors,Zx=Object.getOwnPropertySymbols,Jx=Object.prototype.hasOwnProperty,Xx=Object.prototype.propertyIsEnumerable,Qx=(e,t,i)=>t in e?Wx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,eI=(e,t)=>{for(var i in t||(t={}))Jx.call(t,i)&&Qx(e,i,t[i]);if(Zx)for(var i of Zx(t))Xx.call(t,i)&&Qx(e,i,t[i]);return e},tI=(e,t)=>Gx(e,Yx(t));const iI={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};class sI{constructor(t,i=!1){if(this.url=t,this.disableProviderPing=i,this.events=new e.EventEmitter,this.isAvailable=!1,this.registering=!1,!xb(t))throw new Error(`Provided URL is not compatible with HTTP connection: ${t}`);this.url=t,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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 t=Rl(e),s=await(await i.o(this.url,tI(eI({},iI),{body:t}))).json();this.onPayload({data:s})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!xb(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return t(new Error("HTTP connection is missing or invalid"));e()}))}))}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=Rl({id:1,jsonrpc:"2.0",method:"test",params:[]});await i.o(e,tI(eI({},iI),{body:t}))}this.onOpen()}catch(e){const t=this.parseError(e);throw this.events.emit("register_error",t),this.onClose(),t}}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 t="string"==typeof e.data?Tl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=yb(e,i.message||i.toString());this.events.emit("payload",s)}parseError(e,t=this.url){return ob(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}}const rI="error",nI="universal_provider",oI=`wc@2:${nI}:`,aI="https://rpc.walletconnect.org/v1/",cI="generic",hI=`${aI}bundler`,lI="call_status",uI="default_chain_changed";function dI(e,t,i){const s=Cg(e);return t.rpcMap?.[s.reference]||`${aI}?chainId=${s.namespace}:${s.reference}&projectId=${i}`}function fI(e){return e.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))}function pI(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>t?.chains?.length&&t?.chains?.length>0)))}function gI(e={},t={}){return Ov(pI(yI(e)),pI(yI(t)))}function yI(e){const t={};if(!Cw(e))return t;for(const[i,s]of Object.entries(e)){const e=Pw(i)?[i]:s.chains,r=s.methods||[],n=s.events||[],o=s.rpcMap||{},a=Tw(i);t[a]={...t[a],...s,chains:ay(e,t[a]?.chains),methods:ay(r,t[a]?.methods),events:ay(n,t[a]?.events)},(Cw(o)||Cw(t[a]?.rpcMap||{}))&&(t[a].rpcMap={...o,...t[a]?.rpcMap})}return t}function wI(e){return e.includes(":")?e.split(":")[2]:e}function mI(e){const t={};for(const[i,s]of Object.entries(e)){const e=s.methods||[],r=s.events||[],n=s.accounts||[],o=Pw(i)?[i]:s.chains?s.chains:fI(s.accounts);t[i]={chains:o,methods:e,events:r,accounts:n}}return t}function bI(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const vI={},EI=e=>vI[e],xI=(e,t)=>{vI[e]=t},II="eip155",SI=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],_I=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,OI=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,AI=e=>Object.keys(e).filter((e=>SI.includes(e))).reduce(((t,i)=>(t[i]=PI(e[i]),t)),{}),PI=e=>"string"==typeof e&&function(e){try{const t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;let TI;class RI{constructor(e){this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return TI||(TI=new RI(e)),TI}}async function BI(e,t){const i=Cg(e.result.capabilities.caip345.caip2),s=e.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(s.map((e=>async function(e,t,i){return await i(parseInt(e)).request(pb("eth_getTransactionReceipt",[t]))}(i.reference,e,t)))),n=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)).filter((e=>e));r.filter((e=>"rejected"===e.status)).forEach((e=>console.warn("Failed to fetch transaction receipt:",e.reason)));const o=!n.length||n.some((e=>!e)),a=n.every((e=>"0x1"===e?.status)),c=n.every((e=>"0x0"===e?.status)),h=n.some((e=>"0x0"===e?.status));let l;return o?l=100:a?l=200:c?l=500:h&&(l=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:n,status:l}}async function NI({resultId:e,storage:t}){const i=(await t.getItem(lI))?.[e];if(i&&!ny(i.expiry))return i;await async function({resultId:e,storage:t}){const i=await t.getItem(lI);if(i){delete i[e],await t.setItem(lI,i);for(const e in i)ny(i[e].expiry)&&delete i[e];await t.setItem(lI,i)}}({resultId:e,storage:t})}class CI{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=EI("events"),this.client=EI("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=RI.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":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);case"wallet_sendCalls":return await this.sendCalls(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,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(uI,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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,t){const i=t||dI(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Rb(new sI(i,EI("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach((t=>{const i=parseInt(function(e){return e.includes(":")?e.split(":")[1]:e}(t));e[i]=this.createHttpProvider(i,this.namespace.rpcMap?.[t])})),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders={...this.httpProviders,[t]:this.createHttpProvider(t)},this.httpProviders[t])}async handleSwitchChain(e){let t=e.request.params?e.request.params[0]?.chainId:"0x0";t=t.startsWith("0x")?t:`0x${t}`;const i=parseInt(t,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:t}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${i}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){const t=e.request?.params?.[0],i=e.request?.params?.[1]||[];if(!t)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const s=this.client.session.get(e.topic),r=s?.sessionProperties?.capabilities||{},n=`${t}${i.length>0?i.join(","):`0x${this.chainId.toString(16)}`}`,o=r?.[n];if(o)return o;let a;try{a=((e,t,i)=>{const{sessionProperties:s={},scopedProperties:r={}}=e,n={};if(!Cw(r)&&!Cw(s))return;const o=AI(s);for(const e of i){const i=_I(e);if(!i)continue;n[OI(i)]=o;const s=r?.[`${II}:${i}`];if(s){const e=s?.[`${II}:${i}:${t}`];n[OI(i)]={...n[OI(i)],...AI(e||s)}}}for(const[e,t]of Object.entries(n))0===Object.keys(t).length&&delete n[e];return Object.keys(n).length>0?n:void 0})(s,t,i)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(a)return a;const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:{...s.sessionProperties||{},capabilities:{...r||{},[n]:c}}})}catch(e){console.warn("Failed to update session with capabilities",e)}return c}async getCallStatus(e){const t=this.client.session.get(e.topic),i=t.sessionProperties?.bundler_name;if(i){const t=this.getBundlerUrl(e.chainId,i);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const s=t.sessionProperties?.bundler_url;if(s)try{return await this.getUserOperationReceipt(s,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,s)}const r=await NI({resultId:e.request.params?.[0],storage:this.storage});if(r)try{return await BI(r,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,r)}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,t){const i=new URL(e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(pb("eth_getUserOperationReceipt",[t.request.params?.[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,t){return`${hI}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){const t=await this.client.request(e),i=e.request.params?.[0],s=t?.id,r=t?.capabilities||{},n=r?.caip345?.caip2,o=r?.caip345?.transactionHashes;return!s||!n||!o?.length||await async function({sendCalls:e,storage:t}){const i=await t.getItem(lI);await t.setItem(lI,{...i,[e.result.id]:{request:e.request,result:e.result,expiry:ry(86400)}})}({sendCalls:{request:i,result:t},storage:this.storage}),t}}class UI{constructor(e){this.name=cI,this.namespace=e.namespace,this.events=EI("events"),this.client=EI("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),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,t){this.httpProviders[e]||this.setHttpProvider(e,t);const i=this.chainId;this.chainId=e,this.events.emit(uI,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return Cg(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}createHttpProviders(){const e={};return this.namespace?.accounts?.forEach((t=>{const i=Cg(t),s=this.namespace?.rpcMap?.[`${i.namespace}:${i.reference}`];e[i.reference]=this.createHttpProvider(t,s)})),e}getHttpProvider(e){const t=Cg(e).reference,i=this.httpProviders[t];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||dI(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Rb(new sI(i,EI("disableProviderPing")))}}const kI=class e{constructor(e){this.events=new r.default,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=e,this.logger=nm({logger:e.logger??rI,name:this.providerOpts.name??nI}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(t){const i=new e(t);return await i.initialize(),i}async request(e,t,i){const[s,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:{...e},chainId:`${s}:${r}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const r=(new Date).getTime();this.request(e,i,s).then((e=>t(null,gb(r,e)))).catch((e=>t(e,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(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Mg("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){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,t);i&&(this.uri=i,this.events.emit("display_uri",i));const r=await s();if(this.session=r.session,this.session){const e=mI(this.session.namespaces);this.namespaces=gI(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const r=mI(s.namespaces);return this.namespaces=gI(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),r=this.getProvider(i);r?r.setDefaultChain(s,t):this.session&&this.logger.warn(`Provider for namespace '${i}' not found in setDefaultChain`)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!Nw(t))return;for(const i of t)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: ${t.length}`)}catch(e){this.logger.warn(e,"Failed to cleanup pending pairings")}}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(){if(this.client=this.providerOpts.client||await Hx.init({core:this.providerOpts.core,logger:this.providerOpts.logger||rI,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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(e){throw this.logger.error(e,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[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((e=>Tw(e))))];xI("client",this.client),xI("events",this.events),xI("disableProviderPing",this.disableProviderPing),e.forEach((e=>{if(!this.session)return;const t=function(e,t){const i=Object.keys(t.namespaces).filter((t=>t.includes(e)));if(!i.length)return[];const s=[];return i.forEach((e=>{const i=t.namespaces[e].accounts;s.push(...i)})),s}(e,this.session);if(0===t?.length)return;const i=fI(t),s={...gI(this.namespaces,this.optionalNamespaces)[e],accounts:t,chains:i};if("eip155"===e)this.rpcProviders[e]=new CI({namespace:s});else this.rpcProviders[e]=new UI({namespace:s})}))}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",(e=>{const{topic:t}=e;t===this.session?.topic&&this.events.emit("session_ping",e)})),this.client.on("session_event",(e=>{const{params:t,topic:i}=e;if(i!==this.session?.topic)return;const{event:s}=t;if("accountsChanged"===s.name){const e=s.data;e&&Nw(e)&&this.events.emit("accountsChanged",e.map(wI))}else if("chainChanged"===s.name){const e=t.chainId,i=t.event.data,s=Tw(e),r=bI(e)!==bI(i)?`${s}:${bI(i)}`:e;this.onChainChanged({currentCaipChainId:r})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)})),this.client.on("session_update",(({topic:e,params:t})=>{if(e!==this.session?.topic)return;const{namespaces:i}=t,s=this.client?.session.get(e);this.session={...s,namespaces:i},this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})})),this.client.on("session_delete",(async e=>{e.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...Mg("USER_DISCONNECTED"),data:e.topic}))})),this.on(uI,(e=>{this.onChainChanged({...e,internal:!0})}))}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[cI]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach((e=>{this.getProvider(e).updateNamespace(this.session?.namespaces[e])}))}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:r}=e;this.optionalNamespaces=gI(t,i),this.sessionProperties=s,this.scopedProperties=r}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map((e=>Tw(e))).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=Tw(Object.keys(this.namespaces)[0]);return[s,this.rpcProviders[s].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:i=!1}){if(!this.namespaces)return;const[s,r]=this.validateChain(e);if(r){if(this.updateNamespaceChain(s,r),i)this.events.emit("chainChanged",r),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:t});else{const e=this.getProvider(s);e?e.setDefaultChain(r):this.session&&this.logger.warn(`Provider for namespace '${s}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:i}){try{if(i===t)return;const s=this.session?.namespaces[e]?.accounts;if(!s)return;const r=s.filter((e=>e.includes(`${t}:`))).map(wI);if(!Nw(r))return;this.events.emit("accountsChanged",r)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,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,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){const i=this.session?.topic||"";await this.client.core.storage.setItem(`${oI}/${e}${i}`,t)}async getFromStore(e){const t=this.session?.topic||"";return await this.client.core.storage.getItem(`${oI}/${e}${t}`)}async deleteFromStore(e){const t=this.session?.topic||"";await this.client.core.storage.removeItem(`${oI}/${e}${t}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;const e=await this.client.core.storage.getKeys();for(const t of e)t.startsWith(oI)&&await this.client.core.storage.removeItem(t)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}},LI=["eth_sendTransaction","personal_sign"],qI=["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"],DI=["chainChanged","accountsChanged"],MI=["chainChanged","accountsChanged","message","disconnect","connect"];function $I(e){return Number(e[0].split(":")[1])}function jI(e){return`0x${e.toString(16)}`}let zI=class t{constructor(){this.events=new e.EventEmitter,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY="wc@2:ethereum_provider:",this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(e){const i=new t;return await i.initialize(e),i}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return!!this.signer.client&&this.signer.client.core.relayer.connected}get connecting(){return!!this.signer.client&&this.signer.client.core.relayer.connecting}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=function(e){const{chains:t,optionalChains:i,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=e;if(!Nw(t))throw new Error("Invalid chains");const c={chains:t,methods:s||LI,events:n||DI,rpcMap:{...t.length?{[$I(t)]:a[$I(t)]}:{}}},h=n?.filter((e=>!DI.includes(e))),l=s?.filter((e=>!LI.includes(e)));if(!(i||o||r||h?.length||l?.length))return{required:t.length?c:void 0};const u={chains:[...new Set(h?.length&&l?.length||!i?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(r?.length?r:qI))],events:[...new Set(c.events.concat(o?.length?o:MI))],rpcMap:a};return{required:t.length?c:void 0,optional:i.length?u:void 0}}(this.rpc);try{const s=await new Promise((async(s,r)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState((e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),r(new Error("Connection request reset. Please try again.")))})));const n=e?.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect({namespaces:{...t&&{[this.namespace]:t}},...i&&{optionalNamespaces:{[this.namespace]:i}},pairingTopic:e?.pairingTopic,scopedProperties:n}).then((e=>{s(e)})).catch((e=>{this.modal?.showErrorMessage("Unable to connect"),r(new Error(e.message))}))}));if(!s)return;const r=Ug(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:r),this.setAccounts(r),this.events.emit("connect",{chainId:jI(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.close()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise((async(i,s)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState((e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),s(new Error("Connection request reset. Please try again.")))}))),await this.signer.authenticate({...e,chains:this.rpc.chains},t).then((e=>{i(e)})).catch((e=>{this.modal?.showErrorMessage("Unable to connect"),s(new Error(e.message))}))})),s=i.session;if(s){const e=Ug(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:jI(this.chainId)})}return i}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.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:t}=e,{event:i}=t;"accountsChanged"===i.name?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):"chainChanged"===i.name?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 t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",jI(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",{...Mg("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"string"==typeof e&&e.startsWith(`${this.namespace}:`)}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter((e=>this.isCompatibleChainId(e))).map((e=>this.parseChainId(e)));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",jI(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter((e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId)).map((e=>this.parseAccountId(e).address)),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){const t=e?.chains??[],i=e?.optionalChains??[],s=t.concat(i);if(!s.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const r=t.length?e?.methods||LI:[],n=t.length?e?.events||DI:[],o=e?.optionalMethods||[],a=e?.optionalEvents||[],c=e?.rpcMap||this.buildRpcMap(s,e.projectId),h=e?.qrModalOptions||void 0;return{chains:t?.map((e=>this.formatChainId(e))),optionalChains:i.map((e=>this.formatChainId(e))),methods:r,events:n,optionalMethods:o,optionalEvents:a,rpcMap:c,showQrModal:!!e?.showQrModal,qrModalOptions:h,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach((e=>{i[e]=this.getRpcUrl(e,t)})),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?$I(this.rpc.chains):$I(this.rpc.optionalChains),this.signer=await kI.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 e;try{const t=await(async()=>{const{createAppKit:e}=await Promise.resolve().then((function(){return require("./core-78a709db.cjs")})).then((function(e){return e.core}));return e})(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then((function(){return WI})),s=i({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!s.networks.length)throw new Error("No networks found for WalletConnect");e=t({...s,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:!0===this.rpc.qrModalOptions?.enableMobileFullScreen})}catch(e){throw console.warn(e),new Error("To use QR modal, please install @reown/appkit package")}if(e)try{this.modal=e}catch(e){throw this.signer.logger.error(e),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&Nw(t)&&(this.rpc.chains=t.map((e=>this.formatChainId(e))),t.forEach((e=>{this.rpc.rpcMap[e]=s?.[e]||this.getRpcUrl(e)}))),i&&Nw(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map((e=>this.formatChainId(e))),i.forEach((e=>{this.rpc.rpcMap[e]=s?.[e]||this.getRpcUrl(e)})))}getRpcUrl(e,t){return this.rpc.rpcMap?.[e]||`https://rpc.walletconnect.org/v1/?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch((e=>this.signer.logger.warn(e)))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return"string"==typeof e||e instanceof String?[this.parseAccount(e)]:e.map((e=>this.parseAccount(e)))}};const FI=zI;function KI(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const VI=e=>{const[t,i]=e.split(":");return HI({id:i,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function HI(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var WI=Object.freeze({__proto__:null,convertWCMToAppKitOptions:function(e){const t=e.chains?.map(VI).filter(Boolean);if(0===t.length)throw new Error("At least one chain must be specified");const i=t.find((t=>t.id===e.defaultChain?.id)),s={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:KI(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:i,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:"NONE"===e.explorerRecommendedWalletIds?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:"ALL"===e.explorerExcludedWalletIds?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){const t=[...(e.mobileWallets||[]).map((e=>({id:e.id,name:e.name,links:e.links}))),...(e.desktopWallets||[]).map((e=>({id:e.id,name:e.name,links:{native:e.links.native,universal:e.links.universal}})))],i=[...s.featuredWalletIds||[],...s.excludeWalletIds||[]],r=t.filter((e=>!i.includes(e.id)));r.length&&(s.customWallets=r)}return s},defineChain:HI}),GI=Object.freeze({__proto__:null,EthereumProvider:FI,OPTIONAL_EVENTS:MI,OPTIONAL_METHODS:qI,REQUIRED_EVENTS:DI,REQUIRED_METHODS:LI,default:zI});exports.IEvents=om,exports.IJsonRpcProvider=vb,exports.N=FI,exports.blakejs=Up,exports.cjs=m,exports.cjs$1=cb,exports.concat=co,exports.decode=Rn,exports.detect=g,exports.encode=mn,exports.formatJsonRpcError=yb,exports.formatJsonRpcRequest=pb,exports.formatJsonRpcResult=gb,exports.fromHex=nr,exports.fromString=Ca,exports.getBigIntRpcId=fb,exports.index=GI,exports.isHttpUrl=xb,exports.isJsonRpcError=Tb,exports.isJsonRpcRequest=Ob,exports.isJsonRpcResponse=Ab,exports.isJsonRpcResult=Pb,exports.isLocalhostUrl=Sb,exports.isWsUrl=Ib,exports.parseConnectionError=ob,exports.payloadId=db,exports.recoverAddress=hr,exports.safeJsonParse=Tl,exports.safeJsonStringify=Rl,exports.toString=Ua;
|