@dcl/top-scenes 0.0.1-20574479717.commit-6139329

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/assets/PhArrowCircleDown-B305t-Sh.js +14 -0
  2. package/assets/PhArrowClockwise-CJPxQhr_.js +14 -0
  3. package/assets/PhArrowDown-C4hT9BVu.js +14 -0
  4. package/assets/PhArrowLeft-Way4Cu-r.js +14 -0
  5. package/assets/PhArrowRight-Cp5ZME0F.js +14 -0
  6. package/assets/PhArrowSquareOut-NnrK69c5.js +14 -0
  7. package/assets/PhArrowUp-Dph6j8rm.js +14 -0
  8. package/assets/PhArrowUpRight-BpJjRRRh.js +14 -0
  9. package/assets/PhArrowsClockwise-CFUT8X7R.js +14 -0
  10. package/assets/PhArrowsDownUp-BjBI4ckC.js +14 -0
  11. package/assets/PhArrowsLeftRight-CuLpbKRk.js +14 -0
  12. package/assets/PhBank-Dchr4XQJ.js +14 -0
  13. package/assets/PhBrowser-dUu2TrC1.js +14 -0
  14. package/assets/PhCaretDown-78IuKU3V.js +14 -0
  15. package/assets/PhCaretLeft-_aiyH7n1.js +14 -0
  16. package/assets/PhCaretRight-8zJQEuDX.js +14 -0
  17. package/assets/PhCaretUp-CiCxKWwN.js +14 -0
  18. package/assets/PhCheck-CcADx8br.js +14 -0
  19. package/assets/PhCircleHalf-BYzSzd2h.js +14 -0
  20. package/assets/PhClock-UItiXeJq.js +14 -0
  21. package/assets/PhCompass-CUy3uA7t.js +14 -0
  22. package/assets/PhCopy-C-PDgSlZ.js +14 -0
  23. package/assets/PhCreditCard-CWRaUT6F.js +14 -0
  24. package/assets/PhCurrencyDollar-Cqla3AXT.js +14 -0
  25. package/assets/PhDesktop-BBIPrYLl.js +14 -0
  26. package/assets/PhDeviceMobile-BdsPaATg.js +14 -0
  27. package/assets/PhDotsThree-BMXCQl-0.js +14 -0
  28. package/assets/PhEnvelope-yUsis6yU.js +14 -0
  29. package/assets/PhFunnelSimple-Ba7BbWTp.js +14 -0
  30. package/assets/PhGlobe-DgLxBk5U.js +14 -0
  31. package/assets/PhIdentificationCard-Czjmq9Z3.js +14 -0
  32. package/assets/PhImage-BAJ_erz6.js +14 -0
  33. package/assets/PhInfo-Cr4DhVUE.js +14 -0
  34. package/assets/PhLightbulb-BX_7duTr.js +14 -0
  35. package/assets/PhMagnifyingGlass-Mygfryvz.js +14 -0
  36. package/assets/PhPaperPlaneRight-BeuCA660.js +14 -0
  37. package/assets/PhPlus-BMjcHjsT.js +14 -0
  38. package/assets/PhPower-CGffGmdb.js +14 -0
  39. package/assets/PhPuzzlePiece-wm_GpVSi.js +14 -0
  40. package/assets/PhQrCode-DRwRzXCH.js +14 -0
  41. package/assets/PhQuestion-M09j2U0T.js +14 -0
  42. package/assets/PhQuestionMark-BP9EMB6h.js +14 -0
  43. package/assets/PhSealCheck-BfG80yKn.js +14 -0
  44. package/assets/PhSignOut-C5YOWlPT.js +14 -0
  45. package/assets/PhSpinner-BXooDYzU.js +14 -0
  46. package/assets/PhTrash-Biq6rmmL.js +14 -0
  47. package/assets/PhUser-CAgZSpGe.js +14 -0
  48. package/assets/PhVault-l2PHF38a.js +14 -0
  49. package/assets/PhWarning-DPEydIPw.js +14 -0
  50. package/assets/PhWarningCircle-BqjT745H.js +14 -0
  51. package/assets/PhX-s-SmVExa.js +14 -0
  52. package/assets/Position_Star_Medium_1-D9_Xr-8o.webp +0 -0
  53. package/assets/Position_Star_Medium_3-eBrgImJU.webp +0 -0
  54. package/assets/RoobertPRO-Bold-BLoSpx-h.otf +0 -0
  55. package/assets/RoobertPRO-Bold-zQ2qeH97.ttf +0 -0
  56. package/assets/auto-track-Bi0QWiGn.js +1 -0
  57. package/assets/banner_bg-C4LBAGqQ.webp +0 -0
  58. package/assets/banner_overlay-DrNLUz7T.webp +0 -0
  59. package/assets/basic-F0r-7YBm.js +1435 -0
  60. package/assets/core-BBTIgWQG.js +233 -0
  61. package/assets/create-submenu-DEFVbrc5.png +0 -0
  62. package/assets/explore-submenu-KVl6Dc-h.png +0 -0
  63. package/assets/features-7K-B420g.js +5 -0
  64. package/assets/fortmatic-OXkYrVpn.js +13 -0
  65. package/assets/governance-submenu-CXxLX9nT.png +0 -0
  66. package/assets/index-0Rek36uX.js +2 -0
  67. package/assets/index-4s-7e_Q6.js +12 -0
  68. package/assets/index-B4dMpmQQ.js +1 -0
  69. package/assets/index-BFmw0mfC.js +1 -0
  70. package/assets/index-BMZR33LX.js +1322 -0
  71. package/assets/index-BTDAEI3l.js +1 -0
  72. package/assets/index-BcSn1UAG.js +1 -0
  73. package/assets/index-CFiK0Deq.js +41 -0
  74. package/assets/index-CIX4hu1f.js +36 -0
  75. package/assets/index-Cgd-ACTe.js +752 -0
  76. package/assets/index-D0cZbiaE.js +5 -0
  77. package/assets/index-DgO0Zigb.js +1 -0
  78. package/assets/index-P9m1hcFq.js +1 -0
  79. package/assets/index-SSgaCJsD.js +1 -0
  80. package/assets/index-olsbfI2m.js +2 -0
  81. package/assets/index.umd-COk1Z8BG.js +1 -0
  82. package/assets/inherits_browser-Dbwsx_3T.js +1 -0
  83. package/assets/is-plan-event-enabled-DS1Agtkw.js +1 -0
  84. package/assets/learn-submenu-Xs1jOwfy.png +0 -0
  85. package/assets/man-default1-BEO13leF.png +0 -0
  86. package/assets/marketplace-submenu-CjxTqNhj.png +0 -0
  87. package/assets/property-C9JG5tag.js +27 -0
  88. package/assets/scene-thumbnail-CbK-_jZx.webp +0 -0
  89. package/assets/w3m-modal-Donko-xo.js +1209 -0
  90. package/index.html +43 -0
  91. package/package.json +21 -0
@@ -0,0 +1,41 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-BBTIgWQG.js","assets/index-Cgd-ACTe.js"])))=>i.map(i=>d[i]);
2
+ import{g as Tf,e as xt,c as Ft,x as uc,a as Dy,_ as Ay}from"./index-Cgd-ACTe.js";var ul=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},Py=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),By=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Cy=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),Ty=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Ry=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Uy=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Ny=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hl=3,ky=[["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",Uy]],fl=[["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 jy(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Ry:typeof navigator<"u"?Ly(navigator.userAgent):qy()}function Fy(t){return t!==""&&ky.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function Ly(t){var e=Fy(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new Ty;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<hl&&(s=ul(ul([],s,!0),zy(hl-s.length),!0)):s=[];var n=s.join("."),o=My(t),a=Ny.exec(t);return a&&a[1]?new Cy(r,n,o,a[1]):new Py(r,n,o)}function My(t){for(var e=0,r=fl.length;e<r;e++){var i=fl[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function qy(){var t=typeof process<"u"&&process.version;return t?new By(process.version.slice(1)):null}function zy(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var q={};/*! *****************************************************************************
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
11
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
+ PERFORMANCE OF THIS SOFTWARE.
15
+ ***************************************************************************** */var la=function(t,e){return la=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},la(t,e)};function Vy(t,e){la(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ua=function(){return ua=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ua.apply(this,arguments)};function Hy(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function Ky(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function Wy(t,e){return function(r,i){e(r,i,t)}}function Gy(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Yy(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function Zy(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Jy(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function Xy(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ha(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rf(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function Qy(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Rf(arguments[e]));return t}function e0(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function ds(t){return this instanceof ds?(this.v=t,this):new ds(t)}function t0(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(d){return new Promise(function(g,w){n.push([f,d,g,w])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(g){h(n[0][3],g)}}function c(f){f.value instanceof ds?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),n.shift(),n.length&&a(n[0][0],n[0][1])}}function r0(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:ds(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function i0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof ha=="function"?ha(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function s0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function n0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o0(t){return t&&t.__esModule?t:{default:t}}function a0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function c0(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const l0=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ua},__asyncDelegator:r0,__asyncGenerator:t0,__asyncValues:i0,__await:ds,__awaiter:Yy,__classPrivateFieldGet:a0,__classPrivateFieldSet:c0,__createBinding:Jy,__decorate:Ky,__exportStar:Xy,__extends:Vy,__generator:Zy,__importDefault:o0,__importStar:n0,__makeTemplateObject:s0,__metadata:Gy,__param:Wy,__read:Rf,__rest:Hy,__spread:Qy,__spreadArrays:e0,__values:ha},Symbol.toStringTag,{value:"Module"})),kn=Tf(l0);var co={},Li={},dl;function u0(){if(dl)return Li;dl=1,Object.defineProperty(Li,"__esModule",{value:!0}),Li.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Li.delay=t,Li}var jr={},lo={},Fr={},pl;function h0(){return pl||(pl=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.ONE_THOUSAND=Fr.ONE_HUNDRED=void 0,Fr.ONE_HUNDRED=100,Fr.ONE_THOUSAND=1e3),Fr}var uo={},gl;function f0(){return gl||(gl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(uo)),uo}var yl;function Uf(){return yl||(yl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=kn;e.__exportStar(h0(),t),e.__exportStar(f0(),t)}(lo)),lo}var wl;function d0(){if(wl)return jr;wl=1,Object.defineProperty(jr,"__esModule",{value:!0}),jr.fromMiliseconds=jr.toMiliseconds=void 0;const t=Uf();function e(i){return i*t.ONE_THOUSAND}jr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return jr.fromMiliseconds=r,jr}var ml;function p0(){return ml||(ml=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=kn;e.__exportStar(u0(),t),e.__exportStar(d0(),t)}(co)),co}var di={},bl;function g0(){if(bl)return di;bl=1,Object.defineProperty(di,"__esModule",{value:!0}),di.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return di.Watch=t,di.default=t,di}var ho={},Mi={},vl;function y0(){if(vl)return Mi;vl=1,Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.IWatch=void 0;class t{}return Mi.IWatch=t,Mi}var El;function w0(){return El||(El=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),kn.__exportStar(y0(),t)}(ho)),ho}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=kn;e.__exportStar(p0(),t),e.__exportStar(g0(),t),e.__exportStar(w0(),t),e.__exportStar(Uf(),t)})(q);var ce={};Object.defineProperty(ce,"__esModule",{value:!0});ce.getLocalStorage=ce.getLocalStorageOrThrow=ce.getCrypto=ce.getCryptoOrThrow=Nf=ce.getLocation=ce.getLocationOrThrow=hc=ce.getNavigator=ce.getNavigatorOrThrow=ti=ce.getDocument=ce.getDocumentOrThrow=ce.getFromWindowOrThrow=ce.getFromWindow=void 0;function ai(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ce.getFromWindow=ai;function Ni(t){const e=ai(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ce.getFromWindowOrThrow=Ni;function m0(){return Ni("document")}ce.getDocumentOrThrow=m0;function b0(){return ai("document")}var ti=ce.getDocument=b0;function v0(){return Ni("navigator")}ce.getNavigatorOrThrow=v0;function E0(){return ai("navigator")}var hc=ce.getNavigator=E0;function x0(){return Ni("location")}ce.getLocationOrThrow=x0;function _0(){return ai("location")}var Nf=ce.getLocation=_0;function I0(){return Ni("crypto")}ce.getCryptoOrThrow=I0;function S0(){return ai("crypto")}ce.getCrypto=S0;function O0(){return Ni("localStorage")}ce.getLocalStorageOrThrow=O0;function $0(){return ai("localStorage")}ce.getLocalStorage=$0;var fc={};Object.defineProperty(fc,"__esModule",{value:!0});var kf=fc.getWindowMetadata=void 0;const xl=ce;function D0(){let t,e;try{t=xl.getDocumentOrThrow(),e=xl.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),f=[];for(let d=0;d<h.length;d++){const g=h[d],w=g.getAttribute("rel");if(w&&w.toLowerCase().indexOf("icon")>-1){const m=g.getAttribute("href");if(m)if(m.toLowerCase().indexOf("https:")===-1&&m.toLowerCase().indexOf("http:")===-1&&m.indexOf("//")!==0){let O=e.protocol+"//"+e.host;if(m.indexOf("/")===0)O+=m;else{const C=e.pathname.split("/");C.pop();const b=C.join("/");O+=b+"/"+m}f.push(O)}else if(m.indexOf("//")===0){const O=e.protocol+m;f.push(O)}else f.push(m)}}return f}function i(...h){const f=t.getElementsByTagName("meta");for(let d=0;d<f.length;d++){const g=f[d],w=["itemprop","property","name"].map(m=>g.getAttribute(m)).filter(m=>m?h.includes(m):!1);if(w.length&&w){const m=g.getAttribute("content");if(m)return m}}return""}function s(){let h=i("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function n(){return i("description","og:description","twitter:description","keywords")}const o=s(),a=n(),c=e.origin,l=r();return{description:a,url:c,icons:l,name:o}}kf=fc.getWindowMetadata=D0;const A0="0.1.1";function P0(){return A0}class he extends Error{constructor(e,r={}){const i=(()=>{var c;if(r.cause instanceof he){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof he&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
+ `);super(a,r.cause?{cause:r.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@${P0()}`}),this.cause=r.cause,this.details=i,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return jf(this,e)}}function jf(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?jf(t.cause,e):e?null:t}const pi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function B0(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ps(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ri(t,...e){if(!B0(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function C0(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ps(t.outputLen),ps(t.blockLen)}function Ci(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ff(t,e){ri(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function T0(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ti(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function fo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Bt(t,e){return t<<32-e|t>>>e}const R0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function U0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function N0(t){for(let e=0;e<t.length;e++)t[e]=U0(t[e]);return t}const _l=R0?t=>t:N0;function k0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function jn(t){return typeof t=="string"&&(t=k0(t)),ri(t),t}function j0(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ri(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class dc{}function Lf(t){const e=i=>t().update(jn(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function F0(t=32){if(pi&&typeof pi.getRandomValues=="function")return pi.getRandomValues(new Uint8Array(t));if(pi&&typeof pi.randomBytes=="function")return Uint8Array.from(pi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function L0(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function M0(t,e,r){return t&e^~t&r}function q0(t,e,r){return t&e^t&r^e&r}class z0 extends dc{constructor(e,r,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=fo(this.buffer)}update(e){Ci(this),e=jn(e),ri(e);const{view:r,buffer:i,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=fo(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ci(this),Ff(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,Ti(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;L0(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=fo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const fr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Us=BigInt(2**32-1),Il=BigInt(32);function V0(t,e=!1){return e?{h:Number(t&Us),l:Number(t>>Il&Us)}:{h:Number(t>>Il&Us)|0,l:Number(t&Us)|0}}function H0(t,e=!1){const r=t.length;let i=new Uint32Array(r),s=new Uint32Array(r);for(let n=0;n<r;n++){const{h:o,l:a}=V0(t[n],e);[i[n],s[n]]=[o,a]}return[i,s]}const K0=(t,e,r)=>t<<r|e>>>32-r,W0=(t,e,r)=>e<<r|t>>>32-r,G0=(t,e,r)=>e<<r-32|t>>>64-r,Y0=(t,e,r)=>t<<r-32|e>>>64-r,Z0=BigInt(0),qi=BigInt(1),J0=BigInt(2),X0=BigInt(7),Q0=BigInt(256),ew=BigInt(113),Mf=[],qf=[],zf=[];for(let t=0,e=qi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Mf.push(2*(5*i+r)),qf.push((t+1)*(t+2)/2%64);let s=Z0;for(let n=0;n<7;n++)e=(e<<qi^(e>>X0)*ew)%Q0,e&J0&&(s^=qi<<(qi<<BigInt(n))-qi);zf.push(s)}const Vf=H0(zf,!0),tw=Vf[0],rw=Vf[1],Sl=(t,e,r)=>r>32?G0(t,e,r):K0(t,e,r),Ol=(t,e,r)=>r>32?Y0(t,e,r):W0(t,e,r);function iw(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Sl(l,u,1)^r[a],f=Ol(l,u,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=qf[o],c=Sl(s,n,a),l=Ol(s,n,a),u=Mf[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=tw[i],t[1]^=rw[i]}Ti(r)}class pc extends dc{constructor(e,r,i,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,ps(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=T0(this.state)}clone(){return this._cloneInto()}keccak(){_l(this.state32),iw(this.state32,this.rounds),_l(this.state32),this.posOut=0,this.pos=0}update(e){Ci(this),e=jn(e),ri(e);const{blockLen:r,state:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ci(this,!1),ri(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ps(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ff(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,Ti(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new pc(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const sw=(t,e,r)=>Lf(()=>new pc(e,t,r)),nw=sw(1,136,256/8),ow=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]),dr=new Uint32Array(64);class aw extends z0{constructor(e=32){super(64,e,8,!1),this.A=fr[0]|0,this.B=fr[1]|0,this.C=fr[2]|0,this.D=fr[3]|0,this.E=fr[4]|0,this.F=fr[5]|0,this.G=fr[6]|0,this.H=fr[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)dr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=dr[h-15],d=dr[h-2],g=Bt(f,7)^Bt(f,18)^f>>>3,w=Bt(d,17)^Bt(d,19)^d>>>10;dr[h]=w+dr[h-7]+g+dr[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=Bt(a,6)^Bt(a,11)^Bt(a,25),d=u+f+M0(a,c,l)+ow[h]+dr[h]|0,w=(Bt(i,2)^Bt(i,13)^Bt(i,22))+q0(i,s,n)|0;u=l,l=c,c=a,a=o+d|0,o=n,n=s,s=i,i=d+w|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,s,n,o,a,c,l,u)}roundClean(){Ti(dr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ti(this.buffer)}}const cw=Lf(()=>new aw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gc=BigInt(0),fa=BigInt(1);function _s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yc(t){if(!_s(t))throw new Error("Uint8Array expected")}function gs(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Ns(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Hf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?gc:BigInt("0x"+t)}const Kf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",lw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ys(t){if(yc(t),Kf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=lw[t[r]];return e}const Wt={_0:48,_9:57,A:65,F:70,a:97,f:102};function $l(t){if(t>=Wt._0&&t<=Wt._9)return t-Wt._0;if(t>=Wt.A&&t<=Wt.F)return t-(Wt.A-10);if(t>=Wt.a&&t<=Wt.f)return t-(Wt.a-10)}function gn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Kf)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=$l(t.charCodeAt(n)),a=$l(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function ei(t){return Hf(ys(t))}function Wf(t){return yc(t),Hf(ys(Uint8Array.from(t).reverse()))}function Is(t,e){return gn(t.toString(16).padStart(e*2,"0"))}function Gf(t,e){return Is(t,e).reverse()}function yt(t,e,r){let i;if(typeof e=="string")try{i=gn(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(_s(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function yn(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];yc(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const po=t=>typeof t=="bigint"&&gc<=t;function wc(t,e,r){return po(t)&&po(e)&&po(r)&&e<=t&&t<r}function Oi(t,e,r,i){if(!wc(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function uw(t){let e;for(e=0;t>gc;t>>=fa,e+=1);return e}const Fn=t=>(fa<<BigInt(t))-fa,go=t=>new Uint8Array(t),Dl=t=>Uint8Array.from(t);function hw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let i=go(t),s=go(t),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...h)=>r(s,i,...h),c=(h=go(0))=>{s=a(Dl([0]),h),i=a(),h.length!==0&&(s=a(Dl([1]),h),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){i=a();const d=i.slice();f.push(d),h+=i.length}return yn(...f)};return(h,f)=>{o(),c(h);let d;for(;!(d=f(l()));)c();return o(),d}}const fw={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||_s(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Ln(t,e,r={}){const i=(s,n,o)=>{const a=fw[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function Al(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}function dw(t,e){if(Tl(t)>e)throw new Rw({givenSize:Tl(t),maxSize:e})}const Gt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Pl(t){if(t>=Gt.zero&&t<=Gt.nine)return t-Gt.zero;if(t>=Gt.A&&t<=Gt.F)return t-(Gt.A-10);if(t>=Gt.a&&t<=Gt.f)return t-(Gt.a-10)}function pw(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;if(t.length>i)throw new Uw({size:t.length,targetSize:i,type:"Bytes"});const s=new Uint8Array(i);for(let n=0;n<i;n++){const o=r==="right";s[o?n:i-n-1]=t[o?n:t.length-n-1]}return s}function Yf(t,e){if(Rr(t)>e)throw new Iw({givenSize:Rr(t),maxSize:e})}function gw(t,e){if(typeof e=="number"&&e>0&&e>Rr(t)-1)throw new Xf({offset:e,position:"start",size:Rr(t)})}function yw(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Rr(t)!==r-e)throw new Xf({offset:r,position:"end",size:Rr(t)})}function Zf(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;const s=t.replace("0x","");if(s.length>i*2)throw new Sw({size:Math.ceil(s.length/2),targetSize:i,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](i*2,"0")}`}const ww="#__bigint";function mc(t,e,r){return JSON.stringify(t,(i,s)=>typeof s=="bigint"?s.toString()+ww:s,r)}const mw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function bw(t,e={}){const{strict:r=!1}=e;if(!t)throw new Bl(t);if(typeof t!="string")throw new Bl(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Cl(t);if(!t.startsWith("0x"))throw new Cl(t)}function vw(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function bc(t){return t instanceof Uint8Array?wn(t):Array.isArray(t)?wn(new Uint8Array(t)):t}function wn(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=mw[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(Yf(i,e.size),Jf(i,e.size)):i}function yo(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const l=typeof t=="bigint"?"n":"";throw new _w({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:r,size:i,value:`${t}${l}`})}const c=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?Ew(c,i):c}function Ew(t,e){return Zf(t,{dir:"left",size:e})}function Jf(t,e){return Zf(t,{dir:"right",size:e})}function rr(t,e,r,i={}){const{strict:s}=i;gw(t,e);const n=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&yw(n,e,r),n}function Rr(t){return Math.ceil((t.length-2)/2)}function xw(t,e={}){const{strict:r=!1}=e;try{return bw(t,{strict:r}),!0}catch{return!1}}class _w extends he{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number \`${n}\` is not in safe${s?` ${s*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Bl extends he{constructor(e){super(`Value \`${typeof e=="object"?mc(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 Cl extends he{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"})}}let Iw=class extends he{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class Xf extends he{constructor({offset:e,position:r,size:i}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let Sw=class extends he{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const Ow=new TextEncoder;function $w(t){if(!(t instanceof Uint8Array)){if(!t)throw new ks(t);if(typeof t!="object")throw new ks(t);if(!("BYTES_PER_ELEMENT"in t))throw new ks(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new ks(t)}}function Dw(t){return t instanceof Uint8Array?t:typeof t=="string"?Pw(t):Aw(t)}function Aw(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Pw(t,e={}){const{size:r}=e;let i=t;r&&(Yf(t,r),i=Jf(t,r));let s=i.slice(2);s.length%2&&(s=`0${s}`);const n=s.length/2,o=new Uint8Array(n);for(let a=0,c=0;a<n;a++){const l=Pl(s.charCodeAt(c++)),u=Pl(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new he(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function Bw(t,e={}){const{size:r}=e,i=Ow.encode(t);return typeof r=="number"?(dw(i,r),Cw(i,r)):i}function Cw(t,e){return pw(t,{dir:"right",size:e})}function Tl(t){return t.length}function Tw(t){try{return $w(t),!0}catch{return!1}}class ks extends he{constructor(e){super(`Value \`${typeof e=="object"?mc(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 Rw extends he{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Uw extends he{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Qf(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,i=nw(Dw(t));return r==="Bytes"?i:wn(i)}class Nw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const kw={checksum:new Nw(8192)},wo=kw.checksum;function ed(t,e={}){const{compressed:r}=e,{prefix:i,x:s,y:n}=t;if(r===!1||typeof s=="bigint"&&typeof n=="bigint"){if(i!==4)throw new Rl({prefix:i,cause:new zw});return}if(r===!0||typeof s=="bigint"&&typeof n>"u"){if(i!==3&&i!==2)throw new Rl({prefix:i,cause:new qw});return}throw new Mw({publicKey:t})}function jw(t){const e=(()=>{if(xw(t))return td(t);if(Tw(t))return Fw(t);const{prefix:r,x:i,y:s}=t;return typeof i=="bigint"&&typeof s=="bigint"?{prefix:r??4,x:i,y:s}:{prefix:r,x:i}})();return ed(e),e}function Fw(t){return td(wn(t))}function td(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new Vw({publicKey:t});if(t.length===130){const i=BigInt(rr(t,0,32)),s=BigInt(rr(t,32,64));return{prefix:4,x:i,y:s}}if(t.length===132){const i=Number(rr(t,0,1)),s=BigInt(rr(t,1,33)),n=BigInt(rr(t,33,65));return{prefix:i,x:s,y:n}}const e=Number(rr(t,0,1)),r=BigInt(rr(t,1,33));return{prefix:e,x:r}}function Lw(t,e={}){ed(t);const{prefix:r,x:i,y:s}=t,{includePrefix:n=!0}=e;return vw(n?yo(r,{size:1}):"0x",yo(i,{size:32}),typeof s=="bigint"?yo(s,{size:32}):"0x")}class Mw extends he{constructor({publicKey:e}){super(`Value \`${mc(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 Rl extends he{constructor({prefix:e,cause:r}){super(`Prefix "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class qw extends he{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 zw extends he{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Vw=class extends he{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 ${Rr(bc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Hw=/^0x[a-fA-F0-9]{40}$/;function rd(t,e={}){const{strict:r=!0}=e;if(!Hw.test(t))throw new Ul({address:t,cause:new Gw});if(r){if(t.toLowerCase()===t)return;if(id(t)!==t)throw new Ul({address:t,cause:new Yw})}}function id(t){if(wo.has(t))return wo.get(t);rd(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Qf(Bw(e),{as:"Bytes"}),i=e.split("");for(let n=0;n<40;n+=2)r[n>>1]>>4>=8&&i[n]&&(i[n]=i[n].toUpperCase()),(r[n>>1]&15)>=8&&i[n+1]&&(i[n+1]=i[n+1].toUpperCase());const s=`0x${i.join("")}`;return wo.set(t,s),s}function Kw(t,e={}){const{checksum:r=!1}=e;return rd(t),r?id(t):t}function Ww(t,e={}){const r=Qf(`0x${Lw(t).slice(4)}`).substring(26);return Kw(`0x${r}`,e)}class Ul extends he{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Gw extends he{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 Yw extends he{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class sd extends dc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,C0(e);const i=jn(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Ti(n)}update(e){return Ci(this),this.iHash.update(e),this}digestInto(e){Ci(this),ri(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const nd=(t,e,r)=>new sd(t,e).update(r).digest();nd.create=(t,e)=>new sd(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const et=BigInt(0),Ve=BigInt(1),Yr=BigInt(2),Zw=BigInt(3),od=BigInt(4),ad=BigInt(5),cd=BigInt(8);function Je(t,e){const r=t%e;return r>=et?r:e+r}function ft(t,e,r){let i=t;for(;e-- >et;)i*=i,i%=r;return i}function da(t,e){if(t===et)throw new Error("invert: expected non-zero number");if(e<=et)throw new Error("invert: expected positive modulus, got "+e);let r=Je(t,e),i=e,s=et,n=Ve;for(;r!==et;){const a=i/r,c=i%r,l=s-n*a;i=r,r=c,s=n,n=l}if(i!==Ve)throw new Error("invert: does not exist");return Je(s,e)}function ld(t,e){const r=(t.ORDER+Ve)/od,i=t.pow(e,r);if(!t.eql(t.sqr(i),e))throw new Error("Cannot find square root");return i}function Jw(t,e){const r=(t.ORDER-ad)/cd,i=t.mul(e,Yr),s=t.pow(i,r),n=t.mul(e,s),o=t.mul(t.mul(n,Yr),s),a=t.mul(n,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function Xw(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ve,r=0;for(;e%Yr===et;)e/=Yr,r++;let i=Yr;const s=vc(t);for(;Nl(s,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ld;let n=s.pow(i,e);const o=(e+Ve)/Yr;return function(c,l){if(c.is0(l))return l;if(Nl(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,n),f=c.pow(l,e),d=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,w=c.sqr(f);for(;!c.eql(w,c.ONE);)if(g++,w=c.sqr(w),g===u)throw new Error("Cannot find square root");const m=Ve<<BigInt(u-g-1),O=c.pow(h,m);u=g,h=c.sqr(O),f=c.mul(f,h),d=c.mul(d,O)}return d}}function Qw(t){return t%od===Zw?ld:t%cd===ad?Jw:Xw(t)}const em=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function tm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=em.reduce((i,s)=>(i[s]="function",i),e);return Ln(t,r)}function rm(t,e,r){if(r<et)throw new Error("invalid exponent, negatives unsupported");if(r===et)return t.ONE;if(r===Ve)return e;let i=t.ONE,s=e;for(;r>et;)r&Ve&&(i=t.mul(i,s)),s=t.sqr(s),r>>=Ve;return i}function ud(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),n),i}function Nl(t,e){const r=(t.ORDER-Ve)/Yr,i=t.pow(e,r),s=t.eql(i,t.ONE),n=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function hd(t,e){e!==void 0&&ps(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function vc(t,e,r=!1,i={}){if(t<=et)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=hd(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Fn(s),ZERO:et,ONE:Ve,create:c=>Je(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return et<=c&&c<t},is0:c=>c===et,isOdd:c=>(c&Ve)===Ve,neg:c=>Je(-c,t),eql:(c,l)=>c===l,sqr:c=>Je(c*c,t),add:(c,l)=>Je(c+l,t),sub:(c,l)=>Je(c-l,t),mul:(c,l)=>Je(c*l,t),pow:(c,l)=>rm(a,c,l),div:(c,l)=>Je(c*da(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>da(c,t),sqrt:i.sqrt||(c=>(o||(o=Qw(t)),o(a,c))),toBytes:c=>r?Gf(c,n):Is(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?Wf(c):ei(c)},invertBatch:c=>ud(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function fd(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function dd(t){const e=fd(t);return e+Math.ceil(e/2)}function im(t,e,r=!1){const i=t.length,s=fd(e),n=dd(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?Wf(t):ei(t),a=Je(o,e-Ve)+Ve;return r?Gf(a,s):Is(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kl=BigInt(0),pa=BigInt(1);function mo(t,e){const r=e.negate();return t?r:e}function pd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function bo(t,e){pd(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),s=2**t,n=Fn(t),o=BigInt(t);return{windows:r,windowSize:i,mask:n,maxNumber:s,shiftBy:o}}function jl(t,e,r){const{windowSize:i,mask:s,maxNumber:n,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>i&&(a-=n,c+=pa);const l=e*i,u=l+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:l}}function sm(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function nm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const vo=new WeakMap,gd=new WeakMap;function Eo(t){return gd.get(t)||1}function om(t,e){return{constTimeNegate:mo,hasPrecomputes(r){return Eo(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>kl;)i&pa&&(s=s.add(n)),n=n.double(),i>>=pa;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=bo(i,e),o=[];let a=r,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){let n=t.ZERO,o=t.BASE;const a=bo(r,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:g}=jl(s,c,a);s=l,h?o=o.add(mo(d,i[g])):n=n.add(mo(f,i[u]))}return{p:n,f:o}},wNAFUnsafe(r,i,s,n=t.ZERO){const o=bo(r,e);for(let a=0;a<o.windows&&s!==kl;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=jl(s,a,o);if(s=c,!u){const f=i[l];n=n.add(h?f.negate():f)}}return n},getPrecomputes(r,i,s){let n=vo.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&vo.set(i,s(n))),n},wNAFCached(r,i,s){const n=Eo(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=Eo(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){pd(i,e),gd.set(r,i),vo.delete(r)}}}function am(t,e,r,i){sm(r,t),nm(i,e);const s=r.length,n=i.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=uw(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Fn(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){u.fill(o);for(let w=0;w<n;w++){const m=i[w],O=Number(m>>BigInt(d)&l);u[O]=u[O].add(r[w])}let g=o;for(let w=u.length-1,m=o;w>0;w--)m=m.add(u[w]),g=g.add(m);if(f=f.add(g),d!==0)for(let w=0;w<c;w++)f=f.double()}return f}function yd(t){return tm(t.Fp),Ln(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...hd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Fl(t){t.lowS!==void 0&&gs("lowS",t.lowS),t.prehash!==void 0&&gs("prehash",t.prehash)}function cm(t){const e=yd(t);Ln(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:i,a:s}=e;if(r){if(!i.eql(s,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class lm extends Error{constructor(e=""){super(e)}}const ir={Err:lm,_tlv:{encode:(t,e)=>{const{Err:r}=ir;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=Ns(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?Ns(s.length/2|128):"";return Ns(t)+n+s+e},decode(t,e){const{Err:r}=ir;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=ir;if(t<nr)throw new e("integer: negative integers are not allowed");let r=Ns(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=ir;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ei(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=ir,s=yt("signature",t),{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:u}=i.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=ir,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}};function xo(t,e){return ys(Is(t,e))}const nr=BigInt(0),Se=BigInt(1);BigInt(2);const _o=BigInt(3),um=BigInt(4);function hm(t){const e=cm(t),{Fp:r}=e,i=vc(e.n,e.nBitLength),s=e.toBytes||((b,x,A)=>{const B=x.toAffine();return yn(Uint8Array.from([4]),r.toBytes(B.x),r.toBytes(B.y))}),n=e.fromBytes||(b=>{const x=b.subarray(1),A=r.fromBytes(x.subarray(0,r.BYTES)),B=r.fromBytes(x.subarray(r.BYTES,2*r.BYTES));return{x:A,y:B}});function o(b){const{a:x,b:A}=e,B=r.sqr(b),T=r.mul(B,b);return r.add(r.add(T,r.mul(b,x)),A)}function a(b,x){const A=r.sqr(x),B=o(b);return r.eql(A,B)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,_o),um),l=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,l)))throw new Error("bad curve params: a or b");function u(b){return wc(b,Se,e.n)}function h(b){const{allowedPrivateKeyLengths:x,nByteLength:A,wrapPrivateKey:B,n:T}=e;if(x&&typeof b!="bigint"){if(_s(b)&&(b=ys(b)),typeof b!="string"||!x.includes(b.length))throw new Error("invalid private key");b=b.padStart(A*2,"0")}let R;try{R=typeof b=="bigint"?b:ei(yt("private key",b,A))}catch{throw new Error("invalid private key, expected hex or "+A+" bytes, got "+typeof b)}return B&&(R=Je(R,T)),Oi("private key",R,Se,T),R}function f(b){if(!(b instanceof w))throw new Error("ProjectivePoint expected")}const d=Al((b,x)=>{const{px:A,py:B,pz:T}=b;if(r.eql(T,r.ONE))return{x:A,y:B};const R=b.is0();x==null&&(x=R?r.ONE:r.inv(T));const D=r.mul(A,x),k=r.mul(B,x),j=r.mul(T,x);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(j,r.ONE))throw new Error("invZ was invalid");return{x:D,y:k}}),g=Al(b=>{if(b.is0()){if(e.allowInfinityPoint&&!r.is0(b.py))return;throw new Error("bad point: ZERO")}const{x,y:A}=b.toAffine();if(!r.isValid(x)||!r.isValid(A))throw new Error("bad point: x or y not FE");if(!a(x,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class w{constructor(x,A,B){if(x==null||!r.isValid(x))throw new Error("x required");if(A==null||!r.isValid(A)||r.is0(A))throw new Error("y required");if(B==null||!r.isValid(B))throw new Error("z required");this.px=x,this.py=A,this.pz=B,Object.freeze(this)}static fromAffine(x){const{x:A,y:B}=x||{};if(!x||!r.isValid(A)||!r.isValid(B))throw new Error("invalid affine point");if(x instanceof w)throw new Error("projective point not allowed");const T=R=>r.eql(R,r.ZERO);return T(A)&&T(B)?w.ZERO:new w(A,B,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(x){const A=ud(r,x.map(B=>B.pz));return x.map((B,T)=>B.toAffine(A[T])).map(w.fromAffine)}static fromHex(x){const A=w.fromAffine(n(yt("pointHex",x)));return A.assertValidity(),A}static fromPrivateKey(x){return w.BASE.multiply(h(x))}static msm(x,A){return am(w,i,x,A)}_setWindowSize(x){C.setWindowSize(this,x)}assertValidity(){g(this)}hasEvenY(){const{y:x}=this.toAffine();if(r.isOdd)return!r.isOdd(x);throw new Error("Field doesn't support isOdd")}equals(x){f(x);const{px:A,py:B,pz:T}=this,{px:R,py:D,pz:k}=x,j=r.eql(r.mul(A,k),r.mul(R,T)),P=r.eql(r.mul(B,k),r.mul(D,T));return j&&P}negate(){return new w(this.px,r.neg(this.py),this.pz)}double(){const{a:x,b:A}=e,B=r.mul(A,_o),{px:T,py:R,pz:D}=this;let k=r.ZERO,j=r.ZERO,P=r.ZERO,I=r.mul(T,T),$=r.mul(R,R),p=r.mul(D,D),y=r.mul(T,R);return y=r.add(y,y),P=r.mul(T,D),P=r.add(P,P),k=r.mul(x,P),j=r.mul(B,p),j=r.add(k,j),k=r.sub($,j),j=r.add($,j),j=r.mul(k,j),k=r.mul(y,k),P=r.mul(B,P),p=r.mul(x,p),y=r.sub(I,p),y=r.mul(x,y),y=r.add(y,P),P=r.add(I,I),I=r.add(P,I),I=r.add(I,p),I=r.mul(I,y),j=r.add(j,I),p=r.mul(R,D),p=r.add(p,p),I=r.mul(p,y),k=r.sub(k,I),P=r.mul(p,$),P=r.add(P,P),P=r.add(P,P),new w(k,j,P)}add(x){f(x);const{px:A,py:B,pz:T}=this,{px:R,py:D,pz:k}=x;let j=r.ZERO,P=r.ZERO,I=r.ZERO;const $=e.a,p=r.mul(e.b,_o);let y=r.mul(A,R),v=r.mul(B,D),S=r.mul(T,k),E=r.add(A,B),_=r.add(R,D);E=r.mul(E,_),_=r.add(y,v),E=r.sub(E,_),_=r.add(A,T);let U=r.add(R,k);return _=r.mul(_,U),U=r.add(y,S),_=r.sub(_,U),U=r.add(B,T),j=r.add(D,k),U=r.mul(U,j),j=r.add(v,S),U=r.sub(U,j),I=r.mul($,_),j=r.mul(p,S),I=r.add(j,I),j=r.sub(v,I),I=r.add(v,I),P=r.mul(j,I),v=r.add(y,y),v=r.add(v,y),S=r.mul($,S),_=r.mul(p,_),v=r.add(v,S),S=r.sub(y,S),S=r.mul($,S),_=r.add(_,S),y=r.mul(v,_),P=r.add(P,y),y=r.mul(U,_),j=r.mul(E,j),j=r.sub(j,y),y=r.mul(E,v),I=r.mul(U,I),I=r.add(I,y),new w(j,P,I)}subtract(x){return this.add(x.negate())}is0(){return this.equals(w.ZERO)}wNAF(x){return C.wNAFCached(this,x,w.normalizeZ)}multiplyUnsafe(x){const{endo:A,n:B}=e;Oi("scalar",x,nr,B);const T=w.ZERO;if(x===nr)return T;if(this.is0()||x===Se)return this;if(!A||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,x,w.normalizeZ);let{k1neg:R,k1:D,k2neg:k,k2:j}=A.splitScalar(x),P=T,I=T,$=this;for(;D>nr||j>nr;)D&Se&&(P=P.add($)),j&Se&&(I=I.add($)),$=$.double(),D>>=Se,j>>=Se;return R&&(P=P.negate()),k&&(I=I.negate()),I=new w(r.mul(I.px,A.beta),I.py,I.pz),P.add(I)}multiply(x){const{endo:A,n:B}=e;Oi("scalar",x,Se,B);let T,R;if(A){const{k1neg:D,k1:k,k2neg:j,k2:P}=A.splitScalar(x);let{p:I,f:$}=this.wNAF(k),{p,f:y}=this.wNAF(P);I=C.constTimeNegate(D,I),p=C.constTimeNegate(j,p),p=new w(r.mul(p.px,A.beta),p.py,p.pz),T=I.add(p),R=$.add(y)}else{const{p:D,f:k}=this.wNAF(x);T=D,R=k}return w.normalizeZ([T,R])[0]}multiplyAndAddUnsafe(x,A,B){const T=w.BASE,R=(k,j)=>j===nr||j===Se||!k.equals(T)?k.multiplyUnsafe(j):k.multiply(j),D=R(this,A).add(R(x,B));return D.is0()?void 0:D}toAffine(x){return d(this,x)}isTorsionFree(){const{h:x,isTorsionFree:A}=e;if(x===Se)return!0;if(A)return A(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:x,clearCofactor:A}=e;return x===Se?this:A?A(w,this):this.multiplyUnsafe(e.h)}toRawBytes(x=!0){return gs("isCompressed",x),this.assertValidity(),s(w,this,x)}toHex(x=!0){return gs("isCompressed",x),ys(this.toRawBytes(x))}}w.BASE=new w(e.Gx,e.Gy,r.ONE),w.ZERO=new w(r.ZERO,r.ONE,r.ZERO);const{endo:m,nBitLength:O}=e,C=om(w,m?Math.ceil(O/2):O);return{CURVE:e,ProjectivePoint:w,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function fm(t){const e=yd(t);return Ln(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function dm(t){const e=fm(t),{Fp:r,n:i,nByteLength:s,nBitLength:n}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(p){return Je(p,i)}function l(p){return da(p,i)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:d}=hm({...e,toBytes(p,y,v){const S=y.toAffine(),E=r.toBytes(S.x),_=yn;return gs("isCompressed",v),v?_(Uint8Array.from([y.hasEvenY()?2:3]),E):_(Uint8Array.from([4]),E,r.toBytes(S.y))},fromBytes(p){const y=p.length,v=p[0],S=p.subarray(1);if(y===o&&(v===2||v===3)){const E=ei(S);if(!wc(E,Se,r.ORDER))throw new Error("Point is not on curve");const _=f(E);let U;try{U=r.sqrt(_)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const N=(U&Se)===Se;return(v&1)===1!==N&&(U=r.neg(U)),{x:E,y:U}}else if(y===a&&v===4){const E=r.fromBytes(S.subarray(0,r.BYTES)),_=r.fromBytes(S.subarray(r.BYTES,2*r.BYTES));return{x:E,y:_}}else{const E=o,_=a;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+_+", got "+y)}}});function g(p){const y=i>>Se;return p>y}function w(p){return g(p)?c(-p):p}const m=(p,y,v)=>ei(p.slice(y,v));class O{constructor(y,v,S){Oi("r",y,Se,i),Oi("s",v,Se,i),this.r=y,this.s=v,S!=null&&(this.recovery=S),Object.freeze(this)}static fromCompact(y){const v=s;return y=yt("compactSignature",y,v*2),new O(m(y,0,v),m(y,v,2*v))}static fromDER(y){const{r:v,s:S}=ir.toSig(yt("DER",y));return new O(v,S)}assertValidity(){}addRecoveryBit(y){return new O(this.r,this.s,y)}recoverPublicKey(y){const{r:v,s:S,recovery:E}=this,_=T(yt("msgHash",y));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");const U=E===2||E===3?v+e.n:v;if(U>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const N=E&1?"03":"02",V=u.fromHex(N+xo(U,r.BYTES)),L=l(U),M=c(-_*L),K=c(S*L),G=u.BASE.multiplyAndAddUnsafe(V,M,K);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new O(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return gn(this.toDERHex())}toDERHex(){return ir.hexFromSig(this)}toCompactRawBytes(){return gn(this.toCompactHex())}toCompactHex(){const y=s;return xo(this.r,y)+xo(this.s,y)}}const C={isValidPrivateKey(p){try{return h(p),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const p=dd(e.n);return im(e.randomBytes(p),e.n)},precompute(p=8,y=u.BASE){return y._setWindowSize(p),y.multiply(BigInt(3)),y}};function b(p,y=!0){return u.fromPrivateKey(p).toRawBytes(y)}function x(p){if(typeof p=="bigint")return!1;if(p instanceof u)return!0;const v=yt("key",p).length,S=r.BYTES,E=S+1,_=2*S+1;if(!(e.allowedPrivateKeyLengths||s===E))return v===E||v===_}function A(p,y,v=!0){if(x(p)===!0)throw new Error("first arg must be private key");if(x(y)===!1)throw new Error("second arg must be public key");return u.fromHex(y).multiply(h(p)).toRawBytes(v)}const B=e.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const y=ei(p),v=p.length*8-n;return v>0?y>>BigInt(v):y},T=e.bits2int_modN||function(p){return c(B(p))},R=Fn(n);function D(p){return Oi("num < 2^"+n,p,nr,R),Is(p,s)}function k(p,y,v=j){if(["recovered","canonical"].some(W=>W in v))throw new Error("sign() legacy options not supported");const{hash:S,randomBytes:E}=e;let{lowS:_,prehash:U,extraEntropy:N}=v;_==null&&(_=!0),p=yt("msgHash",p),Fl(v),U&&(p=yt("prehashed msgHash",S(p)));const V=T(p),L=h(y),M=[D(L),D(V)];if(N!=null&&N!==!1){const W=N===!0?E(r.BYTES):N;M.push(yt("extraEntropy",W))}const K=yn(...M),G=V;function J(W){const X=B(W);if(!d(X))return;const fe=l(X),me=u.BASE.multiply(X).toAffine(),Ee=c(me.x);if(Ee===nr)return;const ze=c(fe*c(G+Ee*L));if(ze===nr)return;let Kt=(me.x===Ee?0:2)|Number(me.y&Se),hr=ze;return _&&g(ze)&&(hr=w(ze),Kt^=1),new O(Ee,hr,Kt)}return{seed:K,k2sig:J}}const j={lowS:e.lowS,prehash:!1},P={lowS:e.lowS,prehash:!1};function I(p,y,v=j){const{seed:S,k2sig:E}=k(p,y,v),_=e;return hw(_.hash.outputLen,_.nByteLength,_.hmac)(S,E)}u.BASE._setWindowSize(8);function $(p,y,v,S=P){var Kt;const E=p;y=yt("msgHash",y),v=yt("publicKey",v);const{lowS:_,prehash:U,format:N}=S;if(Fl(S),"strict"in S)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&N!=="compact"&&N!=="der")throw new Error("format must be compact or der");const V=typeof E=="string"||_s(E),L=!V&&!N&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!V&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,K;try{if(L&&(M=new O(E.r,E.s)),V){try{N!=="compact"&&(M=O.fromDER(E))}catch(hr){if(!(hr instanceof ir.Err))throw hr}!M&&N!=="der"&&(M=O.fromCompact(E))}K=u.fromHex(v)}catch{return!1}if(!M||_&&M.hasHighS())return!1;U&&(y=e.hash(y));const{r:G,s:J}=M,W=T(y),X=l(J),fe=c(W*X),me=c(G*X),Ee=(Kt=u.BASE.multiplyAndAddUnsafe(K,fe,me))==null?void 0:Kt.toAffine();return Ee?c(Ee.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:A,sign:I,verify:$,ProjectivePoint:u,Signature:O,utils:C}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pm(t){return{hash:t,hmac:(e,...r)=>nd(t,e,j0(...r)),randomBytes:F0}}function gm(t,e){const r=i=>dm({...t,...pm(i)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ll=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ym=BigInt(0),wm=BigInt(1),ga=BigInt(2),Ml=(t,e)=>(t+e/ga)/e;function mm(t){const e=wd,r=BigInt(3),i=BigInt(6),s=BigInt(11),n=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=ft(u,r,e)*u%e,f=ft(h,r,e)*u%e,d=ft(f,ga,e)*l%e,g=ft(d,s,e)*d%e,w=ft(g,n,e)*g%e,m=ft(w,a,e)*w%e,O=ft(m,c,e)*m%e,C=ft(O,a,e)*w%e,b=ft(C,r,e)*u%e,x=ft(b,o,e)*g%e,A=ft(x,i,e)*l%e,B=ft(A,ga,e);if(!ya.eql(ya.sqr(B),t))throw new Error("Cannot find square root");return B}const ya=vc(wd,void 0,void 0,{sqrt:mm}),bm=gm({a:ym,b:BigInt(7),Fp:ya,n:Ll,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Ll,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-wm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,o=BigInt("0x100000000000000000000000000000000"),a=Ml(n*t,e),c=Ml(-i*t,e);let l=Je(t-a*r-c*s,e),u=Je(-a*i-c*n,e);const h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}}},cw);function vm(t){if(t.length!==130&&t.length!==132)throw new xm({signature:t});const e=BigInt(rr(t,0,32)),r=BigInt(rr(t,32,64)),i=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return Em(s)}catch{throw new _m({value:s})}})();return typeof i>"u"?{r:e,s:r}:{r:e,s:r,yParity:i}}function Em(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Im({value:t})}class xm extends he{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Rr(bc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class _m extends he{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 Im extends he{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"})}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Sm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function md(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function mn(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Ec(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function wa(t){if(!Array.isArray(t))throw new Error("array expected")}function bn(t,e){if(!md(!0,e))throw new Error(`${t}: array of strings expected`)}function Om(t,e){if(!md(!1,e))throw new Error(`${t}: array of numbers expected`)}function $m(...t){const e=n=>n,r=(n,o)=>a=>n(o(a)),i=t.map(n=>n.encode).reduceRight(r,e),s=t.map(n=>n.decode).reduce(r,e);return{encode:i,decode:s}}function Dm(t){const e=typeof t=="string"?t.split(""):t,r=e.length;bn("alphabet",e);const i=new Map(e.map((s,n)=>[s,n]));return{encode:s=>(wa(s),s.map(n=>{if(!Number.isSafeInteger(n)||n<0||n>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);return e[n]})),decode:s=>(wa(s),s.map(n=>{mn("alphabet.decode",n);const o=i.get(n);if(o===void 0)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return o}))}}function Am(t=""){return mn("join",t),{encode:e=>(bn("join.decode",e),e.join(t)),decode:e=>(mn("join.decode",e),e.split(t))}}function Pm(t,e="="){return Ec(t),mn("padding",e),{encode(r){for(bn("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){bn("padding.decode",r);let i=r.length;if(i*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===e;i--)if((i-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}const bd=(t,e)=>e===0?t:bd(e,t%e),vn=(t,e)=>t+(e-bd(t,e)),Io=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function ql(t,e,r,i){if(wa(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(vn(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${vn(e,r)}`);let s=0,n=0;const o=Io[e],a=Io[r]-1,c=[];for(const l of t){if(Ec(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<<e|l,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=r;n-=r)c.push((s>>n-r&a)>>>0);const u=Io[n];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<<r-n&a,!i&&n>=e)throw new Error("Excess padding");if(!i&&s>0)throw new Error(`Non-zero padding: ${s}`);return i&&n>0&&c.push(s>>>0),c}function Bm(t,e=!1){if(Ec(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(vn(8,t)>32||vn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Sm(r))throw new Error("radix2.encode input should be Uint8Array");return ql(Array.from(r),8,t,!e)},decode:r=>(Om("radix2.decode",r),Uint8Array.from(ql(r,t,8,e)))}}const Cm=$m(Bm(5),Dm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Pm(5),Am(""));function Tm(t){return Ww(Rm(t))}function Rm(t){const{payload:e,signature:r}=t,{r:i,s,yParity:n}=r,a=new bm.Signature(BigInt(i),BigInt(s)).addRecoveryBit(n).recoverPublicKey(bc(e).substring(2));return jw(a)}function Um(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,f=0;const d=l.length;for(;f!==d&&l[f]===0;)f++,u++;const g=(d-f)*n+1>>>0,w=new Uint8Array(g);for(;f!==d;){let C=l[f],b=0;for(let x=g-1;(C!==0||b<h)&&x!==-1;x--,b++)C+=256*w[x]>>>0,w[x]=C%r>>>0,C=C/r>>>0;if(C!==0)throw new Error("Non-zero carry");h=b,f++}let m=g-h;for(;m!==g&&w[m]===0;)m++;let O=i.repeat(u);for(;m<g;++m)O+=t.charAt(w[m]);return O}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,f=0;for(;l[u]===i;)h++,u++;const d=(l.length-u)*s+1>>>0,g=new Uint8Array(d);for(;u<l.length;){const C=l.charCodeAt(u);if(C>255)return;let b=e[C];if(b===255)return;let x=0;for(let A=d-1;(b!==0||x<f)&&A!==-1;A--,x++)b+=r*g[A]>>>0,g[A]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=x,u++}let w=d-f;for(;w!==d&&g[w]===0;)w++;const m=new Uint8Array(h+(d-w));let O=h;for(;w!==d;)m[O++]=g[w++];return m}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Nm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Ss=Um(Nm);function km(t){const e=t.length;let r=0,i=0;for(;i<e;){let s=t.charCodeAt(i++);if(s&4294967168)if(!(s&4294965248))r+=2;else{if(s>=55296&&s<=56319&&i<e){const n=t.charCodeAt(i);(n&64512)===56320&&(++i,s=((s&1023)<<10)+(n&1023)+65536)}s&4294901760?r+=4:r+=3}else{r++;continue}}return r}function jm(t,e,r){const i=t.length;let s=r,n=0;for(;n<i;){let o=t.charCodeAt(n++);if(o&4294967168)if(!(o&4294965248))e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&n<i){const a=t.charCodeAt(n);(a&64512)===56320&&(++n,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128):(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128)}else{e[s++]=o;continue}e[s++]=o&63|128}}const Fm=new TextEncoder,Lm=50;function Mm(t,e,r){Fm.encodeInto(t,e.subarray(r))}function qm(t,e,r){t.length>Lm?Mm(t,e,r):jm(t,e,r)}const zm=4096;function vd(t,e,r){let i=e;const s=i+r,n=[];let o="";for(;i<s;){const a=t[i++];if(!(a&128))n.push(a);else if((a&224)===192){const c=t[i++]&63;n.push((a&31)<<6|c)}else if((a&240)===224){const c=t[i++]&63,l=t[i++]&63;n.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[i++]&63,l=t[i++]&63,u=t[i++]&63;let h=(a&7)<<18|c<<12|l<<6|u;h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|h&1023),n.push(h)}else n.push(a);n.length>=zm&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const Vm=new TextDecoder,Hm=200;function Km(t,e,r){const i=t.subarray(e,e+r);return Vm.decode(i)}function Wm(t,e,r){return r>Hm?Km(t,e,r):vd(t,e,r)}class js{constructor(e,r){this.type=e,this.data=r}}class ct extends Error{constructor(e){super(e);const r=Object.create(ct.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const zi=4294967295;function Gm(t,e,r){const i=r/4294967296,s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function Ed(t,e,r){const i=Math.floor(r/4294967296),s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function xd(t,e){const r=t.getInt32(e),i=t.getUint32(e+4);return r*4294967296+i}function Ym(t,e){const r=t.getUint32(e),i=t.getUint32(e+4);return r*4294967296+i}const Zm=-1,Jm=4294967296-1,Xm=17179869184-1;function Qm({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Xm)if(e===0&&t<=Jm){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,i=t&4294967295,s=new Uint8Array(8),n=new DataView(s.buffer);return n.setUint32(0,e<<2|r&3),n.setUint32(4,i),s}else{const r=new Uint8Array(12),i=new DataView(r.buffer);return i.setUint32(0,e),Ed(i,4,t),r}}function eb(t){const e=t.getTime(),r=Math.floor(e/1e3),i=(e-r*1e3)*1e6,s=Math.floor(i/1e9);return{sec:r+s,nsec:i-s*1e9}}function tb(t){if(t instanceof Date){const e=eb(t);return Qm(e)}else return null}function rb(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const r=e.getUint32(0),i=e.getUint32(4),s=(r&3)*4294967296+i,n=r>>>2;return{sec:s,nsec:n}}case 12:{const r=xd(e,4),i=e.getUint32(0);return{sec:r,nsec:i}}default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function ib(t){const e=rb(t);return new Date(e.sec*1e3+e.nsec/1e6)}const sb={type:Zm,encode:tb,decode:ib};class En{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(sb)}register({type:e,encode:r,decode:i}){if(e>=0)this.encoders[e]=r,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=r,this.builtInDecoders[s]=i}}tryToEncode(e,r){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=-1-i;return new js(o,n)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=i;return new js(o,n)}}}return e instanceof js?e:null}decode(e,r,i){const s=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return s?s(e,r,i):new js(r,e)}}En.defaultCodec=new En;function nb(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ma(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):nb(t)?new Uint8Array(t):Uint8Array.from(t)}const ob=100,ab=2048;let cb=class _d{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??En.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??ob,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??ab,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new _d({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,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),i=new Uint8Array(r),s=new DataView(r);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?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)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=km(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),qm(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,r){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const i=ma(e);this.writeU8a(i)}encodeArray(e,r){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)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const s of e)this.doEncode(s,r+1)}countWithoutUndefined(e,r){let i=0;for(const s of r)e[s]!==void 0&&i++;return i}encodeMap(e,r){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)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const n of i){const o=e[n];this.ignoreUndefined&&o===void 0||(this.encodeString(n),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),s=i.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(i);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}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),Gm(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ed(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 lb(t,e){return new cb(e).encodeSharedRef(t)}function So(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const ub=16,hb=16;class fb{constructor(e=ub,r=hb){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,i){const s=this.caches[i-1];e:for(const n of s){const o=n.bytes;for(let a=0;a<i;a++)if(o[a]!==e[r+a])continue e;return n.str}return null}store(e,r){const i=this.caches[e.length-1],s={bytes:e,str:r};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,r,i){const s=this.find(e,r,i);if(s!=null)return this.hit++,s;this.miss++;const n=vd(e,r,i),o=Uint8Array.prototype.slice.call(e,r,r+i);return this.store(o,n),n}}const ba="array",as="map_key",Id="map_value",db=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ct("The type of key must be string or number but "+typeof t)};class pb{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=ba,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=as,r.readCount=0,r.size=e,r.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===ba){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===as||e.type===Id){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Vi=-1,xc=new DataView(new ArrayBuffer(0)),gb=new Uint8Array(xc.buffer);try{xc.getInt8(0)}catch(t){if(!(t 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 zl=new RangeError("Insufficient data"),yb=new fb;let wb=class Sd{constructor(e){this.totalPos=0,this.pos=0,this.view=xc,this.bytes=gb,this.headByte=Vi,this.stack=new pb,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??En.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??zi,this.maxBinLength=(e==null?void 0:e.maxBinLength)??zi,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??zi,this.maxMapLength=(e==null?void 0:e.maxMapLength)??zi,this.maxExtLength=(e==null?void 0:e.maxExtLength)??zi,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:yb,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??db}clone(){return new Sd({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=Vi,this.stack.reset()}setBuffer(e){const r=ma(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Vi&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),i=ma(e),s=new Uint8Array(r.length+i.length);s.set(r),s.set(i,r.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:i}=this;return new RangeError(`Extra ${r.byteLength-i} of ${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}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 r=!1,i;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:s,pos:n,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${So(s)} at ${o} (${n} 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,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let i=r,s=-1;for await(const n of e){if(r&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else{const s=e-160;r=this.decodeString(s,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const s=this.lookU8();r=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();r=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();r=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===196){const s=this.lookU8();r=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();r=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();r=this.decodeBinary(s,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();r=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();r=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();r=this.decodeExtension(s,4)}else throw new ct(`Unrecognized type byte: ${So(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const s=i.top();if(s.type===ba)if(s.array[s.position]=r,s.position++,s.position===s.size)r=s.array,i.release(s);else continue e;else if(s.type===as){if(r==="__proto__")throw new ct("The key __proto__ is not allowed");s.key=this.mapKeyConverter(r),s.type=Id;continue e}else if(s.map[s.key]=r,s.readCount++,s.readCount===s.size)r=s.map,i.release(s);else{s.key=null,s.type=as;continue e}}return r}}readHeadByte(){return this.headByte===Vi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Vi}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 ct(`Unrecognized array type byte: ${So(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){var n;if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw zl;const i=this.pos+r;let s;return this.stateIsMapKey()&&((n=this.keyDecoder)!=null&&n.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,i,e):s=Wm(this.bytes,i,e),this.pos+=r+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===as:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw zl;const i=this.pos+r,s=this.bytes.subarray(i,i+e);return this.pos+=r+e,s}decodeExtension(e,r){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+r),s=this.decodeBinary(e,r+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=Ym(this.view,this.pos);return this.pos+=8,e}readI64(){const e=xd(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 mb(t,e){return new wb(e).decode(t)}const bb=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),vb=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function ii(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return vb(t)}catch{return t}}function si(t){return typeof t=="string"?t:bb(t)||""}function Eb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Od(t,...e){if(!Eb(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Vl(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xb(t,e){Od(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const gi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oo=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function _b(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function $d(t){return typeof t=="string"&&(t=_b(t)),Od(t),t}let Ib=class{clone(){return this._cloneInto()}};function Sb(t){const e=i=>t().update($d(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Dd(t=32){if(gi&&typeof gi.getRandomValues=="function")return gi.getRandomValues(new Uint8Array(t));if(gi&&typeof gi.randomBytes=="function")return gi.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Ob(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}let $b=class extends Ib{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Oo(this.buffer)}update(e){Vl(this);const{view:r,buffer:i,blockLen:s}=this;e=$d(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Oo(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Vl(this),xb(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;Ob(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Oo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const Fs=BigInt(2**32-1),va=BigInt(32);function Ad(t,e=!1){return e?{h:Number(t&Fs),l:Number(t>>va&Fs)}:{h:Number(t>>va&Fs)|0,l:Number(t&Fs)|0}}function Db(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Ad(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Ab=(t,e)=>BigInt(t>>>0)<<va|BigInt(e>>>0),Pb=(t,e,r)=>t>>>r,Bb=(t,e,r)=>t<<32-r|e>>>r,Cb=(t,e,r)=>t>>>r|e<<32-r,Tb=(t,e,r)=>t<<32-r|e>>>r,Rb=(t,e,r)=>t<<64-r|e>>>r-32,Ub=(t,e,r)=>t>>>r-32|e<<64-r,Nb=(t,e)=>e,kb=(t,e)=>t,jb=(t,e,r)=>t<<r|e>>>32-r,Fb=(t,e,r)=>e<<r|t>>>32-r,Lb=(t,e,r)=>e<<r-32|t>>>64-r,Mb=(t,e,r)=>t<<r-32|e>>>64-r;function qb(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const zb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Vb=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,Hb=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Kb=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,Wb=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Gb=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,Z={fromBig:Ad,split:Db,toBig:Ab,shrSH:Pb,shrSL:Bb,rotrSH:Cb,rotrSL:Tb,rotrBH:Rb,rotrBL:Ub,rotr32H:Nb,rotr32L:kb,rotlSH:jb,rotlSL:Fb,rotlBH:Lb,rotlBL:Mb,add:qb,add3L:zb,add3H:Vb,add4L:Hb,add4H:Kb,add5H:Gb,add5L:Wb},[Yb,Zb]=Z.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),pr=new Uint32Array(80),gr=new Uint32Array(80);let Jb=class extends $b{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:d,Gl:g,Hh:w,Hl:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=g|0,this.Hh=w|0,this.Hl=m|0}process(e,r){for(let b=0;b<16;b++,r+=4)pr[b]=e.getUint32(r),gr[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const x=pr[b-15]|0,A=gr[b-15]|0,B=Z.rotrSH(x,A,1)^Z.rotrSH(x,A,8)^Z.shrSH(x,A,7),T=Z.rotrSL(x,A,1)^Z.rotrSL(x,A,8)^Z.shrSL(x,A,7),R=pr[b-2]|0,D=gr[b-2]|0,k=Z.rotrSH(R,D,19)^Z.rotrBH(R,D,61)^Z.shrSH(R,D,6),j=Z.rotrSL(R,D,19)^Z.rotrBL(R,D,61)^Z.shrSL(R,D,6),P=Z.add4L(T,j,gr[b-7],gr[b-16]),I=Z.add4H(P,B,k,pr[b-7],pr[b-16]);pr[b]=I|0,gr[b]=P|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:d,Fl:g,Gh:w,Gl:m,Hh:O,Hl:C}=this;for(let b=0;b<80;b++){const x=Z.rotrSH(h,f,14)^Z.rotrSH(h,f,18)^Z.rotrBH(h,f,41),A=Z.rotrSL(h,f,14)^Z.rotrSL(h,f,18)^Z.rotrBL(h,f,41),B=h&d^~h&w,T=f&g^~f&m,R=Z.add5L(C,A,T,Zb[b],gr[b]),D=Z.add5H(R,O,x,B,Yb[b],pr[b]),k=R|0,j=Z.rotrSH(i,s,28)^Z.rotrBH(i,s,34)^Z.rotrBH(i,s,39),P=Z.rotrSL(i,s,28)^Z.rotrBL(i,s,34)^Z.rotrBL(i,s,39),I=i&n^i&a^n&a,$=s&o^s&c^o&c;O=w|0,C=m|0,w=d|0,m=g|0,d=h|0,g=f|0,{h,l:f}=Z.add(l|0,u|0,D|0,k|0),l=a|0,u=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const p=Z.add3L(k,P,$);i=Z.add3H(p,D,j,I),s=p|0}({h:i,l:s}=Z.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=Z.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=Z.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Z.add(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=Z.add(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:g}=Z.add(this.Fh|0,this.Fl|0,d|0,g|0),{h:w,l:m}=Z.add(this.Gh|0,this.Gl|0,w|0,m|0),{h:O,l:C}=Z.add(this.Hh|0,this.Hl|0,O|0,C|0),this.set(i,s,n,o,a,c,l,u,h,f,d,g,w,m,O,C)}roundClean(){pr.fill(0),gr.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 Xb=Sb(()=>new Jb);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _c=BigInt(0),Pd=BigInt(1),Qb=BigInt(2);function Ic(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Sc(t){if(!Ic(t))throw new Error("Uint8Array expected")}function $o(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const e1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oc(t){Sc(t);let e="";for(let r=0;r<t.length;r++)e+=e1[t[r]];return e}function Bd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?_c:BigInt("0x"+t)}const Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hl(t){if(t>=Yt._0&&t<=Yt._9)return t-Yt._0;if(t>=Yt.A&&t<=Yt.F)return t-(Yt.A-10);if(t>=Yt.a&&t<=Yt.f)return t-(Yt.a-10)}function Cd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Hl(t.charCodeAt(n)),a=Hl(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function t1(t){return Bd(Oc(t))}function an(t){return Sc(t),Bd(Oc(Uint8Array.from(t).reverse()))}function Td(t,e){return Cd(t.toString(16).padStart(e*2,"0"))}function Ea(t,e){return Td(t,e).reverse()}function Zt(t,e,r){let i;if(typeof e=="string")try{i=Cd(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Ic(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Kl(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Sc(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const Do=t=>typeof t=="bigint"&&_c<=t;function r1(t,e,r){return Do(t)&&Do(e)&&Do(r)&&e<=t&&t<r}function Hi(t,e,r,i){if(!r1(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function i1(t){let e;for(e=0;t>_c;t>>=Pd,e+=1);return e}const s1=t=>(Qb<<BigInt(t-1))-Pd,n1={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Ic(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function $c(t,e,r={}){const i=(s,n,o)=>{const a=n1[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function Wl(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const $e=BigInt(0),de=BigInt(1),Kr=BigInt(2),o1=BigInt(3),xa=BigInt(4),Gl=BigInt(5),Yl=BigInt(8);function ve(t,e){const r=t%e;return r>=$e?r:e+r}function a1(t,e,r){if(e<$e)throw new Error("invalid exponent, negatives unsupported");if(r<=$e)throw new Error("invalid modulus");if(r===de)return $e;let i=de;for(;e>$e;)e&de&&(i=i*t%r),t=t*t%r,e>>=de;return i}function Ct(t,e,r){let i=t;for(;e-- >$e;)i*=i,i%=r;return i}function Zl(t,e){if(t===$e)throw new Error("invert: expected non-zero number");if(e<=$e)throw new Error("invert: expected positive modulus, got "+e);let r=ve(t,e),i=e,s=$e,n=de;for(;r!==$e;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==de)throw new Error("invert: does not exist");return ve(s,e)}function c1(t){const e=(t-de)/Kr;let r,i,s;for(r=t-de,i=0;r%Kr===$e;r/=Kr,i++);for(s=Kr;s<t&&a1(s,e,t)!==t-de;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+de)/xa;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(r+de)/Kr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,l=o.pow(o.mul(o.ONE,s),r),u=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let g=o.sqr(h);f<c&&!o.eql(g,o.ONE);f++)g=o.sqr(g);const d=o.pow(l,de<<BigInt(c-f-1));l=o.sqr(d),u=o.mul(u,d),h=o.mul(h,l),c=f}return u}}function l1(t){if(t%xa===o1){const e=(t+de)/xa;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Yl===Gl){const e=(t-Gl)/Yl;return function(r,i){const s=r.mul(i,Kr),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,Kr),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return c1(t)}const u1=(t,e)=>(ve(t,e)&de)===de,h1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function f1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=h1.reduce((i,s)=>(i[s]="function",i),e);return $c(t,r)}function d1(t,e,r){if(r<$e)throw new Error("invalid exponent, negatives unsupported");if(r===$e)return t.ONE;if(r===de)return e;let i=t.ONE,s=e;for(;r>$e;)r&de&&(i=t.mul(i,s)),s=t.sqr(s),r>>=de;return i}function p1(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Rd(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Ud(t,e,r=!1,i={}){if(t<=$e)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Rd(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:s1(s),ZERO:$e,ONE:de,create:c=>ve(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return $e<=c&&c<t},is0:c=>c===$e,isOdd:c=>(c&de)===de,neg:c=>ve(-c,t),eql:(c,l)=>c===l,sqr:c=>ve(c*c,t),add:(c,l)=>ve(c+l,t),sub:(c,l)=>ve(c-l,t),mul:(c,l)=>ve(c*l,t),pow:(c,l)=>d1(a,c,l),div:(c,l)=>ve(c*Zl(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Zl(c,t),sqrt:i.sqrt||(c=>(o||(o=l1(t)),o(a,c))),invertBatch:c=>p1(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>r?Ea(c,n):Td(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?an(c):t1(c)}});return Object.freeze(a)}const Jl=BigInt(0),Ls=BigInt(1);function Ao(t,e){const r=e.negate();return t?r:e}function Nd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Po(t,e){Nd(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function g1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function y1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Bo=new WeakMap,kd=new WeakMap;function Co(t){return kd.get(t)||1}function w1(t,e){return{constTimeNegate:Ao,hasPrecomputes(r){return Co(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Jl;)i&Ls&&(s=s.add(n)),n=n.double(),i>>=Ls;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=Po(i,e),o=[];let a=r,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=Po(r,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**r-1),u=2**r,h=BigInt(r);for(let f=0;f<n;f++){const d=f*o;let g=Number(s&l);s>>=h,g>o&&(g-=u,s+=Ls);const w=d,m=d+Math.abs(g)-1,O=f%2!==0,C=g<0;g===0?c=c.add(Ao(O,i[w])):a=a.add(Ao(C,i[m]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=Po(r,e),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(s===Jl)break;let d=Number(s&c);if(s>>=u,d>a&&(d-=l,s+=Ls),d===0)continue;let g=i[f+Math.abs(d)-1];d<0&&(g=g.negate()),n=n.add(g)}return n},getPrecomputes(r,i,s){let n=Bo.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&Bo.set(i,s(n))),n},wNAFCached(r,i,s){const n=Co(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=Co(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Nd(i,e),kd.set(r,i),Bo.delete(r)}}}function m1(t,e,r,i){if(g1(r,t),y1(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=i1(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),l=Math.floor((e.BITS-1)/o)*o;let u=s;for(let h=l;h>=0;h-=o){c.fill(s);for(let d=0;d<i.length;d++){const g=i[d],w=Number(g>>BigInt(h)&BigInt(a));c[w]=c[w].add(r[d])}let f=s;for(let d=c.length-1,g=s;d>0;d--)g=g.add(c[d]),f=f.add(g);if(u=u.add(f),h!==0)for(let d=0;d<o;d++)u=u.double()}return u}function b1(t){return f1(t.Fp),$c(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Rd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const _t=BigInt(0),We=BigInt(1),Ms=BigInt(2),v1=BigInt(8),E1={zip215:!0};function x1(t){const e=b1(t);return $c(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function _1(t){const e=x1(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,l=Ms<<BigInt(a*8)-We,u=r.create,h=Ud(e.n,e.nBitLength),f=e.uvRatio||((p,y)=>{try{return{isValid:!0,value:r.sqrt(p*r.inv(y))}}catch{return{isValid:!1,value:_t}}}),d=e.adjustScalarBytes||(p=>p),g=e.domain||((p,y,v)=>{if($o("phflag",v),y.length||v)throw new Error("Contexts/pre-hash are not supported");return p});function w(p,y){Hi("coordinate "+p,y,_t,l)}function m(p){if(!(p instanceof b))throw new Error("ExtendedPoint expected")}const O=Wl((p,y)=>{const{ex:v,ey:S,ez:E}=p,_=p.is0();y==null&&(y=_?v1:r.inv(E));const U=u(v*y),N=u(S*y),V=u(E*y);if(_)return{x:_t,y:We};if(V!==We)throw new Error("invZ was invalid");return{x:U,y:N}}),C=Wl(p=>{const{a:y,d:v}=e;if(p.is0())throw new Error("bad point: ZERO");const{ex:S,ey:E,ez:_,et:U}=p,N=u(S*S),V=u(E*E),L=u(_*_),M=u(L*L),K=u(N*y),G=u(L*u(K+V)),J=u(M+u(v*u(N*V)));if(G!==J)throw new Error("bad point: equation left != right (1)");const W=u(S*E),X=u(_*U);if(W!==X)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(y,v,S,E){this.ex=y,this.ey=v,this.ez=S,this.et=E,w("x",y),w("y",v),w("z",S),w("t",E),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof b)throw new Error("extended point not allowed");const{x:v,y:S}=y||{};return w("x",v),w("y",S),new b(v,S,We,u(v*S))}static normalizeZ(y){const v=r.invertBatch(y.map(S=>S.ez));return y.map((S,E)=>S.toAffine(v[E])).map(b.fromAffine)}static msm(y,v){return m1(b,h,y,v)}_setWindowSize(y){B.setWindowSize(this,y)}assertValidity(){C(this)}equals(y){m(y);const{ex:v,ey:S,ez:E}=this,{ex:_,ey:U,ez:N}=y,V=u(v*N),L=u(_*E),M=u(S*N),K=u(U*E);return V===L&&M===K}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:y}=e,{ex:v,ey:S,ez:E}=this,_=u(v*v),U=u(S*S),N=u(Ms*u(E*E)),V=u(y*_),L=v+S,M=u(u(L*L)-_-U),K=V+U,G=K-N,J=V-U,W=u(M*G),X=u(K*J),fe=u(M*J),me=u(G*K);return new b(W,X,me,fe)}add(y){m(y);const{a:v,d:S}=e,{ex:E,ey:_,ez:U,et:N}=this,{ex:V,ey:L,ez:M,et:K}=y;if(v===BigInt(-1)){const il=u((_-E)*(L+V)),sl=u((_+E)*(L-V)),ao=u(sl-il);if(ao===_t)return this.double();const nl=u(U*Ms*K),ol=u(N*Ms*M),al=ol+nl,cl=sl+il,ll=ol-nl,Iy=u(al*ao),Sy=u(cl*ll),Oy=u(al*ll),$y=u(ao*cl);return new b(Iy,Sy,$y,Oy)}const G=u(E*V),J=u(_*L),W=u(N*S*K),X=u(U*M),fe=u((E+_)*(V+L)-G-J),me=X-W,Ee=X+W,ze=u(J-v*G),Kt=u(fe*me),hr=u(Ee*ze),xy=u(fe*ze),_y=u(me*Ee);return new b(Kt,hr,_y,xy)}subtract(y){return this.add(y.negate())}wNAF(y){return B.wNAFCached(this,y,b.normalizeZ)}multiply(y){const v=y;Hi("scalar",v,We,i);const{p:S,f:E}=this.wNAF(v);return b.normalizeZ([S,E])[0]}multiplyUnsafe(y,v=b.ZERO){const S=y;return Hi("scalar",S,_t,i),S===_t?A:this.is0()||S===We?this:B.wNAFCachedUnsafe(this,S,b.normalizeZ,v)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,i).is0()}toAffine(y){return O(this,y)}clearCofactor(){const{h:y}=e;return y===We?this:this.multiplyUnsafe(y)}static fromHex(y,v=!1){const{d:S,a:E}=e,_=r.BYTES;y=Zt("pointHex",y,_),$o("zip215",v);const U=y.slice(),N=y[_-1];U[_-1]=N&-129;const V=an(U),L=v?l:r.ORDER;Hi("pointHex.y",V,_t,L);const M=u(V*V),K=u(M-We),G=u(S*M-E);let{isValid:J,value:W}=f(K,G);if(!J)throw new Error("Point.fromHex: invalid y coordinate");const X=(W&We)===We,fe=(N&128)!==0;if(!v&&W===_t&&fe)throw new Error("Point.fromHex: x=0 and x_0=1");return fe!==X&&(W=u(-W)),b.fromAffine({x:W,y:V})}static fromPrivateKey(y){return D(y).point}toRawBytes(){const{x:y,y:v}=this.toAffine(),S=Ea(v,r.BYTES);return S[S.length-1]|=y&We?128:0,S}toHex(){return Oc(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,We,u(e.Gx*e.Gy)),b.ZERO=new b(_t,We,We,_t);const{BASE:x,ZERO:A}=b,B=w1(b,a*8);function T(p){return ve(p,i)}function R(p){return T(an(p))}function D(p){const y=r.BYTES;p=Zt("private key",p,y);const v=Zt("hashed private key",n(p),2*y),S=d(v.slice(0,y)),E=v.slice(y,2*y),_=R(S),U=x.multiply(_),N=U.toRawBytes();return{head:S,prefix:E,scalar:_,point:U,pointBytes:N}}function k(p){return D(p).pointBytes}function j(p=new Uint8Array,...y){const v=Kl(...y);return R(n(g(v,Zt("context",p),!!s)))}function P(p,y,v={}){p=Zt("message",p),s&&(p=s(p));const{prefix:S,scalar:E,pointBytes:_}=D(y),U=j(v.context,S,p),N=x.multiply(U).toRawBytes(),V=j(v.context,N,_,p),L=T(U+V*E);Hi("signature.s",L,_t,i);const M=Kl(N,Ea(L,r.BYTES));return Zt("result",M,r.BYTES*2)}const I=E1;function $(p,y,v,S=I){const{context:E,zip215:_}=S,U=r.BYTES;p=Zt("signature",p,2*U),y=Zt("message",y),v=Zt("publicKey",v,U),_!==void 0&&$o("zip215",_),s&&(y=s(y));const N=an(p.slice(U,2*U));let V,L,M;try{V=b.fromHex(v,_),L=b.fromHex(p.slice(0,U),_),M=x.multiplyUnsafe(N)}catch{return!1}if(!_&&V.isSmallOrder())return!1;const K=j(E,L.toRawBytes(),V.toRawBytes(),y);return L.add(V.multiplyUnsafe(K)).subtract(M).clearCofactor().equals(b.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:P,verify:$,ExtendedPoint:b,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(r.BYTES),precompute(p=8,y=b.BASE){return y._setWindowSize(p),y.multiply(BigInt(3)),y}}}}BigInt(0),BigInt(1);const Dc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Xl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const I1=BigInt(1),Ql=BigInt(2);BigInt(3);const S1=BigInt(5),O1=BigInt(8);function $1(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=Dc,o=t*t%n*t%n,a=Ct(o,Ql,n)*o%n,c=Ct(a,I1,n)*t%n,l=Ct(c,S1,n)*c%n,u=Ct(l,e,n)*l%n,h=Ct(u,r,n)*u%n,f=Ct(h,i,n)*h%n,d=Ct(f,s,n)*f%n,g=Ct(d,s,n)*f%n,w=Ct(g,e,n)*l%n;return{pow_p_5_8:Ct(w,Ql,n)*t%n,b2:o}}function D1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function A1(t,e){const r=Dc,i=ve(e*e*e,r),s=ve(i*i*e,r),n=$1(t*s).pow_p_5_8;let o=ve(t*i*n,r);const a=ve(e*o*o,r),c=o,l=ve(o*Xl,r),u=a===t,h=a===ve(-t,r),f=a===ve(-t*Xl,r);return u&&(o=c),(h||f)&&(o=l),u1(o,r)&&(o=ve(-o,r)),{isValid:u||h,value:o}}const P1=Ud(Dc,void 0,!0),B1={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:P1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:O1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xb,randomBytes:Dd,adjustScalarBytes:D1,uvRatio:A1},jd=_1(B1),C1="EdDSA",T1="JWT",xn=".",Mn="base64url",Fd="utf8",Ld="utf8",R1=":",U1="did",N1="key",eu="base58btc",k1="z",j1="K36",F1=32;function Ac(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Md(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ac(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function qd(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Md(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Ac(r)}function L1(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,m=0,O=0,C=g.length;O!==C&&g[O]===0;)O++,w++;for(var b=(C-O)*u+1>>>0,x=new Uint8Array(b);O!==C;){for(var A=g[O],B=0,T=b-1;(A!==0||B<m)&&T!==-1;T--,B++)A+=256*x[T]>>>0,x[T]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=B,O++}for(var R=b-m;R!==b&&x[R]===0;)R++;for(var D=c.repeat(w);R<b;++R)D+=t.charAt(x[R]);return D}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var m=0,O=0;g[w]===c;)m++,w++;for(var C=(g.length-w)*l+1>>>0,b=new Uint8Array(C);g[w];){var x=r[g.charCodeAt(w)];if(x===255)return;for(var A=0,B=C-1;(x!==0||A<O)&&B!==-1;B--,A++)x+=a*b[B]>>>0,b[B]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");O=A,w++}if(g[w]!==" "){for(var T=C-O;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(m+(C-T)),D=m;T!==C;)R[D++]=b[T++];return R}}}function d(g){var w=f(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var M1=L1,q1=M1;const zd=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},z1=t=>new TextEncoder().encode(t),V1=t=>new TextDecoder().decode(t);let H1=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},K1=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Vd(this,e)}},W1=class{constructor(e){this.decoders=e}or(e){return Vd(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Vd=(t,e)=>new W1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let G1=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new H1(e,r,i),this.decoder=new K1(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const qn=({name:t,prefix:e,encode:r,decode:i})=>new G1(t,e,r,i),Os=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=q1(r,e);return qn({prefix:t,name:e,encode:i,decode:n=>zd(s(n))})},Y1=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Z1=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Te=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>qn({prefix:e,name:t,encode(s){return Z1(s,i,r)},decode(s){return Y1(s,i,r,t)}}),J1=qn({prefix:"\0",name:"identity",encode:t=>V1(t),decode:t=>z1(t)});var X1=Object.freeze({__proto__:null,identity:J1});const Q1=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ev=Object.freeze({__proto__:null,base2:Q1});const tv=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var rv=Object.freeze({__proto__:null,base8:tv});const iv=Os({prefix:"9",name:"base10",alphabet:"0123456789"});var sv=Object.freeze({__proto__:null,base10:iv});const nv=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ov=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var av=Object.freeze({__proto__:null,base16:nv,base16upper:ov});const cv=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lv=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),uv=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hv=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fv=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dv=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pv=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gv=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yv=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wv=Object.freeze({__proto__:null,base32:cv,base32upper:lv,base32pad:uv,base32padupper:hv,base32hex:fv,base32hexupper:dv,base32hexpad:pv,base32hexpadupper:gv,base32z:yv});const mv=Os({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bv=Os({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vv=Object.freeze({__proto__:null,base36:mv,base36upper:bv});const Ev=Os({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xv=Os({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _v=Object.freeze({__proto__:null,base58btc:Ev,base58flickr:xv});const Iv=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sv=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ov=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$v=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Dv=Object.freeze({__proto__:null,base64:Iv,base64pad:Sv,base64url:Ov,base64urlpad:$v});const Hd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Av=Hd.reduce((t,e,r)=>(t[r]=e,t),[]),Pv=Hd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Bv(t){return t.reduce((e,r)=>(e+=Av[r],e),"")}function Cv(t){const e=[];for(const r of t){const i=Pv[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Tv=qn({prefix:"🚀",name:"base256emoji",encode:Bv,decode:Cv});var Rv=Object.freeze({__proto__:null,base256emoji:Tv}),Uv=Kd,tu=128,Nv=-128,kv=Math.pow(2,31);function Kd(t,e,r){e=e||[],r=r||0;for(var i=r;t>=kv;)e[r++]=t&255|tu,t/=128;for(;t&Nv;)e[r++]=t&255|tu,t>>>=7;return e[r]=t|0,Kd.bytes=r-i+1,e}var jv=_a,Fv=128,ru=127;function _a(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw _a.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&ru)<<s:(o&ru)*Math.pow(2,s),s+=7}while(o>=Fv);return _a.bytes=n-i,r}var Lv=Math.pow(2,7),Mv=Math.pow(2,14),qv=Math.pow(2,21),zv=Math.pow(2,28),Vv=Math.pow(2,35),Hv=Math.pow(2,42),Kv=Math.pow(2,49),Wv=Math.pow(2,56),Gv=Math.pow(2,63),Yv=function(t){return t<Lv?1:t<Mv?2:t<qv?3:t<zv?4:t<Vv?5:t<Hv?6:t<Kv?7:t<Wv?8:t<Gv?9:10},Zv={encode:Uv,decode:jv,encodingLength:Yv},Wd=Zv;const iu=(t,e,r=0)=>(Wd.encode(t,e,r),e),su=t=>Wd.encodingLength(t),Ia=(t,e)=>{const r=e.byteLength,i=su(t),s=i+su(r),n=new Uint8Array(s+r);return iu(t,n,0),iu(r,n,i),n.set(e,s),new Jv(t,r,e,n)};let Jv=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const Gd=({name:t,code:e,encode:r})=>new Xv(t,e,r);let Xv=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ia(this.code,r):r.then(i=>Ia(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Yd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Qv=Gd({name:"sha2-256",code:18,encode:Yd("SHA-256")}),e2=Gd({name:"sha2-512",code:19,encode:Yd("SHA-512")});var t2=Object.freeze({__proto__:null,sha256:Qv,sha512:e2});const Zd=0,r2="identity",Jd=zd,i2=t=>Ia(Zd,Jd(t)),s2={code:Zd,name:r2,encode:Jd,digest:i2};var n2=Object.freeze({__proto__:null,identity:s2});new TextEncoder,new TextDecoder;const nu={...X1,...ev,...rv,...sv,...av,...wv,...vv,..._v,...Dv,...Rv};({...t2,...n2});function Xd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const ou=Xd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),To=Xd("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Md(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Qd={utf8:ou,"utf-8":ou,hex:nu.base16,latin1:To,ascii:To,binary:To,...nu};function zn(t,e="utf8"){const r=Qd[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function ki(t,e="utf8"){const r=Qd[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ac(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function au(t){return ii(zn(ki(t,Mn),Fd))}function _n(t){return zn(ki(si(t),Fd),Mn)}function ep(t){const e=ki(j1,eu),r=k1+zn(qd([e,t]),eu);return[U1,N1,r].join(R1)}function o2(t){return zn(t,Mn)}function a2(t){return ki(t,Mn)}function c2(t){return ki([_n(t.header),_n(t.payload)].join(xn),Ld)}function l2(t){return[_n(t.header),_n(t.payload),o2(t.signature)].join(xn)}function Sa(t){const e=t.split(xn),r=au(e[0]),i=au(e[1]),s=a2(e[2]),n=ki(e.slice(0,2).join(xn),Ld);return{header:r,payload:i,signature:s,data:n}}function cu(t=Dd(F1)){const e=jd.getPublicKey(t);return{secretKey:qd([t,e]),publicKey:e}}async function u2(t,e,r,i,s=q.fromMiliseconds(Date.now())){const n={alg:C1,typ:T1},o=ep(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},l=c2({header:n,payload:c}),u=jd.sign(l,i.secretKey.slice(0,32));return l2({header:n,payload:c,signature:u})}function Pc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function tp(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Pc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function cs(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=tp(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Pc(r)}function h2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,m=0,O=0,C=g.length;O!==C&&g[O]===0;)O++,w++;for(var b=(C-O)*u+1>>>0,x=new Uint8Array(b);O!==C;){for(var A=g[O],B=0,T=b-1;(A!==0||B<m)&&T!==-1;T--,B++)A+=256*x[T]>>>0,x[T]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=B,O++}for(var R=b-m;R!==b&&x[R]===0;)R++;for(var D=c.repeat(w);R<b;++R)D+=t.charAt(x[R]);return D}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var m=0,O=0;g[w]===c;)m++,w++;for(var C=(g.length-w)*l+1>>>0,b=new Uint8Array(C);g[w];){var x=r[g.charCodeAt(w)];if(x===255)return;for(var A=0,B=C-1;(x!==0||A<O)&&B!==-1;B--,A++)x+=a*b[B]>>>0,b[B]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");O=A,w++}if(g[w]!==" "){for(var T=C-O;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(m+(C-T)),D=m;T!==C;)R[D++]=b[T++];return R}}}function d(g){var w=f(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var f2=h2,d2=f2;const p2=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},g2=t=>new TextEncoder().encode(t),y2=t=>new TextDecoder().decode(t);class w2{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class m2{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rp(this,e)}}class b2{constructor(e){this.decoders=e}or(e){return rp(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const rp=(t,e)=>new b2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class v2{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new w2(e,r,i),this.decoder=new m2(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Vn=({name:t,prefix:e,encode:r,decode:i})=>new v2(t,e,r,i),$s=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=d2(r,e);return Vn({prefix:t,name:e,encode:i,decode:n=>p2(s(n))})},E2=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},x2=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Re=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Vn({prefix:e,name:t,encode(s){return x2(s,i,r)},decode(s){return E2(s,i,r,t)}}),_2=Vn({prefix:"\0",name:"identity",encode:t=>y2(t),decode:t=>g2(t)}),I2=Object.freeze(Object.defineProperty({__proto__:null,identity:_2},Symbol.toStringTag,{value:"Module"})),S2=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),O2=Object.freeze(Object.defineProperty({__proto__:null,base2:S2},Symbol.toStringTag,{value:"Module"})),$2=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),D2=Object.freeze(Object.defineProperty({__proto__:null,base8:$2},Symbol.toStringTag,{value:"Module"})),A2=$s({prefix:"9",name:"base10",alphabet:"0123456789"}),P2=Object.freeze(Object.defineProperty({__proto__:null,base10:A2},Symbol.toStringTag,{value:"Module"})),B2=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),C2=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),T2=Object.freeze(Object.defineProperty({__proto__:null,base16:B2,base16upper:C2},Symbol.toStringTag,{value:"Module"})),R2=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),U2=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),N2=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k2=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),j2=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),F2=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),L2=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),M2=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),q2=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),z2=Object.freeze(Object.defineProperty({__proto__:null,base32:R2,base32hex:j2,base32hexpad:L2,base32hexpadupper:M2,base32hexupper:F2,base32pad:N2,base32padupper:k2,base32upper:U2,base32z:q2},Symbol.toStringTag,{value:"Module"})),V2=$s({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),H2=$s({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),K2=Object.freeze(Object.defineProperty({__proto__:null,base36:V2,base36upper:H2},Symbol.toStringTag,{value:"Module"})),W2=$s({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),G2=$s({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Y2=Object.freeze(Object.defineProperty({__proto__:null,base58btc:W2,base58flickr:G2},Symbol.toStringTag,{value:"Module"})),Z2=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),J2=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),X2=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q2=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),eE=Object.freeze(Object.defineProperty({__proto__:null,base64:Z2,base64pad:J2,base64url:X2,base64urlpad:Q2},Symbol.toStringTag,{value:"Module"})),ip=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),tE=ip.reduce((t,e,r)=>(t[r]=e,t),[]),rE=ip.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function iE(t){return t.reduce((e,r)=>(e+=tE[r],e),"")}function sE(t){const e=[];for(const r of t){const i=rE[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const nE=Vn({prefix:"🚀",name:"base256emoji",encode:iE,decode:sE}),oE=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:nE},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const lu={...I2,...O2,...D2,...P2,...T2,...z2,...K2,...Y2,...eE,...oE};function sp(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const uu=sp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ro=sp("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=tp(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),np={utf8:uu,"utf-8":uu,hex:lu.base16,latin1:Ro,ascii:Ro,binary:Ro,...lu};function bt(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Pc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function rt(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const aE={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"}},cE="Input must be an string, Buffer or Uint8Array";function lE(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(cE);return e}function uE(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function qs(t){return(4294967296+t).toString(16).substring(1)}function hE(t,e,r){let i=`
17
+ `+t+" = ";for(let s=0;s<e.length;s+=2){if(r===32)i+=qs(e[s]).toUpperCase(),i+=" ",i+=qs(e[s+1]).toUpperCase();else if(r===64)i+=qs(e[s+1]).toUpperCase(),i+=qs(e[s]).toUpperCase();else throw new Error("Invalid size "+r);s%6===4?i+=`
18
+ `+new Array(t.length+4).join(" "):s<e.length-2&&(i+=" ")}console.log(i)}function fE(t,e,r){let i=new Date().getTime();const s=new Uint8Array(e);for(let o=0;o<e;o++)s[o]=o%256;const n=new Date().getTime();console.log("Generated random input in "+(n-i)+"ms"),i=n;for(let o=0;o<r;o++){const a=t(s),c=new Date().getTime(),l=c-i;i=c,console.log("Hashed in "+l+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(l/1e3)*100)/100+" MB PER SECOND")}}var op={normalizeInput:lE,toHex:uE,debugPrint:hE,testSpeed:fE};const cn=op;function zs(t,e,r){const i=t[e]+t[r];let s=t[e+1]+t[r+1];i>=4294967296&&s++,t[e]=i,t[e+1]=s}function hu(t,e,r,i){let s=t[e]+r;r<0&&(s+=4294967296);let n=t[e+1]+i;s>=4294967296&&n++,t[e]=s,t[e+1]=n}function ap(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function yr(t,e,r,i,s,n){const o=is[s],a=is[s+1],c=is[n],l=is[n+1];zs(Y,t,e),hu(Y,t,o,a);let u=Y[i]^Y[t],h=Y[i+1]^Y[t+1];Y[i]=h,Y[i+1]=u,zs(Y,r,i),u=Y[e]^Y[r],h=Y[e+1]^Y[r+1],Y[e]=u>>>24^h<<8,Y[e+1]=h>>>24^u<<8,zs(Y,t,e),hu(Y,t,c,l),u=Y[i]^Y[t],h=Y[i+1]^Y[t+1],Y[i]=u>>>16^h<<16,Y[i+1]=h>>>16^u<<16,zs(Y,r,i),u=Y[e]^Y[r],h=Y[e+1]^Y[r+1],Y[e]=h>>>31^u<<1,Y[e+1]=u>>>31^h<<1}const cp=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),dE=[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],Ne=new Uint8Array(dE.map(function(t){return t*2})),Y=new Uint32Array(32),is=new Uint32Array(32);function lp(t,e){let r=0;for(r=0;r<16;r++)Y[r]=t.h[r],Y[r+16]=cp[r];for(Y[24]=Y[24]^t.t,Y[25]=Y[25]^t.t/4294967296,e&&(Y[28]=~Y[28],Y[29]=~Y[29]),r=0;r<32;r++)is[r]=ap(t.b,4*r);for(r=0;r<12;r++)yr(0,8,16,24,Ne[r*16+0],Ne[r*16+1]),yr(2,10,18,26,Ne[r*16+2],Ne[r*16+3]),yr(4,12,20,28,Ne[r*16+4],Ne[r*16+5]),yr(6,14,22,30,Ne[r*16+6],Ne[r*16+7]),yr(0,10,20,30,Ne[r*16+8],Ne[r*16+9]),yr(2,12,22,24,Ne[r*16+10],Ne[r*16+11]),yr(4,14,16,26,Ne[r*16+12],Ne[r*16+13]),yr(6,8,18,28,Ne[r*16+14],Ne[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Y[r]^Y[r+16]}const wr=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 up(t,e,r,i){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(i&&i.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const s={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};wr.fill(0),wr[0]=t,e&&(wr[1]=e.length),wr[2]=1,wr[3]=1,r&&wr.set(r,32),i&&wr.set(i,48);for(let n=0;n<16;n++)s.h[n]=cp[n]^ap(wr,n*4);return e&&(Bc(s,e),s.c=128),s}function Bc(t,e){for(let r=0;r<e.length;r++)t.c===128&&(t.t+=t.c,lp(t,!1),t.c=0),t.b[t.c++]=e[r]}function hp(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;lp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3);return e}function fp(t,e,r,i,s){r=r||64,t=cn.normalizeInput(t),i&&(i=cn.normalizeInput(i)),s&&(s=cn.normalizeInput(s));const n=up(r,e,i,s);return Bc(n,t),hp(n)}function pE(t,e,r,i,s){const n=fp(t,e,r,i,s);return cn.toHex(n)}var gE={blake2b:fp,blake2bHex:pE,blake2bInit:up,blake2bUpdate:Bc,blake2bFinal:hp};const dp=op;function yE(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function mr(t,e,r,i,s,n){ie[t]=ie[t]+ie[e]+s,ie[i]=Vs(ie[i]^ie[t],16),ie[r]=ie[r]+ie[i],ie[e]=Vs(ie[e]^ie[r],12),ie[t]=ie[t]+ie[e]+n,ie[i]=Vs(ie[i]^ie[t],8),ie[r]=ie[r]+ie[i],ie[e]=Vs(ie[e]^ie[r],7)}function Vs(t,e){return t>>>e^t<<32-e}const pp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=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]),ie=new Uint32Array(16),De=new Uint32Array(16);function gp(t,e){let r=0;for(r=0;r<8;r++)ie[r]=t.h[r],ie[r+8]=pp[r];for(ie[12]^=t.t,ie[13]^=t.t/4294967296,e&&(ie[14]=~ie[14]),r=0;r<16;r++)De[r]=yE(t.b,4*r);for(r=0;r<10;r++)mr(0,4,8,12,De[ke[r*16+0]],De[ke[r*16+1]]),mr(1,5,9,13,De[ke[r*16+2]],De[ke[r*16+3]]),mr(2,6,10,14,De[ke[r*16+4]],De[ke[r*16+5]]),mr(3,7,11,15,De[ke[r*16+6]],De[ke[r*16+7]]),mr(0,5,10,15,De[ke[r*16+8]],De[ke[r*16+9]]),mr(1,6,11,12,De[ke[r*16+10]],De[ke[r*16+11]]),mr(2,7,8,13,De[ke[r*16+12]],De[ke[r*16+13]]),mr(3,4,9,14,De[ke[r*16+14]],De[ke[r*16+15]]);for(r=0;r<8;r++)t.h[r]^=ie[r]^ie[r+8]}function yp(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const r=e?e.length:0;if(e&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");const i={h:new Uint32Array(pp),b:new Uint8Array(64),c:0,t:0,outlen:t};return i.h[0]^=16842752^r<<8^t,r>0&&(Cc(i,e),i.c=64),i}function Cc(t,e){for(let r=0;r<e.length;r++)t.c===64&&(t.t+=t.c,gp(t,!1),t.c=0),t.b[t.c++]=e[r]}function wp(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;gp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3)&255;return e}function mp(t,e,r){r=r||32,t=dp.normalizeInput(t);const i=yp(r,e);return Cc(i,t),wp(i)}function wE(t,e,r){const i=mp(t,e,r);return dp.toHex(i)}var mE={blake2s:mp,blake2sHex:wE,blake2sInit:yp,blake2sUpdate:Cc,blake2sFinal:wp};const Ki=gE,Wi=mE;var bE={blake2b:Ki.blake2b,blake2bHex:Ki.blake2bHex,blake2bInit:Ki.blake2bInit,blake2bUpdate:Ki.blake2bUpdate,blake2bFinal:Ki.blake2bFinal,blake2s:Wi.blake2s,blake2sHex:Wi.blake2sHex,blake2sInit:Wi.blake2sInit,blake2sUpdate:Wi.blake2sUpdate,blake2sFinal:Wi.blake2sFinal},Mt={exports:{}};function vE(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var EE=xE;function xE(t,e,r){var i=r&&r.stringify||vE,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=i(t);for(var a=1;a<n;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-s,h=-1,f=t&&t.length||0,d=0;d<f;){if(t.charCodeAt(d)===37&&d+1<f){switch(h=h>-1?h:0,t.charCodeAt(d+1)){case 100:case 102:if(u>=c||e[u]==null)break;h<d&&(l+=t.slice(h,d)),l+=Number(e[u]),h=d+2,d++;break;case 105:if(u>=c||e[u]==null)break;h<d&&(l+=t.slice(h,d)),l+=Math.floor(Number(e[u])),h=d+2,d++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;h<d&&(l+=t.slice(h,d));var g=typeof e[u];if(g==="string"){l+="'"+e[u]+"'",h=d+2,d++;break}if(g==="function"){l+=e[u].name||"<anonymous>",h=d+2,d++;break}l+=i(e[u]),h=d+2,d++;break;case 115:if(u>=c)break;h<d&&(l+=t.slice(h,d)),l+=String(e[u]),h=d+2,d++;break;case 37:h<d&&(l+=t.slice(h,d)),l+="%",h=d+2,d++,u--;break}++u}++d}return h===-1?t:(h<f&&(l+=t.slice(h)),l)}const fu=EE;Mt.exports=ar;const ws=kE().console||{},_E={mapHttpRequest:Hs,mapHttpResponse:Hs,wrapRequestSerializer:Uo,wrapResponseSerializer:Uo,wrapErrorSerializer:Uo,req:Hs,res:Hs,err:pu,errWithCause:pu};function Br(t,e){return t==="silent"?1/0:e.levels.values[t]}const Tc=Symbol("pino.logFuncs"),Oa=Symbol("pino.hierarchy"),IE={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function du(t,e){const r={logger:e,parent:t[Oa]};e[Oa]=r}function SE(t,e,r){const i={};e.forEach(s=>{i[s]=r[s]?r[s]:ws[s]||ws[IE[s]||"log"]||$i}),t[Tc]=i}function OE(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function ar(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||ws;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},s=OE(t.browser.serialize,i);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof r=="function"&&a.forEach(function(w){r[w]=r}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(r);l.log||(l.log=$i),SE(l,a,r),du({},l),Object.defineProperty(l,"levelVal",{get:h}),Object.defineProperty(l,"level",{get:f,set:d});const u={transmit:e,serialize:s,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:RE(t),messageKey:t.messageKey||"msg",onChild:t.onChild||$i};l.levels=$E(t),l.level=c,l.isLevelEnabled=function(w){return this.levels.values[w]?this.levels.values[w]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=$i,l.serializers=i,l._serialize=s,l._stdErrSerialize=n,l.child=function(...w){return g.call(this,u,...w)},e&&(l._logEvent=$a());function h(){return Br(this.level,this)}function f(){return this._level}function d(w){if(w!=="silent"&&!this.levels.values[w])throw Error("unknown level "+w);this._level=w,Lr(this,u,l,"error"),Lr(this,u,l,"fatal"),Lr(this,u,l,"warn"),Lr(this,u,l,"info"),Lr(this,u,l,"debug"),Lr(this,u,l,"trace"),o.forEach(m=>{Lr(this,u,l,m)})}function g(w,m,O){if(!m)throw new Error("missing bindings for child Pino");O=O||{},s&&m.serializers&&(O.serializers=m.serializers);const C=O.serializers;if(s&&C){var b=Object.assign({},i,C),x=t.browser.serialize===!0?Object.keys(b):s;delete m.serializers,Rc([m],x,b,this._stdErrSerialize)}function A(T){this._childLevel=(T._childLevel|0)+1,this.bindings=m,b&&(this.serializers=b,this._serialize=x),e&&(this._logEvent=$a([].concat(T._logEvent.bindings,m)))}A.prototype=this;const B=new A(this);return du(this,B),B.child=function(...T){return g.call(this,w,...T)},B.level=O.level||this.level,w.onChild(B),B}return l}function $E(t){const e=t.customLevels||{},r=Object.assign({},ar.levels.values,e),i=Object.assign({},ar.levels.labels,DE(e));return{values:r,labels:i}}function DE(t){const e={};return Object.keys(t).forEach(function(r){e[t[r]]=r}),e}ar.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"}},ar.stdSerializers=_E,ar.stdTimeFunctions=Object.assign({},{nullTime:bp,epochTime:vp,unixTime:UE,isoTime:NE});function AE(t){const e=[];t.bindings&&e.push(t.bindings);let r=t[Oa];for(;r.parent;)r=r.parent,r.logger.bindings&&e.push(r.logger.bindings);return e.reverse()}function Lr(t,e,r,i){if(Object.defineProperty(t,i,{value:Br(t.level,r)>Br(i,r)?$i:r[Tc][i],writable:!0,enumerable:!0,configurable:!0}),t[i]===$i){if(!e.transmit)return;const n=e.transmit.level||t.level,o=Br(n,r);if(Br(i,r)<o)return}t[i]=BE(t,e,r,i);const s=AE(t);s.length!==0&&(t[i]=PE(s,t[i]))}function PE(t,e){return function(){return e.apply(this,[...t,...arguments])}}function BE(t,e,r,i){return function(s){return function(){const n=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ws?ws:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(e.serialize&&(Rc(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?s.call(a,...CE(this,i,o,n,e)):s.apply(a,o),e.transmit){const u=e.transmit.level||t._level,h=Br(u,r),f=Br(i,r);if(f<h)return;TE(this,{ts:n,methodLevel:i,methodValue:f,transmitValue:r.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Br(t._level,r)},o,l)}}}(t[Tc][i])}function CE(t,e,r,i,s){const{level:n,log:o=h=>h}=s.formatters||{},a=r.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),i&&(l.time=i),n){const h=n(e,t.levels.values[e]);Object.assign(l,h)}else l.level=t.levels.values[e];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?fu(a.shift(),a):void 0}else typeof c=="string"&&(c=fu(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function Rc(t,e,r,i){for(const s in t)if(i&&t[s]instanceof Error)t[s]=ar.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s])&&e)for(const n in t[s])e.indexOf(n)>-1&&n in r&&(t[s][n]=r[n](t[s][n]))}function TE(t,e,r,i=!1){const s=e.send,n=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;i||Rc(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=n,t._logEvent.messages=r.filter(function(u){return l.indexOf(u)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,s(o,t._logEvent,c),t._logEvent=$a(l)}function $a(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function pu(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function RE(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?bp:vp}function Hs(){return{}}function Uo(t){return t}function $i(){}function bp(){return!1}function vp(){return Date.now()}function UE(){return Math.round(Date.now()/1e3)}function NE(){return new Date(Date.now()).toISOString()}function kE(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}Mt.exports.default=ar;Mt.exports.pino=ar;const jE={level:"info"},Hn="custom_context",Uc=1e3*1024;var FE=Object.defineProperty,LE=(t,e,r)=>e in t?FE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dr=(t,e,r)=>LE(t,typeof e!="symbol"?e+"":e,r);let ME=class{constructor(e){Dr(this,"nodeValue"),Dr(this,"sizeInBytes"),Dr(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}},gu=class{constructor(e){Dr(this,"lengthInNodes"),Dr(this,"sizeInBytes"),Dr(this,"head"),Dr(this,"tail"),Dr(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new ME(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}};const qE=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r);function yu(t){return typeof t=="string"?t:qE(t)||""}var zE=Object.defineProperty,VE=(t,e,r)=>e in t?zE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ks=(t,e,r)=>VE(t,typeof e!="symbol"?e+"":e,r);let Ep=class{constructor(e,r=Uc){Ks(this,"logs"),Ks(this,"level"),Ks(this,"levelValue"),Ks(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Mt.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new gu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Mt.exports.levels.values.error?console.error(e):r===Mt.exports.levels.values.warn?console.warn(e):r===Mt.exports.levels.values.debug?console.debug(e):r===Mt.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(yu({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new gu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(yu({extraMetadata:e})),new Blob(r,{type:"application/json"})}};var HE=Object.defineProperty,KE=(t,e,r)=>e in t?HE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,WE=(t,e,r)=>KE(t,e+"",r);let GE=class{constructor(e,r=Uc){WE(this,"baseChunkLogger"),this.baseChunkLogger=new Ep(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}};var YE=Object.defineProperty,ZE=(t,e,r)=>e in t?YE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,JE=(t,e,r)=>ZE(t,e+"",r);let XE=class{constructor(e,r=Uc){JE(this,"baseChunkLogger"),this.baseChunkLogger=new Ep(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var QE=Object.defineProperty,ex=Object.defineProperties,tx=Object.getOwnPropertyDescriptors,wu=Object.getOwnPropertySymbols,rx=Object.prototype.hasOwnProperty,ix=Object.prototype.propertyIsEnumerable,mu=(t,e,r)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,In=(t,e)=>{for(var r in e||(e={}))rx.call(e,r)&&mu(t,r,e[r]);if(wu)for(var r of wu(e))ix.call(e,r)&&mu(t,r,e[r]);return t},Sn=(t,e)=>ex(t,tx(e));function sx(t){return Sn(In({},t),{level:(t==null?void 0:t.level)||jE.level})}function nx(t,e,r=Hn){return t[r]=e,t}function it(t,e=Hn){return t[e]||""}function ox(t,e,r=Hn){const i=it(t,r);return i.trim()?`${i}/${e}`:e}function ht(t,e,r=Hn){const i=ox(t,e,r),s=t.child({context:i});return nx(s,i,r)}function ax(t){var e,r;const i=new GE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Mt.exports(Sn(In({},t.opts),{level:"trace",browser:Sn(In({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function cx(t){var e;const r=new XE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Mt.exports(Sn(In({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function xp(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?ax(t):cx(t)}var lx={};const ux=":";function cr(t){const[e,r]=t.split(ux);return{namespace:e,reference:r}}function bu(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function _p(t,e){return t.includes(":")?[t]:e.chains||[]}var hx=Object.defineProperty,fx=Object.defineProperties,dx=Object.getOwnPropertyDescriptors,vu=Object.getOwnPropertySymbols,px=Object.prototype.hasOwnProperty,gx=Object.prototype.propertyIsEnumerable,Da=(t,e,r)=>e in t?hx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Eu=(t,e)=>{for(var r in e||(e={}))px.call(e,r)&&Da(t,r,e[r]);if(vu)for(var r of vu(e))gx.call(e,r)&&Da(t,r,e[r]);return t},yx=(t,e)=>fx(t,dx(e)),xu=(t,e,r)=>Da(t,typeof e!="symbol"?e+"":e,r);const wx="ReactNative",ut={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},mx="js";function On(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Nr(){return!ti()&&!!hc()&&navigator.product===wx}function bx(){return Nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function vx(){return Nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ji(){return!On()&&!!hc()&&!!ti()}function Ds(){return Nr()?ut.reactNative:On()?ut.node:ji()?ut.browser:ut.unknown}function _u(){var t;try{return Nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Ex(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([i],[s])=>i.localeCompare(s)).forEach(([i,s])=>{s!=null&&r.set(i,String(s))}),r.toString()}function xx(t){var e,r;const i=Ip();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),yx(Eu(Eu({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function Ip(){return kf()||{name:"",description:"",url:"",icons:[""]}}function _x(){if(Ds()===ut.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=jy();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Ix(){var t;const e=Ds();return e===ut.browser?[e,((t=Nf())==null?void 0:t.host)||"unknown"].join(":"):e}function Sp(t,e,r){const i=_x(),s=Ix();return[[t,e].join("-"),[mx,r].join("-"),i,s].join("/")}function Sx({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=r.split("?"),u=Sp(t,e,i),h={auth:s,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},f=Ex(l[1]||"",h);return l[0]+"?"+f}function Zr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Aa(t){return Object.fromEntries(t.entries())}function Pa(t){return new Map(Object.entries(t))}function Vr(t=q.FIVE_MINUTES,e){const r=q.toMiliseconds(t||q.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},r),i=a,s=c})}}function qt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function Op(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Ox(t){return Op("topic",t)}function $x(t){return Op("id",t)}function $p(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function ge(t,e){return q.fromMiliseconds(Date.now()+q.toMiliseconds(t))}function Lt(t){return Date.now()>=q.toMiliseconds(t)}function ne(t,e){return`${t}${e?`:${e}`:""}`}function zt(t=[],e=[]){return[...new Set([...t,...e])]}async function Dx({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Ax(n,t,e),a=Ds();if(a===ut.browser){if(!((i=ti())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Px(o)}else a===ut.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function Ax(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Rx(i,!0)}`}else s=`${s}/wc?${i}`;return s}function Px(t){let e="_self";Tx()?e="_top":(Cx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Bx(t,e){let r="";try{if(ji()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Iu(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Su(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Nc(){return typeof process<"u"&&lx.IS_VITEST==="true"}function Cx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Tx(){try{return window.self!==window.top}catch{return!1}}function Rx(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Dp(t){return Buffer.from(t,"base64").toString("utf-8")}function Ux(t){return new Promise(e=>setTimeout(e,t))}let Nx=class{constructor({limit:e}){xu(this,"limit"),xu(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}};const Ws=BigInt(2**32-1),Ou=BigInt(32);function Ap(t,e=!1){return e?{h:Number(t&Ws),l:Number(t>>Ou&Ws)}:{h:Number(t>>Ou&Ws)|0,l:Number(t&Ws)|0}}function Pp(t,e=!1){const r=t.length;let i=new Uint32Array(r),s=new Uint32Array(r);for(let n=0;n<r;n++){const{h:o,l:a}=Ap(t[n],e);[i[n],s[n]]=[o,a]}return[i,s]}const $u=(t,e,r)=>t>>>r,Du=(t,e,r)=>t<<32-r|e>>>r,Sr=(t,e,r)=>t>>>r|e<<32-r,Or=(t,e,r)=>t<<32-r|e>>>r,ss=(t,e,r)=>t<<64-r|e>>>r-32,ns=(t,e,r)=>t>>>r-32|e<<64-r,kx=(t,e)=>e,jx=(t,e)=>t,Fx=(t,e,r)=>t<<r|e>>>32-r,Lx=(t,e,r)=>e<<r|t>>>32-r,Mx=(t,e,r)=>e<<r-32|t>>>64-r,qx=(t,e,r)=>t<<r-32|e>>>64-r;function $t(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const kc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),jc=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,zx=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Vx=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,Hx=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Kx=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,yi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Kn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ur(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Pt(t,...e){if(!Kn(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Wn(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ur(t.outputLen),ur(t.blockLen)}function Ur(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Fc(t,e){Pt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ms(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function No(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Tt(t,e){return t<<32-e|t>>>e}const Bp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Cp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const er=Bp?t=>t:t=>Cp(t);function Wx(t){for(let e=0;e<t.length;e++)t[e]=Cp(t[e]);return t}const $r=Bp?t=>t:Wx,Tp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Gx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Di(t){if(Pt(t),Tp)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Gx[t[r]];return e}const Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Au(t){if(t>=Jt._0&&t<=Jt._9)return t-Jt._0;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function $n(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Tp)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Au(t.charCodeAt(n)),a=Au(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function Rp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function At(t){return typeof t=="string"&&(t=Rp(t)),Pt(t),t}function Ar(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Pt(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Gn=class{};function As(t){const e=i=>t().update(At(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Yx(t){const e=(i,s)=>t(s).update(At(i)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}function ci(t=32){if(yi&&typeof yi.getRandomValues=="function")return yi.getRandomValues(new Uint8Array(t));if(yi&&typeof yi.randomBytes=="function")return Uint8Array.from(yi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Zx=BigInt(0),Gi=BigInt(1),Jx=BigInt(2),Xx=BigInt(7),Qx=BigInt(256),e_=BigInt(113),Up=[],Np=[],kp=[];for(let t=0,e=Gi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Up.push(2*(5*i+r)),Np.push((t+1)*(t+2)/2%64);let s=Zx;for(let n=0;n<7;n++)e=(e<<Gi^(e>>Xx)*e_)%Qx,e&Jx&&(s^=Gi<<(Gi<<BigInt(n))-Gi);kp.push(s)}const jp=Pp(kp,!0),t_=jp[0],r_=jp[1],Pu=(t,e,r)=>r>32?Mx(t,e,r):Fx(t,e,r),Bu=(t,e,r)=>r>32?qx(t,e,r):Lx(t,e,r);function i_(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Pu(l,u,1)^r[a],f=Bu(l,u,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Np[o],c=Pu(s,n,a),l=Bu(s,n,a),u=Up[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=t_[i],t[1]^=r_[i]}Et(r)}let s_=class Fp extends Gn{constructor(e,r,i,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,ur(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ms(this.state)}clone(){return this._cloneInto()}keccak(){$r(this.state32),i_(this.state32,this.rounds),$r(this.state32),this.posOut=0,this.pos=0}update(e){Ur(this),e=At(e),Pt(e);const{blockLen:r,state:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ur(this,!1),Pt(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ur(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Fc(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,Et(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Fp(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const n_=(t,e,r)=>As(()=>new s_(e,t,r)),o_=n_(1,136,256/8);function a_(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function c_(t,e,r){return t&e^~t&r}function l_(t,e,r){return t&e^t&r^e&r}let Lp=class extends Gn{constructor(e,r,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=No(this.buffer)}update(e){Ur(this),e=At(e),Pt(e);const{view:r,buffer:i,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=No(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ur(this),Fc(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,Et(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;a_(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=No(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}};const br=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),je=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Fe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),u_=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]),vr=new Uint32Array(64);class h_ extends Lp{constructor(e=32){super(64,e,8,!1),this.A=br[0]|0,this.B=br[1]|0,this.C=br[2]|0,this.D=br[3]|0,this.E=br[4]|0,this.F=br[5]|0,this.G=br[6]|0,this.H=br[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)vr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=vr[h-15],d=vr[h-2],g=Tt(f,7)^Tt(f,18)^f>>>3,w=Tt(d,17)^Tt(d,19)^d>>>10;vr[h]=w+vr[h-7]+g+vr[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=Tt(a,6)^Tt(a,11)^Tt(a,25),d=u+f+c_(a,c,l)+u_[h]+vr[h]|0,g=(Tt(i,2)^Tt(i,13)^Tt(i,22))+l_(i,s,n)|0;u=l,l=c,c=a,a=o+d|0,o=n,n=s,s=i,i=d+g|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,s,n,o,a,c,l,u)}roundClean(){Et(vr)}destroy(){this.set(0,0,0,0,0,0,0,0),Et(this.buffer)}}const Mp=Pp(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),f_=Mp[0],d_=Mp[1],Er=new Uint32Array(80),xr=new Uint32Array(80);let Lc=class extends Lp{constructor(e=64){super(128,e,16,!1),this.Ah=Fe[0]|0,this.Al=Fe[1]|0,this.Bh=Fe[2]|0,this.Bl=Fe[3]|0,this.Ch=Fe[4]|0,this.Cl=Fe[5]|0,this.Dh=Fe[6]|0,this.Dl=Fe[7]|0,this.Eh=Fe[8]|0,this.El=Fe[9]|0,this.Fh=Fe[10]|0,this.Fl=Fe[11]|0,this.Gh=Fe[12]|0,this.Gl=Fe[13]|0,this.Hh=Fe[14]|0,this.Hl=Fe[15]|0}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:d,Gl:g,Hh:w,Hl:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=g|0,this.Hh=w|0,this.Hl=m|0}process(e,r){for(let b=0;b<16;b++,r+=4)Er[b]=e.getUint32(r),xr[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const x=Er[b-15]|0,A=xr[b-15]|0,B=Sr(x,A,1)^Sr(x,A,8)^$u(x,A,7),T=Or(x,A,1)^Or(x,A,8)^Du(x,A,7),R=Er[b-2]|0,D=xr[b-2]|0,k=Sr(R,D,19)^ss(R,D,61)^$u(R,D,6),j=Or(R,D,19)^ns(R,D,61)^Du(R,D,6),P=zx(T,j,xr[b-7],xr[b-16]),I=Vx(P,B,k,Er[b-7],Er[b-16]);Er[b]=I|0,xr[b]=P|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:d,Fl:g,Gh:w,Gl:m,Hh:O,Hl:C}=this;for(let b=0;b<80;b++){const x=Sr(h,f,14)^Sr(h,f,18)^ss(h,f,41),A=Or(h,f,14)^Or(h,f,18)^ns(h,f,41),B=h&d^~h&w,T=f&g^~f&m,R=Hx(C,A,T,d_[b],xr[b]),D=Kx(R,O,x,B,f_[b],Er[b]),k=R|0,j=Sr(i,s,28)^ss(i,s,34)^ss(i,s,39),P=Or(i,s,28)^ns(i,s,34)^ns(i,s,39),I=i&n^i&a^n&a,$=s&o^s&c^o&c;O=w|0,C=m|0,w=d|0,m=g|0,d=h|0,g=f|0,{h,l:f}=$t(l|0,u|0,D|0,k|0),l=a|0,u=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const p=kc(k,P,$);i=jc(p,D,j,I),s=p|0}({h:i,l:s}=$t(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=$t(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=$t(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=$t(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=$t(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:g}=$t(this.Fh|0,this.Fl|0,d|0,g|0),{h:w,l:m}=$t(this.Gh|0,this.Gl|0,w|0,m|0),{h:O,l:C}=$t(this.Hh|0,this.Hl|0,O|0,C|0),this.set(i,s,n,o,a,c,l,u,h,f,d,g,w,m,O,C)}roundClean(){Et(Er,xr)}destroy(){Et(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class p_ extends Lc{constructor(){super(48),this.Ah=je[0]|0,this.Al=je[1]|0,this.Bh=je[2]|0,this.Bl=je[3]|0,this.Ch=je[4]|0,this.Cl=je[5]|0,this.Dh=je[6]|0,this.Dl=je[7]|0,this.Eh=je[8]|0,this.El=je[9]|0,this.Fh=je[10]|0,this.Fl=je[11]|0,this.Gh=je[12]|0,this.Gl=je[13]|0,this.Hh=je[14]|0,this.Hl=je[15]|0}}const Le=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class g_ extends Lc{constructor(){super(32),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const Yn=As(()=>new h_),y_=As(()=>new Lc),w_=As(()=>new p_),m_=As(()=>new g_),b_=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]),be=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);function _r(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=H[2*t],l=H[2*t+1],u=H[2*e],h=H[2*e+1],f=H[2*r],d=H[2*r+1],g=H[2*i],w=H[2*i+1],m=kc(c,u,o);l=jc(m,l,h,a),c=m|0,{Dh:w,Dl:g}={Dh:w^l,Dl:g^c},{Dh:w,Dl:g}={Dh:kx(w,g),Dl:jx(w)},{h:d,l:f}=$t(d,f,w,g),{Bh:h,Bl:u}={Bh:h^d,Bl:u^f},{Bh:h,Bl:u}={Bh:Sr(h,u,24),Bl:Or(h,u,24)},H[2*t]=c,H[2*t+1]=l,H[2*e]=u,H[2*e+1]=h,H[2*r]=f,H[2*r+1]=d,H[2*i]=g,H[2*i+1]=w}function Ir(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=H[2*t],l=H[2*t+1],u=H[2*e],h=H[2*e+1],f=H[2*r],d=H[2*r+1],g=H[2*i],w=H[2*i+1],m=kc(c,u,o);l=jc(m,l,h,a),c=m|0,{Dh:w,Dl:g}={Dh:w^l,Dl:g^c},{Dh:w,Dl:g}={Dh:Sr(w,g,16),Dl:Or(w,g,16)},{h:d,l:f}=$t(d,f,w,g),{Bh:h,Bl:u}={Bh:h^d,Bl:u^f},{Bh:h,Bl:u}={Bh:ss(h,u,63),Bl:ns(h,u,63)},H[2*t]=c,H[2*t+1]=l,H[2*e]=u,H[2*e+1]=h,H[2*r]=f,H[2*r+1]=d,H[2*i]=g,H[2*i+1]=w}function v_(t,e={},r,i,s){if(ur(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=e;if(n!==void 0&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class E_ extends Gn{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ur(e),ur(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=ms(this.buffer)}update(e){Ur(this),e=At(e),Pt(e);const{blockLen:r,buffer:i,buffer32:s}=this,n=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<n;){this.pos===r&&($r(s),this.compress(s,0,!1),$r(s),this.pos=0);const l=Math.min(r-this.pos,n-c),u=o+c;if(l===r&&!(u%4)&&c+l<n){const h=new Uint32Array(a,u,Math.floor((n-c)/4));$r(h);for(let f=0;c+r<n;f+=s.length,c+=r)this.length+=r,this.compress(h,f,!1);$r(h);continue}i.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Ur(this),Fc(e,this);const{pos:r,buffer32:i}=this;this.finished=!0,Et(this.buffer.subarray(r)),$r(i),this.compress(i,0,!0),$r(i);const s=ms(e);this.get().forEach((n,o)=>s[o]=er(n))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){const{buffer:r,length:i,finished:s,destroyed:n,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=n,e.finished=s,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class x_ extends E_{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=be[0]|0,this.v0h=be[1]|0,this.v1l=be[2]|0,this.v1h=be[3]|0,this.v2l=be[4]|0,this.v2h=be[5]|0,this.v3l=be[6]|0,this.v3h=be[7]|0,this.v4l=be[8]|0,this.v4h=be[9]|0,this.v5l=be[10]|0,this.v5h=be[11]|0,this.v6l=be[12]|0,this.v6h=be[13]|0,this.v7l=be[14]|0,this.v7h=be[15]|0,v_(r,e,64,16,16);let{key:i,personalization:s,salt:n}=e,o=0;if(i!==void 0&&(i=At(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,n!==void 0){n=At(n);const a=ms(n);this.v4l^=er(a[0]),this.v4h^=er(a[1]),this.v5l^=er(a[2]),this.v5h^=er(a[3])}if(s!==void 0){s=At(s);const a=ms(s);this.v6l^=er(a[0]),this.v6h^=er(a[1]),this.v7l^=er(a[2]),this.v7h^=er(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:i,v1h:s,v2l:n,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:h,v5h:f,v6l:d,v6h:g,v7l:w,v7h:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,d,g,w,m){this.v0l=e|0,this.v0h=r|0,this.v1l=i|0,this.v1h=s|0,this.v2l=n|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=h|0,this.v5h=f|0,this.v6l=d|0,this.v6h=g|0,this.v7l=w|0,this.v7h=m|0}compress(e,r,i){this.get().forEach((c,l)=>H[l]=c),H.set(be,16);let{h:s,l:n}=Ap(BigInt(this.length));H[24]=be[8]^n,H[25]=be[9]^s,i&&(H[28]=~H[28],H[29]=~H[29]);let o=0;const a=b_;for(let c=0;c<12;c++)_r(0,4,8,12,e,r+2*a[o++]),Ir(0,4,8,12,e,r+2*a[o++]),_r(1,5,9,13,e,r+2*a[o++]),Ir(1,5,9,13,e,r+2*a[o++]),_r(2,6,10,14,e,r+2*a[o++]),Ir(2,6,10,14,e,r+2*a[o++]),_r(3,7,11,15,e,r+2*a[o++]),Ir(3,7,11,15,e,r+2*a[o++]),_r(0,5,10,15,e,r+2*a[o++]),Ir(0,5,10,15,e,r+2*a[o++]),_r(1,6,11,12,e,r+2*a[o++]),Ir(1,6,11,12,e,r+2*a[o++]),_r(2,7,8,13,e,r+2*a[o++]),Ir(2,7,8,13,e,r+2*a[o++]),_r(3,4,9,14,e,r+2*a[o++]),Ir(3,4,9,14,e,r+2*a[o++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],Et(H)}destroy(){this.destroyed=!0,Et(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const __=Yx(t=>new x_(t)),I_="https://rpc.walletconnect.org/v1";function qp(t){const e=`Ethereum Signed Message:
19
+ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(o_(r)).toString("hex")}async function S_(t,e,r,i,s,n){switch(r.t){case"eip191":return await O_(t,e,r.s);case"eip1271":return await $_(t,e,r.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function O_(t,e,r){const i=vm(r);return Tm({payload:qp(e),signature:i}).toLowerCase()===t.toLowerCase()}async function $_(t,e,r,i,s,n){const o=cr(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=r.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:qp(e)).substring(2),f=a+h+c+u+l,d=await fetch(`${n||I_}/?chainId=${i}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:D_(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:g}=await d.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function D_(){return Date.now()+Math.floor(Math.random()*1e3)}function A_(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(r.length<s)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const n=Buffer.from(t,"base64").slice(1,65);return Ss.encode(n)}function P_(t){const e=new Uint8Array(Buffer.from(t,"base64")),r=Array.from("TransactionData::").map(n=>n.charCodeAt(0)),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length);const s=__(i,{dkLen:32});return Ss.encode(s)}function Cu(t){const e=new Uint8Array(Yn(B_(t)));return Ss.encode(e)}function B_(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Tu(t){const e=Buffer.from(t,"base64"),r=mb(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const i=lb(r),s=Buffer.from("TX"),n=Buffer.concat([s,Buffer.from(i)]),o=m_(n);return Cm.encode(o).replace(/=+$/,"")}function ko(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),Buffer.from(e)}function C_(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),r=Buffer.from(t.signed.authInfoBytes,"base64"),i=Buffer.from(t.signature.signature,"base64"),s=[];s.push(Buffer.from([10])),s.push(ko(e.length)),s.push(e),s.push(Buffer.from([18])),s.push(ko(r.length)),s.push(r),s.push(Buffer.from([26])),s.push(ko(i.length)),s.push(i);const n=Buffer.concat(s),o=Yn(n);return Buffer.from(o).toString("hex").toUpperCase()}function T_(t){var e,r;const i=[];try{if(typeof t=="string")return i.push(t),i;if(typeof t!="object")return i;t!=null&&t.id&&i.push(t.id);const s=(r=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:r.transactionHashes;s&&i.push(...s)}catch(s){console.warn("getWalletSendCallsHashes failed: ",s)}return i}var R_=Object.defineProperty,U_=Object.defineProperties,N_=Object.getOwnPropertyDescriptors,Ru=Object.getOwnPropertySymbols,k_=Object.prototype.hasOwnProperty,j_=Object.prototype.propertyIsEnumerable,Uu=(t,e,r)=>e in t?R_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,F_=(t,e)=>{for(var r in e||(e={}))k_.call(e,r)&&Uu(t,r,e[r]);if(Ru)for(var r of Ru(e))j_.call(e,r)&&Uu(t,r,e[r]);return t},L_=(t,e)=>U_(t,N_(e));const zp="did:pkh:",M_={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},q_=t=>t?M_[t]||t:"",Zn=t=>t==null?void 0:t.split(":"),z_=t=>{const e=t&&Zn(t);if(e)return t.includes(zp)?e[3]:e[1]},V_=t=>{const e=t&&Zn(t);if(e)return t.includes(zp)?e[2]:e[0]},Ba=t=>{const e=t&&Zn(t);if(e)return e[2]+":"+e[3]},Dn=t=>{const e=t&&Zn(t);if(e)return e.pop()};async function Nu(t){const{cacao:e,projectId:r}=t,{s:i,p:s}=e,n=Vp(s,s.iss),o=Dn(s.iss);return await S_(o,n,i,Ba(s.iss),r)}const Vp=(t,e)=>{const r=V_(e);if(!r)throw new Error("Invalid issuer: "+e);const i=`${t.domain} wants you to sign in with your ${q_(r)} account:`,s=Dn(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=t.statement||void 0;const o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${z_(e)}`,l=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,g=t.resources?`Resources:${t.resources.map(m=>`
20
+ - ${m}`).join("")}`:void 0,w=ln(t.resources);if(w){const m=bs(w);n=Q_(n,m)}return[i,s,"",n,"",o,a,c,l,u,h,f,d,g].filter(m=>m!=null).join(`
21
+ `)};function H_(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function K_(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function ni(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function W_(t,e,r,i={}){return r==null||r.sort((s,n)=>s.localeCompare(n)),{att:{[t]:G_(e,r,i)}}}function G_(t,e,r={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${t}/${s}`]:[r]}));return Object.assign({},...i)}function Hp(t){return ni(t),`urn:recap:${H_(t).replace(/=/g,"")}`}function bs(t){const e=K_(t.replace("urn:recap:",""));return ni(e),e}function Y_(t,e,r){const i=W_(t,e,r);return Hp(i)}function Z_(t){return t&&t.includes("urn:recap:")}function J_(t,e){const r=bs(t),i=bs(e),s=X_(r,i);return Hp(s)}function X_(t,e){ni(t),ni(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return r.forEach(s=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;i.att[s]=L_(F_({},i.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((l=e.att[s])==null?void 0:l[a])})})}),i}function Q_(t="",e){ni(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const l={};c.forEach(h=>{l[h.ability]||(l[h.ability]=[]),l[h.ability].push(h.action)});const u=Object.keys(l).map(h=>(s++,`(${s}) '${h}': '${l[h].join("', '")}' for '${a}'.`));i.push(u.join(", ").replace(".,","."))});const n=i.join(" "),o=`${r}${n}`;return`${t?t+" ":""}${o}`}function ku(t){var e;const r=bs(t);ni(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function ju(t){const e=bs(t);ni(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&r.push(s[0].chains)})}),[...new Set(r.flat())]}function ln(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return Z_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Kp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ca(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function jo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Xe(t,...e){if(!Kp(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Fu(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function e3(t,e){Xe(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Tr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ri(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function t3(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const r3=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function i3(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ta(t){if(typeof t=="string")t=i3(t);else if(Kp(t))t=Ra(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function s3(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function n3(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const o3=(t,e)=>{function r(i,...s){if(Xe(i),!r3)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=s[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?Xe(l):Xe(l,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&Xe(s[1]);const o=e(i,...s),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");Xe(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Xe(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(Xe(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(r,t),r};function Lu(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!c3(e))throw new Error("invalid output, must be aligned");return e}function Mu(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n);t.setUint32(e+4,o,i),t.setUint32(e+0,a,i)}function a3(t,e,r){Ca(r);const i=new Uint8Array(16),s=t3(i);return Mu(s,0,BigInt(e),r),Mu(s,8,BigInt(t),r),i}function c3(t){return t.byteOffset%4===0}function Ra(t){return Uint8Array.from(t)}const Wp=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),l3=Wp("expand 16-byte k"),u3=Wp("expand 32-byte k"),h3=Tr(l3),f3=Tr(u3);function te(t,e){return t<<e|t>>>32-e}function Ua(t){return t.byteOffset%4===0}const Gs=64,d3=16,Gp=2**32-1,qu=new Uint32Array;function p3(t,e,r,i,s,n,o,a){const c=s.length,l=new Uint8Array(Gs),u=Tr(l),h=Ua(s)&&Ua(n),f=h?Tr(s):qu,d=h?Tr(n):qu;for(let g=0;g<c;o++){if(t(e,r,i,u,o,a),o>=Gp)throw new Error("arx: counter overflow");const w=Math.min(Gs,c-g);if(h&&w===Gs){const m=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let O=0,C;O<d3;O++)C=m+O,d[C]=f[C]^u[O];g+=Gs;continue}for(let m=0,O;m<w;m++)O=g+m,n[O]=s[O]^l[m];g+=w}}function g3(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=s3({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return jo(s),jo(o),Ca(n),Ca(r),(a,c,l,u,h=0)=>{Xe(a),Xe(c),Xe(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),Xe(u),jo(h),h<0||h>=Gp)throw new Error("arx: counter overflow");if(u.length<f)throw new Error(`arx: output (${u.length}) is shorter than data (${f})`);const d=[];let g=a.length,w,m;if(g===32)d.push(w=Ra(a)),m=f3;else if(g===16&&r)w=new Uint8Array(32),w.set(a),w.set(a,16),m=h3,d.push(w);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);Ua(c)||d.push(c=Ra(c));const O=Tr(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(m,O,Tr(c.subarray(0,16)),O),c=c.subarray(16)}const C=16-s;if(C!==c.length)throw new Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){const x=new Uint8Array(12);x.set(c,n?0:12-c.length),c=x,d.push(c)}const b=Tr(c);return p3(t,m,O,b,l,u,h,o),Ri(...d),u}}const Ae=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class y3{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Ta(e),Xe(e,32);const r=Ae(e,0),i=Ae(e,2),s=Ae(e,4),n=Ae(e,6),o=Ae(e,8),a=Ae(e,10),c=Ae(e,12),l=Ae(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ae(e,16+2*u)}process(e,r,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],h=o[4],f=o[5],d=o[6],g=o[7],w=o[8],m=o[9],O=Ae(e,r+0),C=Ae(e,r+2),b=Ae(e,r+4),x=Ae(e,r+6),A=Ae(e,r+8),B=Ae(e,r+10),T=Ae(e,r+12),R=Ae(e,r+14);let D=n[0]+(O&8191),k=n[1]+((O>>>13|C<<3)&8191),j=n[2]+((C>>>10|b<<6)&8191),P=n[3]+((b>>>7|x<<9)&8191),I=n[4]+((x>>>4|A<<12)&8191),$=n[5]+(A>>>1&8191),p=n[6]+((A>>>14|B<<2)&8191),y=n[7]+((B>>>11|T<<5)&8191),v=n[8]+((T>>>8|R<<8)&8191),S=n[9]+(R>>>5|s),E=0,_=E+D*a+k*(5*m)+j*(5*w)+P*(5*g)+I*(5*d);E=_>>>13,_&=8191,_+=$*(5*f)+p*(5*h)+y*(5*u)+v*(5*l)+S*(5*c),E+=_>>>13,_&=8191;let U=E+D*c+k*a+j*(5*m)+P*(5*w)+I*(5*g);E=U>>>13,U&=8191,U+=$*(5*d)+p*(5*f)+y*(5*h)+v*(5*u)+S*(5*l),E+=U>>>13,U&=8191;let N=E+D*l+k*c+j*a+P*(5*m)+I*(5*w);E=N>>>13,N&=8191,N+=$*(5*g)+p*(5*d)+y*(5*f)+v*(5*h)+S*(5*u),E+=N>>>13,N&=8191;let V=E+D*u+k*l+j*c+P*a+I*(5*m);E=V>>>13,V&=8191,V+=$*(5*w)+p*(5*g)+y*(5*d)+v*(5*f)+S*(5*h),E+=V>>>13,V&=8191;let L=E+D*h+k*u+j*l+P*c+I*a;E=L>>>13,L&=8191,L+=$*(5*m)+p*(5*w)+y*(5*g)+v*(5*d)+S*(5*f),E+=L>>>13,L&=8191;let M=E+D*f+k*h+j*u+P*l+I*c;E=M>>>13,M&=8191,M+=$*a+p*(5*m)+y*(5*w)+v*(5*g)+S*(5*d),E+=M>>>13,M&=8191;let K=E+D*d+k*f+j*h+P*u+I*l;E=K>>>13,K&=8191,K+=$*c+p*a+y*(5*m)+v*(5*w)+S*(5*g),E+=K>>>13,K&=8191;let G=E+D*g+k*d+j*f+P*h+I*u;E=G>>>13,G&=8191,G+=$*l+p*c+y*a+v*(5*m)+S*(5*w),E+=G>>>13,G&=8191;let J=E+D*w+k*g+j*d+P*f+I*h;E=J>>>13,J&=8191,J+=$*u+p*l+y*c+v*a+S*(5*m),E+=J>>>13,J&=8191;let W=E+D*m+k*w+j*g+P*d+I*f;E=W>>>13,W&=8191,W+=$*h+p*u+y*l+v*c+S*a,E+=W>>>13,W&=8191,E=(E<<2)+E|0,E=E+_|0,_=E&8191,E=E>>>13,U+=E,n[0]=_,n[1]=U,n[2]=N,n[3]=V,n[4]=L,n[5]=M,n[6]=K,n[7]=G,n[8]=J,n[9]=W}finalize(){const{h:e,pad:r}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ri(i)}update(e){Fu(this),e=Ta(e),Xe(e);const{buffer:r,blockLen:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}r.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Ri(this.h,this.r,this.buffer,this.pad)}digestInto(e){Fu(this),e3(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function w3(t){const e=(i,s)=>t(s).update(Ta(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const m3=w3(t=>new y3(t));function b3(t,e,r,i,s,n=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],f=e[2],d=e[3],g=e[4],w=e[5],m=e[6],O=e[7],C=s,b=r[0],x=r[1],A=r[2],B=o,T=a,R=c,D=l,k=u,j=h,P=f,I=d,$=g,p=w,y=m,v=O,S=C,E=b,_=x,U=A;for(let V=0;V<n;V+=2)B=B+k|0,S=te(S^B,16),$=$+S|0,k=te(k^$,12),B=B+k|0,S=te(S^B,8),$=$+S|0,k=te(k^$,7),T=T+j|0,E=te(E^T,16),p=p+E|0,j=te(j^p,12),T=T+j|0,E=te(E^T,8),p=p+E|0,j=te(j^p,7),R=R+P|0,_=te(_^R,16),y=y+_|0,P=te(P^y,12),R=R+P|0,_=te(_^R,8),y=y+_|0,P=te(P^y,7),D=D+I|0,U=te(U^D,16),v=v+U|0,I=te(I^v,12),D=D+I|0,U=te(U^D,8),v=v+U|0,I=te(I^v,7),B=B+j|0,U=te(U^B,16),y=y+U|0,j=te(j^y,12),B=B+j|0,U=te(U^B,8),y=y+U|0,j=te(j^y,7),T=T+P|0,S=te(S^T,16),v=v+S|0,P=te(P^v,12),T=T+P|0,S=te(S^T,8),v=v+S|0,P=te(P^v,7),R=R+I|0,E=te(E^R,16),$=$+E|0,I=te(I^$,12),R=R+I|0,E=te(E^R,8),$=$+E|0,I=te(I^$,7),D=D+k|0,_=te(_^D,16),p=p+_|0,k=te(k^p,12),D=D+k|0,_=te(_^D,8),p=p+_|0,k=te(k^p,7);let N=0;i[N++]=o+B|0,i[N++]=a+T|0,i[N++]=c+R|0,i[N++]=l+D|0,i[N++]=u+k|0,i[N++]=h+j|0,i[N++]=f+P|0,i[N++]=d+I|0,i[N++]=g+$|0,i[N++]=w+p|0,i[N++]=m+y|0,i[N++]=O+v|0,i[N++]=C+S|0,i[N++]=b+E|0,i[N++]=x+_|0,i[N++]=A+U|0}const v3=g3(b3,{counterRight:!1,counterLength:4,allowShortKeys:!1}),E3=new Uint8Array(16),zu=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(E3.subarray(r))},x3=new Uint8Array(32);function Vu(t,e,r,i,s){const n=t(e,r,x3),o=m3.create(n);s&&zu(o,s),zu(o,i);const a=a3(i.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Ri(n,a),c}const _3=t=>(e,r,i)=>({encrypt(s,n){const o=s.length;n=Lu(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,r,a,a,1);const c=Vu(t,e,r,a,i);return n.set(c,o),Ri(c),n},decrypt(s,n){n=Lu(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=Vu(t,e,r,o,i);if(!n3(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,r,n,n,1),Ri(c),n}}),Yp=o3({blockSize:64,nonceLength:12,tagLength:16},_3(v3));let Zp=class extends Gn{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Wn(e);const i=At(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Et(n)}update(e){return Ur(this),this.iHash.update(e),this}digestInto(e){Ur(this),Pt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Jn=(t,e,r)=>new Zp(t,e).update(r).digest();Jn.create=(t,e)=>new Zp(t,e);function I3(t,e,r){return Wn(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Jn(t,At(r),At(e))}const Fo=Uint8Array.from([0]),Hu=Uint8Array.of();function S3(t,e,r,i=32){Wn(t),ur(i);const s=t.outputLen;if(i>255*s)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(i/s);r===void 0&&(r=Hu);const o=new Uint8Array(n*s),a=Jn.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<n;u++)Fo[0]=u+1,c.update(u===0?Hu:l).update(r).update(Fo).digestInto(l),o.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),Et(l,Fo),o.slice(0,i)}const O3=(t,e,r,i,s)=>S3(t,I3(t,e,r),i,s),Xn=Yn,Mc=BigInt(0),Na=BigInt(1);function An(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Jr(t,e,r=""){const i=Kn(t),s=t==null?void 0:t.length,n=e!==void 0;if(!i||n&&s!==e){const o=r&&`"${r}" `,a=n?` of length ${e}`:"",c=i?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Ys(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Jp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Mc:BigInt("0x"+t)}function Qn(t){return Jp(Di(t))}function Pn(t){return Pt(t),Jp(Di(Uint8Array.from(t).reverse()))}function qc(t,e){return $n(t.toString(16).padStart(e*2,"0"))}function zc(t,e){return qc(t,e).reverse()}function qe(t,e,r){let i;if(typeof e=="string")try{i=$n(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Kn(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}const Lo=t=>typeof t=="bigint"&&Mc<=t;function $3(t,e,r){return Lo(t)&&Lo(e)&&Lo(r)&&e<=t&&t<r}function ka(t,e,r,i){if(!$3(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function Xp(t){let e;for(e=0;t>Mc;t>>=Na,e+=1);return e}const Ps=t=>(Na<<BigInt(t))-Na;function D3(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const i=f=>new Uint8Array(f),s=f=>Uint8Array.of(f);let n=i(t),o=i(t),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},l=(...f)=>r(o,n,...f),u=(f=i(0))=>{o=l(s(0),f),n=l(),f.length!==0&&(o=l(s(1),f),n=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){n=l();const g=n.slice();d.push(g),f+=n.length}return Ar(...d)};return(f,d)=>{c(),u(f);let g;for(;!(g=d(h()));)u();return c(),g}}function eo(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function i(s,n,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==n||a===null)throw new Error(`param "${s}" is invalid: expected ${n}, got ${c}`)}Object.entries(e).forEach(([s,n])=>i(s,n,!1)),Object.entries(r).forEach(([s,n])=>i(s,n,!0))}function Ku(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const tt=BigInt(0),He=BigInt(1),Xr=BigInt(2),Qp=BigInt(3),eg=BigInt(4),tg=BigInt(5),A3=BigInt(7),rg=BigInt(8),P3=BigInt(9),ig=BigInt(16);function lt(t,e){const r=t%e;return r>=tt?r:e+r}function Ot(t,e,r){let i=t;for(;e-- >tt;)i*=i,i%=r;return i}function Wu(t,e){if(t===tt)throw new Error("invert: expected non-zero number");if(e<=tt)throw new Error("invert: expected positive modulus, got "+e);let r=lt(t,e),i=e,s=tt,n=He;for(;r!==tt;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==He)throw new Error("invert: does not exist");return lt(s,e)}function Vc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function sg(t,e){const r=(t.ORDER+He)/eg,i=t.pow(e,r);return Vc(t,i,e),i}function B3(t,e){const r=(t.ORDER-tg)/rg,i=t.mul(e,Xr),s=t.pow(i,r),n=t.mul(e,s),o=t.mul(t.mul(n,Xr),s),a=t.mul(n,t.sub(o,t.ONE));return Vc(t,a,e),a}function C3(t){const e=kr(t),r=ng(t),i=r(e,e.neg(e.ONE)),s=r(e,i),n=r(e,e.neg(i)),o=(t+A3)/ig;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,i);const h=a.mul(l,s),f=a.mul(l,n),d=a.eql(a.sqr(u),c),g=a.eql(a.sqr(h),c);l=a.cmov(l,u,d),u=a.cmov(f,h,g);const w=a.eql(a.sqr(u),c),m=a.cmov(l,u,w);return Vc(a,m,c),m}}function ng(t){if(t<Qp)throw new Error("sqrt is not defined for small field");let e=t-He,r=0;for(;e%Xr===tt;)e/=Xr,r++;let i=Xr;const s=kr(t);for(;Gu(s,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return sg;let n=s.pow(i,e);const o=(e+He)/Xr;return function(a,c){if(a.is0(c))return c;if(Gu(a,c)!==1)throw new Error("Cannot find square root");let l=r,u=a.mul(a.ONE,n),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let d=1,g=a.sqr(h);for(;!a.eql(g,a.ONE);)if(d++,g=a.sqr(g),d===l)throw new Error("Cannot find square root");const w=He<<BigInt(l-d-1),m=a.pow(u,w);l=d,u=a.sqr(m),h=a.mul(h,u),f=a.mul(f,m)}return f}}function T3(t){return t%eg===Qp?sg:t%rg===tg?B3:t%ig===P3?C3(t):ng(t)}const R3=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function U3(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=R3.reduce((i,s)=>(i[s]="function",i),e);return eo(t,r),t}function N3(t,e,r){if(r<tt)throw new Error("invalid exponent, negatives unsupported");if(r===tt)return t.ONE;if(r===He)return e;let i=t.ONE,s=e;for(;r>tt;)r&He&&(i=t.mul(i,s)),s=t.sqr(s),r>>=He;return i}function og(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),n),i}function Gu(t,e){const r=(t.ORDER-He)/Xr,i=t.pow(e,r),s=t.eql(i,t.ONE),n=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function ag(t,e){e!==void 0&&ur(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function kr(t,e,r=!1,i={}){if(t<=tt)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,n,o=!1,a;if(typeof e=="object"&&e!=null){if(i.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(s=f.BITS),f.sqrt&&(n=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),i.sqrt&&(n=i.sqrt);const{nBitLength:c,nByteLength:l}=ag(t,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:Ps(c),ZERO:tt,ONE:He,allowedLengths:a,create:f=>lt(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return tt<=f&&f<t},is0:f=>f===tt,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&He)===He,neg:f=>lt(-f,t),eql:(f,d)=>f===d,sqr:f=>lt(f*f,t),add:(f,d)=>lt(f+d,t),sub:(f,d)=>lt(f-d,t),mul:(f,d)=>lt(f*d,t),pow:(f,d)=>N3(h,f,d),div:(f,d)=>lt(f*Wu(d,t),t),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Wu(f,t),sqrt:n||(f=>(u||(u=T3(t)),u(h,f))),toBytes:f=>r?zc(f,l):qc(f,l),fromBytes:(f,d=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const w=new Uint8Array(l);w.set(f,r?0:w.length-f.length),f=w}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=r?Pn(f):Qn(f);if(o&&(g=lt(g,t)),!d&&!h.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>og(h,f),cmov:(f,d,g)=>g?d:f});return Object.freeze(h)}function cg(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function lg(t){const e=cg(t);return e+Math.ceil(e/2)}function k3(t,e,r=!1){const i=t.length,s=cg(e),n=lg(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?Pn(t):Qn(t),a=lt(o,e-He)+He;return r?zc(a,s):qc(a,s)}const Ui=BigInt(0),Qr=BigInt(1);function Bn(t,e){const r=e.negate();return t?r:e}function Mo(t,e){const r=og(t.Fp,e.map(i=>i.Z));return e.map((i,s)=>t.fromAffine(i.toAffine(r[s])))}function ug(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function qo(t,e){ug(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),s=2**t,n=Ps(t),o=BigInt(t);return{windows:r,windowSize:i,mask:n,maxNumber:s,shiftBy:o}}function Yu(t,e,r){const{windowSize:i,mask:s,maxNumber:n,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>i&&(a-=n,c+=Qr);const l=e*i,u=l+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:l}}function j3(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function F3(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const zo=new WeakMap,hg=new WeakMap;function Vo(t){return hg.get(t)||1}function Zu(t){if(t!==Ui)throw new Error("invalid wNAF")}class L3{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,i=this.ZERO){let s=e;for(;r>Ui;)r&Qr&&(i=i.add(s)),s=s.double(),r>>=Qr;return i}precomputeWindow(e,r){const{windows:i,windowSize:s}=qo(r,this.bits),n=[];let o=e,a=o;for(let c=0;c<i;c++){a=o,n.push(a);for(let l=1;l<s;l++)a=a.add(o),n.push(a);o=a.double()}return n}wNAF(e,r,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let s=this.ZERO,n=this.BASE;const o=qo(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:d}=Yu(i,a,o);i=c,u?n=n.add(Bn(f,r[d])):s=s.add(Bn(h,r[l]))}return Zu(i),{p:s,f:n}}wNAFUnsafe(e,r,i,s=this.ZERO){const n=qo(e,this.bits);for(let o=0;o<n.windows&&i!==Ui;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Yu(i,o,n);if(i=a,!l){const h=r[c];s=s.add(u?h.negate():h)}}return Zu(i),s}getPrecomputes(e,r,i){let s=zo.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof i=="function"&&(s=i(s)),zo.set(r,s))),s}cached(e,r,i){const s=Vo(e);return this.wNAF(s,this.getPrecomputes(s,e,i),r)}unsafe(e,r,i,s){const n=Vo(e);return n===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(n,this.getPrecomputes(n,e,i),r,s)}createCache(e,r){ug(r,this.bits),hg.set(e,r),zo.delete(e)}hasCache(e){return Vo(e)!==1}}function M3(t,e,r,i){let s=e,n=t.ZERO,o=t.ZERO;for(;r>Ui||i>Ui;)r&Qr&&(n=n.add(s)),i&Qr&&(o=o.add(s)),s=s.double(),r>>=Qr,i>>=Qr;return{p1:n,p2:o}}function q3(t,e,r,i){j3(r,t),F3(i,e);const s=r.length,n=i.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Xp(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ps(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){u.fill(o);for(let w=0;w<n;w++){const m=i[w],O=Number(m>>BigInt(d)&l);u[O]=u[O].add(r[w])}let g=o;for(let w=u.length-1,m=o;w>0;w--)m=m.add(u[w]),g=g.add(m);if(f=f.add(g),d!==0)for(let w=0;w<c;w++)f=f.double()}return f}function Ju(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return U3(e),e}else return kr(t,{isLE:r})}function z3(t,e,r={},i){if(i===void 0&&(i=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>Ui))throw new Error(`CURVE.${a} must be positive bigint`)}const s=Ju(e.p,r.Fp,i),n=Ju(e.n,r.Fn,i),o=["Gx","Gy","a","b"];for(const a of o)if(!s.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:n}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Rp("HashToScalar-");const Yi=BigInt(0),wi=BigInt(1),Zs=BigInt(2);function V3(t){return eo(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function H3(t){const e=V3(t),{P:r,type:i,adjustScalarBytes:s,powPminus2:n,randomBytes:o}=e,a=i==="x25519";if(!a&&i!=="x448")throw new Error("invalid type");const c=o||ci,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),d=a?Zs**BigInt(254):Zs**BigInt(447),g=a?BigInt(8)*Zs**BigInt(251)-wi:BigInt(4)*Zs**BigInt(445)-wi,w=d+g+wi,m=P=>lt(P,r),O=C(h);function C(P){return zc(m(P),u)}function b(P){const I=qe("u coordinate",P,u);return a&&(I[31]&=127),m(Pn(I))}function x(P){return Pn(s(qe("scalar",P,u)))}function A(P,I){const $=R(b(I),x(P));if($===Yi)throw new Error("invalid private or public key received");return C($)}function B(P){return A(P,O)}function T(P,I,$){const p=m(P*(I-$));return I=m(I-p),$=m($+p),{x_2:I,x_3:$}}function R(P,I){ka("u",P,Yi,r),ka("scalar",I,d,w);const $=I,p=P;let y=wi,v=Yi,S=P,E=wi,_=Yi;for(let N=BigInt(l-1);N>=Yi;N--){const V=$>>N&wi;_^=V,{x_2:y,x_3:S}=T(_,y,S),{x_2:v,x_3:E}=T(_,v,E),_=V;const L=y+v,M=m(L*L),K=y-v,G=m(K*K),J=M-G,W=S+E,X=S-E,fe=m(X*L),me=m(W*K),Ee=fe+me,ze=fe-me;S=m(Ee*Ee),E=m(p*m(ze*ze)),y=m(M*G),v=m(J*(M+m(f*J)))}({x_2:y,x_3:S}=T(_,y,S)),{x_2:v,x_3:E}=T(_,v,E);const U=n(v);return m(y*U)}const D={secretKey:u,publicKey:u,seed:u},k=(P=c(u))=>(Pt(P,D.seed),P);function j(P){const I=k(P);return{secretKey:I,publicKey:B(I)}}return{keygen:j,getSharedSecret:(P,I)=>A(P,I),getPublicKey:P=>B(P),scalarMult:A,scalarMultBase:B,utils:{randomSecretKey:k,randomPrivateKey:k},GuBytes:O.slice(),lengths:D}}const K3=BigInt(1),Xu=BigInt(2),W3=BigInt(3),G3=BigInt(5);BigInt(8);const fg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Y3={p:fg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Z3(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=fg,o=t*t%n*t%n,a=Ot(o,Xu,n)*o%n,c=Ot(a,K3,n)*t%n,l=Ot(c,G3,n)*c%n,u=Ot(l,e,n)*l%n,h=Ot(u,r,n)*u%n,f=Ot(h,i,n)*h%n,d=Ot(f,s,n)*f%n,g=Ot(d,s,n)*f%n,w=Ot(g,e,n)*l%n;return{pow_p_5_8:Ot(w,Xu,n)*t%n,b2:o}}function J3(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const X3=kr(Y3.p,{isLE:!0}),ja=(()=>{const t=X3.ORDER;return H3({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:i}=Z3(e);return lt(Ot(r,W3,t)*i,t)},adjustScalarBytes:J3})})(),Qu=(t,e)=>(t+(t>=0?e:-e)/dg)/e;function Q3(t,e,r){const[[i,s],[n,o]]=e,a=Qu(o*t,r),c=Qu(-s*t,r);let l=t-a*i-c*n,u=-a*s-c*o;const h=l<or,f=u<or;h&&(l=-l),f&&(u=-u);const d=Ps(Math.ceil(Xp(r)/2))+Ai;if(l<or||l>=d||u<or||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}function Fa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ho(t,e){const r={};for(let i of Object.keys(e))r[i]=t[i]===void 0?e[i]:t[i];return An(r.lowS,"lowS"),An(r.prehash,"prehash"),r.format!==void 0&&Fa(r.format),r}class eI extends Error{constructor(e=""){super(e)}}const sr={Err:eI,_tlv:{encode:(t,e)=>{const{Err:r}=sr;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=Ys(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?Ys(s.length/2|128):"";return Ys(t)+n+s+e},decode(t,e){const{Err:r}=sr;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=sr;if(t<or)throw new e("integer: negative integers are not allowed");let r=Ys(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=sr;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Qn(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=sr,s=qe("signature",t),{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:u}=i.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=sr,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}},or=BigInt(0),Ai=BigInt(1),dg=BigInt(2),Js=BigInt(3),tI=BigInt(4);function xi(t,e){const{BYTES:r}=t;let i;if(typeof e=="bigint")i=e;else{let s=qe("private key",e);try{i=t.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function rI(t,e={}){const r=z3("weierstrass",t,e),{Fp:i,Fn:s}=r;let n=r.CURVE;const{h:o,n:a}=n;eo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!i.is0(n.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=gg(i,s);function u(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(P,I,$){const{x:p,y}=I.toAffine(),v=i.toBytes(p);if(An($,"isCompressed"),$){u();const S=!i.isOdd(y);return Ar(pg(S),v)}else return Ar(Uint8Array.of(4),v,i.toBytes(y))}function f(P){Jr(P,void 0,"Point");const{publicKey:I,publicKeyUncompressed:$}=l,p=P.length,y=P[0],v=P.subarray(1);if(p===I&&(y===2||y===3)){const S=i.fromBytes(v);if(!i.isValid(S))throw new Error("bad point: is not on curve, wrong x");const E=w(S);let _;try{_=i.sqrt(E)}catch(N){const V=N instanceof Error?": "+N.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}u();const U=i.isOdd(_);return(y&1)===1!==U&&(_=i.neg(_)),{x:S,y:_}}else if(p===$&&y===4){const S=i.BYTES,E=i.fromBytes(v.subarray(0,S)),_=i.fromBytes(v.subarray(S,S*2));if(!m(E,_))throw new Error("bad point: is not on curve");return{x:E,y:_}}else throw new Error(`bad point: got length ${p}, expected compressed=${I} or uncompressed=${$}`)}const d=e.toBytes||h,g=e.fromBytes||f;function w(P){const I=i.sqr(P),$=i.mul(I,P);return i.add(i.add($,i.mul(P,n.a)),n.b)}function m(P,I){const $=i.sqr(I),p=w(P);return i.eql($,p)}if(!m(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const O=i.mul(i.pow(n.a,Js),tI),C=i.mul(i.sqr(n.b),BigInt(27));if(i.is0(i.add(O,C)))throw new Error("bad curve params: a or b");function b(P,I,$=!1){if(!i.isValid(I)||$&&i.is0(I))throw new Error(`bad point coordinate ${P}`);return I}function x(P){if(!(P instanceof D))throw new Error("ProjectivePoint expected")}function A(P){if(!c||!c.basises)throw new Error("no endo");return Q3(P,c.basises,s.ORDER)}const B=Ku((P,I)=>{const{X:$,Y:p,Z:y}=P;if(i.eql(y,i.ONE))return{x:$,y:p};const v=P.is0();I==null&&(I=v?i.ONE:i.inv(y));const S=i.mul($,I),E=i.mul(p,I),_=i.mul(y,I);if(v)return{x:i.ZERO,y:i.ZERO};if(!i.eql(_,i.ONE))throw new Error("invZ was invalid");return{x:S,y:E}}),T=Ku(P=>{if(P.is0()){if(e.allowInfinityPoint&&!i.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:$}=P.toAffine();if(!i.isValid(I)||!i.isValid($))throw new Error("bad point: x or y not field elements");if(!m(I,$))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(P,I,$,p,y){return $=new D(i.mul($.X,P),$.Y,$.Z),I=Bn(p,I),$=Bn(y,$),I.add($)}class D{constructor(I,$,p){this.X=b("x",I),this.Y=b("y",$,!0),this.Z=b("z",p),Object.freeze(this)}static CURVE(){return n}static fromAffine(I){const{x:$,y:p}=I||{};if(!I||!i.isValid($)||!i.isValid(p))throw new Error("invalid affine point");if(I instanceof D)throw new Error("projective point not allowed");return i.is0($)&&i.is0(p)?D.ZERO:new D($,p,i.ONE)}static fromBytes(I){const $=D.fromAffine(g(Jr(I,void 0,"point")));return $.assertValidity(),$}static fromHex(I){return D.fromBytes(qe("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,$=!0){return j.createCache(this,I),$||this.multiply(Js),this}assertValidity(){T(this)}hasEvenY(){const{y:I}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(I)}equals(I){x(I);const{X:$,Y:p,Z:y}=this,{X:v,Y:S,Z:E}=I,_=i.eql(i.mul($,E),i.mul(v,y)),U=i.eql(i.mul(p,E),i.mul(S,y));return _&&U}negate(){return new D(this.X,i.neg(this.Y),this.Z)}double(){const{a:I,b:$}=n,p=i.mul($,Js),{X:y,Y:v,Z:S}=this;let E=i.ZERO,_=i.ZERO,U=i.ZERO,N=i.mul(y,y),V=i.mul(v,v),L=i.mul(S,S),M=i.mul(y,v);return M=i.add(M,M),U=i.mul(y,S),U=i.add(U,U),E=i.mul(I,U),_=i.mul(p,L),_=i.add(E,_),E=i.sub(V,_),_=i.add(V,_),_=i.mul(E,_),E=i.mul(M,E),U=i.mul(p,U),L=i.mul(I,L),M=i.sub(N,L),M=i.mul(I,M),M=i.add(M,U),U=i.add(N,N),N=i.add(U,N),N=i.add(N,L),N=i.mul(N,M),_=i.add(_,N),L=i.mul(v,S),L=i.add(L,L),N=i.mul(L,M),E=i.sub(E,N),U=i.mul(L,V),U=i.add(U,U),U=i.add(U,U),new D(E,_,U)}add(I){x(I);const{X:$,Y:p,Z:y}=this,{X:v,Y:S,Z:E}=I;let _=i.ZERO,U=i.ZERO,N=i.ZERO;const V=n.a,L=i.mul(n.b,Js);let M=i.mul($,v),K=i.mul(p,S),G=i.mul(y,E),J=i.add($,p),W=i.add(v,S);J=i.mul(J,W),W=i.add(M,K),J=i.sub(J,W),W=i.add($,y);let X=i.add(v,E);return W=i.mul(W,X),X=i.add(M,G),W=i.sub(W,X),X=i.add(p,y),_=i.add(S,E),X=i.mul(X,_),_=i.add(K,G),X=i.sub(X,_),N=i.mul(V,W),_=i.mul(L,G),N=i.add(_,N),_=i.sub(K,N),N=i.add(K,N),U=i.mul(_,N),K=i.add(M,M),K=i.add(K,M),G=i.mul(V,G),W=i.mul(L,W),K=i.add(K,G),G=i.sub(M,G),G=i.mul(V,G),W=i.add(W,G),M=i.mul(K,W),U=i.add(U,M),M=i.mul(X,W),_=i.mul(J,_),_=i.sub(_,M),M=i.mul(J,K),N=i.mul(X,N),N=i.add(N,M),new D(_,U,N)}subtract(I){return this.add(I.negate())}is0(){return this.equals(D.ZERO)}multiply(I){const{endo:$}=e;if(!s.isValidNot0(I))throw new Error("invalid scalar: out of range");let p,y;const v=S=>j.cached(this,S,E=>Mo(D,E));if($){const{k1neg:S,k1:E,k2neg:_,k2:U}=A(I),{p:N,f:V}=v(E),{p:L,f:M}=v(U);y=V.add(M),p=R($.beta,N,L,S,_)}else{const{p:S,f:E}=v(I);p=S,y=E}return Mo(D,[p,y])[0]}multiplyUnsafe(I){const{endo:$}=e,p=this;if(!s.isValid(I))throw new Error("invalid scalar: out of range");if(I===or||p.is0())return D.ZERO;if(I===Ai)return p;if(j.hasCache(this))return this.multiply(I);if($){const{k1neg:y,k1:v,k2neg:S,k2:E}=A(I),{p1:_,p2:U}=M3(D,p,v,E);return R($.beta,_,U,y,S)}else return j.unsafe(p,I)}multiplyAndAddUnsafe(I,$,p){const y=this.multiplyUnsafe($).add(I.multiplyUnsafe(p));return y.is0()?void 0:y}toAffine(I){return B(this,I)}isTorsionFree(){const{isTorsionFree:I}=e;return o===Ai?!0:I?I(D,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=e;return o===Ai?this:I?I(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(I=!0){return An(I,"isCompressed"),this.assertValidity(),d(D,this,I)}toHex(I=!0){return Di(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Mo(D,I)}static msm(I,$){return q3(D,s,I,$)}static fromPrivateKey(I){return D.BASE.multiply(xi(s,I))}}D.BASE=new D(n.Gx,n.Gy,i.ONE),D.ZERO=new D(i.ZERO,i.ONE,i.ZERO),D.Fp=i,D.Fn=s;const k=s.BITS,j=new L3(D,e.endo?Math.ceil(k/2):k);return D.BASE.precompute(8),D}function pg(t){return Uint8Array.of(t?2:3)}function gg(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function iI(t,e={}){const{Fn:r}=t,i=e.randomBytes||ci,s=Object.assign(gg(t.Fp,r),{seed:lg(r.ORDER)});function n(f){try{return!!xi(r,f)}catch{return!1}}function o(f,d){const{publicKey:g,publicKeyUncompressed:w}=s;try{const m=f.length;return d===!0&&m!==g||d===!1&&m!==w?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=i(s.seed)){return k3(Jr(f,s.seed,"seed"),r.ORDER)}function c(f,d=!0){return t.BASE.multiply(xi(r,f)).toBytes(d)}function l(f){const d=a(f);return{secretKey:d,publicKey:c(d)}}function u(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:d,publicKey:g,publicKeyUncompressed:w}=s;if(r.allowedLengths||d===g)return;const m=qe("key",f).length;return m===g||m===w}function h(f,d,g=!0){if(u(f)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");const w=xi(r,f);return t.fromHex(d).multiply(w).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:n,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:n,randomPrivateKey:a,normPrivateKeyToScalar:f=>xi(r,f),precompute(f=8,d=t.BASE){return d.precompute(f,!1)}},lengths:s})}function sI(t,e,r={}){Wn(e),eo(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=r.randomBytes||ci,s=r.hmac||(($,...p)=>Jn(e,$,Ar(...p))),{Fp:n,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d}=iI(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},w="compact";function m($){const p=a>>Ai;return $>p}function O($,p){if(!o.isValidNot0(p))throw new Error(`invalid signature ${$}: out of range 1..Point.Fn.ORDER`);return p}function C($,p){Fa(p);const y=d.signature,v=p==="compact"?y:p==="recovered"?y+1:void 0;return Jr($,v,`${p} signature`)}class b{constructor(p,y,v){this.r=O("r",p),this.s=O("s",y),v!=null&&(this.recovery=v),Object.freeze(this)}static fromBytes(p,y=w){C(p,y);let v;if(y==="der"){const{r:U,s:N}=sr.toSig(Jr(p));return new b(U,N)}y==="recovered"&&(v=p[0],y="compact",p=p.subarray(1));const S=o.BYTES,E=p.subarray(0,S),_=p.subarray(S,S*2);return new b(o.fromBytes(E),o.fromBytes(_),v)}static fromHex(p,y){return this.fromBytes($n(p),y)}addRecoveryBit(p){return new b(this.r,this.s,p)}recoverPublicKey(p){const y=n.ORDER,{r:v,s:S,recovery:E}=this;if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");if(a*dg<y&&E>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=E===2||E===3?v+a:v;if(!n.isValid(_))throw new Error("recovery id 2 or 3 invalid");const U=n.toBytes(_),N=t.fromBytes(Ar(pg((E&1)===0),U)),V=o.inv(_),L=A(qe("msgHash",p)),M=o.create(-L*V),K=o.create(S*V),G=t.BASE.multiplyUnsafe(M).add(N.multiplyUnsafe(K));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return m(this.s)}toBytes(p=w){if(Fa(p),p==="der")return $n(sr.hexFromSig(this));const y=o.toBytes(this.r),v=o.toBytes(this.s);if(p==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ar(Uint8Array.of(this.recovery),y,v)}return Ar(y,v)}toHex(p){return Di(this.toBytes(p))}assertValidity(){}static fromCompact(p){return b.fromBytes(qe("sig",p),"compact")}static fromDER(p){return b.fromBytes(qe("sig",p),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Di(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Di(this.toBytes("compact"))}}const x=r.bits2int||function($){if($.length>8192)throw new Error("input is too large");const p=Qn($),y=$.length*8-c;return y>0?p>>BigInt(y):p},A=r.bits2int_modN||function($){return o.create(x($))},B=Ps(c);function T($){return ka("num < 2^"+c,$,or,B),o.toBytes($)}function R($,p){return Jr($,void 0,"message"),p?Jr(e($),void 0,"prehashed message"):$}function D($,p,y){if(["recovered","canonical"].some(K=>K in y))throw new Error("sign() legacy options not supported");const{lowS:v,prehash:S,extraEntropy:E}=Ho(y,g);$=R($,S);const _=A($),U=xi(o,p),N=[T(U),T(_)];if(E!=null&&E!==!1){const K=E===!0?i(d.secretKey):E;N.push(qe("extraEntropy",K))}const V=Ar(...N),L=_;function M(K){const G=x(K);if(!o.isValidNot0(G))return;const J=o.inv(G),W=t.BASE.multiply(G).toAffine(),X=o.create(W.x);if(X===or)return;const fe=o.create(J*o.create(L+X*U));if(fe===or)return;let me=(W.x===X?0:2)|Number(W.y&Ai),Ee=fe;return v&&m(fe)&&(Ee=o.neg(fe),me^=1),new b(X,Ee,me)}return{seed:V,k2sig:M}}function k($,p,y={}){$=qe("message",$);const{seed:v,k2sig:S}=D($,p,y);return D3(e.outputLen,o.BYTES,s)(v,S)}function j($){let p;const y=typeof $=="string"||Kn($),v=!y&&$!==null&&typeof $=="object"&&typeof $.r=="bigint"&&typeof $.s=="bigint";if(!y&&!v)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(v)p=new b($.r,$.s);else if(y){try{p=b.fromBytes(qe("sig",$),"der")}catch(S){if(!(S instanceof sr.Err))throw S}if(!p)try{p=b.fromBytes(qe("sig",$),"compact")}catch{return!1}}return p||!1}function P($,p,y,v={}){const{lowS:S,prehash:E,format:_}=Ho(v,g);if(y=qe("publicKey",y),p=R(qe("message",p),E),"strict"in v)throw new Error("options.strict was renamed to lowS");const U=_===void 0?j($):b.fromBytes(qe("sig",$),_);if(U===!1)return!1;try{const N=t.fromBytes(y);if(S&&U.hasHighS())return!1;const{r:V,s:L}=U,M=A(p),K=o.inv(L),G=o.create(M*K),J=o.create(V*K),W=t.BASE.multiplyUnsafe(G).add(N.multiplyUnsafe(J));return W.is0()?!1:o.create(W.x)===V}catch{return!1}}function I($,p,y={}){const{prehash:v}=Ho(y,g);return p=R(p,v),b.fromBytes($,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d,Point:t,sign:k,verify:P,recoverPublicKey:I,Signature:b,hash:e})}function nI(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let i=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const s=kr(e.n,{BITS:t.nBitLength,allowedLengths:i,modFromBytes:t.wrapPrivateKey}),n={Fp:r,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:n}}function oI(t){const{CURVE:e,curveOpts:r}=nI(t),i={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:i}}function aI(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,ag(r.Fn.ORDER,r.Fn.BITS))})}function cI(t){const{CURVE:e,curveOpts:r,hash:i,ecdsaOpts:s}=oI(t),n=rI(e,r),o=sI(n,i,s);return aI(t,o)}function La(t,e){const r=i=>cI({...t,hash:i});return{...r(e),create:r}}const yg={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},wg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},mg={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},lI=kr(yg.p),uI=kr(wg.p),hI=kr(mg.p),fI=La({...yg,Fp:lI,lowS:!1},Yn);La({...wg,Fp:uI,lowS:!1},w_),La({...mg,Fp:hI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},y_);const dI=fI,bg="base10",Ke="base16",Qe="base64pad",Pr="base64url",Bs="utf8",vg=0,lr=1,Cs=2,pI=0,eh=1,ls=12,Hc=32;function gI(){const t=ja.utils.randomPrivateKey(),e=ja.getPublicKey(t);return{privateKey:rt(t,Ke),publicKey:rt(e,Ke)}}function Ma(){const t=ci(Hc);return rt(t,Ke)}function yI(t,e){const r=ja.getSharedSecret(bt(t,Ke),bt(e,Ke)),i=O3(Xn,r,void 0,void 0,Hc);return rt(i,Ke)}function un(t){const e=Xn(bt(t,Ke));return rt(e,Ke)}function wt(t){const e=Xn(bt(t,Bs));return rt(e,Ke)}function Eg(t){return bt(`${t}`,bg)}function oi(t){return Number(rt(t,bg))}function xg(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function _g(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function wI(t){const e=Eg(typeof t.type<"u"?t.type:vg);if(oi(e)===lr&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?bt(t.senderPublicKey,Ke):void 0,i=typeof t.iv<"u"?bt(t.iv,Ke):ci(ls),s=bt(t.symKey,Ke),n=Yp(s,i).encrypt(bt(t.message,Bs)),o=Ig({type:e,sealed:n,iv:i,senderPublicKey:r});return t.encoding===Pr?xg(o):o}function mI(t){const e=bt(t.symKey,Ke),{sealed:r,iv:i}=vs({encoded:t.encoded,encoding:t.encoding}),s=Yp(e,i).decrypt(r);if(s===null)throw new Error("Failed to decrypt");return rt(s,Bs)}function bI(t,e){const r=Eg(Cs),i=ci(ls),s=bt(t,Bs),n=Ig({type:r,sealed:s,iv:i});return e===Pr?xg(n):n}function vI(t,e){const{sealed:r}=vs({encoded:t,encoding:e});return rt(r,Bs)}function Ig(t){if(oi(t.type)===Cs)return rt(cs([t.type,t.sealed]),Qe);if(oi(t.type)===lr){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return rt(cs([t.type,t.senderPublicKey,t.iv,t.sealed]),Qe)}return rt(cs([t.type,t.iv,t.sealed]),Qe)}function vs(t){const e=(t.encoding||Qe)===Pr?_g(t.encoded):t.encoded,r=bt(e,Qe),i=r.slice(pI,eh),s=eh;if(oi(i)===lr){const c=s+Hc,l=c+ls,u=r.slice(s,c),h=r.slice(c,l),f=r.slice(l);return{type:i,sealed:f,iv:h,senderPublicKey:u}}if(oi(i)===Cs){const c=r.slice(s),l=ci(ls);return{type:i,sealed:c,iv:l}}const n=s+ls,o=r.slice(s,n),a=r.slice(n);return{type:i,sealed:a,iv:o}}function EI(t,e){const r=vs({encoded:t,encoding:e==null?void 0:e.encoding});return Sg({type:oi(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?rt(r.senderPublicKey,Ke):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Sg(t){const e=(t==null?void 0:t.type)||vg;if(e===lr){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function th(t){return t.type===lr&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function rh(t){return t.type===Cs}function xI(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return cs([new Uint8Array([4]),e,r])}function _I(t,e){const[r,i,s]=t.split("."),n=Buffer.from(_g(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${r}.${i}`,l=Xn(c),u=xI(e);if(!dI.verify(cs([o,a]),l,u))throw new Error("Invalid signature");return Sa(t).payload}const II="irn";function Cn(t){return(t==null?void 0:t.relay)||{protocol:II}}function _i(t){const e=aE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var SI=Object.defineProperty,OI=Object.defineProperties,$I=Object.getOwnPropertyDescriptors,ih=Object.getOwnPropertySymbols,DI=Object.prototype.hasOwnProperty,AI=Object.prototype.propertyIsEnumerable,sh=(t,e,r)=>e in t?SI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ko=(t,e)=>{for(var r in e||(e={}))DI.call(e,r)&&sh(t,r,e[r]);if(ih)for(var r of ih(e))AI.call(e,r)&&sh(t,r,e[r]);return t},PI=(t,e)=>OI(t,$I(e));function BI(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=t[s];r[n]=o}}),r}function nh(t){if(!t.includes("wc:")){const l=Dp(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),s=t.substring(e+1,r).split("@"),n=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(n),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:CI(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:BI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function CI(t){return t.startsWith("//")?t.substring(2):t}function TI(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(s=>{const n=s,o=r+e+n;t[n]&&(i[o]=t[n])}),i}function oh(t){const e=new URLSearchParams,r=Ko(Ko(PI(Ko({},TI(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(r).sort(([i],[s])=>i.localeCompare(s)).forEach(([i,s])=>{s!==void 0&&e.append(i,String(s))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function Xs(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var RI=Object.defineProperty,UI=Object.defineProperties,NI=Object.getOwnPropertyDescriptors,ah=Object.getOwnPropertySymbols,kI=Object.prototype.hasOwnProperty,jI=Object.prototype.propertyIsEnumerable,ch=(t,e,r)=>e in t?RI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,FI=(t,e)=>{for(var r in e||(e={}))kI.call(e,r)&&ch(t,r,e[r]);if(ah)for(var r of ah(e))jI.call(e,r)&&ch(t,r,e[r]);return t},LI=(t,e)=>UI(t,NI(e));function Fi(t){const e=[];return t.forEach(r=>{const[i,s]=r.split(":");e.push(`${i}:${s}`)}),e}function Og(t){const e=[];return Object.values(t).forEach(r=>{e.push(...Fi(r.accounts))}),[...new Set(e)]}function MI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.methods)}),[...new Set(e)]}function qI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.events)}),[...new Set(e)]}function zI(t,e){const r=[];return Object.values(t).forEach(i=>{Fi(i.accounts).includes(e)&&r.push(...i.methods)}),r}function VI(t,e){const r=[];return Object.values(t).forEach(i=>{Fi(i.accounts).includes(e)&&r.push(...i.events)}),r}function to(t){return t.includes(":")}function Ii(t){return to(t)?t.split(":")[0]:t}function lh(t){var e,r,i;const s={};if(!Vt(t))return s;for(const[n,o]of Object.entries(t)){const a=to(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],u=Ii(n);s[u]=LI(FI({},s[u]),{chains:zt(a,(e=s[u])==null?void 0:e.chains),methods:zt(c,(r=s[u])==null?void 0:r.methods),events:zt(l,(i=s[u])==null?void 0:i.events)})}return s}function HI(t){const e={};return t==null||t.forEach(r=>{var i;const[s,n]=r.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(r),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function uh(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=HI(e);for(const[i,s]of Object.entries(r))s.methods?s.methods=zt(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return r}function KI(t,e){var r,i,s,n,o,a;const c=lh(t),l=lh(e),u={},h=Object.keys(c).concat(Object.keys(l));for(const f of h)u[f]={chains:zt((r=c[f])==null?void 0:r.chains,(i=l[f])==null?void 0:i.chains),methods:zt((s=c[f])==null?void 0:s.methods,(n=l[f])==null?void 0:n.methods),events:zt((o=c[f])==null?void 0:o.events,(a=l[f])==null?void 0:a.events)};return u}const WI={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}},GI={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 z(t,e){const{message:r,code:i}=GI[t];return{message:e?`${r} ${e}`:r,code:i}}function ue(t,e){const{message:r,code:i}=WI[t];return{message:e?`${r} ${e}`:r,code:i}}function vt(t,e){return!!Array.isArray(t)}function Vt(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Oe(t){return typeof t>"u"}function we(t,e){return e&&Oe(t)?!0:typeof t=="string"&&!!t.trim().length}function Kc(t,e){return typeof t=="number"&&!isNaN(t)}function YI(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),s=Object.keys(r);let n=!0;return Zr(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=Fi(a),h=r[o];(!Zr(_p(o,h),u)||!Zr(h.methods,c)||!Zr(h.events,l))&&(n=!1)}),n):!1}function Tn(t){return we(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function ZI(t){if(we(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Tn(r)}}return!1}function JI(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(we(t,!1)){if(e(t))return!0;const r=Dp(t);return e(r)}}catch{}return!1}function XI(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function QI(t){return t==null?void 0:t.topic}function eS(t,e){let r=null;return we(t==null?void 0:t.publicKey,!1)||(r=z("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function hh(t){let e=!0;return vt(t)?t.length&&(e=t.every(r=>we(r,!1))):e=!1,e}function tS(t,e,r){let i=null;return vt(e)&&e.length?e.forEach(s=>{i||Tn(s)||(i=ue("UNSUPPORTED_CHAINS",`${r}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Tn(t)||(i=ue("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function rS(t,e,r){let i=null;return Object.entries(t).forEach(([s,n])=>{if(i)return;const o=tS(s,_p(s,n),`${e} ${r}`);o&&(i=o)}),i}function iS(t,e){let r=null;return vt(t)?t.forEach(i=>{r||ZI(i)||(r=ue("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=ue("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function sS(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=iS(i==null?void 0:i.accounts,`${e} namespace`);s&&(r=s)}),r}function nS(t,e){let r=null;return hh(t==null?void 0:t.methods)?hh(t==null?void 0:t.events)||(r=ue("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=ue("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function $g(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=nS(i,`${e}, namespace`);s&&(r=s)}),r}function oS(t,e,r){let i=null;if(t&&Vt(t)){const s=$g(t,e);s&&(i=s);const n=rS(t,e,r);n&&(i=n)}else i=z("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function Wo(t,e){let r=null;if(t&&Vt(t)){const i=$g(t,e);i&&(r=i);const s=sS(t,e);s&&(r=s)}else r=z("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Dg(t){return we(t.protocol,!0)}function aS(t,e){let r=!1;return t?t&&vt(t)&&t.length&&t.forEach(i=>{r=Dg(i)}):r=!0,r}function cS(t){return typeof t=="number"}function Ze(t){return typeof t<"u"&&typeof t!==null}function lS(t){return!(!t||typeof t!="object"||!t.code||!Kc(t.code)||!t.message||!we(t.message,!1))}function uS(t){return!(Oe(t)||!we(t.method,!1))}function hS(t){return!(Oe(t)||Oe(t.result)&&Oe(t.error)||!Kc(t.id)||!we(t.jsonrpc,!1))}function fS(t){return!(Oe(t)||!we(t.name,!1))}function fh(t,e){return!(!Tn(e)||!Og(t).includes(e))}function dS(t,e,r){return we(r,!1)?zI(t,e).includes(r):!1}function pS(t,e,r){return we(r,!1)?VI(t,e).includes(r):!1}function dh(t,e,r){let i=null;const s=gS(t),n=yS(e),o=Object.keys(s),a=Object.keys(n),c=ph(Object.keys(t)),l=ph(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
22
+ Required: ${u.toString()}
23
+ Received: ${Object.keys(e).toString()}`)),Zr(o,a)||(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
24
+ Required: ${o.toString()}
25
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const f=Fi(e[h].accounts);f.includes(h)||(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
26
+ Required: ${h}
27
+ Approved: ${f.toString()}`))}),o.forEach(h=>{i||(Zr(s[h].methods,n[h].methods)?Zr(s[h].events,n[h].events)||(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function gS(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(s=>{e[s]={methods:t[r].methods,events:t[r].events}})}),e}function ph(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function yS(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=Fi(t[r].accounts);i==null||i.forEach(s=>{e[s]={accounts:t[r].accounts.filter(n=>n.includes(`${s}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function wS(t,e){return Kc(t)&&t<=e.max&&t>=e.min}function gh(){const t=Ds();return new Promise(e=>{switch(t){case ut.browser:e(mS());break;case ut.reactNative:e(bS());break;case ut.node:e(vS());break;default:e(!0)}})}function mS(){return ji()&&(navigator==null?void 0:navigator.onLine)}async function bS(){if(Nr()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function vS(){return!0}function ES(t){switch(Ds()){case ut.browser:xS(t);break;case ut.reactNative:_S(t);break}}function xS(t){!Nr()&&ji()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function _S(t){Nr()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function IS(){var t;return ji()&&ti()?((t=ti())==null?void 0:t.visibilityState)==="visible":!0}const Go={};class Zi{static get(e){return Go[e]}static set(e,r){Go[e]=r}static delete(e){delete Go[e]}}function SS(t){const e=Ss.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function OS({publicKey:t,signature:e,payload:r}){var i;const s=qa(r.method),n=128|parseInt(((i=r.version)==null?void 0:i.toString())||"4"),o=AS(r.address),a=r.era==="00"?new Uint8Array([0]):qa(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${DS(r.tip)}`),h=BS(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...s]),d=PS(f.length+1);return new Uint8Array([...d,n,...f])}function $S(t){const e=qa(t),r=bE.blake2b(e,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function qa(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function DS(t){return t.startsWith("0x")?t.slice(2):t}function AS(t){const e=Ss.decode(t)[0];return e===42?0:e===60?2:1}function PS(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function BS(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function CS(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),r=SS(t.transaction.address),i=OS({publicKey:r,signature:e,payload:t.transaction}),s=Buffer.from(i).toString("hex");return $S(s)}function Wc({logger:t,name:e}){const r=typeof t=="string"?xp({opts:{level:t,name:e}}).logger:t;return r.level=typeof t=="string"?t:t.level,r}class li{}let TS=class extends li{constructor(e){super()}};const yh=q.FIVE_SECONDS,ui={pulse:"heartbeat_pulse"};let RS=class Ag extends TS{constructor(e){super(e),this.events=new xt.EventEmitter,this.interval=yh,this.interval=(e==null?void 0:e.interval)||yh}static async init(e){const r=new Ag(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),q.toMiliseconds(this.interval))}pulse(){this.events.emit(ui.pulse)}};const US=/"(?:_|\\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*:/,NS=/"(?: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*:/,kS=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function jS(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){FS(t);return}return e}function FS(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Qs(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!kS.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(US.test(t)||NS.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,jS)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function LS(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ie(t,...e){try{return LS(t(...e))}catch(r){return Promise.reject(r)}}function MS(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function qS(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function hn(t){if(MS(t))return String(t);if(qS(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return hn(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const za="base64:";function zS(t){return typeof t=="string"?t:za+KS(t)}function VS(t){return typeof t!="string"||!t.startsWith(za)?t:HS(t.slice(za.length))}function HS(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function KS(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ye(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function WS(...t){return Ye(t.join(":"))}function en(t){return t=Ye(t),t?t+":":""}function GS(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function YS(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const ZS="memory",JS=()=>{const t=new Map;return{name:ZS,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function XS(t={}){const e={mounts:{"":t.driver||JS()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},i=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(l,u)=>{if(e.watching){u=Ye(u);for(const h of e.watchListeners)h(l,u)}},n=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await wh(e.mounts[l],s,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const f=new Map,d=g=>{let w=f.get(g.base);return w||(w={driver:g.driver,base:g.base,items:[]},f.set(g.base,w)),w};for(const g of l){const w=typeof g=="string",m=Ye(w?g:g.key),O=w?void 0:g.value,C=w||!g.options?u:{...u,...g.options},b=r(m);d(b).items.push({key:m,value:O,relativeKey:b.relativeKey,options:C})}return Promise.all([...f.values()].map(g=>h(g))).then(g=>g.flat())},c={hasItem(l,u={}){l=Ye(l);const{relativeKey:h,driver:f}=r(l);return Ie(f.hasItem,h,u)},getItem(l,u={}){l=Ye(l);const{relativeKey:h,driver:f}=r(l);return Ie(f.getItem,h,u).then(d=>Qs(d))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?Ie(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(d=>({key:WS(h.base,d.key),value:Qs(d.value)}))):Promise.all(h.items.map(f=>Ie(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:Qs(d)})))))},getItemRaw(l,u={}){l=Ye(l);const{relativeKey:h,driver:f}=r(l);return f.getItemRaw?Ie(f.getItemRaw,h,u):Ie(f.getItem,h,u).then(d=>VS(d))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Ye(l);const{relativeKey:f,driver:d}=r(l);d.setItem&&(await Ie(d.setItem,f,hn(u),h),d.watch||s("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return Ie(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:hn(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>Ie(h.driver.setItem,f.relativeKey,hn(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Ye(l);const{relativeKey:f,driver:d}=r(l);if(d.setItemRaw)await Ie(d.setItemRaw,f,u,h);else if(d.setItem)await Ie(d.setItem,f,zS(u),h);else return;d.watch||s("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Ye(l);const{relativeKey:h,driver:f}=r(l);f.removeItem&&(await Ie(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await Ie(f.removeItem,h+"$",u),f.watch||s("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Ye(l);const{relativeKey:h,driver:f}=r(l),d=Object.create(null);if(f.getMeta&&Object.assign(d,await Ie(f.getMeta,h,u)),!u.nativeOnly){const g=await Ie(f.getItem,h+"$",u).then(w=>Qs(w));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(d,g))}return d},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){var m;l=en(l);const h=i(l,!0);let f=[];const d=[];let g=!0;for(const O of h){(m=O.driver.flags)!=null&&m.maxDepth||(g=!1);const C=await Ie(O.driver.getKeys,O.relativeBase,u);for(const b of C){const x=O.mountpoint+Ye(b);f.some(A=>x.startsWith(A))||d.push(x)}f=[O.mountpoint,...f.filter(b=>!b.startsWith(O.mountpoint))]}const w=u.maxDepth!==void 0&&!g;return d.filter(O=>(!w||GS(O,u.maxDepth))&&YS(O,l))},async clear(l,u={}){l=en(l),await Promise.all(i(l,!1).map(async h=>{if(h.driver.clear)return Ie(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(d=>h.driver.removeItem(d,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>mh(l)))},async watch(l){return await n(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=en(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(wh(u,s,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){var h,f;l=en(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((f=(h=e.unwatch)[l])==null||f.call(h),delete e.unwatch[l]),u&&await mh(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Ye(l)+":";const u=r(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Ye(l),i(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function wh(t,e,r){return t.watch?t.watch((i,s)=>e(i,r+s)):()=>{}}async function mh(t){typeof t.dispose=="function"&&await Ie(t.dispose)}function hi(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Pg(t,e){let r;const i=()=>{if(r)return r;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),r=hi(s),r.then(n=>{n.onclose=()=>r=void 0},()=>{}),r};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Yo;function Ts(){return Yo||(Yo=Pg("keyval-store","keyval")),Yo}function bh(t,e=Ts()){return e("readonly",r=>hi(r.get(t)))}function QS(t,e,r=Ts()){return r("readwrite",i=>(i.put(e,t),hi(i.transaction)))}function e8(t,e=Ts()){return e("readwrite",r=>(r.delete(t),hi(r.transaction)))}function t8(t=Ts()){return t("readwrite",e=>(e.clear(),hi(e.transaction)))}function r8(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},hi(t.transaction)}function i8(t=Ts()){return t("readonly",e=>{if(e.getAllKeys)return hi(e.getAllKeys());const r=[];return r8(e,i=>r.push(i.key)).then(()=>r)})}const s8="idb-keyval";var n8=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=s=>e+s;let i;return t.dbName&&t.storeName&&(i=Pg(t.dbName,t.storeName)),{name:s8,options:t,async hasItem(s){return!(typeof await bh(r(s),i)>"u")},async getItem(s){return await bh(r(s),i)??null},setItem(s,n){return QS(r(s),n,i)},removeItem(s){return e8(r(s),i)},getKeys(){return i8(i)},clear(){return t8(i)}}};const o8="WALLET_CONNECT_V2_INDEXED_DB",a8="keyvaluestorage";let c8=class{constructor(){this.indexedDb=XS({driver:n8({dbName:o8,storeName:a8})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,si(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Zo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},fn={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Zo<"u"&&Zo.localStorage?fn.exports=Zo.localStorage:typeof window<"u"&&window.localStorage?fn.exports=window.localStorage:fn.exports=new e})();function l8(t){var e;return[t[0],ii((e=t[1])!=null?e:"")]}let u8=class{constructor(){this.localStorage=fn.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(l8)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return ii(r)}async setItem(e,r){this.localStorage.setItem(e,si(r))}async removeItem(e){this.localStorage.removeItem(e)}};const h8="wc_storage_version",vh=1,f8=async(t,e,r)=>{const i=h8,s=await e.getItem(i);if(s&&s>=vh){r(e);return}const n=await t.getKeys();if(!n.length){r(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(i,vh),r(e),d8(t,o)},d8=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let p8=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new u8;this.storage=e;try{const r=new c8;f8(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var g8=Object.defineProperty,y8=(t,e,r)=>e in t?g8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Eh=(t,e,r)=>y8(t,typeof e!="symbol"?e+"":e,r);let w8=class extends li{constructor(e){super(),this.opts=e,Eh(this,"protocol","wc"),Eh(this,"version",2)}};var m8=Object.defineProperty,b8=(t,e,r)=>e in t?m8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,v8=(t,e,r)=>b8(t,e+"",r);let E8=class extends li{constructor(e,r){super(),this.core=e,this.logger=r,v8(this,"records",new Map)}},x8=class{constructor(e,r){this.logger=e,this.core=r}},_8=class extends li{constructor(e,r){super(),this.relayer=e,this.logger=r}},I8=class extends li{constructor(e){super()}},S8=class{constructor(e,r,i,s){this.core=e,this.logger=r,this.name=i}},O8=class extends li{constructor(e,r){super(),this.relayer=e,this.logger=r}},$8=class extends li{constructor(e,r){super(),this.core=e,this.logger=r}},D8=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},A8=class{constructor(e,r){this.projectId=e,this.logger=r}},P8=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var B8=Object.defineProperty,C8=(t,e,r)=>e in t?B8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xh=(t,e,r)=>C8(t,typeof e!="symbol"?e+"":e,r);let T8=class{constructor(e){this.opts=e,xh(this,"protocol","wc"),xh(this,"version",2)}},R8=class{constructor(e){this.client=e}};const U8="PARSE_ERROR",N8="INVALID_REQUEST",k8="METHOD_NOT_FOUND",j8="INVALID_PARAMS",Bg="INTERNAL_ERROR",Gc="SERVER_ERROR",F8=[-32700,-32600,-32601,-32602,-32603],us={[U8]:{code:-32700,message:"Parse error"},[N8]:{code:-32600,message:"Invalid Request"},[k8]:{code:-32601,message:"Method not found"},[j8]:{code:-32602,message:"Invalid params"},[Bg]:{code:-32603,message:"Internal error"},[Gc]:{code:-32e3,message:"Server error"}},Cg=Gc;function L8(t){return F8.includes(t)}function _h(t){return Object.keys(us).includes(t)?us[t]:us[Cg]}function M8(t){const e=Object.values(us).find(r=>r.code===t);return e||us[Cg]}function Tg(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Rg={};/*! *****************************************************************************
28
+ Copyright (c) Microsoft Corporation.
29
+
30
+ Permission to use, copy, modify, and/or distribute this software for any
31
+ purpose with or without fee is hereby granted.
32
+
33
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
34
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
35
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
36
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
37
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
38
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
39
+ PERFORMANCE OF THIS SOFTWARE.
40
+ ***************************************************************************** */var Va=function(t,e){return Va=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},Va(t,e)};function q8(t,e){Va(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ha=function(){return Ha=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ha.apply(this,arguments)};function z8(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function V8(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function H8(t,e){return function(r,i){e(r,i,t)}}function K8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function W8(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function G8(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Y8(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function Z8(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ka(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ug(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function J8(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ug(arguments[e]));return t}function X8(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Es(t){return this instanceof Es?(this.v=t,this):new Es(t)}function Q8(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(d){return new Promise(function(g,w){n.push([f,d,g,w])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(g){h(n[0][3],g)}}function c(f){f.value instanceof Es?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),n.shift(),n.length&&a(n[0][0],n[0][1])}}function eO(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:Es(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function tO(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ka=="function"?Ka(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function rO(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function iO(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function sO(t){return t&&t.__esModule?t:{default:t}}function nO(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function oO(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const aO=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ha},__asyncDelegator:eO,__asyncGenerator:Q8,__asyncValues:tO,__await:Es,__awaiter:W8,__classPrivateFieldGet:nO,__classPrivateFieldSet:oO,__createBinding:Y8,__decorate:V8,__exportStar:Z8,__extends:q8,__generator:G8,__importDefault:sO,__importStar:iO,__makeTemplateObject:rO,__metadata:K8,__param:H8,__read:Ug,__rest:z8,__spread:J8,__spreadArrays:X8,__values:Ka},Symbol.toStringTag,{value:"Module"})),cO=Tf(aO);var Xt={},Ih;function lO(){if(Ih)return Xt;Ih=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.isBrowserCryptoAvailable=Xt.getSubtleCrypto=Xt.getBrowerCrypto=void 0;function t(){return(Ft===null||Ft===void 0?void 0:Ft.crypto)||(Ft===null||Ft===void 0?void 0:Ft.msCrypto)||{}}Xt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Xt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Xt.isBrowserCryptoAvailable=r,Xt}var Qt={},Sh;function uO(){if(Sh)return Qt;Sh=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowser=Qt.isNode=Qt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Qt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Qt.isNode=e;function r(){return!t()&&!e()}return Qt.isBrowser=r,Qt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=cO;e.__exportStar(lO(),t),e.__exportStar(uO(),t)})(Rg);function kt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Cr(t=6){return BigInt(kt(t))}function Dt(t,e,r){return{id:r||kt(),jsonrpc:"2.0",method:t,params:e}}function xs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ro(t,e,r){return{id:t,jsonrpc:"2.0",error:hO(e)}}function hO(t,e){return typeof t>"u"?_h(Bg):(typeof t=="string"&&(t=Object.assign(Object.assign({},_h(Gc)),{message:t})),L8(t.code)&&(t=M8(t.code)),t)}class fO{}class dO extends fO{constructor(){super()}}class pO extends dO{constructor(e){super()}}const gO="^https?:",yO="^wss?:";function wO(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Ng(t,e){const r=wO(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Oh(t){return Ng(t,gO)}function $h(t){return Ng(t,yO)}function mO(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function kg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yc(t){return kg(t)&&"method"in t}function io(t){return kg(t)&&(jt(t)||mt(t))}function jt(t){return"result"in t}function mt(t){return"error"in t}let Zc=class extends pO{constructor(e){super(e),this.events=new xt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Dt(e.method,e.params||[],e.id||Cr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{mt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),io(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const bO=()=>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"),vO=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Dh=t=>t.split("?")[0],Ah=10,EO=bO();let xO=class{constructor(e){if(this.url=e,this.events=new xt.EventEmitter,this.registering=!1,!$h(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(si(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!$h(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=Rg.isReactNative()?void 0:{rejectUnauthorized:!mO(e)},n=new EO(e,[],s);vO()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ii(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=ro(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Tg(e,Dh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ah&&this.events.setMaxListeners(Ah)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Dh(this.url)}`));return this.events.emit("register_error",r),r}};var _O={};const jg="wc",Fg=2,Wa="core",Ht=`${jg}@2:${Wa}:`,IO={logger:"error"},SO={database:":memory:"},OO="crypto",Ph="client_ed25519_seed",$O=q.ONE_DAY,DO="keychain",AO="0.3",PO="messages",BO="0.3",CO=q.SIX_HOURS,TO="publisher",Lg="irn",RO="error",Mg="wss://relay.walletconnect.org",UO="relayer",ye={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},NO="_subscription",dt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},kO=.1,Ga="2.23.1",le={link_mode:"link_mode",relay:"relay"},dn={inbound:"inbound",outbound:"outbound"},jO="0.3",FO="WALLETCONNECT_CLIENT_ID",Bh="WALLETCONNECT_LINK_MODE_APPS",at={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},LO="subscription",MO="0.3",qO="pairing",zO="0.3",Ji={wc_pairingDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:q.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:q.ONE_DAY,prompt:!1,tag:0},res:{ttl:q.ONE_DAY,prompt:!1,tag:0}}},Wr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},It={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},VO="history",HO="0.3",KO="expirer",gt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},WO="0.3",GO="verify-api",YO="https://verify.walletconnect.com",qg="https://verify.walletconnect.org",hs=qg,ZO=`${hs}/v3`,JO=[YO,qg],XO="echo",QO="https://echo.walletconnect.com",Nt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},tr={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},St={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Mr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},qr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},Xi={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},e$=.1,t$="event-client",r$=86400,i$="https://pulse.walletconnect.org/batch";function s$(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,m=0,O=0,C=g.length;O!==C&&g[O]===0;)O++,w++;for(var b=(C-O)*u+1>>>0,x=new Uint8Array(b);O!==C;){for(var A=g[O],B=0,T=b-1;(A!==0||B<m)&&T!==-1;T--,B++)A+=256*x[T]>>>0,x[T]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");m=B,O++}for(var R=b-m;R!==b&&x[R]===0;)R++;for(var D=c.repeat(w);R<b;++R)D+=t.charAt(x[R]);return D}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var m=0,O=0;g[w]===c;)m++,w++;for(var C=(g.length-w)*l+1>>>0,b=new Uint8Array(C);g[w];){var x=r[g.charCodeAt(w)];if(x===255)return;for(var A=0,B=C-1;(x!==0||A<O)&&B!==-1;B--,A++)x+=a*b[B]>>>0,b[B]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");O=A,w++}if(g[w]!==" "){for(var T=C-O;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(m+(C-T)),D=m;T!==C;)R[D++]=b[T++];return R}}}function d(g){var w=f(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var n$=s$,o$=n$;const zg=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},a$=t=>new TextEncoder().encode(t),c$=t=>new TextDecoder().decode(t);class l${constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class u${constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Vg(this,e)}}class h${constructor(e){this.decoders=e}or(e){return Vg(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Vg=(t,e)=>new h$({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class f${constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new l$(e,r,i),this.decoder=new u$(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const so=({name:t,prefix:e,encode:r,decode:i})=>new f$(t,e,r,i),Rs=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=o$(r,e);return so({prefix:t,name:e,encode:i,decode:n=>zg(s(n))})},d$=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},p$=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>so({prefix:e,name:t,encode(s){return p$(s,i,r)},decode(s){return d$(s,i,r,t)}}),g$=so({prefix:"\0",name:"identity",encode:t=>c$(t),decode:t=>a$(t)});var y$=Object.freeze({__proto__:null,identity:g$});const w$=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var m$=Object.freeze({__proto__:null,base2:w$});const b$=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var v$=Object.freeze({__proto__:null,base8:b$});const E$=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var x$=Object.freeze({__proto__:null,base10:E$});const _$=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),I$=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var S$=Object.freeze({__proto__:null,base16:_$,base16upper:I$});const O$=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$$=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),D$=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),A$=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),P$=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),B$=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),C$=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),T$=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),R$=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var U$=Object.freeze({__proto__:null,base32:O$,base32upper:$$,base32pad:D$,base32padupper:A$,base32hex:P$,base32hexupper:B$,base32hexpad:C$,base32hexpadupper:T$,base32z:R$});const N$=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),k$=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var j$=Object.freeze({__proto__:null,base36:N$,base36upper:k$});const F$=Rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),L$=Rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var M$=Object.freeze({__proto__:null,base58btc:F$,base58flickr:L$});const q$=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),z$=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),V$=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),H$=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var K$=Object.freeze({__proto__:null,base64:q$,base64pad:z$,base64url:V$,base64urlpad:H$});const Hg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),W$=Hg.reduce((t,e,r)=>(t[r]=e,t),[]),G$=Hg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Y$(t){return t.reduce((e,r)=>(e+=W$[r],e),"")}function Z$(t){const e=[];for(const r of t){const i=G$[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const J$=so({prefix:"🚀",name:"base256emoji",encode:Y$,decode:Z$});var X$=Object.freeze({__proto__:null,base256emoji:J$}),Q$=Kg,Ch=128,eD=-128,tD=Math.pow(2,31);function Kg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=tD;)e[r++]=t&255|Ch,t/=128;for(;t&eD;)e[r++]=t&255|Ch,t>>>=7;return e[r]=t|0,Kg.bytes=r-i+1,e}var rD=Ya,iD=128,Th=127;function Ya(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Th)<<s:(o&Th)*Math.pow(2,s),s+=7}while(o>=iD);return Ya.bytes=n-i,r}var sD=Math.pow(2,7),nD=Math.pow(2,14),oD=Math.pow(2,21),aD=Math.pow(2,28),cD=Math.pow(2,35),lD=Math.pow(2,42),uD=Math.pow(2,49),hD=Math.pow(2,56),fD=Math.pow(2,63),dD=function(t){return t<sD?1:t<nD?2:t<oD?3:t<aD?4:t<cD?5:t<lD?6:t<uD?7:t<hD?8:t<fD?9:10},pD={encode:Q$,decode:rD,encodingLength:dD},Wg=pD;const Rh=(t,e,r=0)=>(Wg.encode(t,e,r),e),Uh=t=>Wg.encodingLength(t),Za=(t,e)=>{const r=e.byteLength,i=Uh(t),s=i+Uh(r),n=new Uint8Array(s+r);return Rh(t,n,0),Rh(r,n,i),n.set(e,s),new gD(t,r,e,n)};class gD{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const Gg=({name:t,code:e,encode:r})=>new yD(t,e,r);class yD{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Za(this.code,r):r.then(i=>Za(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Yg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),wD=Gg({name:"sha2-256",code:18,encode:Yg("SHA-256")}),mD=Gg({name:"sha2-512",code:19,encode:Yg("SHA-512")});var bD=Object.freeze({__proto__:null,sha256:wD,sha512:mD});const Zg=0,vD="identity",Jg=zg,ED=t=>Za(Zg,Jg(t)),xD={code:Zg,name:vD,encode:Jg,digest:ED};var _D=Object.freeze({__proto__:null,identity:xD});new TextEncoder,new TextDecoder;const Nh={...y$,...m$,...v$,...x$,...S$,...U$,...j$,...M$,...K$,...X$};({...bD,..._D});function Xg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function ID(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Xg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Qg(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const kh=Qg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Jo=Qg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=ID(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),SD={utf8:kh,"utf-8":kh,hex:Nh.base16,latin1:Jo,ascii:Jo,binary:Jo,...Nh};function OD(t,e="utf8"){const r=SD[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var $D=Object.defineProperty,DD=(t,e,r)=>e in t?$D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rt=(t,e,r)=>DD(t,typeof e!="symbol"?e+"":e,r);class AD{constructor(e,r){this.core=e,this.logger=r,Rt(this,"keychain",new Map),Rt(this,"name",DO),Rt(this,"version",AO),Rt(this,"initialized",!1),Rt(this,"storagePrefix",Ht),Rt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Rt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Rt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),Rt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),Rt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=ht(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Aa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PD=Object.defineProperty,BD=(t,e,r)=>e in t?PD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xe=(t,e,r)=>BD(t,typeof e!="symbol"?e+"":e,r);class CD{constructor(e,r,i){this.core=e,this.logger=r,xe(this,"name",OO),xe(this,"keychain"),xe(this,"randomSessionIdentifier",Ma()),xe(this,"initialized",!1),xe(this,"clientId"),xe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),xe(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),xe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=cu(s),o=ep(n.publicKey);return this.clientId=o,o}),xe(this,"generateKeyPair",()=>{this.isInitialized();const s=gI();return this.setPrivateKey(s.publicKey,s.privateKey)}),xe(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=cu(n),a=this.randomSessionIdentifier;return await u2(a,s,$O,o)}),xe(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=yI(a,n);return this.setSymKey(c,o)}),xe(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||un(s);return await this.keychain.set(o,s),o}),xe(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),xe(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),xe(this,"encode",async(s,n,o)=>{this.isInitialized();const a=Sg(o),c=si(n);if(rh(a))return bI(c,o==null?void 0:o.encoding);if(th(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;s=await this.generateSharedKey(f,d)}const l=this.getSymKey(s),{type:u,senderPublicKey:h}=a;return wI({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),xe(this,"decode",async(s,n,o)=>{this.isInitialized();const a=EI(n,o);if(rh(a)){const c=vI(n,o==null?void 0:o.encoding);return ii(c)}if(th(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=mI({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return ii(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),xe(this,"getPayloadType",(s,n=Qe)=>{const o=vs({encoded:s,encoding:n});return oi(o.type)}),xe(this,"getPayloadSenderPublicKey",(s,n=Qe)=>{const o=vs({encoded:s,encoding:n});return o.senderPublicKey?rt(o.senderPublicKey,Ke):void 0}),this.core=e,this.logger=ht(r,this.name),this.keychain=i||new AD(this.core,this.logger)}get context(){return it(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ph)}catch{e=Ma(),await this.keychain.set(Ph,e)}return OD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var TD=Object.defineProperty,RD=Object.defineProperties,UD=Object.getOwnPropertyDescriptors,jh=Object.getOwnPropertySymbols,ND=Object.prototype.hasOwnProperty,kD=Object.prototype.propertyIsEnumerable,Ja=(t,e,r)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jD=(t,e)=>{for(var r in e||(e={}))ND.call(e,r)&&Ja(t,r,e[r]);if(jh)for(var r of jh(e))kD.call(e,r)&&Ja(t,r,e[r]);return t},FD=(t,e)=>RD(t,UD(e)),st=(t,e,r)=>Ja(t,typeof e!="symbol"?e+"":e,r);class LD extends x8{constructor(e,r){super(e,r),this.logger=e,this.core=r,st(this,"messages",new Map),st(this,"messagesWithoutClientAck",new Map),st(this,"name",PO),st(this,"version",BO),st(this,"initialized",!1),st(this,"storagePrefix",Ht),st(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),st(this,"set",async(i,s,n)=>{this.isInitialized();const o=wt(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===dn.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,FD(jD({},c),{[o]:s}))}return await this.persist(),o}),st(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),st(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),st(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=wt(s);return typeof n[o]<"u"}),st(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=wt(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),st(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=ht(e,this.name),this.core=r}get context(){return it(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,Aa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Aa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Pa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Pa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MD=Object.defineProperty,qD=Object.defineProperties,zD=Object.getOwnPropertyDescriptors,Fh=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,HD=Object.prototype.propertyIsEnumerable,Xa=(t,e,r)=>e in t?MD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mi=(t,e)=>{for(var r in e||(e={}))VD.call(e,r)&&Xa(t,r,e[r]);if(Fh)for(var r of Fh(e))HD.call(e,r)&&Xa(t,r,e[r]);return t},Lh=(t,e)=>qD(t,zD(e)),pt=(t,e,r)=>Xa(t,typeof e!="symbol"?e+"":e,r);class KD extends _8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,pt(this,"events",new xt.EventEmitter),pt(this,"name",TO),pt(this,"queue",new Map),pt(this,"publishTimeout",q.toMiliseconds(q.ONE_MINUTE)),pt(this,"initialPublishTimeout",q.toMiliseconds(q.ONE_SECOND*15)),pt(this,"needsTransportRestart",!1),pt(this,"publish",async(i,s,n)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const h=(n==null?void 0:n.ttl)||CO,f=(n==null?void 0:n.prompt)||!1,d=(n==null?void 0:n.tag)||0,g=(n==null?void 0:n.id)||Cr().toString(),w=_i(Cn().protocol),m={id:g,method:(n==null?void 0:n.publishMethod)||w.publish,params:mi({topic:i,message:s,ttl:h,prompt:f,tag:d,attestation:n==null?void 0:n.attestation},n==null?void 0:n.tvf)},O=`Failed to publish payload, please try again. id:${g} tag:${d}`;try{Oe((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Oe((c=m.params)==null?void 0:c.tag)&&((l=m.params)==null||delete l.tag);const C=new Promise(async b=>{const x=({id:B})=>{var T;((T=m.id)==null?void 0:T.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(ye.publish,x),b())};this.relayer.events.on(ye.publish,x);const A=qt(new Promise((B,T)=>{this.rpcPublish(m,n).then(B).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${d}`);try{await A,this.events.removeListener(ye.publish,x)}catch(B){this.queue.set(g,{request:m,opts:n,attempt:1}),this.logger.warn(B,B==null?void 0:B.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:i,message:s,opts:n}}),await qt(C,this.publishTimeout,O)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(u=n==null?void 0:n.internal)!=null&&u.throwOnFailedPublish)throw C}finally{this.queue.delete(g)}}),pt(this,"publishCustom",async i=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:g,tag:w,ttl:m=q.FIVE_MINUTES}=u,O=u.id||Cr().toString(),C=_i(Cn().protocol),b=d||C.publish,x={id:O,method:b,params:mi(Lh(mi({},l),{ttl:m,prompt:g,tag:w,attestation:h}),f)},A=`Failed to publish custom payload, please try again. id:${O} tag:${w}`;try{Oe((s=x.params)==null?void 0:s.prompt)&&((n=x.params)==null||delete n.prompt),Oe((o=x.params)==null?void 0:o.tag)&&((a=x.params)==null||delete a.tag);const B=new Promise(async T=>{const R=({id:k})=>{var j;((j=x.id)==null?void 0:j.toString())===k.toString()&&(this.removeRequestFromQueue(k),this.relayer.events.removeListener(ye.publish,R),T())};this.relayer.events.on(ye.publish,R);const D=qt(new Promise((k,j)=>{this.rpcPublish(x,u).then(k).catch(P=>{this.logger.warn(P,P==null?void 0:P.message),j(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${O} tag:${w}`);try{await D,this.events.removeListener(ye.publish,R)}catch(k){this.queue.set(O,{request:x,opts:u,attempt:1}),this.logger.warn(k,k==null?void 0:k.message)}});this.logger.trace({type:"method",method:"publish",params:{id:O,payload:l,opts:u}}),await qt(B,this.publishTimeout,A)}catch(B){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(B),(c=u==null?void 0:u.internal)!=null&&c.throwOnFailedPublish)throw B}finally{this.queue.delete(O)}}),pt(this,"on",(i,s)=>{this.events.on(i,s)}),pt(this,"once",(i,s)=>{this.events.once(i,s)}),pt(this,"off",(i,s)=>{this.events.off(i,s)}),pt(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=ht(r,this.name),this.registerEventListeners()}get context(){return it(this.logger)}async rpcPublish(e,r){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(ye.publish,mi(mi({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const s=e.attempt+1;this.queue.set(r,Lh(mi({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ui.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ye.connection_stalled);return}this.checkQueue()}),this.relayer.on(ye.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var WD=Object.defineProperty,GD=(t,e,r)=>e in t?WD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bi=(t,e,r)=>GD(t,typeof e!="symbol"?e+"":e,r);class YD{constructor(){bi(this,"map",new Map),bi(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),bi(this,"get",e=>this.map.get(e)||[]),bi(this,"exists",(e,r)=>this.get(e).includes(r)),bi(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),bi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var ZD=Object.defineProperty,JD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,QD=Object.prototype.hasOwnProperty,eA=Object.prototype.propertyIsEnumerable,Qa=(t,e,r)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qi=(t,e)=>{for(var r in e||(e={}))QD.call(e,r)&&Qa(t,r,e[r]);if(Mh)for(var r of Mh(e))eA.call(e,r)&&Qa(t,r,e[r]);return t},Xo=(t,e)=>JD(t,XD(e)),oe=(t,e,r)=>Qa(t,typeof e!="symbol"?e+"":e,r);class tA extends O8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,oe(this,"subscriptions",new Map),oe(this,"topicMap",new YD),oe(this,"events",new xt.EventEmitter),oe(this,"name",LO),oe(this,"version",MO),oe(this,"pending",new Map),oe(this,"cached",[]),oe(this,"initialized",!1),oe(this,"storagePrefix",Ht),oe(this,"subscribeTimeout",q.toMiliseconds(q.ONE_MINUTE)),oe(this,"initialSubscribeTimeout",q.toMiliseconds(q.ONE_SECOND*15)),oe(this,"clientId"),oe(this,"batchSubscribeTopicsLimit",500),oe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),oe(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=Cn(s),a={topic:i,relay:o,transportType:s==null?void 0:s.transportType};(n=s==null?void 0:s.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),oe(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),oe(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),oe(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),oe(this,"on",(i,s)=>{this.events.on(i,s)}),oe(this,"once",(i,s)=>{this.events.once(i,s)}),oe(this,"off",(i,s)=>{this.events.off(i,s)}),oe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),oe(this,"start",async()=>{await this.onConnect()}),oe(this,"stop",async()=>{await this.onDisconnect()}),oe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),oe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),oe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ui.pulse,async()=>{await this.checkPending()}),this.events.on(at.created,async i=>{const s=at.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(at.deleted,async i=>{const s=at.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=ht(r,this.name),this.clientId=""}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const s=Cn(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=ue("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s,n;const o=await this.getSubscriptionId(e);if((s=i==null?void 0:i.internal)!=null&&s.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:_i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=i==null?void 0:i.internal)==null?void 0:n.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},q.toMiliseconds(q.ONE_SECOND)),o;const l=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(at.created,f),h(d.id))};this.events.on(at.created,f);try{const d=await qt(new Promise((g,w)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m==null?void 0:m.message),w(m)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(at.created,f),h(d)}catch{}}),u=await qt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ye.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await qt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ye.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:_i(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await qt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ye.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:_i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,Xo(Qi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Qi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,Qi({},r)),this.topicMap.set(r.topic,e),this.events.emit(at.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(at.deleted,Xo(Qi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(at.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(at.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Xo(Qi({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Ux(q.toMiliseconds(q.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=z("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 wt(e+await this.getClientId())}}var rA=Object.defineProperty,qh=Object.getOwnPropertySymbols,iA=Object.prototype.hasOwnProperty,sA=Object.prototype.propertyIsEnumerable,ec=(t,e,r)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zh=(t,e)=>{for(var r in e||(e={}))iA.call(e,r)&&ec(t,r,e[r]);if(qh)for(var r of qh(e))sA.call(e,r)&&ec(t,r,e[r]);return t},re=(t,e,r)=>ec(t,typeof e!="symbol"?e+"":e,r);class nA extends I8{constructor(e){var r;super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new xt.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",UO),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",q.toMiliseconds(q.THIRTY_SECONDS+q.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",q.toMiliseconds(q.ONE_SECOND*15)),re(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||Cr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),re(this,"resetPingTimeout",()=>{On()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),re(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(ye.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(ye.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),re(this,"registerProviderListeners",()=>{this.provider.on(dt.payload,this.onPayloadHandler),this.provider.on(dt.connect,this.onConnectHandler),this.provider.on(dt.disconnect,this.onDisconnectHandler),this.provider.on(dt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Wc({logger:(r=e.logger)!=null?r:RO,name:this.name}),this.messages=new LD(this.logger,e.core),this.subscriber=new tA(this,this.logger),this.publisher=new KD(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Mg,bx()?this.packageName=_u():vx()&&(this.bundleId=_u()),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==null?void 0:e.message))}get context(){return it(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:le.relay},dn.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(at.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(at.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,zh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await qt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await gh())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=ge(q.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(ye.message,e),await this.recordMessageEvent(e,dn.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(dt.disconnect,n),await qt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(dt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(dt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(dt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,q.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(On())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Zc(new xO(Sx({sdkVersion:Ga,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:s}=e;await this.messages.set(i,s,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Yc(e)){if(!e.method.endsWith(NO))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(zh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else io(e)&&this.events.emit(ye.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,dn.inbound),this.events.emit(ye.message,e))}async acknowledgePayload(e){const r=xs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(dt.payload,this.onPayloadHandler),this.provider.off(dt.connect,this.onConnectHandler),this.provider.off(dt.disconnect,this.onDisconnectHandler),this.provider.off(dt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await gh();ES(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ui.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&IS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ye.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},q.toMiliseconds(kO)))))}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function oA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Vh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const aA="[object RegExp]",cA="[object String]",lA="[object Number]",uA="[object Boolean]",Kh="[object Arguments]",hA="[object Symbol]",fA="[object Date]",dA="[object Map]",pA="[object Set]",gA="[object Array]",yA="[object Function]",wA="[object ArrayBuffer]",Qo="[object Object]",mA="[object Error]",bA="[object DataView]",vA="[object Uint8Array]",EA="[object Uint8ClampedArray]",xA="[object Uint16Array]",_A="[object Uint32Array]",IA="[object BigUint64Array]",SA="[object Int8Array]",OA="[object Int16Array]",$A="[object Int32Array]",DA="[object BigInt64Array]",AA="[object Float32Array]",PA="[object Float64Array]";function BA(){}function Wh(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function CA(t,e,r){return os(t,e,void 0,void 0,void 0,void 0,r)}function os(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return fs(t,e,n,o)}return fs(t,e,n,o)}function fs(t,e,r,i){if(Object.is(t,e))return!0;let s=Hh(t),n=Hh(e);if(s===Kh&&(s=Qo),n===Kh&&(n=Qo),s!==n)return!1;switch(s){case cA:return t.toString()===e.toString();case lA:{const c=t.valueOf(),l=e.valueOf();return oA(c,l)}case uA:case fA:case hA:return Object.is(t.valueOf(),e.valueOf());case aA:return t.source===e.source&&t.flags===e.flags;case yA:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(s){case dA:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!os(l,e.get(c),c,t,e,r,i))return!1;return!0}case pA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(d=>os(h,d,void 0,t,e,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case gA:case vA:case EA:case xA:case _A:case IA:case SA:case OA:case $A:case DA:case AA:case PA:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!os(t[c],e[c],c,t,e,r,i))return!1;return!0}case wA:return t.byteLength!==e.byteLength?!1:fs(new Uint8Array(t),new Uint8Array(e),r,i);case bA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:fs(new Uint8Array(t),new Uint8Array(e),r,i);case mA:return t.name===e.name&&t.message===e.message;case Qo:{if(!(fs(t.constructor,e.constructor,r,i)||Wh(t)&&Wh(e)))return!1;const c=[...Object.keys(t),...Vh(t)],l=[...Object.keys(e),...Vh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!os(f,d,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function TA(t,e){return CA(t,e,BA)}var RA=Object.defineProperty,Gh=Object.getOwnPropertySymbols,UA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,tc=(t,e,r)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))UA.call(e,r)&&tc(t,r,e[r]);if(Gh)for(var r of Gh(e))NA.call(e,r)&&tc(t,r,e[r]);return t},Ge=(t,e,r)=>tc(t,typeof e!="symbol"?e+"":e,r);class fi extends S8{constructor(e,r,i,s=Ht,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,Ge(this,"map",new Map),Ge(this,"version",jO),Ge(this,"cached",[]),Ge(this,"initialized",!1),Ge(this,"getKey"),Ge(this,"storagePrefix",Ht),Ge(this,"recentlyDeleted",[]),Ge(this,"recentlyDeletedLimit",200),Ge(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Oe(o)?this.map.set(this.getKey(o),o):XI(o)?this.map.set(o.id,o):QI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ge(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),Ge(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ge(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>TA(a[c],o[c]))):this.values)),Ge(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Yh(Yh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ge(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=ht(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var kA=Object.defineProperty,jA=(t,e,r)=>e in t?kA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q=(t,e,r)=>jA(t,typeof e!="symbol"?e+"":e,r);class FA{constructor(e,r){this.core=e,this.logger=r,Q(this,"name",qO),Q(this,"version",zO),Q(this,"events",new uc),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",Ht),Q(this,"ignoredPayloadTypes",[lr]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),Q(this,"create",async i=>{this.isInitialized();const s=Ma(),n=await this.core.crypto.setSymKey(s),o=ge(q.FIVE_MINUTES),a={protocol:Lg},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=oh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Wr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:n,uri:l}}),Q(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[Nt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=nh(i.uri);s.props.properties.topic=n,s.addTrace(Nt.pairing_uri_validation_success),s.addTrace(Nt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),s.addTrace(Nt.existing_pairing),u.active)throw s.setError(tr.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(Nt.pairing_not_expired)}const h=c||ge(q.FIVE_MINUTES),f={topic:n,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(n,h),await this.pairings.set(n,f),s.addTrace(Nt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Wr.create,f),s.addTrace(Nt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(Nt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(tr.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(d){throw s.setError(tr.subscribe_pairing_topic_failure),d}return s.addTrace(Nt.subscribe_pairing_topic_success),f}),Q(this,"activate",async({topic:i})=>{this.isInitialized();const s=ge(q.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),Q(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Vr();this.events.once(ne("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),Q(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),Q(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",ue("USER_DISCONNECTED")),await this.deletePairing(s))}),Q(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return oh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(i,s,n)=>{const o=Dt(s,n),a=await this.core.crypto.encode(i,o),c=Ji[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),Q(this,"sendResult",async(i,s,n)=>{const o=xs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Ji[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Q(this,"sendError",async(i,s,n)=>{const o=ro(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Ji[c]?Ji[c].res:Ji.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,ue("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),Q(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Lt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),Q(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),Q(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Wr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{jt(s)?this.events.emit(ne("pairing_ping",n),{}):mt(s)&&this.events.emit(ne("pairing_ping",n),{error:s.error})},500)}),Q(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Wr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=ue("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(ue("WC_METHOD_UNSUPPORTED",i))}),Q(this,"isValidPair",(i,s)=>{var n;if(!Ze(i)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(!JI(i.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(tr.malformed_pairing_uri),new Error(a)}const o=nh(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(tr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&q.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(tr.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async i=>{if(!Ze(i)){const{message:n}=z("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidDisconnect",async i=>{if(!Ze(i)){const{message:n}=z("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidPairingTopic",async i=>{if(!we(i,!1)){const{message:s}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Lt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=z("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=ht(r,this.name),this.pairings=new fi(this.core,this.logger,this.name,this.storagePrefix)}get context(){return it(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ye.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);Yc(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):io(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(gt.expired,async e=>{const{topic:r}=$p(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Wr.expire,{topic:r}))})}}var LA=Object.defineProperty,MA=(t,e,r)=>e in t?LA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>MA(t,typeof e!="symbol"?e+"":e,r);class qA extends E8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Pe(this,"records",new Map),Pe(this,"events",new xt.EventEmitter),Pe(this,"name",VO),Pe(this,"version",HO),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Ht),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Pe(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:ge(q.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(It.created,o)}),Pe(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=mt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(It.updated,s))}),Pe(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),Pe(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(It.deleted,n)}}),this.persist()}),Pe(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),Pe(this,"on",(i,s)=>{this.events.on(i,s)}),Pe(this,"once",(i,s)=>{this.events.once(i,s)}),Pe(this,"off",(i,s)=>{this.events.off(i,s)}),Pe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ht(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Dt(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(It.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(It.created,e=>{const r=It.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(It.updated,e=>{const r=It.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(It.deleted,e=>{const r=It.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ui.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{q.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(It.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zA=Object.defineProperty,VA=(t,e,r)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Me=(t,e,r)=>VA(t,typeof e!="symbol"?e+"":e,r);class HA extends $8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Me(this,"expirations",new Map),Me(this,"events",new xt.EventEmitter),Me(this,"name",KO),Me(this,"version",WO),Me(this,"cached",[]),Me(this,"initialized",!1),Me(this,"storagePrefix",Ht),Me(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Me(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Me(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(gt.created,{target:n,expiration:o})}),Me(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Me(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(gt.deleted,{target:s,expiration:n})}}),Me(this,"on",(i,s)=>{this.events.on(i,s)}),Me(this,"once",(i,s)=>{this.events.once(i,s)}),Me(this,"off",(i,s)=>{this.events.off(i,s)}),Me(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ht(r,this.name)}get context(){return it(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Ox(e);if(typeof e=="number")return $x(e);const{message:r}=z("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(gt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;q.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(gt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ui.pulse,()=>this.checkExpirations()),this.events.on(gt.created,e=>{const r=gt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(gt.expired,e=>{const r=gt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(gt.deleted,e=>{const r=gt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KA=Object.defineProperty,WA=(t,e,r)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pe=(t,e,r)=>WA(t,typeof e!="symbol"?e+"":e,r);class GA extends D8{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,pe(this,"name",GO),pe(this,"abortController"),pe(this,"isDevEnv"),pe(this,"verifyUrlV3",ZO),pe(this,"storagePrefix",Ht),pe(this,"version",Fg),pe(this,"publicKey"),pe(this,"fetchPromise"),pe(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&q.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),pe(this,"register",async s=>{if(!ji()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=ti(),u=this.startAbortTimer(q.ONE_SECOND*5),h=await new Promise((f,d)=>{const g=()=>{window.removeEventListener("message",m),l.body.removeChild(w),d("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const w=l.createElement("iframe");w.src=c,w.style.display="none",w.addEventListener("error",g,{signal:this.abortController.signal});const m=O=>{if(O.data&&typeof O.data=="string")try{const C=JSON.parse(O.data);if(C.type==="verify_attestation"){if(Sa(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(w),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",m),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(w),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),pe(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Sa(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),pe(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(q.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),pe(this,"getVerifyUrl",s=>{let n=s||hs;return JO.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${hs}`),n=hs),n}),pe(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(q.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),pe(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),pe(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),pe(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),pe(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),pe(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),pe(this,"validateAttestation",(s,n)=>{const o=_I(s,n.publicKey),a={hasExpired:q.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=ht(r,this.name),this.abortController=new AbortController,this.isDevEnv=Nc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return it(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),q.toMiliseconds(e))}}var YA=Object.defineProperty,ZA=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zh=(t,e,r)=>ZA(t,typeof e!="symbol"?e+"":e,r);class JA extends A8{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Zh(this,"context",XO),Zh(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${QO}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=ht(r,this.context)}}var XA=Object.defineProperty,Jh=Object.getOwnPropertySymbols,QA=Object.prototype.hasOwnProperty,e6=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,es=(t,e)=>{for(var r in e||(e={}))QA.call(e,r)&&rc(t,r,e[r]);if(Jh)for(var r of Jh(e))e6.call(e,r)&&rc(t,r,e[r]);return t},_e=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class t6 extends P8{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,_e(this,"context",t$),_e(this,"storagePrefix",Ht),_e(this,"storageVersion",e$),_e(this,"events",new Map),_e(this,"shouldPersist",!1),_e(this,"init",async()=>{if(!Nc())try{const s={eventId:Su(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Sp(this.core.relayer.protocol,this.core.relayer.version,Ga)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),_e(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=Su(),u=this.core.projectId||"",h=Date.now(),f=es({eventId:l,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),_e(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return es(es({},a),this.setMethods(a.eventId))}),_e(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),_e(this,"setEventListeners",()=>{this.core.heartbeat.on(ui.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{q.fromMiliseconds(Date.now())-q.fromMiliseconds(s.timestamp)>r$&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),_e(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),_e(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),_e(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),_e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),_e(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,es(es({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),_e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),_e(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${i$}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ga}${n}`,{method:"POST",body:JSON.stringify(s)})}),_e(this,"getAppDomain",()=>Ip().url),this.logger=ht(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var r6=Object.defineProperty,Xh=Object.getOwnPropertySymbols,i6=Object.prototype.hasOwnProperty,s6=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?r6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qh=(t,e)=>{for(var r in e||(e={}))i6.call(e,r)&&ic(t,r,e[r]);if(Xh)for(var r of Xh(e))s6.call(e,r)&&ic(t,r,e[r]);return t},ae=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);let n6=class ey extends w8{constructor(e){var r;super(e),ae(this,"protocol",jg),ae(this,"version",Fg),ae(this,"name",Wa),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new xt.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Mg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=sx({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:IO.logger,name:Wa}),{logger:n,chunkLoggerController:o}=xp({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ht(n,this.name),this.heartbeat=new RS,this.crypto=new CD(this,this.logger,e==null?void 0:e.keychain),this.history=new qA(this,this.logger),this.expirer=new HA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new p8(Qh(Qh({},SO),e==null?void 0:e.storageOptions)),this.relayer=new nA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new FA(this,this.logger),this.verify=new GA(this,this.logger,this.storage),this.echoClient=new JA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new t6(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new ey(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(FO,i),r}get context(){return it(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Bh,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(Bh)||[],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 r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&_O.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const o6=n6,ty="wc",ry=2,iy="client",Jc=`${ty}@${ry}:${iy}:`,ea={name:iy,logger:"error"},ef="WALLETCONNECT_DEEPLINK_CHOICE",a6="proposal",tf="Proposal expired",c6="session",vi=q.SEVEN_DAYS,l6="engine",Be={wc_sessionPropose:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1114},res:{ttl:q.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:q.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:q.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1119}}},ta={min:q.FIVE_MINUTES,max:q.SEVEN_DAYS},Ut={idle:"IDLE",active:"ACTIVE"},u6={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:""}},h6="request",f6=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],d6="wc",p6="auth",g6="authKeys",y6="pairingTopics",w6="requests",no=`${d6}@${1.5}:${p6}:`,pn=`${no}:PUB_KEY`;var m6=Object.defineProperty,b6=Object.defineProperties,v6=Object.getOwnPropertyDescriptors,rf=Object.getOwnPropertySymbols,E6=Object.prototype.hasOwnProperty,x6=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?m6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e)=>{for(var r in e||(e={}))E6.call(e,r)&&sc(t,r,e[r]);if(rf)for(var r of rf(e))x6.call(e,r)&&sc(t,r,e[r]);return t},Ce=(t,e)=>b6(t,v6(e)),F=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class _6 extends R8{constructor(e){super(e),F(this,"name",l6),F(this,"events",new uc),F(this,"initialized",!1),F(this,"requestQueue",{state:Ut.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Ut.idle,queue:[]}),F(this,"emittedSessionRequests",new Nx({limit:500})),F(this,"requestQueueDelay",q.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Be)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ce(se({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=KI(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=s,d=((i=h==null?void 0:h[0])==null?void 0:i.ttl)||Be.wc_sessionPropose.req.ttl||q.FIVE_MINUTES;this.validateRequestExpiry(d);let g=n,w,m=!1;try{if(g){const D=this.client.core.pairing.pairings.get(g);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${g}) failed`),D}if(!g||!m){const{topic:D,uri:k}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});g=D,w=k}if(!g){const{message:D}=z("NO_MATCHING_KEY",`connect() pairing topic: ${g}`);throw new Error(D)}const O=await this.client.core.crypto.generateKeyPair(),C=ge(d),b=se(Ce(se(se({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:Lg}],proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:g},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:kt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(D=>{const{domain:k,chains:j,nonce:P,uri:I,exp:$,nbf:p,type:y,statement:v,requestId:S,resources:E,signatureTypes:_}=D;return{domain:k,chains:j,nonce:P,type:y??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:$,nbf:p,statement:v,requestId:S,resources:E,signatureTypes:_}}),walletPay:f}}),x=ne("session_connect",b.id),{reject:A,resolve:B,done:T}=Vr(d,tf),R=({id:D})=>{D===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(x,{error:{message:tf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(x,({error:D,session:k})=>{this.client.events.off("proposal_expire",R),D?A(D):k&&B(k)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(D=>{throw this.deleteProposal(b.id),D}),{uri:w,approval:T}}),F(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),F(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[St.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(k){throw o.setError(Mr.no_internet_connection),k}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(k){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(Mr.proposal_not_found),k}try{await this.isValidApprove(r)}catch(k){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Mr.session_approve_namespace_validation_failure),k}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:O,optionalNamespaces:C}=g;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:St.session_approve_started,properties:{topic:w,trace:[St.session_approve_started,St.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),A=m.publicKey,B=await this.client.core.crypto.generateSharedKey(x,A),T=Ce(se(se(se({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:x,metadata:this.client.metadata},expiry:ge(vi)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=le.relay;b.addTrace(St.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:R,internal:{skipSubscribe:!0}})}catch(k){throw b.setError(Mr.subscribe_session_topic_failure),k}b.addTrace(St.subscribe_session_topic_success);const D=Ce(se({},T),{topic:B,requiredNamespaces:O,optionalNamespaces:C,pairingTopic:w,acknowledged:!1,self:T.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:x,transportType:le.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(B,D),b.addTrace(St.store_session);try{await this.sendApproveSession({sessionTopic:B,proposal:g,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:se({correlationId:a},this.getTVFApproveParams(D))}}),b.addTrace(St.session_approve_publish_success)}catch(k){throw this.client.logger.error(k),this.client.session.delete(B,ue("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),k}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(B,ge(vi)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}}),F(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&await this.sendError({id:i,topic:n,error:s,rpcOpts:Be.wc_sessionPropose.reject}),await this.deleteProposal(i)}),F(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:s}=r,{done:n,resolve:o,reject:a}=Vr(q.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=kt(),l=Cr().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ne("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:n}}),F(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,s=kt(),{done:n,resolve:o,reject:a}=Vr(q.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ne("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,ge(vi)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),F(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:i,request:s,topic:n,expiry:o=Be.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);(a==null?void 0:a.transportType)===le.relay&&await this.confirmOnlineStateOrThrow();const c=kt(),l=Cr().toString(),{done:u,resolve:h,reject:f}=Vr(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:m,result:O})=>{m?f(m):h(O)});const d="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:d,params:{request:Ce(se({},s),{expiryTimestamp:ge(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(m=>f(m)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await u();const w={request:Ce(se({},s),{expiryTimestamp:ge(o)}),chainId:i};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:d,params:w,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,w)}).catch(O=>f(O)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),m()}),new Promise(async m=>{var O;if(!((O=a.sessionConfig)!=null&&O.disableDeepLink)){const C=await Bx(this.client.core.storage,ef);await Dx({id:c,topic:n,wcDeepLink:C})}m()}),u()]).then(m=>m[2])}),F(this,"respond",async r=>{var i,s;this.isInitialized();const n=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((s=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:s.toString()),trace:[St.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw n.addTrace(h==null?void 0:h.message),n.setError(Mr.session_request_response_validation_failure),h}n.addTrace(St.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,l=this.client.session.get(o);l.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{n.addTrace(St.session_request_response_publish_started),jt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):mt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(r)}catch(h){throw n.addTrace(h==null?void 0:h.message),n.setError(Mr.session_request_response_publish_failure),h}}),F(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=kt(),n=Cr().toString(),{done:o,resolve:a,reject:c}=Vr(q.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ne("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),F(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=Cr().toString(),a=kt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:ue("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),F(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>YI(i,r)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:d,nbf:g,methods:w=[],expiry:m}=r,O=[...r.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const x=await this.client.core.crypto.generateKeyPair(),A=un(x);if(await Promise.all([this.client.auth.authKeys.set(pn,{responseTopic:A,publicKey:x}),this.client.auth.pairingTopics.set(A,{topic:A,pairingTopic:C})]),await this.client.core.relayer.subscribe(A,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),w.length>0){const{namespace:E}=cr(a[0]);let _=Y_(E,"request",w);ln(O)&&(_=J_(_,O.pop())),O.push(_)}const B=m&&m>Be.wc_sessionAuthenticate.req.ttl?m:Be.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:g,resources:O},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:ge(B)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...w])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:ge(Be.wc_sessionPropose.req.ttl),id:kt()},{done:k,resolve:j,reject:P}=Vr(B,"Request expired"),I=kt(),$=ne("session_connect",D.id),p=ne("session_request",I),y=async({error:E,session:_})=>{this.events.off(p,v),E?P(E):_&&j({session:_})},v=async E=>{var _,U,N;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const W=ue("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off($,y),P(E.error.message))}await this.deleteProposal(D.id),this.events.off($,y);const{cacaos:V,responder:L}=E.result,M=[],K=[];for(const W of V){await Nu({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),P(ue("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:X}=W,fe=ln(X.resources),me=[Ba(X.iss)],Ee=Dn(X.iss);if(fe){const ze=ku(fe),Kt=ju(fe);M.push(...ze),me.push(...Kt)}for(const ze of me)K.push(`${ze}:${Ee}`)}const G=await this.client.core.crypto.generateSharedKey(x,L.publicKey);let J;M.length>0&&(J={topic:G,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:ge(vi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:uh([...new Set(M)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,J),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:L.metadata}),J=this.client.session.get(G)),(_=this.client.metadata.redirect)!=null&&_.linkMode&&(U=L.metadata.redirect)!=null&&U.linkMode&&(N=L.metadata.redirect)!=null&&N.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(G,{transportType:le.link_mode})),j({auths:V,session:J})};this.events.once($,y),this.events.once(p,v);let S;try{if(n){const E=Dt("wc_sessionAuthenticate",T,I);this.client.core.history.set(C,E);const _=await this.client.core.crypto.encode("",E,{type:Cs,encoding:Pr});S=Xs(i,C,_)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:D,expiry:Be.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch(E){throw this.events.off($,y),this.events.off(p,v),E}return await this.setProposal(D.id,D),await this.setAuthRequest(I,{request:Ce(se({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:S??b,response:k}}),F(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[qr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw n.setError(Xi.no_internet_connection),m}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Xi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=un(c),h={type:lr,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const m of s){if(!await Nu({cacao:m,projectId:this.client.core.projectId})){n.setError(Xi.invalid_cacao);const A=ue("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:A,encodeOpts:h}),new Error(A.message)}n.addTrace(qr.cacaos_verified);const{p:O}=m,C=ln(O.resources),b=[Ba(O.iss)],x=Dn(O.iss);if(C){const A=ku(C),B=ju(C);f.push(...A),b.push(...B)}for(const A of b)d.push(`${A}:${x}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(qr.create_authenticated_session_topic);let w;if((f==null?void 0:f.length)>0){w={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ge(vi),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:uh([...new Set(f)],[...new Set(d)]),transportType:a},n.addTrace(qr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(m){throw n.setError(Xi.subscribe_authenticated_session_topic_failure),m}n.addTrace(qr.subscribe_authenticated_session_topic_success),await this.client.session.set(g,w),n.addTrace(qr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(qr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw n.setError(Xi.authenticated_session_approve_publish_failure),m}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:w}}),F(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=un(o),l={type:lr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:l,rpcOpts:Be.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),F(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return Vp(i,s)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),F(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),F(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,ue("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(ef).catch(l=>this.client.logger.warn(l)),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Ut.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===s).map(l=>this.deletePendingSessionRequest(l.id,ue("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),F(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Mr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,ue("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),F(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=Ut.idle,this.client.events.emit("session_request_expire",{id:r}))}),F(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),F(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),F(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,ge(Be.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),F(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=le.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||ge(Be.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),F(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,d=Dt(s,n,c);let g;const w=!!u;try{const C=w?Pr:Qe;g=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let m;if(f6.includes(s)){const C=wt(JSON.stringify(d)),b=wt(g);m=await this.client.core.verify.register({id:b,decryptedId:C})}const O=se(se({},Be[s].req),f);if(O.attestation=m,o&&(O.ttl=o),a&&(O.id=a),this.client.core.history.set(i,d),w){const C=Xs(u,i,g);await global.Linking.openURL(C,this.client.name)}else O.tvf=Ce(se({},h),{correlationId:d.id}),l?(O.internal=Ce(se({},O.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,g,O)):this.client.core.relayer.publish(i,g,O).catch(C=>this.client.logger.error(C));return d.id}),F(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:s}=r,n=Dt("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,n);const o=await this.client.core.crypto.encode(i.pairingTopic,n,{encoding:Qe}),a=wt(JSON.stringify(n)),c=wt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Ce(se({},s),{publishMethod:"wc_proposeSession",attestation:l})})}),F(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:s,proposal:n,sessionSettleRequest:o,publishOpts:a}=r,c=xs(n.id,s),l=await this.client.core.crypto.encode(n.pairingTopic,c,{encoding:Qe}),u=Dt("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(i,u,{encoding:Qe});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:n.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Ce(se({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=xs(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const g=h?Pr:Qe;u=await this.client.core.crypto.encode(s,l,Ce(se({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),g}let f,d;try{f=await this.client.core.history.get(s,i);const g=f.request;try{d=this.getTVFParams(i,g.params,n)}catch(w){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${w==null?void 0:w.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),g}if(h){const g=Xs(c,s,u);await global.Linking.openURL(g,this.client.name)}else{const g=f.request.method,w=Be[g].res;w.tvf=Ce(se({},d),{correlationId:i}),o?(w.internal=Ce(se({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,w)):this.client.core.relayer.publish(s,u,w).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),F(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=ro(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?Pr:Qe;u=await this.client.core.crypto.encode(s,l,Ce(se({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),d}let f;try{f=await this.client.core.history.get(s,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),d}if(h){const d=Xs(c,s,u);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=a||Be[d].res;this.client.core.relayer.publish(s,u,g)}await this.client.core.history.resolve(l)}),F(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Lt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Lt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),F(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),F(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ut.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Ut.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Ut.idle}),F(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=z("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),F(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(tr.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const u=a.expiryTimestamp||ge(Be.wc_sessionPropose.req.ttl),h=se({id:c,pairingTopic:i,expiryTimestamp:u,attestation:n,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:n,hash:wt(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});l==null||l.addTrace(Nt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:Be.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),F(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(jt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:r,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(mt(i)){await this.deleteProposal(n);const o=ne("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),F(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,g=[...this.pendingSessions.values()].find(O=>O.sessionTopic===r);if(!g)return this.client.logger.error(`Pending session not found for topic ${r}`);const w=this.client.proposal.get(g.proposalId),m=Ce(se(se(se({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:le.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(ne("session_connect",g.proposalId),{session:m})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;jt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ne("session_approve",s),{})):mt(i)&&(await this.client.session.delete(r,ue("USER_DISCONNECTED")),this.events.emit(ne("session_approve",s),{error:i.error}))}),F(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=Zi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:ue("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:r},s));try{Zi.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0})}catch(c){throw Zi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=ne("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_update",s),{}):mt(i)&&this.events.emit(ne("session_update",s),{error:i.error})}),F(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,ge(vi)),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=ne("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_extend",s),{}):mt(i)&&this.events.emit(ne("session_extend",s),{error:i.error})}),F(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=ne("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);jt(i)?this.events.emit(ne("session_ping",s),{}):mt(i)&&this.events.emit(ne("session_ping",s),{error:i.error})},500)}),F(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:ue("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:s})}catch(n){this.client.logger.error(n)}}),F(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:h,params:f}=a;try{await this.isValidRequest(se({topic:o},f));const d=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:wt(JSON.stringify(Dt("wc_sessionRequest",f,h))),encryptedId:l,metadata:d.peer.metadata,transportType:u}),w={id:h,topic:o,params:f,verifyContext:g};await this.setPendingSessionRequest(w),u===le.link_mode&&(i=d.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=d.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(w):(this.addSessionRequestToSessionRequestQueue(w),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),F(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=ne("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);jt(i)?this.events.emit(ne("session_request",s),{result:i.result}):mt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),F(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=Zi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),Zi.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),jt(i)?this.events.emit(ne("session_request",s),{result:i.result}):mt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),F(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:h}=n.params,f=await this.getVerifyContext({attestationId:o,hash:wt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),d={requester:l,pairingTopic:s,id:n.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:d,pairingTopic:s,transportType:c}),c===le.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(n.params.requester.metadata,c),d={type:lr,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:l,encodeOpts:d,rpcOpts:Be.wc_sessionAuthenticate.autoReject,appLink:f})}}),F(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),F(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ut.idle,this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{this.events.emit(ne("session_request",n.request.id),{error:i})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ut.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),F(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Ut.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),F(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Dt("wc_sessionPropose",Ce(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),F(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:l}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Oe(i)||await this.isValidPairingTopic(i),!aS(c)){const{message:l}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!Oe(s)&&Vt(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(n&&!Oe(n)&&Vt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),o&&!Oe(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Oe(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),F(this,"validateNamespaces",(r,i)=>{const s=oS(r,"connect()",i);if(s)throw new Error(s.message)}),F(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=Wo(s,"approve()");if(l)throw new Error(l.message);const u=dh(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!we(n,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(o&&!Oe(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Oe(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),F(this,"isValidReject",async r=>{if(!Ze(r)){const{message:n}=z("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!lS(s)){const{message:n}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),F(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:l}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!Dg(i)){const{message:l}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=eS(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Wo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Lt(o)){const{message:l}=z("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),F(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Wo(s,"update()");if(o)throw new Error(o.message);const a=dh(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),F(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!fh(a,n)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!uS(s)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!dS(a,n,s.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),F(this,"isValidRespond",async r=>{var i;if(!Ze(r)){const{message:a}=z("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!hS(n)){const{message:a}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(a)}const o=this.client.pendingRequest.get(n.id);if(o.topic!==s){const{message:a}=z("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),F(this,"isValidPing",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!fh(o,n)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!fS(s)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!pS(o,n,s.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!we(s,!1))throw new Error("uri is required parameter");if(!we(n,!1))throw new Error("domain is required parameter");if(!we(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>cr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=cr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||hs,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=z("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),F(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),F(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,l,u,h,f;return!r||i!==le.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r==null?void 0:r.redirect)==null?void 0:u.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r==null?void 0:r.redirect)==null?void 0:s.universal:void 0}),F(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Iu(r,"topic")||"",s=decodeURIComponent(Iu(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),F(this,"registerLinkModeListeners",async()=>{var r;if(Nc()||Nr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),F(this,"getTVFApproveParams",r=>{try{const i=Og(r.namespaces),s=MI(r.namespaces),n=qI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:s,approvedEvents:n,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),F(this,"getTVFParams",(r,i,s)=>{var n,o,a;if(!((n=i.request)!=null&&n.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),F(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(r,i)=>{var s;try{if(!i)return[];const n=r.method,o=u6[n];if(n==="sui_signTransaction")return[P_(i.transactionBytes)];if(n==="near_signTransaction")return[Cu(i)];if(n==="near_signTransactions")return i.map(c=>Cu(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=i.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[CS({transaction:r.params.transactionPayload,signature:i.signature})];if(n==="algo_signTxn")return vt(i)?i.map(c=>Tu(c)):[Tu(i)];if(n==="cosmos_signDirect")return[C_(i)];if(n==="wallet_sendCalls")return T_(i);if(typeof i=="string")return[i];const a=i[o.key];if(vt(a))return n==="solana_signAllTransactions"?a.map(c=>A_(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn(n,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ye.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(pn)?this.client.auth.authKeys.get(pn):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===le.link_mode?Pr:Qe});Yc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:wt(i)})):io(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(gt.expired,async e=>{const{topic:r,id:i}=$p(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,z("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,z("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Wr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Wr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!we(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!we(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=z("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=z("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(we(e,!1)){const{message:r}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!cS(e)){const{message:r}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Lt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=z("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!wS(e,ta)){const{message:r}=z("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${ta.min} and ${ta.max}`);throw new Error(r)}}}class I6 extends fi{constructor(e,r){super(e,r,a6,Jc),this.core=e,this.logger=r}}let S6=class extends fi{constructor(e,r){super(e,r,c6,Jc),this.core=e,this.logger=r}};class O6 extends fi{constructor(e,r){super(e,r,h6,Jc,i=>i.id),this.core=e,this.logger=r}}class $6 extends fi{constructor(e,r){super(e,r,g6,no,()=>pn),this.core=e,this.logger=r}}class D6 extends fi{constructor(e,r){super(e,r,y6,no),this.core=e,this.logger=r}}class A6 extends fi{constructor(e,r){super(e,r,w6,no,i=>i.id),this.core=e,this.logger=r}}var P6=Object.defineProperty,B6=(t,e,r)=>e in t?P6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ra=(t,e,r)=>B6(t,typeof e!="symbol"?e+"":e,r);class C6{constructor(e,r){this.core=e,this.logger=r,ra(this,"authKeys"),ra(this,"pairingTopics"),ra(this,"requests"),this.authKeys=new $6(this.core,this.logger),this.pairingTopics=new D6(this.core,this.logger),this.requests=new A6(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var T6=Object.defineProperty,R6=(t,e,r)=>e in t?T6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>R6(t,typeof e!="symbol"?e+"":e,r);class Xc extends T8{constructor(e){super(e),ee(this,"protocol",ty),ee(this,"version",ry),ee(this,"name",ea.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new xt.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(i,s)=>this.events.on(i,s)),ee(this,"once",(i,s)=>this.events.once(i,s)),ee(this,"off",(i,s)=>this.events.off(i,s)),ee(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),ee(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ee(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ee(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),ee(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||ea.name,this.metadata=xx(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Wc({logger:(e==null?void 0:e.logger)||ea.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new o6(e),this.session=new S6(this.core,this.logger),this.proposal=new I6(this.core,this.logger),this.pendingRequest=new O6(this.core,this.logger),this.engine=new _6(this),this.auth=new C6(this.core,this.logger)}static async init(e){const r=new Xc(e);return await r.initialize(),r}get context(){return it(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}}}const U6=Xc;var nc={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ft<"u"&&Ft,i=function(){function n(){this.fetch=!1,this.DOMException=r.DOMException}return n.prototype=r,new n}();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof Ft<"u"&&Ft||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(p){return p&&DataView.prototype.isPrototypeOf(p)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(p){return p&&u.indexOf(Object.prototype.toString.call(p))>-1};function f(p){if(typeof p!="string"&&(p=String(p)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(p)||p==="")throw new TypeError('Invalid character in header field name: "'+p+'"');return p.toLowerCase()}function d(p){return typeof p!="string"&&(p=String(p)),p}function g(p){var y={next:function(){var v=p.shift();return{done:v===void 0,value:v}}};return c.iterable&&(y[Symbol.iterator]=function(){return y}),y}function w(p){this.map={},p instanceof w?p.forEach(function(y,v){this.append(v,y)},this):Array.isArray(p)?p.forEach(function(y){if(y.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+y.length);this.append(y[0],y[1])},this):p&&Object.getOwnPropertyNames(p).forEach(function(y){this.append(y,p[y])},this)}w.prototype.append=function(p,y){p=f(p),y=d(y);var v=this.map[p];this.map[p]=v?v+", "+y:y},w.prototype.delete=function(p){delete this.map[f(p)]},w.prototype.get=function(p){return p=f(p),this.has(p)?this.map[p]:null},w.prototype.has=function(p){return this.map.hasOwnProperty(f(p))},w.prototype.set=function(p,y){this.map[f(p)]=d(y)},w.prototype.forEach=function(p,y){for(var v in this.map)this.map.hasOwnProperty(v)&&p.call(y,this.map[v],v,this)},w.prototype.keys=function(){var p=[];return this.forEach(function(y,v){p.push(v)}),g(p)},w.prototype.values=function(){var p=[];return this.forEach(function(y){p.push(y)}),g(p)},w.prototype.entries=function(){var p=[];return this.forEach(function(y,v){p.push([v,y])}),g(p)},c.iterable&&(w.prototype[Symbol.iterator]=w.prototype.entries);function m(p){if(!p._noBody){if(p.bodyUsed)return Promise.reject(new TypeError("Already read"));p.bodyUsed=!0}}function O(p){return new Promise(function(y,v){p.onload=function(){y(p.result)},p.onerror=function(){v(p.error)}})}function C(p){var y=new FileReader,v=O(y);return y.readAsArrayBuffer(p),v}function b(p){var y=new FileReader,v=O(y),S=/charset=([A-Za-z0-9_-]+)/.exec(p.type),E=S?S[1]:"utf-8";return y.readAsText(p,E),v}function x(p){for(var y=new Uint8Array(p),v=new Array(y.length),S=0;S<y.length;S++)v[S]=String.fromCharCode(y[S]);return v.join("")}function A(p){if(p.slice)return p.slice(0);var y=new Uint8Array(p.byteLength);return y.set(new Uint8Array(p)),y.buffer}function B(){return this.bodyUsed=!1,this._initBody=function(p){this.bodyUsed=this.bodyUsed,this._bodyInit=p,p?typeof p=="string"?this._bodyText=p:c.blob&&Blob.prototype.isPrototypeOf(p)?this._bodyBlob=p:c.formData&&FormData.prototype.isPrototypeOf(p)?this._bodyFormData=p:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)?this._bodyText=p.toString():c.arrayBuffer&&c.blob&&l(p)?(this._bodyArrayBuffer=A(p.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(p)||h(p))?this._bodyArrayBuffer=A(p):this._bodyText=p=Object.prototype.toString.call(p):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof p=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(p)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var p=m(this);if(p)return p;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var p=m(this);return p||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var p=m(this);if(p)return p;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(x(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(k)}),this.json=function(){return this.text().then(JSON.parse)},this}var T=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(p){var y=p.toUpperCase();return T.indexOf(y)>-1?y:p}function D(p,y){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');y=y||{};var v=y.body;if(p instanceof D){if(p.bodyUsed)throw new TypeError("Already read");this.url=p.url,this.credentials=p.credentials,y.headers||(this.headers=new w(p.headers)),this.method=p.method,this.mode=p.mode,this.signal=p.signal,!v&&p._bodyInit!=null&&(v=p._bodyInit,p.bodyUsed=!0)}else this.url=String(p);if(this.credentials=y.credentials||this.credentials||"same-origin",(y.headers||!this.headers)&&(this.headers=new w(y.headers)),this.method=R(y.method||this.method||"GET"),this.mode=y.mode||this.mode||null,this.signal=y.signal||this.signal||function(){if("AbortController"in a){var _=new AbortController;return _.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&v)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(v),(this.method==="GET"||this.method==="HEAD")&&(y.cache==="no-store"||y.cache==="no-cache")){var S=/([?&])_=[^&]*/;if(S.test(this.url))this.url=this.url.replace(S,"$1_="+new Date().getTime());else{var E=/\?/;this.url+=(E.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}D.prototype.clone=function(){return new D(this,{body:this._bodyInit})};function k(p){var y=new FormData;return p.trim().split("&").forEach(function(v){if(v){var S=v.split("="),E=S.shift().replace(/\+/g," "),_=S.join("=").replace(/\+/g," ");y.append(decodeURIComponent(E),decodeURIComponent(_))}}),y}function j(p){var y=new w,v=p.replace(/\r?\n[\t ]+/g," ");return v.split("\r").map(function(S){return S.indexOf(`
41
+ `)===0?S.substr(1,S.length):S}).forEach(function(S){var E=S.split(":"),_=E.shift().trim();if(_){var U=E.join(":").trim();try{y.append(_,U)}catch(N){console.warn("Response "+N.message)}}}),y}B.call(D.prototype);function P(p,y){if(!(this instanceof P))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(y||(y={}),this.type="default",this.status=y.status===void 0?200:y.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=y.statusText===void 0?"":""+y.statusText,this.headers=new w(y.headers),this.url=y.url||"",this._initBody(p)}B.call(P.prototype),P.prototype.clone=function(){return new P(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new w(this.headers),url:this.url})},P.error=function(){var p=new P(null,{status:200,statusText:""});return p.ok=!1,p.status=0,p.type="error",p};var I=[301,302,303,307,308];P.redirect=function(p,y){if(I.indexOf(y)===-1)throw new RangeError("Invalid status code");return new P(null,{status:y,headers:{location:p}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(y,v){this.message=y,this.name=v;var S=Error(y);this.stack=S.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function $(p,y){return new Promise(function(v,S){var E=new D(p,y);if(E.signal&&E.signal.aborted)return S(new o.DOMException("Aborted","AbortError"));var _=new XMLHttpRequest;function U(){_.abort()}_.onload=function(){var L={statusText:_.statusText,headers:j(_.getAllResponseHeaders()||"")};E.url.indexOf("file://")===0&&(_.status<200||_.status>599)?L.status=200:L.status=_.status,L.url="responseURL"in _?_.responseURL:L.headers.get("X-Request-URL");var M="response"in _?_.response:_.responseText;setTimeout(function(){v(new P(M,L))},0)},_.onerror=function(){setTimeout(function(){S(new TypeError("Network request failed"))},0)},_.ontimeout=function(){setTimeout(function(){S(new TypeError("Network request timed out"))},0)},_.onabort=function(){setTimeout(function(){S(new o.DOMException("Aborted","AbortError"))},0)};function N(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(_.open(E.method,N(E.url),!0),E.credentials==="include"?_.withCredentials=!0:E.credentials==="omit"&&(_.withCredentials=!1),"responseType"in _&&(c.blob?_.responseType="blob":c.arrayBuffer&&(_.responseType="arraybuffer")),y&&typeof y.headers=="object"&&!(y.headers instanceof w||a.Headers&&y.headers instanceof a.Headers)){var V=[];Object.getOwnPropertyNames(y.headers).forEach(function(L){V.push(f(L)),_.setRequestHeader(L,d(y.headers[L]))}),E.headers.forEach(function(L,M){V.indexOf(M)===-1&&_.setRequestHeader(M,L)})}else E.headers.forEach(function(L,M){_.setRequestHeader(M,L)});E.signal&&(E.signal.addEventListener("abort",U),_.onreadystatechange=function(){_.readyState===4&&E.signal.removeEventListener("abort",U)}),_.send(typeof E._bodyInit>"u"?null:E._bodyInit)})}return $.polyfill=!0,a.fetch||(a.fetch=$,a.Headers=w,a.Request=D,a.Response=P),o.Headers=w,o.Request=D,o.Response=P,o.fetch=$,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(nc,nc.exports);var N6=nc.exports;const sf=Dy(N6);var k6=Object.defineProperty,j6=Object.defineProperties,F6=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,L6=Object.prototype.hasOwnProperty,M6=Object.prototype.propertyIsEnumerable,of=(t,e,r)=>e in t?k6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,af=(t,e)=>{for(var r in e||(e={}))L6.call(e,r)&&of(t,r,e[r]);if(nf)for(var r of nf(e))M6.call(e,r)&&of(t,r,e[r]);return t},cf=(t,e)=>j6(t,F6(e));const q6={Accept:"application/json","Content-Type":"application/json"},z6="POST",lf={headers:q6,method:z6},uf=10;let sy=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new xt.EventEmitter,this.isAvailable=!1,this.registering=!1,!Oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=si(e),i=await(await sf(this.url,cf(af({},lf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Oh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=si({id:1,jsonrpc:"2.0",method:"test",params:[]});await sf(e,cf(af({},lf),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?ii(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=ro(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Tg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>uf&&this.events.setMaxListeners(uf)}};function Qc(t){return t==null||typeof t!="object"&&typeof t!="function"}function ny(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function oy(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const V6="[object RegExp]",ay="[object String]",cy="[object Number]",ly="[object Boolean]",uy="[object Arguments]",H6="[object Symbol]",K6="[object Date]",W6="[object Map]",G6="[object Set]",Y6="[object Array]",Z6="[object ArrayBuffer]",J6="[object Object]",X6="[object DataView]",Q6="[object Uint8Array]",eP="[object Uint8ClampedArray]",tP="[object Uint16Array]",rP="[object Uint32Array]",iP="[object Int8Array]",sP="[object Int16Array]",nP="[object Int32Array]",oP="[object Float32Array]",aP="[object Float64Array]";function el(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function cP(t,e){return Si(t,void 0,t,new Map,e)}function Si(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(Qc(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Si(t[a],a,r,i,s);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Si(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Si(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(el(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Si(t[a],a,r,i,s);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Gr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Gr(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Gr(o,t,r,i,s),o}if(typeof t=="object"&&lP(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Gr(o,t,r,i,s),o}return t}function Gr(t,e,r=t,i,s){const n=[...Object.keys(e),...ny(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Si(e[a],a,r,i,s))}}function lP(t){switch(oy(t)){case uy:case Y6:case Z6:case X6:case ly:case K6:case oP:case aP:case iP:case sP:case nP:case W6:case cy:case J6:case V6:case G6:case ay:case H6:case Q6:case eP:case tP:case rP:return!0;default:return!1}}function uP(t,e){return cP(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case cy:case ay:case ly:{const o=new t.constructor(t==null?void 0:t.valueOf());return Gr(o,t),o}case uy:{const o={};return Gr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function hf(t){return uP(t)}function ff(t){return t!==null&&typeof t=="object"&&oy(t)==="[object Arguments]"}function df(t){return typeof t=="object"&&t!==null}function hP(){}function fP(t){return el(t)}function dP(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function pP(t){if(Qc(t))return t;if(Array.isArray(t)||el(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function gP(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=oc(s,o,i,new Map)}return s}function oc(t,e,r,i){if(Qc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return pP(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...ny(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(ff(a)&&(a={...a}),ff(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=hf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||df(c)&&df(a)?t[o]=oc(c,a,r,i):c==null&&dP(a)?t[o]=oc({},a,r,i):c==null&&fP(a)?t[o]=hf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function yP(t,...e){return gP(t,...e,hP)}const pf="error",wP="wss://relay.walletconnect.org",mP="wc",hy="universal_provider",tn=`${mP}@2:${hy}:`,fy="https://rpc.walletconnect.org/v1/",dy="generic",bP=`${fy}bundler`,Pi="call_status",vP=86400,tl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var EP=Object.defineProperty,xP=Object.defineProperties,_P=Object.getOwnPropertyDescriptors,gf=Object.getOwnPropertySymbols,IP=Object.prototype.hasOwnProperty,SP=Object.prototype.propertyIsEnumerable,yf=(t,e,r)=>e in t?EP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))IP.call(e,r)&&yf(t,r,e[r]);if(gf)for(var r of gf(e))SP.call(e,r)&&yf(t,r,e[r]);return t},OP=(t,e)=>xP(t,_P(e));function py(t,e,r){var i;const s=cr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${fy}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function $P(t){return t.includes(":")?t.split(":")[1]:t}function gy(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function DP(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function wf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,s;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((s=r==null?void 0:r.chains)==null?void 0:s.length)>0}))}function sn(t={},e={}){const r=wf(mf(t)),i=wf(mf(e));return yP(r,i)}function mf(t){var e,r,i,s,n;const o={};if(!Vt(t))return o;for(const[a,c]of Object.entries(t)){const l=to(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Ii(a);o[d]=OP(rn(rn({},o[d]),c),{chains:zt(l,(e=o[d])==null?void 0:e.chains),methods:zt(u,(r=o[d])==null?void 0:r.methods),events:zt(h,(i=o[d])==null?void 0:i.events)}),(Vt(f)||Vt(((s=o[d])==null?void 0:s.rpcMap)||{}))&&(o[d].rpcMap=rn(rn({},f),(n=o[d])==null?void 0:n.rpcMap))}return o}function bf(t){return t.includes(":")?t.split(":")[2]:t}function vf(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=to(r)?[r]:i.chains?i.chains:gy(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function ia(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function AP(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const yy={},Bi=t=>yy[t],sa=(t,e)=>{yy[t]=e};var PP=Object.defineProperty,Ef=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,xf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_f=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&xf(t,r,e[r]);if(Ef)for(var r of Ef(e))CP.call(e,r)&&xf(t,r,e[r]);return t};const If="eip155",TP=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],RP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,na=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Sf=t=>Object.keys(t).filter(e=>TP.includes(e)).reduce((e,r)=>(e[r]=UP(t[r]),e),{}),UP=t=>typeof t=="string"&&AP(t)?JSON.parse(t):t,NP=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:s={}}=t,n={};if(!Vt(s)&&!Vt(i))return;const o=Sf(i);for(const a of r){const c=RP(a);if(!c)continue;n[na(c)]=o;const l=s==null?void 0:s[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];n[na(c)]=_f(_f({},n[na(c)]),Sf(u||l))}}for(const[a,c]of Object.entries(n))Object.keys(c).length===0&&delete n[a];return Object.keys(n).length>0?n:void 0};var kP=Object.defineProperty,jP=(t,e,r)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,FP=(t,e,r)=>jP(t,e+"",r);let oa,LP=class wy{constructor(e){FP(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return oa||(oa=new wy(e)),oa}};var MP=Object.defineProperty,qP=Object.defineProperties,zP=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,VP=Object.prototype.hasOwnProperty,HP=Object.prototype.propertyIsEnumerable,$f=(t,e,r)=>e in t?MP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KP=(t,e)=>{for(var r in e||(e={}))VP.call(e,r)&&$f(t,r,e[r]);if(Of)for(var r of Of(e))HP.call(e,r)&&$f(t,r,e[r]);return t},WP=(t,e)=>qP(t,zP(e));async function GP(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(i.map(h=>YP(r.reference,h,e))),n=s.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);s.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!n.length||n.some(h=>!h),a=n.every(h=>(h==null?void 0:h.status)==="0x1"),c=n.every(h=>(h==null?void 0:h.status)==="0x0"),l=n.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:n,status:u}}async function YP(t,e,r){return await r(parseInt(t)).request(Dt("eth_getTransactionReceipt",[e]))}async function ZP({sendCalls:t,storage:e}){const r=await e.getItem(Pi);await e.setItem(Pi,WP(KP({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:ge(vP)}}))}async function JP({resultId:t,storage:e}){const r=await e.getItem(Pi);if(r){delete r[t],await e.setItem(Pi,r);for(const i in r)Lt(r[i].expiry)&&delete r[i];await e.setItem(Pi,r)}}async function XP({resultId:t,storage:e}){const r=await e.getItem(Pi),i=r==null?void 0:r[t];if(i&&!Lt(i.expiry))return i;await JP({resultId:t,storage:e})}var QP=Object.defineProperty,e4=Object.defineProperties,t4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,r4=Object.prototype.hasOwnProperty,i4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?QP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e)=>{for(var r in e||(e={}))r4.call(e,r)&&ac(t,r,e[r]);if(Df)for(var r of Df(e))i4.call(e,r)&&ac(t,r,e[r]);return t},ca=(t,e)=>e4(t,t4(e)),zr=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class s4{constructor(e){zr(this,"name","eip155"),zr(this,"client"),zr(this,"chainId"),zr(this,"namespace"),zr(this,"httpProviders"),zr(this,"events"),zr(this,"storage"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=LP.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{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,r){const i=r||py(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt($P(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=ca(aa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=NP(l,a,c)}catch(w){console.warn("Failed to extract capabilities from session",w)}if(d)return d;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:ca(aa({},l.sessionProperties||{}),{capabilities:ca(aa({},u||{}),{[h]:g})})})}catch(w){console.warn("Failed to update session with capabilities",w)}return g}async getCallStatus(e){var r,i,s;const n=this.client.session.get(e.topic),o=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await XP({resultId:(s=e.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await GP(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dt("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${bP}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,s;const n=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=n==null?void 0:n.id,c=(n==null?void 0:n.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(s=c==null?void 0:c.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await ZP({sendCalls:{request:o,result:n},storage:this.storage}),n}}var n4=Object.defineProperty,o4=(t,e,r)=>e in t?n4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>o4(t,typeof e!="symbol"?e+"":e,r);class a4{constructor(e){Ei(this,"name",dy),Ei(this,"client"),Ei(this,"httpProviders"),Ei(this,"events"),Ei(this,"namespace"),Ei(this,"chainId"),this.namespace=e.namespace,this.events=Bi("events"),this.client=Bi("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,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(tl.DEFAULT_CHAIN_CHANGED,{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 cr(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{var n,o;const a=cr(s),c=(o=(n=this.namespace)==null?void 0:n.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(s,c)}),i}getHttpProvider(e){const r=cr(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||py(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Zc(new sy(i,Bi("disableProviderPing")))}}var c4=Object.defineProperty,l4=Object.defineProperties,u4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,f4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?c4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ts=(t,e)=>{for(var r in e||(e={}))h4.call(e,r)&&cc(t,r,e[r]);if(Af)for(var r of Af(e))f4.call(e,r)&&cc(t,r,e[r]);return t},nn=(t,e)=>l4(t,u4(e)),nt=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class rl{constructor(e){nt(this,"client"),nt(this,"namespaces"),nt(this,"optionalNamespaces"),nt(this,"sessionProperties"),nt(this,"scopedProperties"),nt(this,"events",new uc),nt(this,"rpcProviders",{}),nt(this,"session"),nt(this,"providerOpts"),nt(this,"logger"),nt(this,"uri"),nt(this,"disableProviderPing",!1),nt(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Wc({logger:(r=e.logger)!=null?r:pf,name:(i=this.providerOpts.name)!=null?i:hy}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new rl(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:ts({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,xs(n,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ue("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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=vf(this.session.namespaces);this.namespaces=sn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});s&&(this.uri=s,this.events.emit("display_uri",s));const o=await n();this.session=o;const a=vf(o.namespaces);return this.namespaces=sn(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e);this.getProvider(i).setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!vt(r))return;for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"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(){var e,r;if(this.client=this.providerOpts.client||await U6.init({core:this.providerOpts.core,logger:this.providerOpts.logger||pf,relayUrl:this.providerOpts.relayUrl||wP,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Ii(r)))];sa("client",this.client),sa("events",this.events),sa("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=DP(r,this.session);if((i==null?void 0:i.length)===0)return;const s=gy(i),n=sn(this.namespaces,this.optionalNamespaces),o=nn(ts({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new s4({namespace:o});break;default:this.rpcProviders[r]=new a4({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&vt(o)&&this.events.emit("accountsChanged",o.map(bf))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Ii(o),l=ia(o)!==ia(a)?`${c}:${ia(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=nn(ts({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",nn(ts({},ue("USER_DISCONNECTED")),{data:e.topic})))}),this.on(tl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(nn(ts({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dy]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=sn(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Ii(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=Ii(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[s,n]=this.validateChain(e);n&&(this.updateNamespaceChain(s,n),i?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(s).setDefaultChain(n),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var s,n;try{if(i===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(bf);if(!vt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.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,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${tn}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${tn}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${tn}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(tn)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const d4=rl,p4="wc",g4="ethereum_provider",y4=`${p4}@2:${g4}:`,w4="https://rpc.walletconnect.org/v1/",Rn=["eth_sendTransaction","personal_sign"],my=["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"],Un=["chainChanged","accountsChanged"],by=["chainChanged","accountsChanged","message","disconnect","connect"],m4=async()=>{const{createAppKit:t}=await Ay(()=>import("./core-BBTIgWQG.js").then(e=>e.bt),__vite__mapDeps([0,1]));return t};var b4=Object.defineProperty,v4=Object.defineProperties,E4=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,x4=Object.prototype.hasOwnProperty,_4=Object.prototype.propertyIsEnumerable,lc=(t,e,r)=>e in t?b4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hr=(t,e)=>{for(var r in e||(e={}))x4.call(e,r)&&lc(t,r,e[r]);if(Pf)for(var r of Pf(e))_4.call(e,r)&&lc(t,r,e[r]);return t},rs=(t,e)=>v4(t,E4(e)),ot=(t,e,r)=>lc(t,typeof e!="symbol"?e+"":e,r);function Nn(t){return Number(t[0].split(":")[1])}function on(t){return`0x${t.toString(16)}`}function I4(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!vt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Rn,events:n||Un,rpcMap:Hr({},e.length?{[Nn(e)]:a[Nn(e)]}:{})},l=n==null?void 0:n.filter(d=>!Un.includes(d)),u=i==null?void 0:i.filter(d=>!Rn.includes(d));if(!r&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:my))],events:[...new Set(c.events.concat(o!=null&&o.length?o:by))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class oo{constructor(){ot(this,"events",new xt.EventEmitter),ot(this,"namespace","eip155"),ot(this,"accounts",[]),ot(this,"signer"),ot(this,"chainId",1),ot(this,"modal"),ot(this,"rpc"),ot(this,"STORAGE_KEY",y4),ot(this,"on",(e,r)=>(this.events.on(e,r),this)),ot(this,"once",(e,r)=>(this.events.once(e,r),this)),ot(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ot(this,"off",(e,r)=>(this.events.off(e,r),this)),ot(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new oo;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=I4(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(rs(Hr({namespaces:Hr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!n)return;const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(rs(Hr({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=bu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:on(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",on(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",rs(Hr({},ue("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",on(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Rn:[],c=s.length?(e==null?void 0:e.events)||Un:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(d=>this.formatChainId(d)),optionalChains:n.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Nn(this.rpc.chains):Nn(this.rpc.optionalChains),this.signer=await d4.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 i;try{const s=await m4(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return U4}),o=n(rs(Hr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=s(rs(Hr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&vt(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&vt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${w4}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const S4=oo;var O4=Object.defineProperty,$4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,Bf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Cf=(t,e,r)=>e in t?O4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vy=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Cf(t,r,e[r]);if(Bf)for(var r of Bf(e))P4.call(e,r)&&Cf(t,r,e[r]);return t},B4=(t,e)=>$4(t,D4(e));function C4(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const T4=t=>{const[e,r]=t.split(":");return Ey({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function R4(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(T4).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:C4(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:B4(vy({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(g=>({id:g.id,name:g.name,links:g.links})),...(t.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(g=>!f.includes(g.id));d.length&&(u.customWallets=d)}return u}function Ey(t){return vy({formatters:void 0,fees:void 0,serializers:void 0},t)}var U4=Object.freeze({__proto__:null,convertWCMToAppKitOptions:R4,defineChain:Ey});const O5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:S4,OPTIONAL_EVENTS:by,OPTIONAL_METHODS:my,REQUIRED_EVENTS:Un,REQUIRED_METHODS:Rn,default:oo},Symbol.toStringTag,{value:"Module"}));export{RS as A,Dt as B,aE as C,ui as D,Zc as E,xO as F,Yc as G,io as H,li as I,xs as J,u2 as K,Cr as L,ro as M,jt as N,mt as O,cu as P,ep as Q,kt as R,sy as S,O5 as T,si as a,t8 as b,Pg as c,Qs as d,e8 as e,QS as f,bh as g,kf as h,bt as i,q as j,i8 as k,ti as l,hc as m,jy as n,Nf as o,cs as p,Sa as q,Ss as r,ii as s,rt as t,mb as u,lb as v,Cm as w,bE as x,vm as y,Tm as z};