@dcl/vesting-dashboard 3.5.1 → 3.5.2-16060301920.commit-19f00cd

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 (99) hide show
  1. package/assets/add-c08adc0e.js +15 -0
  2. package/assets/all-wallets-2a56fdfd.js +6 -0
  3. package/assets/app-store-da9c80fc.js +17 -0
  4. package/assets/apple-f02fda7c.js +18 -0
  5. package/assets/arrow-bottom-74d2c273.js +8 -0
  6. package/assets/arrow-bottom-circle-cd6d3810.js +11 -0
  7. package/assets/arrow-left-fce04d7d.js +8 -0
  8. package/assets/arrow-right-9d8342cc.js +8 -0
  9. package/assets/arrow-top-01a87a07.js +8 -0
  10. package/assets/bank-fd1d03ae.js +14 -0
  11. package/assets/basic-4bd75c12.js +2128 -0
  12. package/assets/browser-9c02f01f.js +14 -0
  13. package/assets/card-49bc08a4.js +14 -0
  14. package/assets/checkmark-029608ab.js +11 -0
  15. package/assets/checkmark-bold-ecc7e4f6.js +8 -0
  16. package/assets/chevron-bottom-2b428154.js +8 -0
  17. package/assets/chevron-left-90ed61cf.js +8 -0
  18. package/assets/chevron-right-7c821860.js +8 -0
  19. package/assets/chevron-top-3d95f11a.js +8 -0
  20. package/assets/chrome-store-5a22713f.js +61 -0
  21. package/assets/clock-d1a052f4.js +8 -0
  22. package/assets/close-31d55d62.js +8 -0
  23. package/assets/coinPlaceholder-134fe1d0.js +8 -0
  24. package/assets/compass-4ac3881d.js +8 -0
  25. package/assets/copy-3ce752e8.js +15 -0
  26. package/assets/core-f5e3f11a.js +910 -0
  27. package/assets/cursor-1a5c116f.js +3 -0
  28. package/assets/cursor-transparent-8446a811.js +12 -0
  29. package/assets/desktop-8e0cdd17.js +9 -0
  30. package/assets/disconnect-89f3c151.js +8 -0
  31. package/assets/discord-5e171d91.js +17 -0
  32. package/assets/etherscan-e5da137a.js +6 -0
  33. package/assets/exclamation-triangle-ff9f2a46.js +4 -0
  34. package/assets/extension-315957ae.js +8 -0
  35. package/assets/external-link-44309326.js +8 -0
  36. package/assets/facebook-1cf0b4b8.js +26 -0
  37. package/assets/farcaster-215b1536.js +12 -0
  38. package/assets/filters-8cbdc04e.js +8 -0
  39. package/assets/{fortmatic-c3020796.js → fortmatic-77630451.js} +1 -1
  40. package/assets/github-01b19bf7.js +18 -0
  41. package/assets/google-cba03f8d.js +18 -0
  42. package/assets/help-circle-72ebe183.js +12 -0
  43. package/assets/id-9562a05c.js +12 -0
  44. package/assets/image-a4f8645b.js +4 -0
  45. package/assets/index-23cd0f55.js +1069 -0
  46. package/assets/index-4acb66cd.js +1 -0
  47. package/assets/{index-a0af7e8f.css → index-6a75d29a.css} +7 -7
  48. package/assets/index-8a83ce69.js +5 -0
  49. package/assets/{index-5e7ee73d.js → index-c3d52160.js} +5 -5
  50. package/assets/index-dfb5c925.js +1 -0
  51. package/assets/index-fc25cd20.js +394 -0
  52. package/assets/index.es-d9174431.js +26 -0
  53. package/assets/info-circle-07ea8fe3.js +12 -0
  54. package/assets/info-d1d382ad.js +3 -0
  55. package/assets/lightbulb-bb330403.js +3 -0
  56. package/assets/mail-84d8e8e1.js +8 -0
  57. package/assets/man-default1-6c97f8cc.png +0 -0
  58. package/assets/mobile-e2b09bb7.js +9 -0
  59. package/assets/more-3f40c7df.js +11 -0
  60. package/assets/network-placeholder-71c396aa.js +14 -0
  61. package/assets/nftPlaceholder-d89385d8.js +8 -0
  62. package/assets/off-2724934c.js +8 -0
  63. package/assets/play-store-1abafce5.js +32 -0
  64. package/assets/plus-6ad83a15.js +13 -0
  65. package/assets/qr-code-ca4014d4.js +6 -0
  66. package/assets/recycle-horizontal-a7953996.js +9 -0
  67. package/assets/refresh-ba92c07d.js +8 -0
  68. package/assets/reown-logo-1c881aeb.js +12 -0
  69. package/assets/search-e44b04b5.js +8 -0
  70. package/assets/secp256k1-c8041f84.js +1 -0
  71. package/assets/secp256k1-e555dfeb.js +1 -0
  72. package/assets/send-7181ced0.js +15 -0
  73. package/assets/swapHorizontal-acbca5b3.js +8 -0
  74. package/assets/swapHorizontalBold-47299b30.js +8 -0
  75. package/assets/swapHorizontalMedium-c35a984b.js +16 -0
  76. package/assets/swapHorizontalRoundedBold-cbf29e59.js +8 -0
  77. package/assets/swapVertical-f4e5432e.js +8 -0
  78. package/assets/telegram-f120d2fa.js +16 -0
  79. package/assets/three-dots-afde7907.js +5 -0
  80. package/assets/twitch-a1f9688c.js +18 -0
  81. package/assets/twitterIcon-ff394218.js +6 -0
  82. package/assets/verify-822d6b22.js +8 -0
  83. package/assets/verify-filled-6087cf80.js +8 -0
  84. package/assets/w3m-modal-a28c18e8.js +642 -0
  85. package/assets/wallet-095d2cfd.js +8 -0
  86. package/assets/wallet-placeholder-82b67b5f.js +14 -0
  87. package/assets/walletconnect-9023b42a.js +30 -0
  88. package/assets/warning-circle-209b10bc.js +12 -0
  89. package/assets/x-2ab98c1d.js +12 -0
  90. package/index.html +4 -4
  91. package/package.json +3 -3
  92. package/assets/index-09f330a8.js +0 -1
  93. package/assets/index-2be79e9f.js +0 -572
  94. package/assets/index-4e853dd7.js +0 -54
  95. package/assets/index-5cc94cfd.js +0 -14
  96. package/assets/index-ea8e4214.js +0 -5
  97. package/assets/index-eb7b778e.js +0 -1
  98. package/assets/index.es-0516976f.js +0 -49
  99. /package/assets/{man-default-5d829f5a.png → 805322223c96be40-5d829f5a.png} +0 -0
@@ -0,0 +1,26 @@
1
+ import{p as lt,g as Np,_ as ml,a as K,B as X,e as gt,b as Up,c as Vi,N as xa,o as fc}from"./index-23cd0f55.js";var pc=globalThis&&globalThis.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,s=e.length,n;r<s;r++)(n||!(r in e))&&(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return t.concat(n||Array.prototype.slice.call(e))},Bp=function(){function t(e,i,r){this.name=e,this.version=i,this.os=r,this.type="browser"}return t}(),kp=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=lt.platform}return t}(),jp=function(){function t(e,i,r,s){this.name=e,this.version=i,this.os=r,this.bot=s,this.type="bot-device"}return t}(),Lp=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Mp=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),qp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,zp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,gc=3,Hp=[["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",qp]],yc=[["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 Vp(t){return t?wc(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Mp:typeof navigator<"u"?wc(navigator.userAgent):Gp()}function Kp(t){return t!==""&&Hp.reduce(function(e,i){var r=i[0],s=i[1];if(e)return e;var n=s.exec(t);return!!n&&[r,n]},!1)}function wc(t){var e=Kp(t);if(!e)return null;var i=e[0],r=e[1];if(i==="searchbot")return new Lp;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length<gc&&(s=pc(pc([],s,!0),Yp(gc-s.length),!0)):s=[];var n=s.join("."),o=Wp(t),a=zp.exec(t);return a&&a[1]?new jp(i,n,o,a[1]):new Bp(i,n,o)}function Wp(t){for(var e=0,i=yc.length;e<i;e++){var r=yc[e],s=r[0],n=r[1],o=n.exec(t);if(o)return s}return null}function Gp(){var t=typeof lt<"u"&&lt.version;return t?new kp(lt.version.slice(1)):null}function Yp(t){for(var e=[],i=0;i<t;i++)e.push("0");return e}var L={};/*! *****************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */var To=function(t,e){return To=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var s in r)r.hasOwnProperty(s)&&(i[s]=r[s])},To(t,e)};function Jp(t,e){To(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}var Fo=function(){return Fo=Object.assign||function(e){for(var i,r=1,s=arguments.length;r<s;r++){i=arguments[r];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},Fo.apply(this,arguments)};function Zp(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(i[r[s]]=t[r[s]]);return i}function Qp(t,e,i,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,i,n):o(e,i))||n);return s>3&&n&&Object.defineProperty(e,i,n),n}function Xp(t,e){return function(i,r){e(i,r,t)}}function eg(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function tg(t,e,i,r){function s(n){return n instanceof i?n:new i(function(o){o(n)})}return new(i||(i=Promise))(function(n,o){function a(u){try{h(r.next(u))}catch(l){o(l)}}function c(u){try{h(r.throw(u))}catch(l){o(l)}}function h(u){u.done?n(u.value):s(u.value).then(a,c)}h((r=r.apply(t,e||[])).next())})}function ig(t,e){var i={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},r,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(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,s&&(n=h[0]&2?s.return:h[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,h[1])).done)return n;switch(s=0,n&&(h=[h[0]&2,n.value]),h[0]){case 0:case 1:n=h;break;case 4:return i.label++,{value:h[1],done:!1};case 5:i.label++,s=h[1],h=[0];continue;case 7:h=i.ops.pop(),i.trys.pop();continue;default:if(n=i.trys,!(n=n.length>0&&n[n.length-1])&&(h[0]===6||h[0]===2)){i=0;continue}if(h[0]===3&&(!n||h[1]>n[0]&&h[1]<n[3])){i.label=h[1];break}if(h[0]===6&&i.label<n[1]){i.label=n[1],n=h;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(h);break}n[2]&&i.ops.pop(),i.trys.pop();continue}h=e.call(t,i)}catch(u){h=[6,u],s=0}finally{r=n=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function rg(t,e,i,r){r===void 0&&(r=i),t[r]=e[i]}function sg(t,e){for(var i in t)i!=="default"&&!e.hasOwnProperty(i)&&(e[i]=t[i])}function Ro(t){var e=typeof Symbol=="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function bl(t,e){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return n}function ng(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(bl(arguments[e]));return t}function og(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<i;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)r[s]=n[o];return r}function ss(t){return this instanceof ss?(this.v=t,this):new ss(t)}function ag(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){r[d]&&(s[d]=function(p){return new Promise(function(f,g){n.push([d,p,f,g])>1||a(d,p)})})}function a(d,p){try{c(r[d](p))}catch(f){l(n[0][3],f)}}function c(d){d.value instanceof ss?Promise.resolve(d.value.v).then(h,u):l(n[0][2],d)}function h(d){a("next",d)}function u(d){a("throw",d)}function l(d,p){d(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function cg(t){var e,i;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,n){e[s]=t[s]?function(o){return(i=!i)?{value:ss(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function hg(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],i;return e?e.call(t):(t=typeof Ro=="function"?Ro(t):t[Symbol.iterator](),i={},r("next"),r("throw"),r("return"),i[Symbol.asyncIterator]=function(){return this},i);function r(n){i[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(h){n({value:h,done:a})},o)}}function ug(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function lg(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i in t)Object.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e.default=t,e}function dg(t){return t&&t.__esModule?t:{default:t}}function fg(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function pg(t,e,i){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,i),i}const gg=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Fo},__asyncDelegator:cg,__asyncGenerator:ag,__asyncValues:hg,__await:ss,__awaiter:tg,__classPrivateFieldGet:fg,__classPrivateFieldSet:pg,__createBinding:rg,__decorate:Qp,__exportStar:sg,__extends:Jp,__generator:ig,__importDefault:dg,__importStar:lg,__makeTemplateObject:ug,__metadata:eg,__param:Xp,__read:bl,__rest:Zp,__spread:ng,__spreadArrays:og,__values:Ro},Symbol.toStringTag,{value:"Module"})),fs=Np(gg);var Vn={},Dr={},mc;function yg(){if(mc)return Dr;mc=1,Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.delay=void 0;function t(e){return new Promise(i=>{setTimeout(()=>{i(!0)},e)})}return Dr.delay=t,Dr}var bi={},Kn={},vi={},bc;function wg(){return bc||(bc=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.ONE_THOUSAND=vi.ONE_HUNDRED=void 0,vi.ONE_HUNDRED=100,vi.ONE_THOUSAND=1e3),vi}var Wn={},vc;function mg(){return vc||(vc=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}(Wn)),Wn}var Ec;function vl(){return Ec||(Ec=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fs;e.__exportStar(wg(),t),e.__exportStar(mg(),t)}(Kn)),Kn}var Ic;function bg(){if(Ic)return bi;Ic=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.fromMiliseconds=bi.toMiliseconds=void 0;const t=vl();function e(r){return r*t.ONE_THOUSAND}bi.toMiliseconds=e;function i(r){return Math.floor(r/t.ONE_THOUSAND)}return bi.fromMiliseconds=i,bi}var _c;function vg(){return _c||(_c=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fs;e.__exportStar(yg(),t),e.__exportStar(bg(),t)}(Vn)),Vn}var Ki={},xc;function Eg(){if(xc)return Ki;xc=1,Object.defineProperty(Ki,"__esModule",{value:!0}),Ki.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(i){if(this.timestamps.has(i))throw new Error(`Watch already started for label: ${i}`);this.timestamps.set(i,{started:Date.now()})}stop(i){const r=this.get(i);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${i}`);const s=Date.now()-r.started;this.timestamps.set(i,{started:r.started,elapsed:s})}get(i){const r=this.timestamps.get(i);if(typeof r>"u")throw new Error(`No timestamp found for label: ${i}`);return r}elapsed(i){const r=this.get(i);return r.elapsed||Date.now()-r.started}}return Ki.Watch=t,Ki.default=t,Ki}var Gn={},Ar={},$c;function Ig(){if($c)return Ar;$c=1,Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.IWatch=void 0;class t{}return Ar.IWatch=t,Ar}var Sc;function _g(){return Sc||(Sc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),fs.__exportStar(Ig(),t)}(Gn)),Gn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fs;e.__exportStar(vg(),t),e.__exportStar(Eg(),t),e.__exportStar(_g(),t),e.__exportStar(vl(),t)})(L);var he={};Object.defineProperty(he,"__esModule",{value:!0});he.getLocalStorage=he.getLocalStorageOrThrow=he.getCrypto=he.getCryptoOrThrow=El=he.getLocation=he.getLocationOrThrow=$a=he.getNavigator=he.getNavigatorOrThrow=Fi=he.getDocument=he.getDocumentOrThrow=he.getFromWindowOrThrow=he.getFromWindow=void 0;function ki(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}he.getFromWindow=ki;function br(t){const e=ki(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}he.getFromWindowOrThrow=br;function xg(){return br("document")}he.getDocumentOrThrow=xg;function $g(){return ki("document")}var Fi=he.getDocument=$g;function Sg(){return br("navigator")}he.getNavigatorOrThrow=Sg;function Dg(){return ki("navigator")}var $a=he.getNavigator=Dg;function Ag(){return br("location")}he.getLocationOrThrow=Ag;function Pg(){return ki("location")}var El=he.getLocation=Pg;function Og(){return br("crypto")}he.getCryptoOrThrow=Og;function Cg(){return ki("crypto")}he.getCrypto=Cg;function Tg(){return br("localStorage")}he.getLocalStorageOrThrow=Tg;function Fg(){return ki("localStorage")}he.getLocalStorage=Fg;var Sa={};Object.defineProperty(Sa,"__esModule",{value:!0});var Il=Sa.getWindowMetadata=void 0;const Dc=he;function Rg(){let t,e;try{t=Dc.getDocumentOrThrow(),e=Dc.getLocationOrThrow()}catch{return null}function i(){const l=t.getElementsByTagName("link"),d=[];for(let p=0;p<l.length;p++){const f=l[p],g=f.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=f.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let v=e.protocol+"//"+e.host;if(y.indexOf("/")===0)v+=y;else{const E=e.pathname.split("/");E.pop();const m=E.join("/");v+=m+"/"+y}d.push(v)}else if(y.indexOf("//")===0){const v=e.protocol+y;d.push(v)}else d.push(y)}}return d}function r(...l){const d=t.getElementsByTagName("meta");for(let p=0;p<d.length;p++){const f=d[p],g=["itemprop","property","name"].map(y=>f.getAttribute(y)).filter(y=>y?l.includes(y):!1);if(g.length&&g){const y=f.getAttribute("content");if(y)return y}}return""}function s(){let l=r("name","og:site_name","og:title","twitter:title");return l||(l=t.title),l}function n(){return r("description","og:description","twitter:description","keywords")}const o=s(),a=n(),c=e.origin,h=i();return{description:a,url:c,icons:h,name:o}}Il=Sa.getWindowMetadata=Rg;function ns(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function No(t){return ns(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const _l="2.31.0";let Pr={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:i})=>e?`${t??"https://viem.sh"}${e}${i?`#${i}`:""}`:void 0,version:`viem@${_l}`};class Ri extends Error{constructor(e,i={}){var a;const r=(()=>{var c;return i.cause instanceof Ri?i.cause.details:(c=i.cause)!=null&&c.message?i.cause.message:i.details})(),s=(()=>i.cause instanceof Ri&&i.cause.docsPath||i.docsPath)(),n=(a=Pr.getDocsUrl)==null?void 0:a.call(Pr,{...i,docsPath:s}),o=[e||"An error occurred.","",...i.metaMessages?[...i.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Pr.version?[`Version: ${Pr.version}`]:[]].join(`
15
+ `);super(o,i.cause?{cause:i.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=s,this.metaMessages=i.metaMessages,this.name=i.name??this.name,this.shortMessage=e,this.version=_l}walk(e){return xl(this,e)}}function xl(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?xl(t.cause,e):e?null:t}class $l extends Ri{constructor({size:e,targetSize:i,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${i}).`,{name:"SizeExceedsPaddingSizeError"})}}function vr(t,{dir:e,size:i=32}={}){return typeof t=="string"?Ng(t,{dir:e,size:i}):Ug(t,{dir:e,size:i})}function Ng(t,{dir:e,size:i=32}={}){if(i===null)return t;const r=t.replace("0x","");if(r.length>i*2)throw new $l({size:Math.ceil(r.length/2),targetSize:i,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](i*2,"0")}`}function Ug(t,{dir:e,size:i=32}={}){if(i===null)return t;if(t.length>i)throw new $l({size:t.length,targetSize:i,type:"bytes"});const r=new Uint8Array(i);for(let s=0;s<i;s++){const n=e==="right";r[n?s:i-s-1]=t[n?s:t.length-s-1]}return r}class Bg extends Ri{constructor({max:e,min:i,signed:r,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${i} to ${e})`:`(above ${i})`}`,{name:"IntegerOutOfRangeError"})}}class kg extends Ri{constructor({givenSize:e,maxSize:i}){super(`Size cannot exceed ${i} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Er(t,{size:e}){if(No(t)>e)throw new kg({givenSize:No(t),maxSize:e})}function Uo(t,e={}){const{signed:i}=e;e.size&&Er(t,{size:e.size});const r=BigInt(t);if(!i)return r;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function jg(t,e={}){return Number(Uo(t,e))}const Lg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Bo(t,e={}){return typeof t=="number"||typeof t=="bigint"?Dl(t,e):typeof t=="string"?zg(t,e):typeof t=="boolean"?Mg(t,e):Sl(t,e)}function Mg(t,e={}){const i=`0x${Number(t)}`;return typeof e.size=="number"?(Er(i,{size:e.size}),vr(i,{size:e.size})):i}function Sl(t,e={}){let i="";for(let s=0;s<t.length;s++)i+=Lg[t[s]];const r=`0x${i}`;return typeof e.size=="number"?(Er(r,{size:e.size}),vr(r,{dir:"right",size:e.size})):r}function Dl(t,e={}){const{signed:i,size:r}=e,s=BigInt(t);let n;r?i?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&i?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new Bg({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:i,size:r,value:`${t}${c}`})}const a=`0x${(i&&s<0?(1n<<BigInt(r*8))+BigInt(s):s).toString(16)}`;return r?vr(a,{size:r}):a}const qg=new TextEncoder;function zg(t,e={}){const i=qg.encode(t);return Sl(i,e)}const Hg=new TextEncoder;function Vg(t,e={}){return typeof t=="number"||typeof t=="bigint"?Wg(t,e):typeof t=="boolean"?Kg(t,e):ns(t)?Al(t,e):Pl(t,e)}function Kg(t,e={}){const i=new Uint8Array(1);return i[0]=Number(t),typeof e.size=="number"?(Er(i,{size:e.size}),vr(i,{size:e.size})):i}const jt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ac(t){if(t>=jt.zero&&t<=jt.nine)return t-jt.zero;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 Al(t,e={}){let i=t;e.size&&(Er(i,{size:e.size}),i=vr(i,{dir:"right",size:e.size}));let r=i.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=Ac(r.charCodeAt(a++)),h=Ac(r.charCodeAt(a++));if(c===void 0||h===void 0)throw new Ri(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+h}return n}function Wg(t,e){const i=Dl(t,e);return Al(i)}function Pl(t,e={}){const i=Hg.encode(t);return typeof e.size=="number"?(Er(i,{size:e.size}),vr(i,{dir:"right",size:e.size})):i}const Ss=BigInt(2**32-1),Pc=BigInt(32);function Gg(t,e=!1){return e?{h:Number(t&Ss),l:Number(t>>Pc&Ss)}:{h:Number(t>>Pc&Ss)|0,l:Number(t&Ss)|0}}function Yg(t,e=!1){const i=t.length;let r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:o,l:a}=Gg(t[n],e);[r[n],s[n]]=[o,a]}return[r,s]}const Jg=(t,e,i)=>t<<i|e>>>32-i,Zg=(t,e,i)=>e<<i|t>>>32-i,Qg=(t,e,i)=>e<<i-32|t>>>64-i,Xg=(t,e,i)=>t<<i-32|e>>>64-i,Wi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function e0(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function os(t,...e){if(!e0(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 Z6(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");sn(t.outputLen),sn(t.blockLen)}function Oc(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 t0(t,e){os(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function i0(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ol(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Q6(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function X6(t,e){return t<<32-e|t>>>e}const r0=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function s0(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]=s0(t[e]);return t}const Cc=r0?t=>t:n0;function o0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Cl(t){return typeof t=="string"&&(t=o0(t)),os(t),t}function eA(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];os(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}class a0{}function c0(t){const e=r=>t().update(Cl(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function tA(t=32){if(Wi&&typeof Wi.getRandomValues=="function")return Wi.getRandomValues(new Uint8Array(t));if(Wi&&typeof Wi.randomBytes=="function")return Uint8Array.from(Wi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const h0=BigInt(0),Or=BigInt(1),u0=BigInt(2),l0=BigInt(7),d0=BigInt(256),f0=BigInt(113),Tl=[],Fl=[],Rl=[];for(let t=0,e=Or,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],Tl.push(2*(5*r+i)),Fl.push((t+1)*(t+2)/2%64);let s=h0;for(let n=0;n<7;n++)e=(e<<Or^(e>>l0)*f0)%d0,e&u0&&(s^=Or<<(Or<<BigInt(n))-Or);Rl.push(s)}const Nl=Yg(Rl,!0),p0=Nl[0],g0=Nl[1],Tc=(t,e,i)=>i>32?Qg(t,e,i):Jg(t,e,i),Fc=(t,e,i)=>i>32?Xg(t,e,i):Zg(t,e,i);function y0(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[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,h=i[c],u=i[c+1],l=Tc(h,u,1)^i[a],d=Fc(h,u,1)^i[a+1];for(let p=0;p<50;p+=10)t[o+p]^=l,t[o+p+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Fl[o],c=Tc(s,n,a),h=Fc(s,n,a),u=Tl[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=p0[r],t[1]^=g0[r]}Ol(i)}class Da extends a0{constructor(e,i,r,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=i,this.outputLen=r,this.enableXOF=s,this.rounds=n,sn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=i0(this.state)}clone(){return this._cloneInto()}keccak(){Cc(this.state32),y0(this.state32,this.rounds),Cc(this.state32),this.posOut=0,this.pos=0}update(e){Oc(this),e=Cl(e),os(e);const{blockLen:i,state:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:s}=this;e[r]^=i,i&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Oc(this,!1),os(e),this.finish();const i=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(i.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 sn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(t0(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,Ol(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Da(i,r,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=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const w0=(t,e,i)=>c0(()=>new Da(e,t,i)),m0=(()=>w0(1,136,256/8))();function Ul(t,e){const i=e||"hex",r=m0(ns(t,{strict:!1})?Vg(t):t);return i==="bytes"?r:Bo(r)}class b0 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const i=super.get(e);return super.has(e)&&i!==void 0&&(this.delete(e),super.set(e,i)),i}set(e,i){if(super.set(e,i),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Yn=new b0(8192);function v0(t,e){if(Yn.has(`${t}.${e}`))return Yn.get(`${t}.${e}`);const i=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=Ul(Pl(i),"bytes"),s=(e?i.substring(`${e}0x`.length):i).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(r[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return Yn.set(`${t}.${e}`,n),n}function E0(t){const e=Ul(`0x${t.substring(4)}`).substring(26);return v0(`0x${e}`)}async function I0({hash:t,signature:e}){const i=ns(t)?t:Bo(t),{secp256k1:r}=await ml(()=>import("./secp256k1-c8041f84.js"),["assets/secp256k1-c8041f84.js","assets/index-23cd0f55.js","assets/index-6a75d29a.css"]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:u,v:l,yParity:d}=e,p=Number(d??l),f=Rc(p);return new r.Signature(Uo(h),Uo(u)).addRecoveryBit(f)}const o=ns(e)?e:Bo(e);if(No(o)!==65)throw new Error("invalid signature length");const a=jg(`0x${o.slice(130)}`),c=Rc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(i.substring(2)).toHex(!1)}`}function Rc(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function _0({hash:t,signature:e}){return E0(await I0({hash:t,signature:e}))}function x0(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<t.length;h++){const u=t.charAt(h),l=u.charCodeAt(0);if(e[l]!==255)throw new TypeError(u+" is ambiguous");e[l]=h}const i=t.length,r=t.charAt(0),s=Math.log(i)/Math.log(256),n=Math.log(256)/Math.log(i);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let u=0,l=0,d=0;const p=h.length;for(;d!==p&&h[d]===0;)d++,u++;const f=(p-d)*n+1>>>0,g=new Uint8Array(f);for(;d!==p;){let E=h[d],m=0;for(let A=f-1;(E!==0||m<l)&&A!==-1;A--,m++)E+=256*g[A]>>>0,g[A]=E%i>>>0,E=E/i>>>0;if(E!==0)throw new Error("Non-zero carry");l=m,d++}let y=f-l;for(;y!==f&&g[y]===0;)y++;let v=r.repeat(u);for(;y<f;++y)v+=t.charAt(g[y]);return v}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let u=0,l=0,d=0;for(;h[u]===r;)l++,u++;const p=(h.length-u)*s+1>>>0,f=new Uint8Array(p);for(;u<h.length;){const E=h.charCodeAt(u);if(E>255)return;let m=e[E];if(m===255)return;let A=0;for(let $=p-1;(m!==0||A<d)&&$!==-1;$--,A++)m+=i*f[$]>>>0,f[$]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");d=A,u++}let g=p-d;for(;g!==p&&f[g]===0;)g++;const y=new Uint8Array(l+(p-g));let v=l;for(;g!==p;)y[v++]=f[g++];return y}function c(h){const u=a(h);if(u)return u;throw new Error("Non-base"+i+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var $0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const ps=x0($0);function S0(t){const e=t.length;let i=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if(s&4294967168)if(!(s&4294965248))i+=2;else{if(s>=55296&&s<=56319&&r<e){const n=t.charCodeAt(r);(n&64512)===56320&&(++r,s=((s&1023)<<10)+(n&1023)+65536)}s&4294901760?i+=4:i+=3}else{i++;continue}}return i}function D0(t,e,i){const r=t.length;let s=i,n=0;for(;n<r;){let o=t.charCodeAt(n++);if(o&4294967168)if(!(o&4294965248))e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&n<r){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 A0=new TextEncoder,P0=50;function O0(t,e,i){A0.encodeInto(t,e.subarray(i))}function C0(t,e,i){t.length>P0?O0(t,e,i):D0(t,e,i)}const T0=4096;function Bl(t,e,i){let r=e;const s=r+i,n=[];let o="";for(;r<s;){const a=t[r++];if(!(a&128))n.push(a);else if((a&224)===192){const c=t[r++]&63;n.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,h=t[r++]&63;n.push((a&31)<<12|c<<6|h)}else if((a&248)===240){const c=t[r++]&63,h=t[r++]&63,u=t[r++]&63;let l=(a&7)<<18|c<<12|h<<6|u;l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|l&1023),n.push(l)}else n.push(a);n.length>=T0&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const F0=new TextDecoder,R0=200;function N0(t,e,i){const r=t.subarray(e,e+i);return F0.decode(r)}function U0(t,e,i){return i>R0?N0(t,e,i):Bl(t,e,i)}class Ds{constructor(e,i){this.type=e,this.data=i}}class it extends Error{constructor(e){super(e);const i=Object.create(it.prototype);Object.setPrototypeOf(this,i),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:it.name})}}const Cr=4294967295;function B0(t,e,i){const r=i/4294967296,s=i;t.setUint32(e,r),t.setUint32(e+4,s)}function kl(t,e,i){const r=Math.floor(i/4294967296),s=i;t.setUint32(e,r),t.setUint32(e+4,s)}function jl(t,e){const i=t.getInt32(e),r=t.getUint32(e+4);return i*4294967296+r}function k0(t,e){const i=t.getUint32(e),r=t.getUint32(e+4);return i*4294967296+r}const j0=-1,L0=4294967296-1,M0=17179869184-1;function q0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=M0)if(e===0&&t<=L0){const i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,t),i}else{const i=t/4294967296,r=t&4294967295,s=new Uint8Array(8),n=new DataView(s.buffer);return n.setUint32(0,e<<2|i&3),n.setUint32(4,r),s}else{const i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,e),kl(r,4,t),i}}function z0(t){const e=t.getTime(),i=Math.floor(e/1e3),r=(e-i*1e3)*1e6,s=Math.floor(r/1e9);return{sec:i+s,nsec:r-s*1e9}}function H0(t){if(t instanceof Date){const e=z0(t);return q0(e)}else return null}function V0(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 i=e.getUint32(0),r=e.getUint32(4),s=(i&3)*4294967296+r,n=i>>>2;return{sec:s,nsec:n}}case 12:{const i=jl(e,4),r=e.getUint32(0);return{sec:i,nsec:r}}default:throw new it(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function K0(t){const e=V0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const W0={type:j0,encode:H0,decode:K0};class nn{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(W0)}register({type:e,encode:i,decode:r}){if(e>=0)this.encoders[e]=i,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=i,this.builtInDecoders[s]=r}}tryToEncode(e,i){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const n=s(e,i);if(n!=null){const o=-1-r;return new Ds(o,n)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const n=s(e,i);if(n!=null){const o=r;return new Ds(o,n)}}}return e instanceof Ds?e:null}decode(e,i,r){const s=i<0?this.builtInDecoders[-1-i]:this.decoders[i];return s?s(e,i,r):new Ds(i,e)}}nn.defaultCodec=new nn;function G0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ko(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):G0(t)?new Uint8Array(t):Uint8Array.from(t)}const Y0=100,J0=2048;let Z0=class Ll{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??nn.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)??Y0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??J0,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 Ll({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,i){if(i>this.maxDepth)throw new Error(`Too deep objects in depth ${i}`);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,i)}ensureBufferSizeToWrite(e){const i=this.pos+e;this.view.byteLength<i&&this.resizeBuffer(i*2)}resizeBuffer(e){const i=new ArrayBuffer(e),r=new Uint8Array(i),s=new DataView(i);r.set(this.bytes),this.view=s,this.bytes=r}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 r=S0(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),C0(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,i){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,i);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,i);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const i=e.byteLength;if(i<256)this.writeU8(196),this.writeU8(i);else if(i<65536)this.writeU8(197),this.writeU16(i);else if(i<4294967296)this.writeU8(198),this.writeU32(i);else throw new Error(`Too large binary: ${i}`);const r=ko(e);this.writeU8a(r)}encodeArray(e,i){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,i+1)}countWithoutUndefined(e,i){let r=0;for(const s of i)e[s]!==void 0&&r++;return r}encodeMap(e,i){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.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 r){const o=e[n];this.ignoreUndefined&&o===void 0||(this.encodeString(n),this.doEncode(o,i+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const i=e.data.length;if(i===1)this.writeU8(212);else if(i===2)this.writeU8(213);else if(i===4)this.writeU8(214);else if(i===8)this.writeU8(215);else if(i===16)this.writeU8(216);else if(i<256)this.writeU8(199),this.writeU8(i);else if(i<65536)this.writeU8(200),this.writeU16(i);else if(i<4294967296)this.writeU8(201),this.writeU32(i);else throw new Error(`Too large extension object: ${i}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const i=e.length;this.ensureBufferSizeToWrite(i),this.bytes.set(e,this.pos),this.pos+=i}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),B0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),kl(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 Q0(t,e){return new Z0(e).encodeSharedRef(t)}function Jn(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const X0=16,ey=16;class ty{constructor(e=X0,i=ey){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=i,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,i,r){const s=this.caches[r-1];e:for(const n of s){const o=n.bytes;for(let a=0;a<r;a++)if(o[a]!==e[i+a])continue e;return n.str}return null}store(e,i){const r=this.caches[e.length-1],s={bytes:e,str:i};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,i,r){const s=this.find(e,i,r);if(s!=null)return this.hit++,s;this.miss++;const n=Bl(e,i,r),o=Uint8Array.prototype.slice.call(e,i,i+r);return this.store(o,n),n}}const jo="array",Yr="map_key",Ml="map_value",iy=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new it("The type of key must be string or number but "+typeof t)};class ry{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const i=this.getUninitializedStateFromPool();i.type=jo,i.position=0,i.size=e,i.array=new Array(e)}pushMapState(e){const i=this.getUninitializedStateFromPool();i.type=Yr,i.readCount=0,i.size=e,i.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===jo){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Yr||e.type===Ml){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Tr=-1,Aa=new DataView(new ArrayBuffer(0)),sy=new Uint8Array(Aa.buffer);try{Aa.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 Nc=new RangeError("Insufficient data"),ny=new ty;let oy=class ql{constructor(e){this.totalPos=0,this.pos=0,this.view=Aa,this.bytes=sy,this.headByte=Tr,this.stack=new ry,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??nn.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)??Cr,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Cr,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Cr,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Cr,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Cr,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:ny,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??iy}clone(){return new ql({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=Tr,this.stack.reset()}setBuffer(e){const i=ko(e);this.bytes=i,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Tr&&!this.hasRemaining(1))this.setBuffer(e);else{const i=this.bytes.subarray(this.pos),r=ko(e),s=new Uint8Array(i.length+r.length);s.set(i),s.set(r,i.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:i,pos:r}=this;return new RangeError(`Extra ${i.byteLength-r} of ${i.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 i=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return i}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 i=!1,r;for await(const a of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),i=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:n,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Jn(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,i){if(this.entered){yield*this.clone().decodeMultiAsync(e,i);return}try{this.entered=!0;let r=i,s=-1;for await(const n of e){if(i&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),r&&(s=this.readArraySize(),r=!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 i;if(e>=224)i=e-256;else if(e<192)if(e<128)i=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else{const s=e-160;i=this.decodeString(s,0)}else if(e===192)i=null;else if(e===194)i=!1;else if(e===195)i=!0;else if(e===202)i=this.readF32();else if(e===203)i=this.readF64();else if(e===204)i=this.readU8();else if(e===205)i=this.readU16();else if(e===206)i=this.readU32();else if(e===207)this.useBigInt64?i=this.readU64AsBigInt():i=this.readU64();else if(e===208)i=this.readI8();else if(e===209)i=this.readI16();else if(e===210)i=this.readI32();else if(e===211)this.useBigInt64?i=this.readI64AsBigInt():i=this.readI64();else if(e===217){const s=this.lookU8();i=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();i=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();i=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e===196){const s=this.lookU8();i=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();i=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();i=this.decodeBinary(s,4)}else if(e===212)i=this.decodeExtension(1,0);else if(e===213)i=this.decodeExtension(2,0);else if(e===214)i=this.decodeExtension(4,0);else if(e===215)i=this.decodeExtension(8,0);else if(e===216)i=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();i=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();i=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();i=this.decodeExtension(s,4)}else throw new it(`Unrecognized type byte: ${Jn(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===jo)if(s.array[s.position]=i,s.position++,s.position===s.size)i=s.array,r.release(s);else continue e;else if(s.type===Yr){if(i==="__proto__")throw new it("The key __proto__ is not allowed");s.key=this.mapKeyConverter(i),s.type=Ml;continue e}else if(s.map[s.key]=i,s.readCount++,s.readCount===s.size)i=s.map,r.release(s);else{s.key=null,s.type=Yr;continue e}}return i}}readHeadByte(){return this.headByte===Tr&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Tr}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 it(`Unrecognized array type byte: ${Jn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new it(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new it(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,i){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,i):this.decodeBinary(e,i)}decodeUtf8String(e,i){var n;if(e>this.maxStrLength)throw new it(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+i+e)throw Nc;const r=this.pos+i;let s;return this.stateIsMapKey()&&((n=this.keyDecoder)!=null&&n.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=U0(this.bytes,r,e),this.pos+=i+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Yr:!1}decodeBinary(e,i){if(e>this.maxBinLength)throw new it(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+i))throw Nc;const r=this.pos+i,s=this.bytes.subarray(r,r+e);return this.pos+=i+e,s}decodeExtension(e,i){if(e>this.maxExtLength)throw new it(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+i),s=this.decodeBinary(e,i+1);return this.extensionCodec.decode(s,r,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=k0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=jl(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 ay(t,e){return new oy(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function cy(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zl(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(i=>typeof i=="string"):e.every(i=>Number.isSafeInteger(i)):!1}function on(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Pa(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Lo(t){if(!Array.isArray(t))throw new Error("array expected")}function an(t,e){if(!zl(!0,e))throw new Error(`${t}: array of strings expected`)}function hy(t,e){if(!zl(!1,e))throw new Error(`${t}: array of numbers expected`)}function uy(...t){const e=n=>n,i=(n,o)=>a=>n(o(a)),r=t.map(n=>n.encode).reduceRight(i,e),s=t.map(n=>n.decode).reduce(i,e);return{encode:r,decode:s}}function ly(t){const e=typeof t=="string"?t.split(""):t,i=e.length;an("alphabet",e);const r=new Map(e.map((s,n)=>[s,n]));return{encode:s=>(Lo(s),s.map(n=>{if(!Number.isSafeInteger(n)||n<0||n>=i)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);return e[n]})),decode:s=>(Lo(s),s.map(n=>{on("alphabet.decode",n);const o=r.get(n);if(o===void 0)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return o}))}}function dy(t=""){return on("join",t),{encode:e=>(an("join.decode",e),e.join(t)),decode:e=>(on("join.decode",e),e.split(t))}}function fy(t,e="="){return Pa(t),on("padding",e),{encode(i){for(an("padding.encode",i);i.length*t%8;)i.push(e);return i},decode(i){an("padding.decode",i);let r=i.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&i[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return i.slice(0,r)}}}const Hl=(t,e)=>e===0?t:Hl(e,t%e),cn=(t,e)=>t+(e-Hl(t,e)),Zn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Uc(t,e,i,r){if(Lo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(i<=0||i>32)throw new Error(`convertRadix2: wrong to=${i}`);if(cn(e,i)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${i} carryBits=${cn(e,i)}`);let s=0,n=0;const o=Zn[e],a=Zn[i]-1,c=[];for(const h of t){if(Pa(h),h>=o)throw new Error(`convertRadix2: invalid data word=${h} from=${e}`);if(s=s<<e|h,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=i;n-=i)c.push((s>>n-i&a)>>>0);const u=Zn[n];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<<i-n&a,!r&&n>=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&n>0&&c.push(s>>>0),c}function py(t,e=!1){if(Pa(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(cn(8,t)>32||cn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:i=>{if(!cy(i))throw new Error("radix2.encode input should be Uint8Array");return Uc(Array.from(i),8,t,!e)},decode:i=>(hy("radix2.decode",i),Uint8Array.from(Uc(i,t,8,e)))}}const gy=uy(py(5),ly("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),fy(5),dy("")),yy=t=>JSON.stringify(t,(e,i)=>typeof i=="bigint"?i.toString()+"n":i),wy=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,i=t.replace(e,'$1"$2n"$3');return JSON.parse(i,(r,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Ni(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return wy(t)}catch{return t}}function Yt(t){return typeof t=="string"?t:yy(t)||""}function my(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Vl(t,...e){if(!my(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 Bc(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 by(t,e){Vl(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}const Gi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Qn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function vy(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Kl(t){return typeof t=="string"&&(t=vy(t)),Vl(t),t}let Ey=class{clone(){return this._cloneInto()}};function Iy(t){const e=r=>t().update(Kl(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function Wl(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 _y(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+h,a,r)}let xy=class extends Ey{constructor(e,i,r,s){super(),this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Qn(this.buffer)}update(e){Bc(this);const{view:i,buffer:r,blockLen:s}=this;e=Kl(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=Qn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Bc(this),by(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;i[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)i[l]=0;_y(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=Qn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<h;l++)a.setUint32(4*l,u[l],n)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%i&&e.buffer.set(r),e}};const As=BigInt(2**32-1),Mo=BigInt(32);function Gl(t,e=!1){return e?{h:Number(t&As),l:Number(t>>Mo&As)}:{h:Number(t>>Mo&As)|0,l:Number(t&As)|0}}function $y(t,e=!1){let i=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Gl(t[s],e);[i[s],r[s]]=[n,o]}return[i,r]}const Sy=(t,e)=>BigInt(t>>>0)<<Mo|BigInt(e>>>0),Dy=(t,e,i)=>t>>>i,Ay=(t,e,i)=>t<<32-i|e>>>i,Py=(t,e,i)=>t>>>i|e<<32-i,Oy=(t,e,i)=>t<<32-i|e>>>i,Cy=(t,e,i)=>t<<64-i|e>>>i-32,Ty=(t,e,i)=>t>>>i-32|e<<64-i,Fy=(t,e)=>e,Ry=(t,e)=>t,Ny=(t,e,i)=>t<<i|e>>>32-i,Uy=(t,e,i)=>e<<i|t>>>32-i,By=(t,e,i)=>e<<i-32|t>>>64-i,ky=(t,e,i)=>t<<i-32|e>>>64-i;function jy(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:s|0}}const Ly=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),My=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,qy=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),zy=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,Hy=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),Vy=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0,Y={fromBig:Gl,split:$y,toBig:Sy,shrSH:Dy,shrSL:Ay,rotrSH:Py,rotrSL:Oy,rotrBH:Cy,rotrBL:Ty,rotr32H:Fy,rotr32L:Ry,rotlSH:Ny,rotlSL:Uy,rotlBH:By,rotlBL:ky,add:jy,add3L:Ly,add3H:My,add4L:qy,add4H:zy,add5H:Vy,add5L:Hy},[Ky,Wy]=(()=>Y.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))))(),Zt=new Uint32Array(80),Qt=new Uint32Array(80);let Gy=class extends xy{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:i,Bh:r,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:h,El:u,Fh:l,Fl:d,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y]}set(e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,i){for(let m=0;m<16;m++,i+=4)Zt[m]=e.getUint32(i),Qt[m]=e.getUint32(i+=4);for(let m=16;m<80;m++){const A=Zt[m-15]|0,$=Qt[m-15]|0,k=Y.rotrSH(A,$,1)^Y.rotrSH(A,$,8)^Y.shrSH(A,$,7),B=Y.rotrSL(A,$,1)^Y.rotrSL(A,$,8)^Y.shrSL(A,$,7),T=Zt[m-2]|0,w=Qt[m-2]|0,O=Y.rotrSH(T,w,19)^Y.rotrBH(T,w,61)^Y.shrSH(T,w,6),_=Y.rotrSL(T,w,19)^Y.rotrBL(T,w,61)^Y.shrSL(T,w,6),D=Y.add4L(B,_,Qt[m-7],Qt[m-16]),C=Y.add4H(D,k,O,Zt[m-7],Zt[m-16]);Zt[m]=C|0,Qt[m]=D|0}let{Ah:r,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:h,Dl:u,Eh:l,El:d,Fh:p,Fl:f,Gh:g,Gl:y,Hh:v,Hl:E}=this;for(let m=0;m<80;m++){const A=Y.rotrSH(l,d,14)^Y.rotrSH(l,d,18)^Y.rotrBH(l,d,41),$=Y.rotrSL(l,d,14)^Y.rotrSL(l,d,18)^Y.rotrBL(l,d,41),k=l&p^~l&g,B=d&f^~d&y,T=Y.add5L(E,$,B,Wy[m],Qt[m]),w=Y.add5H(T,v,A,k,Ky[m],Zt[m]),O=T|0,_=Y.rotrSH(r,s,28)^Y.rotrBH(r,s,34)^Y.rotrBH(r,s,39),D=Y.rotrSL(r,s,28)^Y.rotrBL(r,s,34)^Y.rotrBL(r,s,39),C=r&n^r&a^n&a,U=s&o^s&c^o&c;v=g|0,E=y|0,g=p|0,y=f|0,p=l|0,f=d|0,{h:l,l:d}=Y.add(h|0,u|0,w|0,O|0),h=a|0,u=c|0,a=n|0,c=o|0,n=r|0,o=s|0;const I=Y.add3L(O,D,U);r=Y.add3H(I,w,_,C),s=I|0}({h:r,l:s}=Y.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:n,l:o}=Y.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h,l:u}=Y.add(this.Dh|0,this.Dl|0,h|0,u|0),{h:l,l:d}=Y.add(this.Eh|0,this.El|0,l|0,d|0),{h:p,l:f}=Y.add(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=Y.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:v,l:E}=Y.add(this.Hh|0,this.Hl|0,v|0,E|0),this.set(r,s,n,o,a,c,h,u,l,d,p,f,g,y,v,E)}roundClean(){Zt.fill(0),Qt.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 Yy=Iy(()=>new Gy);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oa=BigInt(0),Yl=BigInt(1),Jy=BigInt(2);function Ca(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ta(t){if(!Ca(t))throw new Error("Uint8Array expected")}function Xn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Zy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Fa(t){Ta(t);let e="";for(let i=0;i<t.length;i++)e+=Zy[t[i]];return e}function Jl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Oa:BigInt("0x"+t)}const Lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function kc(t){if(t>=Lt._0&&t<=Lt._9)return t-Lt._0;if(t>=Lt.A&&t<=Lt.F)return t-(Lt.A-10);if(t>=Lt.a&&t<=Lt.f)return t-(Lt.a-10)}function Zl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let s=0,n=0;s<i;s++,n+=2){const o=kc(t.charCodeAt(n)),a=kc(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)}r[s]=o*16+a}return r}function Qy(t){return Jl(Fa(t))}function Ys(t){return Ta(t),Jl(Fa(Uint8Array.from(t).reverse()))}function Ql(t,e){return Zl(t.toString(16).padStart(e*2,"0"))}function qo(t,e){return Ql(t,e).reverse()}function Mt(t,e,i){let r;if(typeof e=="string")try{r=Zl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Ca(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof i=="number"&&s!==i)throw new Error(t+" of length "+i+" expected, got "+s);return r}function jc(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Ta(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}const eo=t=>typeof t=="bigint"&&Oa<=t;function Xy(t,e,i){return eo(t)&&eo(e)&&eo(i)&&e<=t&&t<i}function Fr(t,e,i,r){if(!Xy(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function ew(t){let e;for(e=0;t>Oa;t>>=Yl,e+=1);return e}const tw=t=>(Jy<<BigInt(t-1))-Yl,iw={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"||Ca(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 Ra(t,e,i={}){const r=(s,n,o)=>{const a=iw[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))r(s,n,!1);for(const[s,n]of Object.entries(i))r(s,n,!0);return t}function Lc(t){const e=new WeakMap;return(i,...r)=>{const s=e.get(i);if(s!==void 0)return s;const n=t(i,...r);return e.set(i,n),n}}const xe=BigInt(0),pe=BigInt(1),$i=BigInt(2),rw=BigInt(3),zo=BigInt(4),Mc=BigInt(5),qc=BigInt(8);function be(t,e){const i=t%e;return i>=xe?i:e+i}function sw(t,e,i){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(i<=xe)throw new Error("invalid modulus");if(i===pe)return xe;let r=pe;for(;e>xe;)e&pe&&(r=r*t%i),t=t*t%i,e>>=pe;return r}function Dt(t,e,i){let r=t;for(;e-- >xe;)r*=r,r%=i;return r}function zc(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let i=be(t,e),r=e,s=xe,n=pe;for(;i!==xe;){const o=r/i,a=r%i,c=s-n*o;r=i,i=a,s=n,n=c}if(r!==pe)throw new Error("invert: does not exist");return be(s,e)}function nw(t){const e=(t-pe)/$i;let i,r,s;for(i=t-pe,r=0;i%$i===xe;i/=$i,r++);for(s=$i;s<t&&sw(s,e,t)!==t-pe;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+pe)/zo;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(i+pe)/$i;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,h=o.pow(o.mul(o.ONE,s),i),u=o.pow(a,n),l=o.pow(a,i);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let d=1;for(let f=o.sqr(l);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(h,pe<<BigInt(c-d-1));h=o.sqr(p),u=o.mul(u,p),l=o.mul(l,h),c=d}return u}}function ow(t){if(t%zo===rw){const e=(t+pe)/zo;return function(i,r){const s=i.pow(r,e);if(!i.eql(i.sqr(s),r))throw new Error("Cannot find square root");return s}}if(t%qc===Mc){const e=(t-Mc)/qc;return function(i,r){const s=i.mul(r,$i),n=i.pow(s,e),o=i.mul(r,n),a=i.mul(i.mul(o,$i),n),c=i.mul(o,i.sub(a,i.ONE));if(!i.eql(i.sqr(c),r))throw new Error("Cannot find square root");return c}}return nw(t)}const aw=(t,e)=>(be(t,e)&pe)===pe,cw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},i=cw.reduce((r,s)=>(r[s]="function",r),e);return Ra(t,i)}function uw(t,e,i){if(i<xe)throw new Error("invalid exponent, negatives unsupported");if(i===xe)return t.ONE;if(i===pe)return e;let r=t.ONE,s=e;for(;i>xe;)i&pe&&(r=t.mul(r,s)),s=t.sqr(s),i>>=pe;return r}function lw(t,e){const i=new Array(e.length),r=e.reduce((n,o,a)=>t.is0(o)?n:(i[a]=n,t.mul(n,o)),t.ONE),s=t.inv(r);return e.reduceRight((n,o,a)=>t.is0(o)?n:(i[a]=t.mul(n,i[a]),t.mul(n,o)),s),i}function Xl(t,e){const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function ed(t,e,i=!1,r={}){if(t<=xe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Xl(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:i,BITS:s,BYTES:n,MASK:tw(s),ZERO:xe,ONE:pe,create:c=>be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<t},is0:c=>c===xe,isOdd:c=>(c&pe)===pe,neg:c=>be(-c,t),eql:(c,h)=>c===h,sqr:c=>be(c*c,t),add:(c,h)=>be(c+h,t),sub:(c,h)=>be(c-h,t),mul:(c,h)=>be(c*h,t),pow:(c,h)=>uw(a,c,h),div:(c,h)=>be(c*zc(h,t),t),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>zc(c,t),sqrt:r.sqrt||(c=>(o||(o=ow(t)),o(a,c))),invertBatch:c=>lw(a,c),cmov:(c,h,u)=>u?h:c,toBytes:c=>i?qo(c,n):Ql(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return i?Ys(c):Qy(c)}});return Object.freeze(a)}const Hc=BigInt(0),Ps=BigInt(1);function to(t,e){const i=e.negate();return t?i:e}function td(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function io(t,e){td(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1);return{windows:i,windowSize:r}}function dw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function fw(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const ro=new WeakMap,id=new WeakMap;function so(t){return id.get(t)||1}function pw(t,e){return{constTimeNegate:to,hasPrecomputes(i){return so(i)!==1},unsafeLadder(i,r,s=t.ZERO){let n=i;for(;r>Hc;)r&Ps&&(s=s.add(n)),n=n.double(),r>>=Ps;return s},precomputeWindow(i,r){const{windows:s,windowSize:n}=io(r,e),o=[];let a=i,c=a;for(let h=0;h<s;h++){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(i,r,s){const{windows:n,windowSize:o}=io(i,e);let a=t.ZERO,c=t.BASE;const h=BigInt(2**i-1),u=2**i,l=BigInt(i);for(let d=0;d<n;d++){const p=d*o;let f=Number(s&h);s>>=l,f>o&&(f-=u,s+=Ps);const g=p,y=p+Math.abs(f)-1,v=d%2!==0,E=f<0;f===0?c=c.add(to(v,r[g])):a=a.add(to(E,r[y]))}return{p:a,f:c}},wNAFUnsafe(i,r,s,n=t.ZERO){const{windows:o,windowSize:a}=io(i,e),c=BigInt(2**i-1),h=2**i,u=BigInt(i);for(let l=0;l<o;l++){const d=l*a;if(s===Hc)break;let p=Number(s&c);if(s>>=u,p>a&&(p-=h,s+=Ps),p===0)continue;let f=r[d+Math.abs(p)-1];p<0&&(f=f.negate()),n=n.add(f)}return n},getPrecomputes(i,r,s){let n=ro.get(r);return n||(n=this.precomputeWindow(r,i),i!==1&&ro.set(r,s(n))),n},wNAFCached(i,r,s){const n=so(i);return this.wNAF(n,this.getPrecomputes(n,i,s),r)},wNAFCachedUnsafe(i,r,s,n){const o=so(i);return o===1?this.unsafeLadder(i,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,i,s),r,n)},setWindowSize(i,r){td(r,e),id.set(i,r),ro.delete(i)}}}function gw(t,e,i,r){if(dw(i,t),fw(r,e),i.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=ew(BigInt(i.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),h=Math.floor((e.BITS-1)/o)*o;let u=s;for(let l=h;l>=0;l-=o){c.fill(s);for(let p=0;p<r.length;p++){const f=r[p],g=Number(f>>BigInt(l)&BigInt(a));c[g]=c[g].add(i[p])}let d=s;for(let p=c.length-1,f=s;p>0;p--)f=f.add(c[p]),d=d.add(f);if(u=u.add(d),l!==0)for(let p=0;p<o;p++)u=u.double()}return u}function yw(t){return hw(t.Fp),Ra(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Xl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const mt=BigInt(0),ze=BigInt(1),Os=BigInt(2),ww=BigInt(8),mw={zip215:!0};function bw(t){const e=yw(t);return Ra(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function vw(t){const e=bw(t),{Fp:i,n:r,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,h=Os<<BigInt(a*8)-ze,u=i.create,l=ed(e.n,e.nBitLength),d=e.uvRatio||((I,b)=>{try{return{isValid:!0,value:i.sqrt(I*i.inv(b))}}catch{return{isValid:!1,value:mt}}}),p=e.adjustScalarBytes||(I=>I),f=e.domain||((I,b,x)=>{if(Xn("phflag",x),b.length||x)throw new Error("Contexts/pre-hash are not supported");return I});function g(I,b){Fr("coordinate "+I,b,mt,h)}function y(I){if(!(I instanceof m))throw new Error("ExtendedPoint expected")}const v=Lc((I,b)=>{const{ex:x,ey:P,ez:S}=I,R=I.is0();b==null&&(b=R?ww:i.inv(S));const N=u(x*b),q=u(P*b),z=u(S*b);if(R)return{x:mt,y:ze};if(z!==ze)throw new Error("invZ was invalid");return{x:N,y:q}}),E=Lc(I=>{const{a:b,d:x}=e;if(I.is0())throw new Error("bad point: ZERO");const{ex:P,ey:S,ez:R,et:N}=I,q=u(P*P),z=u(S*S),H=u(R*R),V=u(H*H),W=u(q*b),ne=u(H*u(W+z)),se=u(V+u(x*u(q*z)));if(ne!==se)throw new Error("bad point: equation left != right (1)");const J=u(P*S),fe=u(R*N);if(J!==fe)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(b,x,P,S){this.ex=b,this.ey=x,this.ez=P,this.et=S,g("x",b),g("y",x),g("z",P),g("t",S),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");const{x,y:P}=b||{};return g("x",x),g("y",P),new m(x,P,ze,u(x*P))}static normalizeZ(b){const x=i.invertBatch(b.map(P=>P.ez));return b.map((P,S)=>P.toAffine(x[S])).map(m.fromAffine)}static msm(b,x){return gw(m,l,b,x)}_setWindowSize(b){k.setWindowSize(this,b)}assertValidity(){E(this)}equals(b){y(b);const{ex:x,ey:P,ez:S}=this,{ex:R,ey:N,ez:q}=b,z=u(x*q),H=u(R*S),V=u(P*q),W=u(N*S);return z===H&&V===W}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:b}=e,{ex:x,ey:P,ez:S}=this,R=u(x*x),N=u(P*P),q=u(Os*u(S*S)),z=u(b*R),H=x+P,V=u(u(H*H)-R-N),W=z+N,ne=W-q,se=z-N,J=u(V*ne),fe=u(W*se),$e=u(V*se),mi=u(ne*W);return new m(J,fe,mi,$e)}add(b){y(b);const{a:x,d:P}=e,{ex:S,ey:R,ez:N,et:q}=this,{ex:z,ey:H,ez:V,et:W}=b;if(x===BigInt(-1)){const oc=u((R-S)*(H+z)),ac=u((R+S)*(H-z)),Hn=u(ac-oc);if(Hn===mt)return this.double();const cc=u(N*Os*W),hc=u(q*Os*V),uc=hc+cc,lc=ac+oc,dc=hc-cc,Cp=u(uc*Hn),Tp=u(lc*dc),Fp=u(uc*dc),Rp=u(Hn*lc);return new m(Cp,Tp,Rp,Fp)}const ne=u(S*z),se=u(R*H),J=u(q*P*W),fe=u(N*V),$e=u((S+R)*(z+H)-ne-se),mi=fe-J,$s=fe+J,Hi=u(se-x*ne),zn=u($e*mi),Ap=u($s*Hi),Pp=u($e*Hi),Op=u(mi*$s);return new m(zn,Ap,Op,Pp)}subtract(b){return this.add(b.negate())}wNAF(b){return k.wNAFCached(this,b,m.normalizeZ)}multiply(b){const x=b;Fr("scalar",x,ze,r);const{p:P,f:S}=this.wNAF(x);return m.normalizeZ([P,S])[0]}multiplyUnsafe(b,x=m.ZERO){const P=b;return Fr("scalar",P,mt,r),P===mt?$:this.is0()||P===ze?this:k.wNAFCachedUnsafe(this,P,m.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return k.unsafeLadder(this,r).is0()}toAffine(b){return v(this,b)}clearCofactor(){const{h:b}=e;return b===ze?this:this.multiplyUnsafe(b)}static fromHex(b,x=!1){const{d:P,a:S}=e,R=i.BYTES;b=Mt("pointHex",b,R),Xn("zip215",x);const N=b.slice(),q=b[R-1];N[R-1]=q&-129;const z=Ys(N),H=x?h:i.ORDER;Fr("pointHex.y",z,mt,H);const V=u(z*z),W=u(V-ze),ne=u(P*V-S);let{isValid:se,value:J}=d(W,ne);if(!se)throw new Error("Point.fromHex: invalid y coordinate");const fe=(J&ze)===ze,$e=(q&128)!==0;if(!x&&J===mt&&$e)throw new Error("Point.fromHex: x=0 and x_0=1");return $e!==fe&&(J=u(-J)),m.fromAffine({x:J,y:z})}static fromPrivateKey(b){return w(b).point}toRawBytes(){const{x:b,y:x}=this.toAffine(),P=qo(x,i.BYTES);return P[P.length-1]|=b&ze?128:0,P}toHex(){return Fa(this.toRawBytes())}}m.BASE=new m(e.Gx,e.Gy,ze,u(e.Gx*e.Gy)),m.ZERO=new m(mt,ze,ze,mt);const{BASE:A,ZERO:$}=m,k=pw(m,a*8);function B(I){return be(I,r)}function T(I){return B(Ys(I))}function w(I){const b=i.BYTES;I=Mt("private key",I,b);const x=Mt("hashed private key",n(I),2*b),P=p(x.slice(0,b)),S=x.slice(b,2*b),R=T(P),N=A.multiply(R),q=N.toRawBytes();return{head:P,prefix:S,scalar:R,point:N,pointBytes:q}}function O(I){return w(I).pointBytes}function _(I=new Uint8Array,...b){const x=jc(...b);return T(n(f(x,Mt("context",I),!!s)))}function D(I,b,x={}){I=Mt("message",I),s&&(I=s(I));const{prefix:P,scalar:S,pointBytes:R}=w(b),N=_(x.context,P,I),q=A.multiply(N).toRawBytes(),z=_(x.context,q,R,I),H=B(N+z*S);Fr("signature.s",H,mt,r);const V=jc(q,qo(H,i.BYTES));return Mt("result",V,i.BYTES*2)}const C=mw;function U(I,b,x,P=C){const{context:S,zip215:R}=P,N=i.BYTES;I=Mt("signature",I,2*N),b=Mt("message",b),x=Mt("publicKey",x,N),R!==void 0&&Xn("zip215",R),s&&(b=s(b));const q=Ys(I.slice(N,2*N));let z,H,V;try{z=m.fromHex(x,R),H=m.fromHex(I.slice(0,N),R),V=A.multiplyUnsafe(q)}catch{return!1}if(!R&&z.isSmallOrder())return!1;const W=_(S,H.toRawBytes(),z.toRawBytes(),b);return H.add(z.multiplyUnsafe(W)).subtract(V).clearCofactor().equals(m.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:O,sign:D,verify:U,ExtendedPoint:m,utils:{getExtendedPublicKey:w,randomPrivateKey:()=>o(i.BYTES),precompute(I=8,b=m.BASE){return b._setWindowSize(I),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const Na=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Vc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ew=BigInt(1),Kc=BigInt(2);BigInt(3);const Iw=BigInt(5),_w=BigInt(8);function xw(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),n=Na,o=t*t%n*t%n,a=Dt(o,Kc,n)*o%n,c=Dt(a,Ew,n)*t%n,h=Dt(c,Iw,n)*c%n,u=Dt(h,e,n)*h%n,l=Dt(u,i,n)*u%n,d=Dt(l,r,n)*l%n,p=Dt(d,s,n)*d%n,f=Dt(p,s,n)*d%n,g=Dt(f,e,n)*h%n;return{pow_p_5_8:Dt(g,Kc,n)*t%n,b2:o}}function $w(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Sw(t,e){const i=Na,r=be(e*e*e,i),s=be(r*r*e,i),n=xw(t*s).pow_p_5_8;let o=be(t*r*n,i);const a=be(e*o*o,i),c=o,h=be(o*Vc,i),u=a===t,l=a===be(-t,i),d=a===be(-t*Vc,i);return u&&(o=c),(l||d)&&(o=h),aw(o,i)&&(o=be(-o,i)),{isValid:u||l,value:o}}const Dw=(()=>ed(Na,void 0,!0))(),Aw=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dw,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_w,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Yy,randomBytes:Wl,adjustScalarBytes:$w,uvRatio:Sw}))(),rd=(()=>vw(Aw))(),Pw="EdDSA",Ow="JWT",hn=".",_n="base64url",sd="utf8",nd="utf8",Cw=":",Tw="did",Fw="key",Wc="base58btc",Rw="z",Nw="K36",Uw=32;function Ua(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function od(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ua(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ad(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const i=od(e);let r=0;for(const s of t)i.set(s,r),r+=s.length;return Ua(i)}function Bw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,v=0,E=f.length;v!==E&&f[v]===0;)v++,g++;for(var m=(E-v)*u+1>>>0,A=new Uint8Array(m);v!==E;){for(var $=f[v],k=0,B=m-1;($!==0||k<y)&&B!==-1;B--,k++)$+=256*A[B]>>>0,A[B]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");y=k,v++}for(var T=m-y;T!==m&&A[T]===0;)T++;for(var w=c.repeat(g);T<m;++T)w+=t.charAt(A[T]);return w}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,v=0;f[g]===c;)y++,g++;for(var E=(f.length-g)*h+1>>>0,m=new Uint8Array(E);f[g];){var A=i[f.charCodeAt(g)];if(A===255)return;for(var $=0,k=E-1;(A!==0||$<v)&&k!==-1;k--,$++)A+=a*m[k]>>>0,m[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=$,g++}if(f[g]!==" "){for(var B=E-v;B!==E&&m[B]===0;)B++;for(var T=new Uint8Array(y+(E-B)),w=y;B!==E;)T[w++]=m[B++];return T}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:p}}var kw=Bw,jw=kw;const cd=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")},Lw=t=>new TextEncoder().encode(t),Mw=t=>new TextDecoder().decode(t);let qw=class{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},zw=class{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}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 hd(this,e)}},Hw=class{constructor(e){this.decoders=e}or(e){return hd(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const hd=(t,e)=>new Hw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Vw=class{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new qw(e,i,r),this.decoder=new zw(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const xn=({name:t,prefix:e,encode:i,decode:r})=>new Vw(t,e,i,r),gs=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=jw(i,e);return xn({prefix:t,name:e,encode:r,decode:n=>cd(s(n))})},Kw=(t,e,i,r)=>{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*i/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[t[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Ww=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Ce=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>xn({prefix:e,name:t,encode(s){return Ww(s,r,i)},decode(s){return Kw(s,r,i,t)}}),Gw=xn({prefix:"\0",name:"identity",encode:t=>Mw(t),decode:t=>Lw(t)});var Yw=Object.freeze({__proto__:null,identity:Gw});const Jw=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zw=Object.freeze({__proto__:null,base2:Jw});const Qw=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Xw=Object.freeze({__proto__:null,base8:Qw});const em=gs({prefix:"9",name:"base10",alphabet:"0123456789"});var tm=Object.freeze({__proto__:null,base10:em});const im=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rm=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sm=Object.freeze({__proto__:null,base16:im,base16upper:rm});const nm=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),om=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),am=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cm=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hm=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),um=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),lm=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),dm=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fm=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var pm=Object.freeze({__proto__:null,base32:nm,base32upper:om,base32pad:am,base32padupper:cm,base32hex:hm,base32hexupper:um,base32hexpad:lm,base32hexpadupper:dm,base32z:fm});const gm=gs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ym=gs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wm=Object.freeze({__proto__:null,base36:gm,base36upper:ym});const mm=gs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bm=gs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var vm=Object.freeze({__proto__:null,base58btc:mm,base58flickr:bm});const Em=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Im=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_m=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xm=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $m=Object.freeze({__proto__:null,base64:Em,base64pad:Im,base64url:_m,base64urlpad:xm});const ud=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Sm=ud.reduce((t,e,i)=>(t[i]=e,t),[]),Dm=ud.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function Am(t){return t.reduce((e,i)=>(e+=Sm[i],e),"")}function Pm(t){const e=[];for(const i of t){const r=Dm[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const Om=xn({prefix:"🚀",name:"base256emoji",encode:Am,decode:Pm});var Cm=Object.freeze({__proto__:null,base256emoji:Om}),Tm=ld,Gc=128,Fm=127,Rm=~Fm,Nm=Math.pow(2,31);function ld(t,e,i){e=e||[],i=i||0;for(var r=i;t>=Nm;)e[i++]=t&255|Gc,t/=128;for(;t&Rm;)e[i++]=t&255|Gc,t>>>=7;return e[i]=t|0,ld.bytes=i-r+1,e}var Um=Ho,Bm=128,Yc=127;function Ho(t,r){var i=0,r=r||0,s=0,n=r,o,a=t.length;do{if(n>=a)throw Ho.bytes=0,new RangeError("Could not decode varint");o=t[n++],i+=s<28?(o&Yc)<<s:(o&Yc)*Math.pow(2,s),s+=7}while(o>=Bm);return Ho.bytes=n-r,i}var km=Math.pow(2,7),jm=Math.pow(2,14),Lm=Math.pow(2,21),Mm=Math.pow(2,28),qm=Math.pow(2,35),zm=Math.pow(2,42),Hm=Math.pow(2,49),Vm=Math.pow(2,56),Km=Math.pow(2,63),Wm=function(t){return t<km?1:t<jm?2:t<Lm?3:t<Mm?4:t<qm?5:t<zm?6:t<Hm?7:t<Vm?8:t<Km?9:10},Gm={encode:Tm,decode:Um,encodingLength:Wm},dd=Gm;const Jc=(t,e,i=0)=>(dd.encode(t,e,i),e),Zc=t=>dd.encodingLength(t),Vo=(t,e)=>{const i=e.byteLength,r=Zc(t),s=r+Zc(i),n=new Uint8Array(s+i);return Jc(t,n,0),Jc(i,n,r),n.set(e,s),new Ym(t,i,e,n)};let Ym=class{constructor(e,i,r,s){this.code=e,this.size=i,this.digest=r,this.bytes=s}};const fd=({name:t,code:e,encode:i})=>new Jm(t,e,i);let Jm=class{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Vo(this.code,i):i.then(r=>Vo(this.code,r))}else throw Error("Unknown type, must be binary type")}};const pd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Zm=fd({name:"sha2-256",code:18,encode:pd("SHA-256")}),Qm=fd({name:"sha2-512",code:19,encode:pd("SHA-512")});var Xm=Object.freeze({__proto__:null,sha256:Zm,sha512:Qm});const gd=0,e1="identity",yd=cd,t1=t=>Vo(gd,yd(t)),i1={code:gd,name:e1,encode:yd,digest:t1};var r1=Object.freeze({__proto__:null,identity:i1});new TextEncoder,new TextDecoder;const Qc={...Yw,...Zw,...Xw,...tm,...sm,...pm,...wm,...vm,...$m,...Cm};({...Xm,...r1});function wd(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Xc=wd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),no=wd("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=od(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),md={utf8:Xc,"utf-8":Xc,hex:Qc.base16,latin1:no,ascii:no,binary:no,...Qc};function $n(t,e="utf8"){const i=md[e];if(!i)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"):i.encoder.encode(t).substring(1)}function Ir(t,e="utf8"){const i=md[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ua(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function eh(t){return Ni($n(Ir(t,_n),sd))}function un(t){return $n(Ir(Yt(t),sd),_n)}function bd(t){const e=Ir(Nw,Wc),i=Rw+$n(ad([e,t]),Wc);return[Tw,Fw,i].join(Cw)}function s1(t){return $n(t,_n)}function n1(t){return Ir(t,_n)}function o1(t){return Ir([un(t.header),un(t.payload)].join(hn),nd)}function a1(t){return[un(t.header),un(t.payload),s1(t.signature)].join(hn)}function Ko(t){const e=t.split(hn),i=eh(e[0]),r=eh(e[1]),s=n1(e[2]),n=Ir(e.slice(0,2).join(hn),nd);return{header:i,payload:r,signature:s,data:n}}function th(t=Wl(Uw)){const e=rd.getPublicKey(t);return{secretKey:ad([t,e]),publicKey:e}}async function c1(t,e,i,r,s=L.fromMiliseconds(Date.now())){const n={alg:Pw,typ:Ow},o=bd(r.publicKey),a=s+i,c={iss:o,sub:t,aud:e,iat:s,exp:a},h=o1({header:n,payload:c}),u=rd.sign(h,r.secretKey.slice(0,32));return a1({header:n,payload:c,signature:u})}function Ba(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function vd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ba(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jr(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const i=vd(e);let r=0;for(const s of t)i.set(s,r),r+=s.length;return Ba(i)}function h1(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,v=0,E=f.length;v!==E&&f[v]===0;)v++,g++;for(var m=(E-v)*u+1>>>0,A=new Uint8Array(m);v!==E;){for(var $=f[v],k=0,B=m-1;($!==0||k<y)&&B!==-1;B--,k++)$+=256*A[B]>>>0,A[B]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");y=k,v++}for(var T=m-y;T!==m&&A[T]===0;)T++;for(var w=c.repeat(g);T<m;++T)w+=t.charAt(A[T]);return w}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,v=0;f[g]===c;)y++,g++;for(var E=(f.length-g)*h+1>>>0,m=new Uint8Array(E);f[g];){var A=i[f.charCodeAt(g)];if(A===255)return;for(var $=0,k=E-1;(A!==0||$<v)&&k!==-1;k--,$++)A+=a*m[k]>>>0,m[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=$,g++}if(f[g]!==" "){for(var B=E-v;B!==E&&m[B]===0;)B++;for(var T=new Uint8Array(y+(E-B)),w=y;B!==E;)T[w++]=m[B++];return T}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:p}}var u1=h1,l1=u1;const d1=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")},f1=t=>new TextEncoder().encode(t),p1=t=>new TextDecoder().decode(t);class g1{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class y1{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}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 Ed(this,e)}}class w1{constructor(e){this.decoders=e}or(e){return Ed(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ed=(t,e)=>new w1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class m1{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new g1(e,i,r),this.decoder=new y1(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Sn=({name:t,prefix:e,encode:i,decode:r})=>new m1(t,e,i,r),ys=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=l1(i,e);return Sn({prefix:t,name:e,encode:r,decode:n=>d1(s(n))})},b1=(t,e,i,r)=>{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*i/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[t[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},v1=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Te=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>Sn({prefix:e,name:t,encode(s){return v1(s,r,i)},decode(s){return b1(s,r,i,t)}}),E1=Sn({prefix:"\0",name:"identity",encode:t=>p1(t),decode:t=>f1(t)}),I1=Object.freeze(Object.defineProperty({__proto__:null,identity:E1},Symbol.toStringTag,{value:"Module"})),_1=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),x1=Object.freeze(Object.defineProperty({__proto__:null,base2:_1},Symbol.toStringTag,{value:"Module"})),$1=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),S1=Object.freeze(Object.defineProperty({__proto__:null,base8:$1},Symbol.toStringTag,{value:"Module"})),D1=ys({prefix:"9",name:"base10",alphabet:"0123456789"}),A1=Object.freeze(Object.defineProperty({__proto__:null,base10:D1},Symbol.toStringTag,{value:"Module"})),P1=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),O1=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),C1=Object.freeze(Object.defineProperty({__proto__:null,base16:P1,base16upper:O1},Symbol.toStringTag,{value:"Module"})),T1=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),F1=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),R1=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),N1=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),U1=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),B1=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),k1=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),j1=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),L1=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),M1=Object.freeze(Object.defineProperty({__proto__:null,base32:T1,base32hex:U1,base32hexpad:k1,base32hexpadupper:j1,base32hexupper:B1,base32pad:R1,base32padupper:N1,base32upper:F1,base32z:L1},Symbol.toStringTag,{value:"Module"})),q1=ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),z1=ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),H1=Object.freeze(Object.defineProperty({__proto__:null,base36:q1,base36upper:z1},Symbol.toStringTag,{value:"Module"})),V1=ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),K1=ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),W1=Object.freeze(Object.defineProperty({__proto__:null,base58btc:V1,base58flickr:K1},Symbol.toStringTag,{value:"Module"})),G1=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Y1=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J1=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Z1=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Q1=Object.freeze(Object.defineProperty({__proto__:null,base64:G1,base64pad:Y1,base64url:J1,base64urlpad:Z1},Symbol.toStringTag,{value:"Module"})),Id=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),X1=Id.reduce((t,e,i)=>(t[i]=e,t),[]),eb=Id.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function tb(t){return t.reduce((e,i)=>(e+=X1[i],e),"")}function ib(t){const e=[];for(const i of t){const r=eb[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const rb=Sn({prefix:"🚀",name:"base256emoji",encode:tb,decode:ib}),sb=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:rb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const ih={...I1,...x1,...S1,...A1,...C1,...M1,...H1,...W1,...Q1,...sb};function _d(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const rh=_d("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),oo=_d("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=vd(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),xd={utf8:rh,"utf-8":rh,hex:ih.base16,latin1:oo,ascii:oo,binary:oo,...ih};function ut(t,e="utf8"){const i=xd[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ba(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function Ze(t,e="utf8"){const i=xd[e];if(!i)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"):i.encoder.encode(t).substring(1)}const nb={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"}},ob="Input must be an string, Buffer or Uint8Array";function ab(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(ob);return e}function cb(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Cs(t){return(4294967296+t).toString(16).substring(1)}function hb(t,e,i){let r=`
16
+ `+t+" = ";for(let s=0;s<e.length;s+=2){if(i===32)r+=Cs(e[s]).toUpperCase(),r+=" ",r+=Cs(e[s+1]).toUpperCase();else if(i===64)r+=Cs(e[s+1]).toUpperCase(),r+=Cs(e[s]).toUpperCase();else throw new Error("Invalid size "+i);s%6===4?r+=`
17
+ `+new Array(t.length+4).join(" "):s<e.length-2&&(r+=" ")}console.log(r)}function ub(t,e,i){let r=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-r)+"ms"),r=n;for(let o=0;o<i;o++){const a=t(s),c=new Date().getTime(),h=c-r;r=c,console.log("Hashed in "+h+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(h/1e3)*100)/100+" MB PER SECOND")}}var $d={normalizeInput:ab,toHex:cb,debugPrint:hb,testSpeed:ub};const Js=$d;function Ts(t,e,i){const r=t[e]+t[i];let s=t[e+1]+t[i+1];r>=4294967296&&s++,t[e]=r,t[e+1]=s}function sh(t,e,i,r){let s=t[e]+i;i<0&&(s+=4294967296);let n=t[e+1]+r;s>=4294967296&&n++,t[e]=s,t[e+1]=n}function Sd(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Xt(t,e,i,r,s,n){const o=Hr[s],a=Hr[s+1],c=Hr[n],h=Hr[n+1];Ts(G,t,e),sh(G,t,o,a);let u=G[r]^G[t],l=G[r+1]^G[t+1];G[r]=l,G[r+1]=u,Ts(G,i,r),u=G[e]^G[i],l=G[e+1]^G[i+1],G[e]=u>>>24^l<<8,G[e+1]=l>>>24^u<<8,Ts(G,t,e),sh(G,t,c,h),u=G[r]^G[t],l=G[r+1]^G[t+1],G[r]=u>>>16^l<<16,G[r+1]=l>>>16^u<<16,Ts(G,i,r),u=G[e]^G[i],l=G[e+1]^G[i+1],G[e]=l>>>31^u<<1,G[e+1]=u>>>31^l<<1}const Dd=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),lb=[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],Re=new Uint8Array(lb.map(function(t){return t*2})),G=new Uint32Array(32),Hr=new Uint32Array(32);function Ad(t,e){let i=0;for(i=0;i<16;i++)G[i]=t.h[i],G[i+16]=Dd[i];for(G[24]=G[24]^t.t,G[25]=G[25]^t.t/4294967296,e&&(G[28]=~G[28],G[29]=~G[29]),i=0;i<32;i++)Hr[i]=Sd(t.b,4*i);for(i=0;i<12;i++)Xt(0,8,16,24,Re[i*16+0],Re[i*16+1]),Xt(2,10,18,26,Re[i*16+2],Re[i*16+3]),Xt(4,12,20,28,Re[i*16+4],Re[i*16+5]),Xt(6,14,22,30,Re[i*16+6],Re[i*16+7]),Xt(0,10,20,30,Re[i*16+8],Re[i*16+9]),Xt(2,12,22,24,Re[i*16+10],Re[i*16+11]),Xt(4,14,16,26,Re[i*16+12],Re[i*16+13]),Xt(6,8,18,28,Re[i*16+14],Re[i*16+15]);for(i=0;i<16;i++)t.h[i]=t.h[i]^G[i]^G[i+16]}const ei=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 Pd(t,e,i,r){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(i&&i.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.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};ei.fill(0),ei[0]=t,e&&(ei[1]=e.length),ei[2]=1,ei[3]=1,i&&ei.set(i,32),r&&ei.set(r,48);for(let n=0;n<16;n++)s.h[n]=Dd[n]^Sd(ei,n*4);return e&&(ka(s,e),s.c=128),s}function ka(t,e){for(let i=0;i<e.length;i++)t.c===128&&(t.t+=t.c,Ad(t,!1),t.c=0),t.b[t.c++]=e[i]}function Od(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;Ad(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3);return e}function Cd(t,e,i,r,s){i=i||64,t=Js.normalizeInput(t),r&&(r=Js.normalizeInput(r)),s&&(s=Js.normalizeInput(s));const n=Pd(i,e,r,s);return ka(n,t),Od(n)}function db(t,e,i,r,s){const n=Cd(t,e,i,r,s);return Js.toHex(n)}var fb={blake2b:Cd,blake2bHex:db,blake2bInit:Pd,blake2bUpdate:ka,blake2bFinal:Od};const Td=$d;function pb(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function ti(t,e,i,r,s,n){ie[t]=ie[t]+ie[e]+s,ie[r]=Fs(ie[r]^ie[t],16),ie[i]=ie[i]+ie[r],ie[e]=Fs(ie[e]^ie[i],12),ie[t]=ie[t]+ie[e]+n,ie[r]=Fs(ie[r]^ie[t],8),ie[i]=ie[i]+ie[r],ie[e]=Fs(ie[e]^ie[i],7)}function Fs(t,e){return t>>>e^t<<32-e}const Fd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ne=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),Se=new Uint32Array(16);function Rd(t,e){let i=0;for(i=0;i<8;i++)ie[i]=t.h[i],ie[i+8]=Fd[i];for(ie[12]^=t.t,ie[13]^=t.t/4294967296,e&&(ie[14]=~ie[14]),i=0;i<16;i++)Se[i]=pb(t.b,4*i);for(i=0;i<10;i++)ti(0,4,8,12,Se[Ne[i*16+0]],Se[Ne[i*16+1]]),ti(1,5,9,13,Se[Ne[i*16+2]],Se[Ne[i*16+3]]),ti(2,6,10,14,Se[Ne[i*16+4]],Se[Ne[i*16+5]]),ti(3,7,11,15,Se[Ne[i*16+6]],Se[Ne[i*16+7]]),ti(0,5,10,15,Se[Ne[i*16+8]],Se[Ne[i*16+9]]),ti(1,6,11,12,Se[Ne[i*16+10]],Se[Ne[i*16+11]]),ti(2,7,8,13,Se[Ne[i*16+12]],Se[Ne[i*16+13]]),ti(3,4,9,14,Se[Ne[i*16+14]],Se[Ne[i*16+15]]);for(i=0;i<8;i++)t.h[i]^=ie[i]^ie[i+8]}function Nd(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const i=e?e.length:0;if(e&&!(i>0&&i<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(Fd),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^i<<8^t,i>0&&(ja(r,e),r.c=64),r}function ja(t,e){for(let i=0;i<e.length;i++)t.c===64&&(t.t+=t.c,Rd(t,!1),t.c=0),t.b[t.c++]=e[i]}function Ud(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;Rd(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3)&255;return e}function Bd(t,e,i){i=i||32,t=Td.normalizeInput(t);const r=Nd(i,e);return ja(r,t),Ud(r)}function gb(t,e,i){const r=Bd(t,e,i);return Td.toHex(r)}var yb={blake2s:Bd,blake2sHex:gb,blake2sInit:Nd,blake2sUpdate:ja,blake2sFinal:Ud};const Rr=fb,Nr=yb;var wb={blake2b:Rr.blake2b,blake2bHex:Rr.blake2bHex,blake2bInit:Rr.blake2bInit,blake2bUpdate:Rr.blake2bUpdate,blake2bFinal:Rr.blake2bFinal,blake2s:Nr.blake2s,blake2sHex:Nr.blake2sHex,blake2sInit:Nr.blake2sInit,blake2sUpdate:Nr.blake2sUpdate,blake2sFinal:Nr.blake2sFinal};const mb=":";function yr(t){const[e,i]=t.split(mb);return{namespace:e,reference:i}}function nh(t,e=[]){const i=[];return Object.keys(t).forEach(r=>{if(e.length&&!e.includes(r))return;const s=t[r];i.push(...s.accounts)}),i}function kd(t,e){return t.includes(":")?[t]:e.chains||[]}var bb=Object.defineProperty,vb=Object.defineProperties,Eb=Object.getOwnPropertyDescriptors,oh=Object.getOwnPropertySymbols,Ib=Object.prototype.hasOwnProperty,_b=Object.prototype.propertyIsEnumerable,Wo=(t,e,i)=>e in t?bb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ah=(t,e)=>{for(var i in e||(e={}))Ib.call(e,i)&&Wo(t,i,e[i]);if(oh)for(var i of oh(e))_b.call(e,i)&&Wo(t,i,e[i]);return t},xb=(t,e)=>vb(t,Eb(e)),ch=(t,e,i)=>Wo(t,typeof e!="symbol"?e+"":e,i);const $b="ReactNative",rt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Sb="js";function ln(){return typeof lt<"u"&&typeof lt.versions<"u"&&typeof lt.versions.node<"u"}function wi(){return!Fi()&&!!$a()&&navigator.product===$b}function Db(){return wi()&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"&&(K==null?void 0:K.Platform.OS)==="android"}function Ab(){return wi()&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"&&(K==null?void 0:K.Platform.OS)==="ios"}function _r(){return!ln()&&!!$a()&&!!Fi()}function ws(){return wi()?rt.reactNative:ln()?rt.node:_r()?rt.browser:rt.unknown}function hh(){var t;try{return wi()&&typeof K<"u"&&typeof(K==null?void 0:K.Application)<"u"?(t=K.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Pb(t,e){const i=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const s=e[r];s!==void 0&&i.set(r,s)}return i.toString()}function Ob(t){var e,i;const r=jd();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),xb(ah(ah({},r),t),{url:(t==null?void 0:t.url)||r.url,name:(t==null?void 0:t.name)||r.name,description:(t==null?void 0:t.description)||r.description,icons:(i=t==null?void 0:t.icons)!=null&&i.length&&t.icons.length>0?t.icons:r.icons})}catch(s){return console.warn("Error populating app metadata",s),t||r}}function jd(){return Il()||{name:"",description:"",url:"",icons:[""]}}function Cb(){if(ws()===rt.reactNative&&typeof K<"u"&&typeof(K==null?void 0:K.Platform)<"u"){const{OS:i,Version:r}=K.Platform;return[i,r].join("-")}const t=Vp();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 Tb(){var t;const e=ws();return e===rt.browser?[e,((t=El())==null?void 0:t.host)||"unknown"].join(":"):e}function Ld(t,e,i){const r=Cb(),s=Tb();return[[t,e].join("-"),[Sb,i].join("-"),r,s].join("/")}function Fb({protocol:t,version:e,relayUrl:i,sdkVersion:r,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=i.split("?"),u=Ld(t,e,r),l={auth:s,ua:u,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=Pb(h[1]||"",l);return h[0]+"?"+d}function Ai(t,e){return t.filter(i=>e.includes(i)).length===t.length}function Go(t){return Object.fromEntries(t.entries())}function Yo(t){return new Map(Object.entries(t))}function _i(t=L.FIVE_MINUTES,e){const i=L.toMiliseconds(t||L.FIVE_MINUTES);let r,s,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(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 h=new Error(e);o=Promise.reject(h),c(h)},i),r=a,s=c})}}function fi(t,e,i){return new Promise(async(r,s)=>{const n=setTimeout(()=>s(new Error(i)),e);try{const o=await t;r(o)}catch(o){s(o)}clearTimeout(n)})}function Md(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 Rb(t){return Md("topic",t)}function Nb(t){return Md("id",t)}function qd(t){const[e,i]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof i=="string")r.topic=i;else if(e==="id"&&Number.isInteger(Number(i)))r.id=Number(i);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${i}`);return r}function me(t,e){return L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function ci(t){return Date.now()>=L.toMiliseconds(t)}function oe(t,e){return`${t}${e?`:${e}`:""}`}function Nt(t=[],e=[]){return[...new Set([...t,...e])]}async function Ub({id:t,topic:e,wcDeepLink:i}){var r;try{if(!i)return;const s=typeof i=="string"?JSON.parse(i):i,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Bb(n,t,e),a=ws();if(a===rt.browser){if(!((r=Fi())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}kb(o)}else a===rt.reactNative&&typeof(K==null?void 0:K.Linking)<"u"&&await K.Linking.openURL(o)}catch(s){console.error(s)}}function Bb(t,e,i){const r=`requestId=${e}&sessionTopic=${i}`;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}${qb(r,!0)}`}else s=`${s}/wc?${r}`;return s}function kb(t){let e="_self";Mb()?e="_top":(Lb()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function jb(t,e){let i="";try{if(_r()&&(i=localStorage.getItem(e),i))return i;i=await t.getItem(e)}catch(r){console.error(r)}return i}function uh(t,e){if(!t.includes(e))return null;const i=t.split(/([&,?,=])/),r=i.indexOf(e);return i[r+2]}function lh(){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 La(){return typeof lt<"u"&&{}.IS_VITEST==="true"}function Lb(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Mb(){try{return window.self!==window.top}catch{return!1}}function qb(t,e=!1){const i=X.from(t).toString("base64");return e?i.replace(/[=]/g,""):i}function zd(t){return X.from(t,"base64").toString("utf-8")}function zb(t){return new Promise(e=>setTimeout(e,t))}let Hb=class{constructor({limit:e}){ch(this,"limit"),ch(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const i=this.set.values().next().value;i&&this.set.delete(i)}this.set.add(e)}}has(e){return this.set.has(e)}};const Rs=BigInt(2**32-1),dh=BigInt(32);function Hd(t,e=!1){return e?{h:Number(t&Rs),l:Number(t>>dh&Rs)}:{h:Number(t>>dh&Rs)|0,l:Number(t&Rs)|0}}function Vd(t,e=!1){const i=t.length;let r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:o,l:a}=Hd(t[n],e);[r[n],s[n]]=[o,a]}return[r,s]}const fh=(t,e,i)=>t>>>i,ph=(t,e,i)=>t<<32-i|e>>>i,hi=(t,e,i)=>t>>>i|e<<32-i,ui=(t,e,i)=>t<<32-i|e>>>i,Vr=(t,e,i)=>t<<64-i|e>>>i-32,Kr=(t,e,i)=>t>>>i-32|e<<64-i,Vb=(t,e)=>e,Kb=(t,e)=>t,Wb=(t,e,i)=>t<<i|e>>>32-i,Gb=(t,e,i)=>e<<i|t>>>32-i,Yb=(t,e,i)=>e<<i-32|t>>>64-i,Jb=(t,e,i)=>t<<i-32|e>>>64-i;function _t(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:s|0}}const Ma=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),qa=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,Zb=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),Qb=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,Xb=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),ev=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0,Yi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function za(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Jt(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ft(t,...e){if(!za(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 Ha(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Jt(t.outputLen),Jt(t.blockLen)}function yi(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 Va(t,e){ft(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function as(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function pt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ao(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function At(t,e){return t<<32-e|t>>>e}const Kd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Wd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Vt=Kd?t=>t:t=>Wd(t);function tv(t){for(let e=0;e<t.length;e++)t[e]=Wd(t[e]);return t}const li=Kd?t=>t:tv,Gd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",iv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function cs(t){if(ft(t),Gd)return t.toHex();let e="";for(let i=0;i<t.length;i++)e+=iv[t[i]];return e}const qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function gh(t){if(t>=qt._0&&t<=qt._9)return t-qt._0;if(t>=qt.A&&t<=qt.F)return t-(qt.A-10);if(t>=qt.a&&t<=qt.f)return t-(qt.a-10)}function Ka(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Gd)return Uint8Array.fromHex(t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let s=0,n=0;s<i;s++,n+=2){const o=gh(t.charCodeAt(n)),a=gh(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)}r[s]=o*16+a}return r}function rv(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function $t(t){return typeof t=="string"&&(t=rv(t)),ft(t),t}function Pi(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];ft(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}let Dn=class{};function ms(t){const e=r=>t().update($t(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function sv(t){const e=(r,s)=>t(s).update($t(r)).digest(),i=t({});return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}function xr(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 nv=BigInt(0),Ur=BigInt(1),ov=BigInt(2),av=BigInt(7),cv=BigInt(256),hv=BigInt(113),Yd=[],Jd=[],Zd=[];for(let t=0,e=Ur,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],Yd.push(2*(5*r+i)),Jd.push((t+1)*(t+2)/2%64);let s=nv;for(let n=0;n<7;n++)e=(e<<Ur^(e>>av)*hv)%cv,e&ov&&(s^=Ur<<(Ur<<BigInt(n))-Ur);Zd.push(s)}const Qd=Vd(Zd,!0),uv=Qd[0],lv=Qd[1],yh=(t,e,i)=>i>32?Yb(t,e,i):Wb(t,e,i),wh=(t,e,i)=>i>32?Jb(t,e,i):Gb(t,e,i);function dv(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[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,h=i[c],u=i[c+1],l=yh(h,u,1)^i[a],d=wh(h,u,1)^i[a+1];for(let p=0;p<50;p+=10)t[o+p]^=l,t[o+p+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Jd[o],c=yh(s,n,a),h=wh(s,n,a),u=Yd[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=uv[r],t[1]^=lv[r]}pt(i)}let fv=class Xd extends Dn{constructor(e,i,r,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=i,this.outputLen=r,this.enableXOF=s,this.rounds=n,Jt(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=as(this.state)}clone(){return this._cloneInto()}keccak(){li(this.state32),dv(this.state32,this.rounds),li(this.state32),this.posOut=0,this.pos=0}update(e){yi(this),e=$t(e),ft(e);const{blockLen:i,state:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:s}=this;e[r]^=i,i&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){yi(this,!1),ft(e),this.finish();const i=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(i.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 Jt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Va(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,pt(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Xd(i,r,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=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const pv=(t,e,i)=>ms(()=>new fv(e,t,i)),gv=pv(1,136,256/8);function yv(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+h,a,r)}function wv(t,e,i){return t&e^~t&i}function mv(t,e,i){return t&e^t&i^e&i}let ef=class extends Dn{constructor(e,i,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ao(this.buffer)}update(e){yi(this),e=$t(e),ft(e);const{view:i,buffer:r,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=ao(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){yi(this),Va(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;i[o++]=128,pt(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)i[l]=0;yv(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=ao(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<h;l++)a.setUint32(4*l,u[l],n)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%i&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const ii=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ue=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Be=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),bv=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]),ri=new Uint32Array(64);let vv=class extends ef{constructor(e=32){super(64,e,8,!1),this.A=ii[0]|0,this.B=ii[1]|0,this.C=ii[2]|0,this.D=ii[3]|0,this.E=ii[4]|0,this.F=ii[5]|0,this.G=ii[6]|0,this.H=ii[7]|0}get(){const{A:e,B:i,C:r,D:s,E:n,F:o,G:a,H:c}=this;return[e,i,r,s,n,o,a,c]}set(e,i,r,s,n,o,a,c){this.A=e|0,this.B=i|0,this.C=r|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,i){for(let l=0;l<16;l++,i+=4)ri[l]=e.getUint32(i,!1);for(let l=16;l<64;l++){const d=ri[l-15],p=ri[l-2],f=At(d,7)^At(d,18)^d>>>3,g=At(p,17)^At(p,19)^p>>>10;ri[l]=g+ri[l-7]+f+ri[l-16]|0}let{A:r,B:s,C:n,D:o,E:a,F:c,G:h,H:u}=this;for(let l=0;l<64;l++){const d=At(a,6)^At(a,11)^At(a,25),p=u+d+wv(a,c,h)+bv[l]+ri[l]|0,f=(At(r,2)^At(r,13)^At(r,22))+mv(r,s,n)|0;u=h,h=c,c=a,a=o+p|0,o=n,n=s,s=r,r=p+f|0}r=r+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,h=h+this.G|0,u=u+this.H|0,this.set(r,s,n,o,a,c,h,u)}roundClean(){pt(ri)}destroy(){this.set(0,0,0,0,0,0,0,0),pt(this.buffer)}};const tf=Vd(["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))),Ev=tf[0],Iv=tf[1],si=new Uint32Array(80),ni=new Uint32Array(80);let Wa=class extends ef{constructor(e=64){super(128,e,16,!1),this.Ah=Be[0]|0,this.Al=Be[1]|0,this.Bh=Be[2]|0,this.Bl=Be[3]|0,this.Ch=Be[4]|0,this.Cl=Be[5]|0,this.Dh=Be[6]|0,this.Dl=Be[7]|0,this.Eh=Be[8]|0,this.El=Be[9]|0,this.Fh=Be[10]|0,this.Fl=Be[11]|0,this.Gh=Be[12]|0,this.Gl=Be[13]|0,this.Hh=Be[14]|0,this.Hl=Be[15]|0}get(){const{Ah:e,Al:i,Bh:r,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:h,El:u,Fh:l,Fl:d,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y]}set(e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,i){for(let m=0;m<16;m++,i+=4)si[m]=e.getUint32(i),ni[m]=e.getUint32(i+=4);for(let m=16;m<80;m++){const A=si[m-15]|0,$=ni[m-15]|0,k=hi(A,$,1)^hi(A,$,8)^fh(A,$,7),B=ui(A,$,1)^ui(A,$,8)^ph(A,$,7),T=si[m-2]|0,w=ni[m-2]|0,O=hi(T,w,19)^Vr(T,w,61)^fh(T,w,6),_=ui(T,w,19)^Kr(T,w,61)^ph(T,w,6),D=Zb(B,_,ni[m-7],ni[m-16]),C=Qb(D,k,O,si[m-7],si[m-16]);si[m]=C|0,ni[m]=D|0}let{Ah:r,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:h,Dl:u,Eh:l,El:d,Fh:p,Fl:f,Gh:g,Gl:y,Hh:v,Hl:E}=this;for(let m=0;m<80;m++){const A=hi(l,d,14)^hi(l,d,18)^Vr(l,d,41),$=ui(l,d,14)^ui(l,d,18)^Kr(l,d,41),k=l&p^~l&g,B=d&f^~d&y,T=Xb(E,$,B,Iv[m],ni[m]),w=ev(T,v,A,k,Ev[m],si[m]),O=T|0,_=hi(r,s,28)^Vr(r,s,34)^Vr(r,s,39),D=ui(r,s,28)^Kr(r,s,34)^Kr(r,s,39),C=r&n^r&a^n&a,U=s&o^s&c^o&c;v=g|0,E=y|0,g=p|0,y=f|0,p=l|0,f=d|0,{h:l,l:d}=_t(h|0,u|0,w|0,O|0),h=a|0,u=c|0,a=n|0,c=o|0,n=r|0,o=s|0;const I=Ma(O,D,U);r=qa(I,w,_,C),s=I|0}({h:r,l:s}=_t(this.Ah|0,this.Al|0,r|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:u}=_t(this.Dh|0,this.Dl|0,h|0,u|0),{h:l,l:d}=_t(this.Eh|0,this.El|0,l|0,d|0),{h:p,l:f}=_t(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=_t(this.Gh|0,this.Gl|0,g|0,y|0),{h:v,l:E}=_t(this.Hh|0,this.Hl|0,v|0,E|0),this.set(r,s,n,o,a,c,h,u,l,d,p,f,g,y,v,E)}roundClean(){pt(si,ni)}destroy(){pt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_v=class extends Wa{constructor(){super(48),this.Ah=Ue[0]|0,this.Al=Ue[1]|0,this.Bh=Ue[2]|0,this.Bl=Ue[3]|0,this.Ch=Ue[4]|0,this.Cl=Ue[5]|0,this.Dh=Ue[6]|0,this.Dl=Ue[7]|0,this.Eh=Ue[8]|0,this.El=Ue[9]|0,this.Fh=Ue[10]|0,this.Fl=Ue[11]|0,this.Gh=Ue[12]|0,this.Gl=Ue[13]|0,this.Hh=Ue[14]|0,this.Hl=Ue[15]|0}};const ke=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class xv extends Wa{constructor(){super(32),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}}const An=ms(()=>new vv),$v=ms(()=>new Wa),Sv=ms(()=>new _v),Dv=ms(()=>new xv),Av=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]),we=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),M=new Uint32Array(32);function oi(t,e,i,r,s,n){const o=s[n],a=s[n+1];let c=M[2*t],h=M[2*t+1],u=M[2*e],l=M[2*e+1],d=M[2*i],p=M[2*i+1],f=M[2*r],g=M[2*r+1],y=Ma(c,u,o);h=qa(y,h,l,a),c=y|0,{Dh:g,Dl:f}={Dh:g^h,Dl:f^c},{Dh:g,Dl:f}={Dh:Vb(g,f),Dl:Kb(g)},{h:p,l:d}=_t(p,d,g,f),{Bh:l,Bl:u}={Bh:l^p,Bl:u^d},{Bh:l,Bl:u}={Bh:hi(l,u,24),Bl:ui(l,u,24)},M[2*t]=c,M[2*t+1]=h,M[2*e]=u,M[2*e+1]=l,M[2*i]=d,M[2*i+1]=p,M[2*r]=f,M[2*r+1]=g}function ai(t,e,i,r,s,n){const o=s[n],a=s[n+1];let c=M[2*t],h=M[2*t+1],u=M[2*e],l=M[2*e+1],d=M[2*i],p=M[2*i+1],f=M[2*r],g=M[2*r+1],y=Ma(c,u,o);h=qa(y,h,l,a),c=y|0,{Dh:g,Dl:f}={Dh:g^h,Dl:f^c},{Dh:g,Dl:f}={Dh:hi(g,f,16),Dl:ui(g,f,16)},{h:p,l:d}=_t(p,d,g,f),{Bh:l,Bl:u}={Bh:l^p,Bl:u^d},{Bh:l,Bl:u}={Bh:Vr(l,u,63),Bl:Kr(l,u,63)},M[2*t]=c,M[2*t+1]=h,M[2*e]=u,M[2*e+1]=l,M[2*i]=d,M[2*i+1]=p,M[2*r]=f,M[2*r+1]=g}function Pv(t,e={},i,r,s){if(Jt(i),t<0||t>i)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=e;if(n!==void 0&&(n.length<1||n.length>i))throw new Error("key length must be undefined or 1.."+i);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class Ov extends Dn{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Jt(e),Jt(i),this.blockLen=e,this.outputLen=i,this.buffer=new Uint8Array(e),this.buffer32=as(this.buffer)}update(e){yi(this),e=$t(e),ft(e);const{blockLen:i,buffer:r,buffer32:s}=this,n=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<n;){this.pos===i&&(li(s),this.compress(s,0,!1),li(s),this.pos=0);const h=Math.min(i-this.pos,n-c),u=o+c;if(h===i&&!(u%4)&&c+h<n){const l=new Uint32Array(a,u,Math.floor((n-c)/4));li(l);for(let d=0;c+i<n;d+=s.length,c+=i)this.length+=i,this.compress(l,d,!1);li(l);continue}r.set(e.subarray(c,c+h),this.pos),this.pos+=h,this.length+=h,c+=h}return this}digestInto(e){yi(this),Va(e,this);const{pos:i,buffer32:r}=this;this.finished=!0,pt(this.buffer.subarray(i)),li(r),this.compress(r,0,!0),li(r);const s=as(e);this.get().forEach((n,o)=>s[o]=Vt(n))}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){const{buffer:i,length:r,finished:s,destroyed:n,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(i),e.destroyed=n,e.finished=s,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Cv extends Ov{constructor(e={}){const i=e.dkLen===void 0?64:e.dkLen;super(128,i),this.v0l=we[0]|0,this.v0h=we[1]|0,this.v1l=we[2]|0,this.v1h=we[3]|0,this.v2l=we[4]|0,this.v2h=we[5]|0,this.v3l=we[6]|0,this.v3h=we[7]|0,this.v4l=we[8]|0,this.v4h=we[9]|0,this.v5l=we[10]|0,this.v5h=we[11]|0,this.v6l=we[12]|0,this.v6h=we[13]|0,this.v7l=we[14]|0,this.v7h=we[15]|0,Pv(i,e,64,16,16);let{key:r,personalization:s,salt:n}=e,o=0;if(r!==void 0&&(r=$t(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,n!==void 0){n=$t(n);const a=as(n);this.v4l^=Vt(a[0]),this.v4h^=Vt(a[1]),this.v5l^=Vt(a[2]),this.v5h^=Vt(a[3])}if(s!==void 0){s=$t(s);const a=as(s);this.v6l^=Vt(a[0]),this.v6h^=Vt(a[1]),this.v7l^=Vt(a[2]),this.v7h^=Vt(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:i,v1l:r,v1h:s,v2l:n,v2h:o,v3l:a,v3h:c,v4l:h,v4h:u,v5l:l,v5h:d,v6l:p,v6h:f,v7l:g,v7h:y}=this;return[e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y]}set(e,i,r,s,n,o,a,c,h,u,l,d,p,f,g,y){this.v0l=e|0,this.v0h=i|0,this.v1l=r|0,this.v1h=s|0,this.v2l=n|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=h|0,this.v4h=u|0,this.v5l=l|0,this.v5h=d|0,this.v6l=p|0,this.v6h=f|0,this.v7l=g|0,this.v7h=y|0}compress(e,i,r){this.get().forEach((c,h)=>M[h]=c),M.set(we,16);let{h:s,l:n}=Hd(BigInt(this.length));M[24]=we[8]^n,M[25]=we[9]^s,r&&(M[28]=~M[28],M[29]=~M[29]);let o=0;const a=Av;for(let c=0;c<12;c++)oi(0,4,8,12,e,i+2*a[o++]),ai(0,4,8,12,e,i+2*a[o++]),oi(1,5,9,13,e,i+2*a[o++]),ai(1,5,9,13,e,i+2*a[o++]),oi(2,6,10,14,e,i+2*a[o++]),ai(2,6,10,14,e,i+2*a[o++]),oi(3,7,11,15,e,i+2*a[o++]),ai(3,7,11,15,e,i+2*a[o++]),oi(0,5,10,15,e,i+2*a[o++]),ai(0,5,10,15,e,i+2*a[o++]),oi(1,6,11,12,e,i+2*a[o++]),ai(1,6,11,12,e,i+2*a[o++]),oi(2,7,8,13,e,i+2*a[o++]),ai(2,7,8,13,e,i+2*a[o++]),oi(3,4,9,14,e,i+2*a[o++]),ai(3,4,9,14,e,i+2*a[o++]);this.v0l^=M[0]^M[16],this.v0h^=M[1]^M[17],this.v1l^=M[2]^M[18],this.v1h^=M[3]^M[19],this.v2l^=M[4]^M[20],this.v2h^=M[5]^M[21],this.v3l^=M[6]^M[22],this.v3h^=M[7]^M[23],this.v4l^=M[8]^M[24],this.v4h^=M[9]^M[25],this.v5l^=M[10]^M[26],this.v5h^=M[11]^M[27],this.v6l^=M[12]^M[28],this.v6h^=M[13]^M[29],this.v7l^=M[14]^M[30],this.v7h^=M[15]^M[31],pt(M)}destroy(){this.destroyed=!0,pt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Tv=sv(t=>new Cv(t)),Fv="https://rpc.walletconnect.org/v1";function rf(t){const e=`Ethereum Signed Message:
18
+ ${t.length}`,i=new TextEncoder().encode(e+t);return"0x"+X.from(gv(i)).toString("hex")}async function Rv(t,e,i,r,s,n){switch(i.t){case"eip191":return await Nv(t,e,i.s);case"eip1271":return await Uv(t,e,i.s,r,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}async function Nv(t,e,i){return(await _0({hash:rf(e),signature:i})).toLowerCase()===t.toLowerCase()}async function Uv(t,e,i,r,s,n){const o=yr(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h=i.substring(2),u=(h.length/2).toString(16).padStart(64,"0"),l=(e.startsWith("0x")?e:rf(e)).substring(2),d=a+l+c+u+h,p=await fetch(`${n||Fv}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Bv(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:f}=await p.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Bv(){return Date.now()+Math.floor(Math.random()*1e3)}function kv(t){const e=atob(t),i=new Uint8Array(e.length);for(let o=0;o<e.length;o++)i[o]=e.charCodeAt(o);const r=i[0];if(r===0)throw new Error("No signatures found");const s=1+r*64;if(i.length<s)throw new Error("Transaction data too short for claimed signature count");if(i.length<100)throw new Error("Transaction too short");const n=X.from(t,"base64").slice(1,65);return ps.encode(n)}function jv(t){const e=new Uint8Array(X.from(t,"base64")),i=Array.from("TransactionData::").map(n=>n.charCodeAt(0)),r=new Uint8Array(i.length+e.length);r.set(i),r.set(e,i.length);const s=Tv(r,{dkLen:32});return ps.encode(s)}function mh(t){const e=new Uint8Array(An(Lv(t)));return ps.encode(e)}function Lv(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 bh(t){const e=X.from(t,"base64"),i=ay(e).txn;if(!i)throw new Error("Invalid signed transaction: missing 'txn' field");const r=Q0(i),s=X.from("TX"),n=X.concat([s,X.from(r)]),o=Dv(n);return gy.encode(o).replace(/=+$/,"")}function co(t){const e=[];let i=BigInt(t);for(;i>=BigInt(128);)e.push(Number(i&BigInt(127)|BigInt(128))),i>>=BigInt(7);return e.push(Number(i)),X.from(e)}function Mv(t){const e=X.from(t.signed.bodyBytes,"base64"),i=X.from(t.signed.authInfoBytes,"base64"),r=X.from(t.signature.signature,"base64"),s=[];s.push(X.from([10])),s.push(co(e.length)),s.push(e),s.push(X.from([18])),s.push(co(i.length)),s.push(i),s.push(X.from([26])),s.push(co(r.length)),s.push(r);const n=X.concat(s),o=An(n);return X.from(o).toString("hex").toUpperCase()}var qv=Object.defineProperty,zv=Object.defineProperties,Hv=Object.getOwnPropertyDescriptors,vh=Object.getOwnPropertySymbols,Vv=Object.prototype.hasOwnProperty,Kv=Object.prototype.propertyIsEnumerable,Eh=(t,e,i)=>e in t?qv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Wv=(t,e)=>{for(var i in e||(e={}))Vv.call(e,i)&&Eh(t,i,e[i]);if(vh)for(var i of vh(e))Kv.call(e,i)&&Eh(t,i,e[i]);return t},Gv=(t,e)=>zv(t,Hv(e));const Yv="did:pkh:",Ga=t=>t==null?void 0:t.split(":"),Jv=t=>{const e=t&&Ga(t);if(e)return t.includes(Yv)?e[3]:e[1]},Jo=t=>{const e=t&&Ga(t);if(e)return e[2]+":"+e[3]},dn=t=>{const e=t&&Ga(t);if(e)return e.pop()};async function Ih(t){const{cacao:e,projectId:i}=t,{s:r,p:s}=e,n=sf(s,s.iss),o=dn(s.iss);return await Rv(o,n,r,Jo(s.iss),i)}const sf=(t,e)=>{const i=`${t.domain} wants you to sign in with your Ethereum account:`,r=dn(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${Jv(e)}`,c=`Nonce: ${t.nonce}`,h=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,l=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(g=>`
19
+ - ${g}`).join("")}`:void 0,f=Zs(t.resources);if(f){const g=hs(f);s=n2(s,g)}return[i,r,"",s,"",n,o,a,c,h,u,l,d,p].filter(g=>g!=null).join(`
20
+ `)};function Zv(t){return X.from(JSON.stringify(t)).toString("base64")}function Qv(t){return JSON.parse(X.from(t,"base64").toString("utf-8"))}function Ui(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(i=>{const r=t.att[i];if(Array.isArray(r))throw new Error(`Resource must be an object: ${i}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${i}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${i}`);Object.keys(r).forEach(s=>{const n=r[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 Xv(t,e,i,r={}){return i==null||i.sort((s,n)=>s.localeCompare(n)),{att:{[t]:e2(e,i,r)}}}function e2(t,e,i={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const r=e.map(s=>({[`${t}/${s}`]:[i]}));return Object.assign({},...r)}function nf(t){return Ui(t),`urn:recap:${Zv(t).replace(/=/g,"")}`}function hs(t){const e=Qv(t.replace("urn:recap:",""));return Ui(e),e}function t2(t,e,i){const r=Xv(t,e,i);return nf(r)}function i2(t){return t&&t.includes("urn:recap:")}function r2(t,e){const i=hs(t),r=hs(e),s=s2(i,r);return nf(s)}function s2(t,e){Ui(t),Ui(e);const i=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),r={att:{}};return i.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,h;r.att[s]=Gv(Wv({},r.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((h=e.att[s])==null?void 0:h[a])})})}),r}function n2(t="",e){Ui(e);const i="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(i))return t;const r=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(l=>({ability:l.split("/")[0],action:l.split("/")[1]}));c.sort((l,d)=>l.action.localeCompare(d.action));const h={};c.forEach(l=>{h[l.ability]||(h[l.ability]=[]),h[l.ability].push(l.action)});const u=Object.keys(h).map(l=>(s++,`(${s}) '${l}': '${h[l].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const n=r.join(" "),o=`${i}${n}`;return`${t?t+" ":""}${o}`}function _h(t){var e;const i=hs(t);Ui(i);const r=(e=i.att)==null?void 0:e.eip155;return r?Object.keys(r).map(s=>s.split("/")[1]):[]}function xh(t){const e=hs(t);Ui(e);const i=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&i.push(s[0].chains)})}),[...new Set(i.flat())]}function Zs(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return i2(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function of(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Zo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ho(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ye(t,...e){if(!of(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 $h(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 o2(t,e){Ye(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function gi(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function wr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function a2(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const c2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function h2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Qo(t){if(typeof t=="string")t=h2(t);else if(of(t))t=Xo(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function u2(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function l2(t,e){if(t.length!==e.length)return!1;let i=0;for(let r=0;r<t.length;r++)i|=t[r]^e[r];return i===0}const d2=(t,e)=>{function i(r,...s){if(Ye(r),!c2)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const h=s[0];if(!h)throw new Error("nonce / iv required");t.varSizeNonce?Ye(h):Ye(h,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&Ye(s[1]);const o=e(r,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ye(u)}};let c=!1;return{encrypt(h,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ye(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ye(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(h,u)}}}return Object.assign(i,t),i};function Sh(t,e,i=!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(i&&!p2(e))throw new Error("invalid output, must be aligned");return e}function Dh(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,h=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+h,a,r)}function f2(t,e,i){Zo(i);const r=new Uint8Array(16),s=a2(r);return Dh(s,0,BigInt(e),i),Dh(s,8,BigInt(t),i),r}function p2(t){return t.byteOffset%4===0}function Xo(t){return Uint8Array.from(t)}const af=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),g2=af("expand 16-byte k"),y2=af("expand 32-byte k"),w2=gi(g2),m2=gi(y2);function ee(t,e){return t<<e|t>>>32-e}function ea(t){return t.byteOffset%4===0}const Ns=64,b2=16,cf=2**32-1,Ah=new Uint32Array;function v2(t,e,i,r,s,n,o,a){const c=s.length,h=new Uint8Array(Ns),u=gi(h),l=ea(s)&&ea(n),d=l?gi(s):Ah,p=l?gi(n):Ah;for(let f=0;f<c;o++){if(t(e,i,r,u,o,a),o>=cf)throw new Error("arx: counter overflow");const g=Math.min(Ns,c-f);if(l&&g===Ns){const y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let v=0,E;v<b2;v++)E=y+v,p[E]=d[E]^u[v];f+=Ns;continue}for(let y=0,v;y<g;y++)v=f+y,n[v]=s[v]^h[y];f+=g}}function E2(t,e){const{allowShortKeys:i,extendNonceFn:r,counterLength:s,counterRight:n,rounds:o}=u2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return ho(s),ho(o),Zo(n),Zo(i),(a,c,h,u,l=0)=>{Ye(a),Ye(c),Ye(h);const d=h.length;if(u===void 0&&(u=new Uint8Array(d)),Ye(u),ho(l),l<0||l>=cf)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);const p=[];let f=a.length,g,y;if(f===32)p.push(g=Xo(a)),y=m2;else if(f===16&&i)g=new Uint8Array(32),g.set(a),g.set(a,16),y=w2,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);ea(c)||p.push(c=Xo(c));const v=gi(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,v,gi(c.subarray(0,16)),v),c=c.subarray(16)}const E=16-s;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,p.push(c)}const m=gi(c);return v2(t,y,v,m,h,u,l,o),wr(...p),u}}const De=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class I2{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=Qo(e),Ye(e,32);const i=De(e,0),r=De(e,2),s=De(e,4),n=De(e,6),o=De(e,8),a=De(e,10),c=De(e,12),h=De(e,14);this.r[0]=i&8191,this.r[1]=(i>>>13|r<<3)&8191,this.r[2]=(r>>>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|h<<8)&8191,this.r[9]=h>>>5&127;for(let u=0;u<8;u++)this.pad[u]=De(e,16+2*u)}process(e,i,r=!1){const s=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],u=o[3],l=o[4],d=o[5],p=o[6],f=o[7],g=o[8],y=o[9],v=De(e,i+0),E=De(e,i+2),m=De(e,i+4),A=De(e,i+6),$=De(e,i+8),k=De(e,i+10),B=De(e,i+12),T=De(e,i+14);let w=n[0]+(v&8191),O=n[1]+((v>>>13|E<<3)&8191),_=n[2]+((E>>>10|m<<6)&8191),D=n[3]+((m>>>7|A<<9)&8191),C=n[4]+((A>>>4|$<<12)&8191),U=n[5]+($>>>1&8191),I=n[6]+(($>>>14|k<<2)&8191),b=n[7]+((k>>>11|B<<5)&8191),x=n[8]+((B>>>8|T<<8)&8191),P=n[9]+(T>>>5|s),S=0,R=S+w*a+O*(5*y)+_*(5*g)+D*(5*f)+C*(5*p);S=R>>>13,R&=8191,R+=U*(5*d)+I*(5*l)+b*(5*u)+x*(5*h)+P*(5*c),S+=R>>>13,R&=8191;let N=S+w*c+O*a+_*(5*y)+D*(5*g)+C*(5*f);S=N>>>13,N&=8191,N+=U*(5*p)+I*(5*d)+b*(5*l)+x*(5*u)+P*(5*h),S+=N>>>13,N&=8191;let q=S+w*h+O*c+_*a+D*(5*y)+C*(5*g);S=q>>>13,q&=8191,q+=U*(5*f)+I*(5*p)+b*(5*d)+x*(5*l)+P*(5*u),S+=q>>>13,q&=8191;let z=S+w*u+O*h+_*c+D*a+C*(5*y);S=z>>>13,z&=8191,z+=U*(5*g)+I*(5*f)+b*(5*p)+x*(5*d)+P*(5*l),S+=z>>>13,z&=8191;let H=S+w*l+O*u+_*h+D*c+C*a;S=H>>>13,H&=8191,H+=U*(5*y)+I*(5*g)+b*(5*f)+x*(5*p)+P*(5*d),S+=H>>>13,H&=8191;let V=S+w*d+O*l+_*u+D*h+C*c;S=V>>>13,V&=8191,V+=U*a+I*(5*y)+b*(5*g)+x*(5*f)+P*(5*p),S+=V>>>13,V&=8191;let W=S+w*p+O*d+_*l+D*u+C*h;S=W>>>13,W&=8191,W+=U*c+I*a+b*(5*y)+x*(5*g)+P*(5*f),S+=W>>>13,W&=8191;let ne=S+w*f+O*p+_*d+D*l+C*u;S=ne>>>13,ne&=8191,ne+=U*h+I*c+b*a+x*(5*y)+P*(5*g),S+=ne>>>13,ne&=8191;let se=S+w*g+O*f+_*p+D*d+C*l;S=se>>>13,se&=8191,se+=U*u+I*h+b*c+x*a+P*(5*y),S+=se>>>13,se&=8191;let J=S+w*y+O*g+_*f+D*p+C*d;S=J>>>13,J&=8191,J+=U*l+I*u+b*h+x*c+P*a,S+=J>>>13,J&=8191,S=(S<<2)+S|0,S=S+R|0,R=S&8191,S=S>>>13,N+=S,n[0]=R,n[1]=N,n[2]=q,n[3]=z,n[4]=H,n[5]=V,n[6]=W,n[7]=ne,n[8]=se,n[9]=J}finalize(){const{h:e,pad:i}=this,r=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,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[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]+i[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+i[a]|0)+(o>>>16)|0,e[a]=o&65535;wr(r)}update(e){$h(this),e=Qo(e),Ye(e);const{buffer:i,blockLen:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);if(o===r){for(;r<=s-n;n+=r)this.process(e,n);continue}i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(i,0,!1),this.pos=0)}return this}destroy(){wr(this.h,this.r,this.buffer,this.pad)}digestInto(e){$h(this),o2(e,this),this.finished=!0;const{buffer:i,h:r}=this;let{pos:s}=this;if(s){for(i[s++]=1;s<16;s++)i[s]=0;this.process(i,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}}function _2(t){const e=(r,s)=>t(s).update(Qo(r)).digest(),i=t(new Uint8Array(32));return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}const x2=_2(t=>new I2(t));function $2(t,e,i,r,s,n=20){let o=t[0],a=t[1],c=t[2],h=t[3],u=e[0],l=e[1],d=e[2],p=e[3],f=e[4],g=e[5],y=e[6],v=e[7],E=s,m=i[0],A=i[1],$=i[2],k=o,B=a,T=c,w=h,O=u,_=l,D=d,C=p,U=f,I=g,b=y,x=v,P=E,S=m,R=A,N=$;for(let z=0;z<n;z+=2)k=k+O|0,P=ee(P^k,16),U=U+P|0,O=ee(O^U,12),k=k+O|0,P=ee(P^k,8),U=U+P|0,O=ee(O^U,7),B=B+_|0,S=ee(S^B,16),I=I+S|0,_=ee(_^I,12),B=B+_|0,S=ee(S^B,8),I=I+S|0,_=ee(_^I,7),T=T+D|0,R=ee(R^T,16),b=b+R|0,D=ee(D^b,12),T=T+D|0,R=ee(R^T,8),b=b+R|0,D=ee(D^b,7),w=w+C|0,N=ee(N^w,16),x=x+N|0,C=ee(C^x,12),w=w+C|0,N=ee(N^w,8),x=x+N|0,C=ee(C^x,7),k=k+_|0,N=ee(N^k,16),b=b+N|0,_=ee(_^b,12),k=k+_|0,N=ee(N^k,8),b=b+N|0,_=ee(_^b,7),B=B+D|0,P=ee(P^B,16),x=x+P|0,D=ee(D^x,12),B=B+D|0,P=ee(P^B,8),x=x+P|0,D=ee(D^x,7),T=T+C|0,S=ee(S^T,16),U=U+S|0,C=ee(C^U,12),T=T+C|0,S=ee(S^T,8),U=U+S|0,C=ee(C^U,7),w=w+O|0,R=ee(R^w,16),I=I+R|0,O=ee(O^I,12),w=w+O|0,R=ee(R^w,8),I=I+R|0,O=ee(O^I,7);let q=0;r[q++]=o+k|0,r[q++]=a+B|0,r[q++]=c+T|0,r[q++]=h+w|0,r[q++]=u+O|0,r[q++]=l+_|0,r[q++]=d+D|0,r[q++]=p+C|0,r[q++]=f+U|0,r[q++]=g+I|0,r[q++]=y+b|0,r[q++]=v+x|0,r[q++]=E+P|0,r[q++]=m+S|0,r[q++]=A+R|0,r[q++]=$+N|0}const S2=E2($2,{counterRight:!1,counterLength:4,allowShortKeys:!1}),D2=new Uint8Array(16),Ph=(t,e)=>{t.update(e);const i=e.length%16;i&&t.update(D2.subarray(i))},A2=new Uint8Array(32);function Oh(t,e,i,r,s){const n=t(e,i,A2),o=x2.create(n);s&&Ph(o,s),Ph(o,r);const a=f2(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return wr(n,a),c}const P2=t=>(e,i,r)=>({encrypt(s,n){const o=s.length;n=Sh(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,i,a,a,1);const c=Oh(t,e,i,a,r);return n.set(c,o),wr(c),n},decrypt(s,n){n=Sh(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=Oh(t,e,i,o,r);if(!l2(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,i,n,n,1),wr(c),n}}),hf=d2({blockSize:64,nonceLength:12,tagLength:16},P2(S2));let uf=class extends Dn{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,Ha(e);const r=$t(i);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(r.length>s?e.create().update(r).digest():r);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),pt(n)}update(e){return yi(this),this.iHash.update(e),this}digestInto(e){yi(this),ft(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:i,iHash:r,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=i._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Pn=(t,e,i)=>new uf(t,e).update(i).digest();Pn.create=(t,e)=>new uf(t,e);function O2(t,e,i){return Ha(t),i===void 0&&(i=new Uint8Array(t.outputLen)),Pn(t,$t(i),$t(e))}const uo=Uint8Array.from([0]),Ch=Uint8Array.of();function C2(t,e,i,r=32){Ha(t),Jt(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(r/s);i===void 0&&(i=Ch);const o=new Uint8Array(n*s),a=Pn.create(t,e),c=a._cloneInto(),h=new Uint8Array(a.outputLen);for(let u=0;u<n;u++)uo[0]=u+1,c.update(u===0?Ch:h).update(i).update(uo).digestInto(h),o.set(h,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),pt(h,uo),o.slice(0,r)}const T2=(t,e,i,r,s)=>C2(t,O2(t,e,i),r,s),On=An,Ya=BigInt(0),ta=BigInt(1);function fn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Us(t){const e=t.toString(16);return e.length&1?"0"+e:e}function lf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ya:BigInt("0x"+t)}function Cn(t){return lf(cs(t))}function pn(t){return ft(t),lf(cs(Uint8Array.from(t).reverse()))}function Ja(t,e){return Ka(t.toString(16).padStart(e*2,"0"))}function Za(t,e){return Ja(t,e).reverse()}function Ge(t,e,i){let r;if(typeof e=="string")try{r=Ka(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(za(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof i=="number"&&s!==i)throw new Error(t+" of length "+i+" expected, got "+s);return r}const lo=t=>typeof t=="bigint"&&Ya<=t;function F2(t,e,i){return lo(t)&&lo(e)&&lo(i)&&e<=t&&t<i}function ia(t,e,i,r){if(!F2(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function R2(t){let e;for(e=0;t>Ya;t>>=ta,e+=1);return e}const Tn=t=>(ta<<BigInt(t))-ta;function N2(t,e,i){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 i!="function")throw new Error("hmacFn must be a function");const r=d=>new Uint8Array(d),s=d=>Uint8Array.of(d);let n=r(t),o=r(t),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},h=(...d)=>i(o,n,...d),u=(d=r(0))=>{o=h(s(0),d),n=h(),d.length!==0&&(o=h(s(1),d),n=h())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const p=[];for(;d<e;){n=h();const f=n.slice();p.push(f),d+=n.length}return Pi(...p)};return(d,p)=>{c(),u(d);let f;for(;!(f=p(l()));)u();return c(),f}}function Fn(t,e,i={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(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])=>r(s,n,!1)),Object.entries(i).forEach(([s,n])=>r(s,n,!0))}function Th(t){const e=new WeakMap;return(i,...r)=>{const s=e.get(i);if(s!==void 0)return s;const n=t(i,...r);return e.set(i,n),n}}const Je=BigInt(0),Le=BigInt(1),Oi=BigInt(2),U2=BigInt(3),df=BigInt(4),ff=BigInt(5),pf=BigInt(8);function ht(t,e){const i=t%e;return i>=Je?i:e+i}function It(t,e,i){let r=t;for(;e-- >Je;)r*=r,r%=i;return r}function Fh(t,e){if(t===Je)throw new Error("invert: expected non-zero number");if(e<=Je)throw new Error("invert: expected positive modulus, got "+e);let i=ht(t,e),r=e,s=Je,n=Le;for(;i!==Je;){const o=r/i,a=r%i,c=s-n*o;r=i,i=a,s=n,n=c}if(r!==Le)throw new Error("invert: does not exist");return ht(s,e)}function gf(t,e){const i=(t.ORDER+Le)/df,r=t.pow(e,i);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function B2(t,e){const i=(t.ORDER-ff)/pf,r=t.mul(e,Oi),s=t.pow(r,i),n=t.mul(e,s),o=t.mul(t.mul(n,Oi),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 k2(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Le,i=0;for(;e%Oi===Je;)e/=Oi,i++;let r=Oi;const s=$r(t);for(;Rh(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(i===1)return gf;let n=s.pow(r,e);const o=(e+Le)/Oi;return function(a,c){if(a.is0(c))return c;if(Rh(a,c)!==1)throw new Error("Cannot find square root");let h=i,u=a.mul(a.ONE,n),l=a.pow(c,e),d=a.pow(c,o);for(;!a.eql(l,a.ONE);){if(a.is0(l))return a.ZERO;let p=1,f=a.sqr(l);for(;!a.eql(f,a.ONE);)if(p++,f=a.sqr(f),p===h)throw new Error("Cannot find square root");const g=Le<<BigInt(h-p-1),y=a.pow(u,g);h=p,u=a.sqr(y),l=a.mul(l,u),d=a.mul(d,y)}return d}}function j2(t){return t%df===U2?gf:t%pf===ff?B2:k2(t)}const L2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function M2(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},i=L2.reduce((r,s)=>(r[s]="function",r),e);return Fn(t,i),t}function q2(t,e,i){if(i<Je)throw new Error("invalid exponent, negatives unsupported");if(i===Je)return t.ONE;if(i===Le)return e;let r=t.ONE,s=e;for(;i>Je;)i&Le&&(r=t.mul(r,s)),s=t.sqr(s),i>>=Le;return r}function yf(t,e,i=!1){const r=new Array(e.length).fill(i?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),n),r}function Rh(t,e){const i=(t.ORDER-Le)/Oi,r=t.pow(e,i),s=t.eql(r,t.ONE),n=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function z2(t,e){e!==void 0&&Jt(e);const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function $r(t,e,i=!1,r={}){if(t<=Je)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,n;if(typeof e=="object"&&e!=null){if(r.sqrt||i)throw new Error("cannot specify opts in two arguments");const u=e;u.BITS&&(s=u.BITS),u.sqrt&&(n=u.sqrt),typeof u.isLE=="boolean"&&(i=u.isLE)}else typeof e=="number"&&(s=e),r.sqrt&&(n=r.sqrt);const{nBitLength:o,nByteLength:a}=z2(t,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const h=Object.freeze({ORDER:t,isLE:i,BITS:o,BYTES:a,MASK:Tn(o),ZERO:Je,ONE:Le,create:u=>ht(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Je<=u&&u<t},is0:u=>u===Je,isValidNot0:u=>!h.is0(u)&&h.isValid(u),isOdd:u=>(u&Le)===Le,neg:u=>ht(-u,t),eql:(u,l)=>u===l,sqr:u=>ht(u*u,t),add:(u,l)=>ht(u+l,t),sub:(u,l)=>ht(u-l,t),mul:(u,l)=>ht(u*l,t),pow:(u,l)=>q2(h,u,l),div:(u,l)=>ht(u*Fh(l,t),t),sqrN:u=>u*u,addN:(u,l)=>u+l,subN:(u,l)=>u-l,mulN:(u,l)=>u*l,inv:u=>Fh(u,t),sqrt:n||(u=>(c||(c=j2(t)),c(h,u))),toBytes:u=>i?Za(u,a):Ja(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return i?pn(u):Cn(u)},invertBatch:u=>yf(h,u),cmov:(u,l,d)=>d?l:u});return Object.freeze(h)}function wf(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 mf(t){const e=wf(t);return e+Math.ceil(e/2)}function H2(t,e,i=!1){const r=t.length,s=wf(e),n=mf(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=i?pn(t):Cn(t),a=ht(o,e-Le)+Le;return i?Za(a,s):Ja(a,s)}const mr=BigInt(0),Ci=BigInt(1);function Zr(t,e){const i=e.negate();return t?i:e}function V2(t,e,i){const r=e==="pz"?n=>n.pz:n=>n.ez,s=yf(t.Fp,i.map(r));return i.map((n,o)=>n.toAffine(s[o])).map(t.fromAffine)}function bf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function fo(t,e){bf(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,n=Tn(t),o=BigInt(t);return{windows:i,windowSize:r,mask:n,maxNumber:s,shiftBy:o}}function Nh(t,e,i){const{windowSize:r,mask:s,maxNumber:n,shiftBy:o}=i;let a=Number(t&s),c=t>>o;a>r&&(a-=n,c+=Ci);const h=e*r,u=h+Math.abs(a)-1,l=a===0,d=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:h}}function K2(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function W2(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const po=new WeakMap,vf=new WeakMap;function go(t){return vf.get(t)||1}function Uh(t){if(t!==mr)throw new Error("invalid wNAF")}function G2(t,e){return{constTimeNegate:Zr,hasPrecomputes(i){return go(i)!==1},unsafeLadder(i,r,s=t.ZERO){let n=i;for(;r>mr;)r&Ci&&(s=s.add(n)),n=n.double(),r>>=Ci;return s},precomputeWindow(i,r){const{windows:s,windowSize:n}=fo(r,e),o=[];let a=i,c=a;for(let h=0;h<s;h++){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(i,r,s){let n=t.ZERO,o=t.BASE;const a=fo(i,e);for(let c=0;c<a.windows;c++){const{nextN:h,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:f}=Nh(s,c,a);s=h,l?o=o.add(Zr(p,r[f])):n=n.add(Zr(d,r[u]))}return Uh(s),{p:n,f:o}},wNAFUnsafe(i,r,s,n=t.ZERO){const o=fo(i,e);for(let a=0;a<o.windows&&s!==mr;a++){const{nextN:c,offset:h,isZero:u,isNeg:l}=Nh(s,a,o);if(s=c,!u){const d=r[h];n=n.add(l?d.negate():d)}}return Uh(s),n},getPrecomputes(i,r,s){let n=po.get(r);return n||(n=this.precomputeWindow(r,i),i!==1&&(typeof s=="function"&&(n=s(n)),po.set(r,n))),n},wNAFCached(i,r,s){const n=go(i);return this.wNAF(n,this.getPrecomputes(n,i,s),r)},wNAFCachedUnsafe(i,r,s,n){const o=go(i);return o===1?this.unsafeLadder(i,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,i,s),r,n)},setWindowSize(i,r){bf(r,e),vf.set(i,r),po.delete(i)}}}function Y2(t,e,i,r){let s=e,n=t.ZERO,o=t.ZERO;for(;i>mr||r>mr;)i&Ci&&(n=n.add(s)),r&Ci&&(o=o.add(s)),s=s.double(),i>>=Ci,r>>=Ci;return{p1:n,p2:o}}function J2(t,e,i,r){K2(i,t),W2(r,e);const s=i.length,n=r.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=R2(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=Tn(c),u=new Array(Number(h)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c;let d=o;for(let p=l;p>=0;p-=c){u.fill(o);for(let g=0;g<n;g++){const y=r[g],v=Number(y>>BigInt(p)&h);u[v]=u[v].add(i[g])}let f=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[g]),f=f.add(y);if(d=d.add(f),p!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Bh(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return M2(e),e}else return $r(t)}function Z2(t,e,i={}){if(!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const o of["p","n","h"]){const a=e[o];if(!(typeof a=="bigint"&&a>mr))throw new Error(`CURVE.${o} must be positive bigint`)}const r=Bh(e.p,i.Fp),s=Bh(e.n,i.Fn),n=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const o of n)if(!r.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Br=BigInt(0),Ji=BigInt(1),Bs=BigInt(2);function Q2(t){return Fn(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function X2(t){const e=Q2(t),{P:i,type:r,adjustScalarBytes:s,powPminus2:n,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||xr,h=a?255:448,u=a?32:56,l=BigInt(a?9:5),d=BigInt(a?121665:39081),p=a?Bs**BigInt(254):Bs**BigInt(447),f=a?BigInt(8)*Bs**BigInt(251)-Ji:BigInt(4)*Bs**BigInt(445)-Ji,g=p+f+Ji,y=w=>ht(w,i),v=E(l);function E(w){return Za(y(w),u)}function m(w){const O=Ge("u coordinate",w,u);return a&&(O[31]&=127),y(pn(O))}function A(w){return pn(s(Ge("scalar",w,u)))}function $(w,O){const _=T(m(O),A(w));if(_===Br)throw new Error("invalid private or public key received");return E(_)}function k(w){return $(w,v)}function B(w,O,_){const D=y(w*(O-_));return O=y(O-D),_=y(_+D),{x_2:O,x_3:_}}function T(w,O){ia("u",w,Br,i),ia("scalar",O,p,g);const _=O,D=w;let C=Ji,U=Br,I=w,b=Ji,x=Br;for(let S=BigInt(h-1);S>=Br;S--){const R=_>>S&Ji;x^=R,{x_2:C,x_3:I}=B(x,C,I),{x_2:U,x_3:b}=B(x,U,b),x=R;const N=C+U,q=y(N*N),z=C-U,H=y(z*z),V=q-H,W=I+b,ne=I-b,se=y(ne*N),J=y(W*z),fe=se+J,$e=se-J;I=y(fe*fe),b=y(D*y($e*$e)),C=y(q*H),U=y(V*(q+y(d*V)))}({x_2:C,x_3:I}=B(x,C,I)),{x_2:U,x_3:b}=B(x,U,b);const P=n(U);return y(C*P)}return{scalarMult:$,scalarMultBase:k,getSharedSecret:(w,O)=>$(w,O),getPublicKey:w=>k(w),utils:{randomPrivateKey:()=>c(u)},GuBytes:v.slice()}}BigInt(0);const eE=BigInt(1),kh=BigInt(2),tE=BigInt(3),iE=BigInt(5),rE=BigInt(8),Ef={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:rE,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sE(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),n=Ef.p,o=t*t%n*t%n,a=It(o,kh,n)*o%n,c=It(a,eE,n)*t%n,h=It(c,iE,n)*c%n,u=It(h,e,n)*h%n,l=It(u,i,n)*u%n,d=It(l,r,n)*l%n,p=It(d,s,n)*d%n,f=It(p,s,n)*d%n,g=It(f,e,n)*h%n;return{pow_p_5_8:It(g,kh,n)*t%n,b2:o}}function nE(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ra=(()=>{const t=Ef.p;return X2({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:i,b2:r}=sE(e);return ht(It(i,tE,t)*r,t)},adjustScalarBytes:nE})})();function jh(t){t.lowS!==void 0&&fn("lowS",t.lowS),t.prehash!==void 0&&fn("prehash",t.prehash)}class oE extends Error{constructor(e=""){super(e)}}const Wt={Err:oE,_tlv:{encode:(t,e)=>{const{Err:i}=Wt;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length&1)throw new i("tlv.encode: unpadded data");const r=e.length/2,s=Us(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");const n=r>127?Us(s.length/2|128):"";return Us(t)+n+s+e},decode(t,e){const{Err:i}=Wt;let r=0;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new i("tlv.decode: wrong tlv");const s=e[r++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new i("tlv.decode(long): indefinite length not supported");if(c>4)throw new i("tlv.decode(long): byte length is too big");const h=e.subarray(r,r+c);if(h.length!==c)throw new i("tlv.decode: length bytes not complete");if(h[0]===0)throw new i("tlv.decode(long): zero leftmost byte");for(const u of h)o=o<<8|u;if(r+=c,o<128)throw new i("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new i("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=Wt;if(t<Qr)throw new e("integer: negative integers are not allowed");let i=Us(t);if(Number.parseInt(i[0],16)&8&&(i="00"+i),i.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return i},decode(t){const{Err:e}=Wt;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 Cn(t)}},toSig(t){const{Err:e,_int:i,_tlv:r}=Wt,s=Ge("signature",t),{v:n,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:h,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(h)}},hexFromSig(t){const{_tlv:e,_int:i}=Wt,r=e.encode(2,i.encode(t.r)),s=e.encode(2,i.encode(t.s)),n=r+s;return e.encode(48,n)}},Qr=BigInt(0),Xr=BigInt(1),aE=BigInt(2),ks=BigInt(3),cE=BigInt(4);function hE(t,e,i){function r(s){const n=t.sqr(s),o=t.mul(n,s);return t.add(t.add(o,t.mul(s,e)),i)}return r}function If(t,e,i){const{BYTES:r}=t;function s(n){let o;if(typeof n=="bigint")o=n;else{let a=Ge("private key",n);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{o=t.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof n}`)}}if(i&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return s}function uE(t,e={}){const{Fp:i,Fn:r}=Z2("weierstrass",t,e),{h:s,n}=t;Fn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!i.is0(t.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(T,w,O){const{x:_,y:D}=w.toAffine(),C=i.toBytes(_);if(fn("isCompressed",O),O){a();const U=!i.isOdd(D);return Pi(_f(U),C)}else return Pi(Uint8Array.of(4),C,i.toBytes(D))}function h(T){ft(T);const w=i.BYTES,O=w+1,_=2*w+1,D=T.length,C=T[0],U=T.subarray(1);if(D===O&&(C===2||C===3)){const I=i.fromBytes(U);if(!i.isValid(I))throw new Error("bad point: is not on curve, wrong x");const b=d(I);let x;try{x=i.sqrt(b)}catch(S){const R=S instanceof Error?": "+S.message:"";throw new Error("bad point: is not on curve, sqrt error"+R)}a();const P=i.isOdd(x);return(C&1)===1!==P&&(x=i.neg(x)),{x:I,y:x}}else if(D===_&&C===4){const I=i.fromBytes(U.subarray(w*0,w*1)),b=i.fromBytes(U.subarray(w*1,w*2));if(!p(I,b))throw new Error("bad point: is not on curve");return{x:I,y:b}}else throw new Error(`bad point: got length ${D}, expected compressed=${O} or uncompressed=${_}`)}const u=e.toBytes||c,l=e.fromBytes||h,d=hE(i,t.a,t.b);function p(T,w){const O=i.sqr(w),_=d(T);return i.eql(O,_)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const f=i.mul(i.pow(t.a,ks),cE),g=i.mul(i.sqr(t.b),BigInt(27));if(i.is0(i.add(f,g)))throw new Error("bad curve params: a or b");function y(T,w,O=!1){if(!i.isValid(w)||O&&i.is0(w))throw new Error(`bad point coordinate ${T}`);return w}function v(T){if(!(T instanceof $))throw new Error("ProjectivePoint expected")}const E=Th((T,w)=>{const{px:O,py:_,pz:D}=T;if(i.eql(D,i.ONE))return{x:O,y:_};const C=T.is0();w==null&&(w=C?i.ONE:i.inv(D));const U=i.mul(O,w),I=i.mul(_,w),b=i.mul(D,w);if(C)return{x:i.ZERO,y:i.ZERO};if(!i.eql(b,i.ONE))throw new Error("invZ was invalid");return{x:U,y:I}}),m=Th(T=>{if(T.is0()){if(e.allowInfinityPoint&&!i.is0(T.py))return;throw new Error("bad point: ZERO")}const{x:w,y:O}=T.toAffine();if(!i.isValid(w)||!i.isValid(O))throw new Error("bad point: x or y not field elements");if(!p(w,O))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(T,w,O,_,D){return O=new $(i.mul(O.px,T),O.py,O.pz),w=Zr(_,w),O=Zr(D,O),w.add(O)}class ${constructor(w,O,_){this.px=y("x",w),this.py=y("y",O,!0),this.pz=y("z",_),Object.freeze(this)}static fromAffine(w){const{x:O,y:_}=w||{};if(!w||!i.isValid(O)||!i.isValid(_))throw new Error("invalid affine point");if(w instanceof $)throw new Error("projective point not allowed");return i.is0(O)&&i.is0(_)?$.ZERO:new $(O,_,i.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){return V2($,"pz",w)}static fromBytes(w){return ft(w),$.fromHex(w)}static fromHex(w){const O=$.fromAffine(l(Ge("pointHex",w)));return O.assertValidity(),O}static fromPrivateKey(w){const O=If(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return $.BASE.multiply(O(w))}static msm(w,O){return J2($,r,w,O)}precompute(w=8,O=!0){return B.setWindowSize(this,w),O||this.multiply(ks),this}_setWindowSize(w){this.precompute(w)}assertValidity(){m(this)}hasEvenY(){const{y:w}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(w)}equals(w){v(w);const{px:O,py:_,pz:D}=this,{px:C,py:U,pz:I}=w,b=i.eql(i.mul(O,I),i.mul(C,D)),x=i.eql(i.mul(_,I),i.mul(U,D));return b&&x}negate(){return new $(this.px,i.neg(this.py),this.pz)}double(){const{a:w,b:O}=t,_=i.mul(O,ks),{px:D,py:C,pz:U}=this;let I=i.ZERO,b=i.ZERO,x=i.ZERO,P=i.mul(D,D),S=i.mul(C,C),R=i.mul(U,U),N=i.mul(D,C);return N=i.add(N,N),x=i.mul(D,U),x=i.add(x,x),I=i.mul(w,x),b=i.mul(_,R),b=i.add(I,b),I=i.sub(S,b),b=i.add(S,b),b=i.mul(I,b),I=i.mul(N,I),x=i.mul(_,x),R=i.mul(w,R),N=i.sub(P,R),N=i.mul(w,N),N=i.add(N,x),x=i.add(P,P),P=i.add(x,P),P=i.add(P,R),P=i.mul(P,N),b=i.add(b,P),R=i.mul(C,U),R=i.add(R,R),P=i.mul(R,N),I=i.sub(I,P),x=i.mul(R,S),x=i.add(x,x),x=i.add(x,x),new $(I,b,x)}add(w){v(w);const{px:O,py:_,pz:D}=this,{px:C,py:U,pz:I}=w;let b=i.ZERO,x=i.ZERO,P=i.ZERO;const S=t.a,R=i.mul(t.b,ks);let N=i.mul(O,C),q=i.mul(_,U),z=i.mul(D,I),H=i.add(O,_),V=i.add(C,U);H=i.mul(H,V),V=i.add(N,q),H=i.sub(H,V),V=i.add(O,D);let W=i.add(C,I);return V=i.mul(V,W),W=i.add(N,z),V=i.sub(V,W),W=i.add(_,D),b=i.add(U,I),W=i.mul(W,b),b=i.add(q,z),W=i.sub(W,b),P=i.mul(S,V),b=i.mul(R,z),P=i.add(b,P),b=i.sub(q,P),P=i.add(q,P),x=i.mul(b,P),q=i.add(N,N),q=i.add(q,N),z=i.mul(S,z),V=i.mul(R,V),q=i.add(q,z),z=i.sub(N,z),z=i.mul(S,z),V=i.add(V,z),N=i.mul(q,V),x=i.add(x,N),N=i.mul(W,V),b=i.mul(H,b),b=i.sub(b,N),N=i.mul(H,q),P=i.mul(W,P),P=i.add(P,N),new $(b,x,P)}subtract(w){return this.add(w.negate())}is0(){return this.equals($.ZERO)}multiply(w){const{endo:O}=e;if(!r.isValidNot0(w))throw new Error("invalid scalar: out of range");let _,D;const C=U=>B.wNAFCached(this,U,$.normalizeZ);if(O){const{k1neg:U,k1:I,k2neg:b,k2:x}=O.splitScalar(w),{p:P,f:S}=C(I),{p:R,f:N}=C(x);D=S.add(N),_=A(O.beta,P,R,U,b)}else{const{p:U,f:I}=C(w);_=U,D=I}return $.normalizeZ([_,D])[0]}multiplyUnsafe(w){const{endo:O}=e,_=this;if(!r.isValid(w))throw new Error("invalid scalar: out of range");if(w===Qr||_.is0())return $.ZERO;if(w===Xr)return _;if(B.hasPrecomputes(this))return this.multiply(w);if(O){const{k1neg:D,k1:C,k2neg:U,k2:I}=O.splitScalar(w),{p1:b,p2:x}=Y2($,_,C,I);return A(O.beta,b,x,D,U)}else return B.wNAFCachedUnsafe(_,w)}multiplyAndAddUnsafe(w,O,_){const D=this.multiplyUnsafe(O).add(w.multiplyUnsafe(_));return D.is0()?void 0:D}toAffine(w){return E(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return s===Xr?!0:w?w($,this):B.wNAFCachedUnsafe(this,n).is0()}clearCofactor(){const{clearCofactor:w}=e;return s===Xr?this:w?w($,this):this.multiplyUnsafe(s)}toBytes(w=!0){return fn("isCompressed",w),this.assertValidity(),u($,this,w)}toRawBytes(w=!0){return this.toBytes(w)}toHex(w=!0){return cs(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}$.BASE=new $(t.Gx,t.Gy,i.ONE),$.ZERO=new $(i.ZERO,i.ONE,i.ZERO),$.Fp=i,$.Fn=r;const k=r.BITS,B=G2($,e.endo?Math.ceil(k/2):k);return $}function _f(t){return Uint8Array.of(t?2:3)}function lE(t,e,i={}){Fn(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=e.randomBytes||xr,s=e.hmac||((_,...D)=>Pn(e.hash,_,Pi(...D))),{Fp:n,Fn:o}=t,{ORDER:a,BITS:c}=o;function h(_){const D=a>>Xr;return _>D}function u(_){return h(_)?o.neg(_):_}function l(_,D){if(!o.isValidNot0(D))throw new Error(`invalid signature ${_}: out of range 1..CURVE.n`)}class d{constructor(D,C,U){l("r",D),l("s",C),this.r=D,this.s=C,U!=null&&(this.recovery=U),Object.freeze(this)}static fromCompact(D){const C=o.BYTES,U=Ge("compactSignature",D,C*2);return new d(o.fromBytes(U.subarray(0,C)),o.fromBytes(U.subarray(C,C*2)))}static fromDER(D){const{r:C,s:U}=Wt.toSig(Ge("DER",D));return new d(C,U)}assertValidity(){}addRecoveryBit(D){return new d(this.r,this.s,D)}recoverPublicKey(D){const C=n.ORDER,{r:U,s:I,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(a*aE<C&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");const x=b===2||b===3?U+a:U;if(!n.isValid(x))throw new Error("recovery id 2 or 3 invalid");const P=n.toBytes(x),S=t.fromHex(Pi(_f((b&1)===0),P)),R=o.inv(x),N=m(Ge("msgHash",D)),q=o.create(-N*R),z=o.create(I*R),H=t.BASE.multiplyUnsafe(q).add(S.multiplyUnsafe(z));if(H.is0())throw new Error("point at infinify");return H.assertValidity(),H}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,o.neg(this.s),this.recovery):this}toBytes(D){if(D==="compact")return Pi(o.toBytes(this.r),o.toBytes(this.s));if(D==="der")return Ka(Wt.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return cs(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return cs(this.toBytes("compact"))}}const p=If(o,i.allowedPrivateKeyLengths,i.wrapPrivateKey),f={isValidPrivateKey(_){try{return p(_),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const _=a;return H2(r(mf(_)),_)},precompute(_=8,D=t.BASE){return D.precompute(_,!1)}};function g(_,D=!0){return t.fromPrivateKey(_).toBytes(D)}function y(_){if(typeof _=="bigint")return!1;if(_ instanceof t)return!0;const D=Ge("key",_).length,C=n.BYTES,U=C+1,I=2*C+1;if(!(i.allowedPrivateKeyLengths||o.BYTES===U))return D===U||D===I}function v(_,D,C=!0){if(y(_)===!0)throw new Error("first arg must be private key");if(y(D)===!1)throw new Error("second arg must be public key");return t.fromHex(D).multiply(p(_)).toBytes(C)}const E=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const D=Cn(_),C=_.length*8-c;return C>0?D>>BigInt(C):D},m=e.bits2int_modN||function(_){return o.create(E(_))},A=Tn(c);function $(_){return ia("num < 2^"+c,_,Qr,A),o.toBytes(_)}function k(_,D,C=B){if(["recovered","canonical"].some(H=>H in C))throw new Error("sign() legacy options not supported");const{hash:U}=e;let{lowS:I,prehash:b,extraEntropy:x}=C;I==null&&(I=!0),_=Ge("msgHash",_),jh(C),b&&(_=Ge("prehashed msgHash",U(_)));const P=m(_),S=p(D),R=[$(S),$(P)];if(x!=null&&x!==!1){const H=x===!0?r(n.BYTES):x;R.push(Ge("extraEntropy",H))}const N=Pi(...R),q=P;function z(H){const V=E(H);if(!o.isValidNot0(V))return;const W=o.inv(V),ne=t.BASE.multiply(V).toAffine(),se=o.create(ne.x);if(se===Qr)return;const J=o.create(W*o.create(q+se*S));if(J===Qr)return;let fe=(ne.x===se?0:2)|Number(ne.y&Xr),$e=J;return I&&h(J)&&($e=u(J),fe^=1),new d(se,$e,fe)}return{seed:N,k2sig:z}}const B={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function w(_,D,C=B){const{seed:U,k2sig:I}=k(_,D,C);return N2(e.hash.outputLen,o.BYTES,s)(U,I)}t.BASE.precompute(8);function O(_,D,C,U=T){const I=_;D=Ge("msgHash",D),C=Ge("publicKey",C),jh(U);const{lowS:b,prehash:x,format:P}=U;if("strict"in U)throw new Error("options.strict was renamed to lowS");if(P!==void 0&&!["compact","der","js"].includes(P))throw new Error('format must be "compact", "der" or "js"');const S=typeof I=="string"||za(I),R=!S&&!P&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!S&&!R)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,q;try{if(R)if(P===void 0||P==="js")N=new d(I.r,I.s);else throw new Error("invalid format");if(S){try{P!=="compact"&&(N=d.fromDER(I))}catch(fe){if(!(fe instanceof Wt.Err))throw fe}!N&&P!=="der"&&(N=d.fromCompact(I))}q=t.fromHex(C)}catch{return!1}if(!N||b&&N.hasHighS())return!1;x&&(D=e.hash(D));const{r:z,s:H}=N,V=m(D),W=o.inv(H),ne=o.create(V*W),se=o.create(z*W),J=t.BASE.multiplyUnsafe(ne).add(q.multiplyUnsafe(se));return J.is0()?!1:o.create(J.x)===z}return Object.freeze({getPublicKey:g,getSharedSecret:v,sign:w,verify:O,utils:f,Point:t,Signature:d})}function dE(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},i=t.Fp,r=$r(e.n,t.nBitLength),s={Fp:i,Fn:r,allowedPrivateKeyLengths:t.allowedPrivateKeyLengths,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,wrapPrivateKey:t.wrapPrivateKey,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function fE(t){const{CURVE:e,curveOpts:i}=dE(t),r={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:i,ecdsaOpts:r}}function pE(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function gE(t){const{CURVE:e,curveOpts:i,ecdsaOpts:r}=fE(t),s=uE(e,i),n=lE(s,r,i);return pE(t,n)}function sa(t,e){const i=r=>gE({...t,hash:r});return{...i(e),create:i}}const xf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},$f={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Sf={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},yE=$r(xf.p),wE=$r($f.p),mE=$r(Sf.p),bE=sa({...xf,Fp:yE,lowS:!1},An);sa({...$f,Fp:wE,lowS:!1},Sv),sa({...Sf,Fp:mE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},$v);const vE=bE,Df="base10",Me="base16",xt="base64pad",di="base64url",bs="utf8",Af=0,Gt=1,vs=2,EE=0,Lh=1,es=12,Qa=32;function IE(){const t=ra.utils.randomPrivateKey(),e=ra.getPublicKey(t);return{privateKey:Ze(t,Me),publicKey:Ze(e,Me)}}function na(){const t=xr(Qa);return Ze(t,Me)}function _E(t,e){const i=ra.getSharedSecret(ut(t,Me),ut(e,Me)),r=T2(On,i,void 0,void 0,Qa);return Ze(r,Me)}function Qs(t){const e=On(ut(t,Me));return Ze(e,Me)}function Rt(t){const e=On(ut(t,bs));return Ze(e,Me)}function Pf(t){return ut(`${t}`,Df)}function Bi(t){return Number(Ze(t,Df))}function Of(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Cf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),i=(4-e.length%4)%4;return e+"=".repeat(i)}function xE(t){const e=Pf(typeof t.type<"u"?t.type:Af);if(Bi(e)===Gt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof t.senderPublicKey<"u"?ut(t.senderPublicKey,Me):void 0,r=typeof t.iv<"u"?ut(t.iv,Me):xr(es),s=ut(t.symKey,Me),n=hf(s,r).encrypt(ut(t.message,bs)),o=Tf({type:e,sealed:n,iv:r,senderPublicKey:i});return t.encoding===di?Of(o):o}function $E(t){const e=ut(t.symKey,Me),{sealed:i,iv:r}=us({encoded:t.encoded,encoding:t.encoding}),s=hf(e,r).decrypt(i);if(s===null)throw new Error("Failed to decrypt");return Ze(s,bs)}function SE(t,e){const i=Pf(vs),r=xr(es),s=ut(t,bs),n=Tf({type:i,sealed:s,iv:r});return e===di?Of(n):n}function DE(t,e){const{sealed:i}=us({encoded:t,encoding:e});return Ze(i,bs)}function Tf(t){if(Bi(t.type)===vs)return Ze(Jr([t.type,t.sealed]),xt);if(Bi(t.type)===Gt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ze(Jr([t.type,t.senderPublicKey,t.iv,t.sealed]),xt)}return Ze(Jr([t.type,t.iv,t.sealed]),xt)}function us(t){const e=(t.encoding||xt)===di?Cf(t.encoded):t.encoded,i=ut(e,xt),r=i.slice(EE,Lh),s=Lh;if(Bi(r)===Gt){const c=s+Qa,h=c+es,u=i.slice(s,c),l=i.slice(c,h),d=i.slice(h);return{type:r,sealed:d,iv:l,senderPublicKey:u}}if(Bi(r)===vs){const c=i.slice(s),h=xr(es);return{type:r,sealed:c,iv:h}}const n=s+es,o=i.slice(s,n),a=i.slice(n);return{type:r,sealed:a,iv:o}}function AE(t,e){const i=us({encoded:t,encoding:e==null?void 0:e.encoding});return Ff({type:Bi(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?Ze(i.senderPublicKey,Me):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Ff(t){const e=(t==null?void 0:t.type)||Af;if(e===Gt){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 Mh(t){return t.type===Gt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function qh(t){return t.type===vs}function PE(t){const e=X.from(t.x,"base64"),i=X.from(t.y,"base64");return Jr([new Uint8Array([4]),e,i])}function OE(t,e){const[i,r,s]=t.split("."),n=X.from(Cf(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${i}.${r}`,h=On(c),u=PE(e);if(!vE.verify(Jr([o,a]),h,u))throw new Error("Invalid signature");return Ko(t).payload}const CE="irn";function gn(t){return(t==null?void 0:t.relay)||{protocol:CE}}function Wr(t){const e=nb[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function TE(t,e="-"){const i={},r="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(r)){const n=s.replace(r,""),o=t[s];i[n]=o}}),i}function zh(t){if(!t.includes("wc:")){const h=zd(t);h!=null&&h.includes("wc:")&&(t=h)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),i=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),s=t.substring(e+1,i).split("@"),n=typeof i<"u"?t.substring(i):"",o=new URLSearchParams(n),a={};o.forEach((h,u)=>{a[u]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:FE(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:TE(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function FE(t){return t.startsWith("//")?t.substring(2):t}function RE(t,e="-"){const i="relay",r={};return Object.keys(t).forEach(s=>{const n=s,o=i+e+n;t[n]&&(r[o]=t[n])}),r}function Hh(t){const e=new URLSearchParams,i=RE(t.relay);Object.keys(i).sort().forEach(s=>{e.set(s,i[s])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function js(t,e,i){return`${t}?wc_ev=${i}&topic=${e}`}var NE=Object.defineProperty,UE=Object.defineProperties,BE=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,kE=Object.prototype.hasOwnProperty,jE=Object.prototype.propertyIsEnumerable,Kh=(t,e,i)=>e in t?NE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,LE=(t,e)=>{for(var i in e||(e={}))kE.call(e,i)&&Kh(t,i,e[i]);if(Vh)for(var i of Vh(e))jE.call(e,i)&&Kh(t,i,e[i]);return t},ME=(t,e)=>UE(t,BE(e));function Sr(t){const e=[];return t.forEach(i=>{const[r,s]=i.split(":");e.push(`${r}:${s}`)}),e}function qE(t){const e=[];return Object.values(t).forEach(i=>{e.push(...Sr(i.accounts))}),e}function zE(t,e){const i=[];return Object.values(t).forEach(r=>{Sr(r.accounts).includes(e)&&i.push(...r.methods)}),i}function HE(t,e){const i=[];return Object.values(t).forEach(r=>{Sr(r.accounts).includes(e)&&i.push(...r.events)}),i}function Rn(t){return t.includes(":")}function pr(t){return Rn(t)?t.split(":")[0]:t}function Wh(t){var e,i,r;const s={};if(!Ut(t))return s;for(const[n,o]of Object.entries(t)){const a=Rn(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],u=pr(n);s[u]=ME(LE({},s[u]),{chains:Nt(a,(e=s[u])==null?void 0:e.chains),methods:Nt(c,(i=s[u])==null?void 0:i.methods),events:Nt(h,(r=s[u])==null?void 0:r.events)})}return s}function VE(t){const e={};return t==null||t.forEach(i=>{var r;const[s,n]=i.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(i),(r=e[s].chains)==null||r.push(`${s}:${n}`)}),e}function Gh(t,e){e=e.map(r=>r.replace("did:pkh:",""));const i=VE(e);for(const[r,s]of Object.entries(i))s.methods?s.methods=Nt(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return i}function KE(t,e){var i,r,s,n,o,a;const c=Wh(t),h=Wh(e),u={},l=Object.keys(c).concat(Object.keys(h));for(const d of l)u[d]={chains:Nt((i=c[d])==null?void 0:i.chains,(r=h[d])==null?void 0:r.chains),methods:Nt((s=c[d])==null?void 0:s.methods,(n=h[d])==null?void 0:n.methods),events:Nt((o=c[d])==null?void 0:o.events,(a=h[d])==null?void 0:a.events)};return u}const WE={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}},GE={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 j(t,e){const{message:i,code:r}=GE[t];return{message:e?`${i} ${e}`:i,code:r}}function de(t,e){const{message:i,code:r}=WE[t];return{message:e?`${i} ${e}`:i,code:r}}function dt(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ut(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Oe(t){return typeof t>"u"}function ye(t,e){return e&&Oe(t)?!0:typeof t=="string"&&!!t.trim().length}function Xa(t,e){return e&&Oe(t)?!0:typeof t=="number"&&!isNaN(t)}function YE(t,e){const{requiredNamespaces:i}=e,r=Object.keys(t.namespaces),s=Object.keys(i);let n=!0;return Ai(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:h}=t.namespaces[o],u=Sr(a),l=i[o];(!Ai(kd(o,l),u)||!Ai(l.methods,c)||!Ai(l.events,h))&&(n=!1)}),n):!1}function yn(t){return ye(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function JE(t){if(ye(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const i=e[0]+":"+e[1];return!!e[2]&&yn(i)}}return!1}function ZE(t){function e(i){try{return typeof new URL(i)<"u"}catch{return!1}}try{if(ye(t,!1)){if(e(t))return!0;const i=zd(t);return e(i)}}catch{}return!1}function QE(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function XE(t){return t==null?void 0:t.topic}function e3(t,e){let i=null;return ye(t==null?void 0:t.publicKey,!1)||(i=j("MISSING_OR_INVALID",`${e} controller public key should be a string`)),i}function Yh(t){let e=!0;return dt(t)?t.length&&(e=t.every(i=>ye(i,!1))):e=!1,e}function t3(t,e,i){let r=null;return dt(e)&&e.length?e.forEach(s=>{r||yn(s)||(r=de("UNSUPPORTED_CHAINS",`${i}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):yn(t)||(r=de("UNSUPPORTED_CHAINS",`${i}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function i3(t,e,i){let r=null;return Object.entries(t).forEach(([s,n])=>{if(r)return;const o=t3(s,kd(s,n),`${e} ${i}`);o&&(r=o)}),r}function r3(t,e){let i=null;return dt(t)?t.forEach(r=>{i||JE(r)||(i=de("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):i=de("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function s3(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const s=r3(r==null?void 0:r.accounts,`${e} namespace`);s&&(i=s)}),i}function n3(t,e){let i=null;return Yh(t==null?void 0:t.methods)?Yh(t==null?void 0:t.events)||(i=de("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):i=de("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),i}function Rf(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const s=n3(r,`${e}, namespace`);s&&(i=s)}),i}function o3(t,e,i){let r=null;if(t&&Ut(t)){const s=Rf(t,e);s&&(r=s);const n=i3(t,e,i);n&&(r=n)}else r=j("MISSING_OR_INVALID",`${e}, ${i} should be an object with data`);return r}function yo(t,e){let i=null;if(t&&Ut(t)){const r=Rf(t,e);r&&(i=r);const s=s3(t,e);s&&(i=s)}else i=j("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return i}function Nf(t){return ye(t.protocol,!0)}function a3(t,e){let i=!1;return e&&!t?i=!0:t&&dt(t)&&t.length&&t.forEach(r=>{i=Nf(r)}),i}function c3(t){return typeof t=="number"}function We(t){return typeof t<"u"&&typeof t!==null}function h3(t){return!(!t||typeof t!="object"||!t.code||!Xa(t.code,!1)||!t.message||!ye(t.message,!1))}function u3(t){return!(Oe(t)||!ye(t.method,!1))}function l3(t){return!(Oe(t)||Oe(t.result)&&Oe(t.error)||!Xa(t.id,!1)||!ye(t.jsonrpc,!1))}function d3(t){return!(Oe(t)||!ye(t.name,!1))}function Jh(t,e){return!(!yn(e)||!qE(t).includes(e))}function f3(t,e,i){return ye(i,!1)?zE(t,e).includes(i):!1}function p3(t,e,i){return ye(i,!1)?HE(t,e).includes(i):!1}function Zh(t,e,i){let r=null;const s=g3(t),n=y3(e),o=Object.keys(s),a=Object.keys(n),c=Qh(Object.keys(t)),h=Qh(Object.keys(e)),u=c.filter(l=>!h.includes(l));return u.length&&(r=j("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.
21
+ Required: ${u.toString()}
22
+ Received: ${Object.keys(e).toString()}`)),Ai(o,a)||(r=j("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.
23
+ Required: ${o.toString()}
24
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(l=>{if(!l.includes(":")||r)return;const d=Sr(e[l].accounts);d.includes(l)||(r=j("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${l}
25
+ Required: ${l}
26
+ Approved: ${d.toString()}`))}),o.forEach(l=>{r||(Ai(s[l].methods,n[l].methods)?Ai(s[l].events,n[l].events)||(r=j("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${l}`)):r=j("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${l}`))}),r}function g3(t){const e={};return Object.keys(t).forEach(i=>{var r;i.includes(":")?e[i]=t[i]:(r=t[i].chains)==null||r.forEach(s=>{e[s]={methods:t[i].methods,events:t[i].events}})}),e}function Qh(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function y3(t){const e={};return Object.keys(t).forEach(i=>{if(i.includes(":"))e[i]=t[i];else{const r=Sr(t[i].accounts);r==null||r.forEach(s=>{e[s]={accounts:t[i].accounts.filter(n=>n.includes(`${s}:`)),methods:t[i].methods,events:t[i].events}})}}),e}function w3(t,e){return Xa(t,!1)&&t<=e.max&&t>=e.min}function Xh(){const t=ws();return new Promise(e=>{switch(t){case rt.browser:e(m3());break;case rt.reactNative:e(b3());break;case rt.node:e(v3());break;default:e(!0)}})}function m3(){return _r()&&(navigator==null?void 0:navigator.onLine)}async function b3(){if(wi()&&typeof K<"u"&&K!=null&&K.NetInfo){const t=await(K==null?void 0:K.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function v3(){return!0}function E3(t){switch(ws()){case rt.browser:I3(t);break;case rt.reactNative:_3(t);break}}function I3(t){!wi()&&_r()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function _3(t){var e;wi()&&typeof K<"u"&&K!=null&&K.NetInfo&&((e=K)==null||e.NetInfo.addEventListener(i=>t(i==null?void 0:i.isConnected)))}function x3(){var t;return _r()&&Fi()?((t=Fi())==null?void 0:t.visibilityState)==="visible":!0}const wo={};class kr{static get(e){return wo[e]}static set(e,i){wo[e]=i}static delete(e){delete wo[e]}}function $3(t){const e=ps.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function S3({publicKey:t,signature:e,payload:i}){var r;const s=oa(i.method),n=128|parseInt(((r=i.version)==null?void 0:r.toString())||"4"),o=P3(i.address),a=i.era==="00"?new Uint8Array([0]):oa(i.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(i.nonce,16),h=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${A3(i.tip)}`),l=C3(u),d=new Uint8Array([0,...t,o,...e,...a,...h,...l,...s]),p=O3(d.length+1);return new Uint8Array([...p,n,...d])}function D3(t){const e=oa(t),i=wb.blake2b(e,void 0,32);return"0x"+X.from(i).toString("hex")}function oa(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function A3(t){return t.startsWith("0x")?t.slice(2):t}function P3(t){const e=ps.decode(t)[0];return e===42?0:e===60?2:1}function O3(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 C3(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 T3(t){const e=Uint8Array.from(X.from(t.signature,"hex")),i=$3(t.transaction.address),r=S3({publicKey:i,signature:e,payload:t.transaction}),s=X.from(r).toString("hex");return D3(s)}class ji{}let F3=class extends ji{constructor(e){super()}};const eu=L.FIVE_SECONDS,Li={pulse:"heartbeat_pulse"};let R3=class Uf extends F3{constructor(e){super(e),this.events=new gt.EventEmitter,this.interval=eu,this.interval=(e==null?void 0:e.interval)||eu}static async init(e){const i=new Uf(e);return await i.init(),i}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(Li.pulse)}};const N3=/"(?:_|\\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*:/,U3=/"(?: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*:/,B3=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function k3(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){j3(t);return}return e}function j3(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Ls(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const i=t.trim();if(i.length<=9)switch(i.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(!B3.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(N3.test(t)||U3.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,k3)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function L3(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ie(t,...e){try{return L3(t(...e))}catch(i){return Promise.reject(i)}}function M3(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function q3(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Xs(t){if(M3(t))return String(t);if(q3(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Xs(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const aa="base64:";function z3(t){return typeof t=="string"?t:aa+K3(t)}function H3(t){return typeof t!="string"||!t.startsWith(aa)?t:V3(t.slice(aa.length))}function V3(t){return globalThis.Buffer?X.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function K3(t){return globalThis.Buffer?X.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ke(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function W3(...t){return Ke(t.join(":"))}function Ms(t){return t=Ke(t),t?t+":":""}function G3(t,e){if(e===void 0)return!0;let i=0,r=t.indexOf(":");for(;r>-1;)i++,r=t.indexOf(":",r+1);return i<=e}function Y3(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const J3="memory",Z3=()=>{const t=new Map;return{name:J3,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,i){t.set(e,i)},setItemRaw(e,i){t.set(e,i)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Q3(t={}){const e={mounts:{"":t.driver||Z3()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=h=>{for(const u of e.mountpoints)if(h.startsWith(u))return{base:u,relativeKey:h.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:h,driver:e.mounts[""]}},r=(h,u)=>e.mountpoints.filter(l=>l.startsWith(h)||u&&h.startsWith(l)).map(l=>({relativeBase:h.length>l.length?h.slice(l.length):void 0,mountpoint:l,driver:e.mounts[l]})),s=(h,u)=>{if(e.watching){u=Ke(u);for(const l of e.watchListeners)l(h,u)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await tu(e.mounts[h],s,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,u,l)=>{const d=new Map,p=f=>{let g=d.get(f.base);return g||(g={driver:f.driver,base:f.base,items:[]},d.set(f.base,g)),g};for(const f of h){const g=typeof f=="string",y=Ke(g?f:f.key),v=g?void 0:f.value,E=g||!f.options?u:{...u,...f.options},m=i(y);p(m).items.push({key:y,value:v,relativeKey:m.relativeKey,options:E})}return Promise.all([...d.values()].map(f=>l(f))).then(f=>f.flat())},c={hasItem(h,u={}){h=Ke(h);const{relativeKey:l,driver:d}=i(h);return Ie(d.hasItem,l,u)},getItem(h,u={}){h=Ke(h);const{relativeKey:l,driver:d}=i(h);return Ie(d.getItem,l,u).then(p=>Ls(p))},getItems(h,u={}){return a(h,u,l=>l.driver.getItems?Ie(l.driver.getItems,l.items.map(d=>({key:d.relativeKey,options:d.options})),u).then(d=>d.map(p=>({key:W3(l.base,p.key),value:Ls(p.value)}))):Promise.all(l.items.map(d=>Ie(l.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:Ls(p)})))))},getItemRaw(h,u={}){h=Ke(h);const{relativeKey:l,driver:d}=i(h);return d.getItemRaw?Ie(d.getItemRaw,l,u):Ie(d.getItem,l,u).then(p=>H3(p))},async setItem(h,u,l={}){if(u===void 0)return c.removeItem(h);h=Ke(h);const{relativeKey:d,driver:p}=i(h);p.setItem&&(await Ie(p.setItem,d,Xs(u),l),p.watch||s("update",h))},async setItems(h,u){await a(h,u,async l=>{if(l.driver.setItems)return Ie(l.driver.setItems,l.items.map(d=>({key:d.relativeKey,value:Xs(d.value),options:d.options})),u);l.driver.setItem&&await Promise.all(l.items.map(d=>Ie(l.driver.setItem,d.relativeKey,Xs(d.value),d.options)))})},async setItemRaw(h,u,l={}){if(u===void 0)return c.removeItem(h,l);h=Ke(h);const{relativeKey:d,driver:p}=i(h);if(p.setItemRaw)await Ie(p.setItemRaw,d,u,l);else if(p.setItem)await Ie(p.setItem,d,z3(u),l);else return;p.watch||s("update",h)},async removeItem(h,u={}){typeof u=="boolean"&&(u={removeMeta:u}),h=Ke(h);const{relativeKey:l,driver:d}=i(h);d.removeItem&&(await Ie(d.removeItem,l,u),(u.removeMeta||u.removeMata)&&await Ie(d.removeItem,l+"$",u),d.watch||s("remove",h))},async getMeta(h,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),h=Ke(h);const{relativeKey:l,driver:d}=i(h),p=Object.create(null);if(d.getMeta&&Object.assign(p,await Ie(d.getMeta,l,u)),!u.nativeOnly){const f=await Ie(d.getItem,l+"$",u).then(g=>Ls(g));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(p,f))}return p},setMeta(h,u,l={}){return this.setItem(h+"$",u,l)},removeMeta(h,u={}){return this.removeItem(h+"$",u)},async getKeys(h,u={}){var y;h=Ms(h);const l=r(h,!0);let d=[];const p=[];let f=!0;for(const v of l){(y=v.driver.flags)!=null&&y.maxDepth||(f=!1);const E=await Ie(v.driver.getKeys,v.relativeBase,u);for(const m of E){const A=v.mountpoint+Ke(m);d.some($=>A.startsWith($))||p.push(A)}d=[v.mountpoint,...d.filter(m=>!m.startsWith(v.mountpoint))]}const g=u.maxDepth!==void 0&&!f;return p.filter(v=>(!g||G3(v,u.maxDepth))&&Y3(v,h))},async clear(h,u={}){h=Ms(h),await Promise.all(r(h,!1).map(async l=>{if(l.driver.clear)return Ie(l.driver.clear,l.relativeBase,u);if(l.driver.removeItem){const d=await l.driver.getKeys(l.relativeBase||"",u);return Promise.all(d.map(p=>l.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>iu(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,u){if(h=Ms(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((l,d)=>d.length-l.length)),e.mounts[h]=u,e.watching&&Promise.resolve(tu(u,s,h)).then(l=>{e.unwatch[h]=l}).catch(console.error),c},async unmount(h,u=!0){var l,d;h=Ms(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&((d=(l=e.unwatch)[h])==null||d.call(l),delete e.unwatch[h]),u&&await iu(e.mounts[h]),e.mountpoints=e.mountpoints.filter(p=>p!==h),delete e.mounts[h])},getMount(h=""){h=Ke(h)+":";const u=i(h);return{driver:u.driver,base:u.base}},getMounts(h="",u={}){return h=Ke(h),r(h,u.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(h,u={})=>c.getKeys(h,u),get:(h,u={})=>c.getItem(h,u),set:(h,u,l={})=>c.setItem(h,u,l),has:(h,u={})=>c.hasItem(h,u),del:(h,u={})=>c.removeItem(h,u),remove:(h,u={})=>c.removeItem(h,u)};return c}function tu(t,e,i){return t.watch?t.watch((r,s)=>e(r,i+s)):()=>{}}async function iu(t){typeof t.dispose=="function"&&await Ie(t.dispose)}function Mi(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Bf(t,e){let i;const r=()=>{if(i)return i;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),i=Mi(s),i.then(n=>{n.onclose=()=>i=void 0},()=>{}),i};return(s,n)=>r().then(o=>n(o.transaction(e,s).objectStore(e)))}let mo;function Es(){return mo||(mo=Bf("keyval-store","keyval")),mo}function ru(t,e=Es()){return e("readonly",i=>Mi(i.get(t)))}function X3(t,e,i=Es()){return i("readwrite",r=>(r.put(e,t),Mi(r.transaction)))}function eI(t,e=Es()){return e("readwrite",i=>(i.delete(t),Mi(i.transaction)))}function tI(t=Es()){return t("readwrite",e=>(e.clear(),Mi(e.transaction)))}function iI(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Mi(t.transaction)}function rI(t=Es()){return t("readonly",e=>{if(e.getAllKeys)return Mi(e.getAllKeys());const i=[];return iI(e,r=>i.push(r.key)).then(()=>i)})}const sI="idb-keyval";var nI=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",i=s=>e+s;let r;return t.dbName&&t.storeName&&(r=Bf(t.dbName,t.storeName)),{name:sI,options:t,async hasItem(s){return!(typeof await ru(i(s),r)>"u")},async getItem(s){return await ru(i(s),r)??null},setItem(s,n){return X3(i(s),n,r)},removeItem(s){return eI(i(s),r)},getKeys(){return rI(r)},clear(){return tI(r)}}};const oI="WALLET_CONNECT_V2_INDEXED_DB",aI="keyvaluestorage";let cI=class{constructor(){this.indexedDb=Q3({driver:nI({dbName:oI,storeName:aI})})}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 i=await this.indexedDb.getItem(e);if(i!==null)return i}async setItem(e,i){await this.indexedDb.setItem(e,Yt(i))}async removeItem(e){await this.indexedDb.removeItem(e)}};var bo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof K<"u"?K:typeof self<"u"?self:{},en={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(i){return this.hasOwnProperty(i)?String(this[i]):null},t.prototype.setItem=function(i,r){this[i]=String(r)},t.prototype.removeItem=function(i){delete this[i]},t.prototype.clear=function(){const i=this;Object.keys(i).forEach(function(r){i[r]=void 0,delete i[r]})},t.prototype.key=function(i){return i=i||0,Object.keys(this)[i]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof bo<"u"&&bo.localStorage?en.exports=bo.localStorage:typeof window<"u"&&window.localStorage?en.exports=window.localStorage:en.exports=new e})();function hI(t){var e;return[t[0],Ni((e=t[1])!=null?e:"")]}let uI=class{constructor(){this.localStorage=en.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(hI)}async getItem(e){const i=this.localStorage.getItem(e);if(i!==null)return Ni(i)}async setItem(e,i){this.localStorage.setItem(e,Yt(i))}async removeItem(e){this.localStorage.removeItem(e)}};const lI="wc_storage_version",su=1,dI=async(t,e,i)=>{const r=lI,s=await e.getItem(r);if(s&&s>=su){i(e);return}const n=await t.getKeys();if(!n.length){i(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 h=await t.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(r,su),i(e),fI(t,o)},fI=async(t,e)=>{e.length&&e.forEach(async i=>{await t.removeItem(i)})};let pI=class{constructor(){this.initialized=!1,this.setInitialized=i=>{this.storage=i,this.initialized=!0};const e=new uI;this.storage=e;try{const i=new cI;dI(e,i,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,i){return await this.initialize(),this.storage.setItem(e,i)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const i=setInterval(()=>{this.initialized&&(clearInterval(i),e())},20)})}};function gI(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var yI=wI;function wI(t,e,i){var r=i&&i.stringify||gI,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]=r(t);for(var a=1;a<n;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var h="",u=1-s,l=-1,d=t&&t.length||0,p=0;p<d;){if(t.charCodeAt(p)===37&&p+1<d){switch(l=l>-1?l:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=c||e[u]==null)break;l<p&&(h+=t.slice(l,p)),h+=Number(e[u]),l=p+2,p++;break;case 105:if(u>=c||e[u]==null)break;l<p&&(h+=t.slice(l,p)),h+=Math.floor(Number(e[u])),l=p+2,p++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;l<p&&(h+=t.slice(l,p));var f=typeof e[u];if(f==="string"){h+="'"+e[u]+"'",l=p+2,p++;break}if(f==="function"){h+=e[u].name||"<anonymous>",l=p+2,p++;break}h+=r(e[u]),l=p+2,p++;break;case 115:if(u>=c)break;l<p&&(h+=t.slice(l,p)),h+=String(e[u]),l=p+2,p++;break;case 37:l<p&&(h+=t.slice(l,p)),h+="%",l=p+2,p++,u--;break}++u}++p}return l===-1?t:(l<d&&(h+=t.slice(l)),h)}const nu=yI;var dr=Bt;const ls=DI().console||{},mI={mapHttpRequest:qs,mapHttpResponse:qs,wrapRequestSerializer:vo,wrapResponseSerializer:vo,wrapErrorSerializer:vo,req:qs,res:qs,err:_I};function bI(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Bt(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 i=t.browser.write||ls;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},s=bI(t.browser.serialize,r);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof i=="function"&&(i.error=i.fatal=i.warn=i.info=i.debug=i.trace=i),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(i);c.log||(c.log=ds),Object.defineProperty(c,"levelVal",{get:u}),Object.defineProperty(c,"level",{get:l,set:d});const h={transmit:e,serialize:s,asObject:t.browser.asObject,levels:o,timestamp:xI(t)};c.levels=Bt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=ds,c.serializers=r,c._serialize=s,c._stdErrSerialize=n,c.child=p,e&&(c._logEvent=ca());function u(){return this.level==="silent"?1/0:this.levels.values[this.level]}function l(){return this._level}function d(f){if(f!=="silent"&&!this.levels.values[f])throw Error("unknown level "+f);this._level=f,Zi(h,c,"error","log"),Zi(h,c,"fatal","error"),Zi(h,c,"warn","error"),Zi(h,c,"info","log"),Zi(h,c,"debug","log"),Zi(h,c,"trace","log")}function p(f,g){if(!f)throw new Error("missing bindings for child Pino");g=g||{},s&&f.serializers&&(g.serializers=f.serializers);const y=g.serializers;if(s&&y){var v=Object.assign({},r,y),E=t.browser.serialize===!0?Object.keys(v):s;delete f.serializers,Nn([f],E,v,this._stdErrSerialize)}function m(A){this._childLevel=(A._childLevel|0)+1,this.error=Qi(A,f,"error"),this.fatal=Qi(A,f,"fatal"),this.warn=Qi(A,f,"warn"),this.info=Qi(A,f,"info"),this.debug=Qi(A,f,"debug"),this.trace=Qi(A,f,"trace"),v&&(this.serializers=v,this._serialize=E),e&&(this._logEvent=ca([].concat(A._logEvent.bindings,f)))}return m.prototype=this,new m(this)}return c}Bt.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"}};Bt.stdSerializers=mI;Bt.stdTimeFunctions=Object.assign({},{nullTime:kf,epochTime:jf,unixTime:$I,isoTime:SI});function Zi(t,e,i,r){const s=Object.getPrototypeOf(e);e[i]=e.levelVal>e.levels.values[i]?ds:s[i]?s[i]:ls[i]||ls[r]||ds,vI(t,e,i)}function vI(t,e,i){!t.transmit&&e[i]===ds||(e[i]=function(r){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ls?ls:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Nn(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,EI(this,i,o,n)):r.apply(a,o),t.transmit){const h=t.transmit.level||e.level,u=Bt.levels.values[h],l=Bt.levels.values[i];if(l<u)return;II(this,{ts:n,methodLevel:i,methodValue:l,transmitLevel:h,transmitValue:Bt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[i]))}function EI(t,e,i,r){t._serialize&&Nn(i,t._serialize,t.serializers,t._stdErrSerialize);const s=i.slice();let n=s[0];const o={};r&&(o.time=r),o.level=Bt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof s[0]=="object";)Object.assign(o,s.shift());n=s.length?nu(s.shift(),s):void 0}else typeof n=="string"&&(n=nu(s.shift(),s));return n!==void 0&&(o.msg=n),o}function Nn(t,e,i,r){for(const s in t)if(r&&t[s]instanceof Error)t[s]=Bt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s]))for(const n in t[s])e&&e.indexOf(n)>-1&&n in i&&(t[s][n]=i[n](t[s][n]))}function Qi(t,e,i){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var s=1;s<r.length;s++)r[s]=arguments[s-1];return t[i].apply(this,r)}}function II(t,e,i){const r=e.send,s=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Nn(i,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=i.filter(function(h){return c.indexOf(h)===-1}),t._logEvent.level.label=n,t._logEvent.level.value=o,r(n,t._logEvent,a),t._logEvent=ca(c)}function ca(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function _I(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const i in t)e[i]===void 0&&(e[i]=t[i]);return e}function xI(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?kf:jf}function qs(){return{}}function vo(t){return t}function ds(){}function kf(){return!1}function jf(){return Date.now()}function $I(){return Math.round(Date.now()/1e3)}function SI(){return new Date(Date.now()).toISOString()}function DI(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const Is=Up(dr),AI={level:"info"},_s="custom_context",ec=1e3*1024;let PI=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},ou=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const i=new PI(e);if(i.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${i.size}`);for(;this.size+i.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=i),this.tail=i):(this.head=i,this.tail=i),this.lengthInNodes++,this.sizeInBytes+=i.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 i=this.head;for(;i!==null;)e.push(i.value),i=i.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 i=e.value;return e=e.next,{done:!1,value:i}}}}},Lf=class{constructor(e,i=ec){this.level=e??"error",this.levelValue=dr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=i,this.logs=new ou(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,i){i===dr.levels.values.error?console.error(e):i===dr.levels.values.warn?console.warn(e):i===dr.levels.values.debug?console.debug(e):i===dr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Yt({timestamp:new Date().toISOString(),log:e}));const i=typeof e=="string"?JSON.parse(e).level:e.level;i>=this.levelValue&&this.forwardToConsole(e,i)}getLogs(){return this.logs}clearLogs(){this.logs=new ou(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const i=this.getLogArray();return i.push(Yt({extraMetadata:e})),new Blob(i,{type:"application/json"})}},OI=class{constructor(e,i=ec){this.baseChunkLogger=new Lf(e,i)}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 i=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=i,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(i)}},CI=class{constructor(e,i=ec){this.baseChunkLogger=new Lf(e,i)}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 TI=Object.defineProperty,FI=Object.defineProperties,RI=Object.getOwnPropertyDescriptors,au=Object.getOwnPropertySymbols,NI=Object.prototype.hasOwnProperty,UI=Object.prototype.propertyIsEnumerable,cu=(t,e,i)=>e in t?TI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,wn=(t,e)=>{for(var i in e||(e={}))NI.call(e,i)&&cu(t,i,e[i]);if(au)for(var i of au(e))UI.call(e,i)&&cu(t,i,e[i]);return t},mn=(t,e)=>FI(t,RI(e));function Un(t){return mn(wn({},t),{level:(t==null?void 0:t.level)||AI.level})}function BI(t,e=_s){return t[e]||""}function kI(t,e,i=_s){return t[i]=e,t}function Qe(t,e=_s){let i="";return typeof t.bindings>"u"?i=BI(t,e):i=t.bindings().context||"",i}function jI(t,e,i=_s){const r=Qe(t,i);return r.trim()?`${r}/${e}`:e}function qe(t,e,i=_s){const r=jI(t,e,i),s=t.child({context:r});return kI(s,r,i)}function LI(t){var e,i;const r=new OI((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Is(mn(wn({},t.opts),{level:"trace",browser:mn(wn({},(i=t.opts)==null?void 0:i.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function MI(t){var e;const i=new CI((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Is(mn(wn({},t.opts),{level:"trace"}),i),chunkLoggerController:i}}function qI(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?LI(t):MI(t)}var zI=Object.defineProperty,HI=(t,e,i)=>e in t?zI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,hu=(t,e,i)=>HI(t,typeof e!="symbol"?e+"":e,i);let VI=class extends ji{constructor(e){super(),this.opts=e,hu(this,"protocol","wc"),hu(this,"version",2)}};var KI=Object.defineProperty,WI=(t,e,i)=>e in t?KI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,GI=(t,e,i)=>WI(t,typeof e!="symbol"?e+"":e,i);let YI=class extends ji{constructor(e,i){super(),this.core=e,this.logger=i,GI(this,"records",new Map)}},JI=class{constructor(e,i){this.logger=e,this.core=i}};class ZI extends ji{constructor(e,i){super(),this.relayer=e,this.logger=i}}let QI=class extends ji{constructor(e){super()}},XI=class{constructor(e,i,r,s){this.core=e,this.logger=i,this.name=r}},e_=class extends ji{constructor(e,i){super(),this.relayer=e,this.logger=i}},t_=class extends ji{constructor(e,i){super(),this.core=e,this.logger=i}},i_=class{constructor(e,i,r){this.core=e,this.logger=i,this.store=r}},r_=class{constructor(e,i){this.projectId=e,this.logger=i}},s_=class{constructor(e,i,r){this.core=e,this.logger=i,this.telemetryEnabled=r}};var n_=Object.defineProperty,o_=(t,e,i)=>e in t?n_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,uu=(t,e,i)=>o_(t,typeof e!="symbol"?e+"":e,i);let a_=class{constructor(e){this.opts=e,uu(this,"protocol","wc"),uu(this,"version",2)}},c_=class{constructor(e){this.client=e}};const h_="PARSE_ERROR",u_="INVALID_REQUEST",l_="METHOD_NOT_FOUND",d_="INVALID_PARAMS",Mf="INTERNAL_ERROR",tc="SERVER_ERROR",f_=[-32700,-32600,-32601,-32602,-32603],ts={[h_]:{code:-32700,message:"Parse error"},[u_]:{code:-32600,message:"Invalid Request"},[l_]:{code:-32601,message:"Method not found"},[d_]:{code:-32602,message:"Invalid params"},[Mf]:{code:-32603,message:"Internal error"},[tc]:{code:-32e3,message:"Server error"}},qf=tc;function p_(t){return f_.includes(t)}function lu(t){return Object.keys(ts).includes(t)?ts[t]:ts[qf]}function g_(t){const e=Object.values(ts).find(i=>i.code===t);return e||ts[qf]}function zf(t,e,i){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${e}`):t}var Hf={},zt={},du;function y_(){if(du)return zt;du=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.isBrowserCryptoAvailable=zt.getSubtleCrypto=zt.getBrowerCrypto=void 0;function t(){return(Vi===null||Vi===void 0?void 0:Vi.crypto)||(Vi===null||Vi===void 0?void 0:Vi.msCrypto)||{}}zt.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}zt.getSubtleCrypto=e;function i(){return!!t()&&!!e()}return zt.isBrowserCryptoAvailable=i,zt}var Ht={},fu;function w_(){if(fu)return Ht;fu=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.isBrowser=Ht.isNode=Ht.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ht.isReactNative=t;function e(){return typeof lt<"u"&&typeof lt.versions<"u"&&typeof lt.versions.node<"u"}Ht.isNode=e;function i(){return!t()&&!e()}return Ht.isBrowser=i,Ht}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=fs;e.__exportStar(y_(),t),e.__exportStar(w_(),t)})(Hf);function Tt(t=3){const e=Date.now()*Math.pow(10,t),i=Math.floor(Math.random()*Math.pow(10,t));return e+i}function Ti(t=6){return BigInt(Tt(t))}function pi(t,e,i){return{id:i||Tt(),jsonrpc:"2.0",method:t,params:e}}function Bn(t,e){return{id:t,jsonrpc:"2.0",result:e}}function kn(t,e,i){return{id:t,jsonrpc:"2.0",error:m_(e,i)}}function m_(t,e){return typeof t>"u"?lu(Mf):(typeof t=="string"&&(t=Object.assign(Object.assign({},lu(tc)),{message:t})),typeof e<"u"&&(t.data=e),p_(t.code)&&(t=g_(t.code)),t)}class b_{}class v_ extends b_{constructor(){super()}}class E_ extends v_{constructor(e){super()}}const I_="^https?:",__="^wss?:";function x_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Vf(t,e){const i=x_(t);return typeof i>"u"?!1:new RegExp(e).test(i)}function pu(t){return Vf(t,I_)}function gu(t){return Vf(t,__)}function $_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Kf(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ic(t){return Kf(t)&&"method"in t}function jn(t){return Kf(t)&&(Ft(t)||ct(t))}function Ft(t){return"result"in t}function ct(t){return"error"in t}class yt extends E_{constructor(e){super(e),this.events=new gt.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,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async request(e,i){return this.requestStrict(pi(e.method,e.params||[],e.id||Ti().toString()),i)}async requestStrict(e,i){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{ct(n)?s(n.error):r(n.result)});try{await this.connection.send(e,i)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),jn(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 S_=()=>typeof WebSocket<"u"?WebSocket:typeof K<"u"&&typeof K.WebSocket<"u"?K.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),D_=()=>typeof WebSocket<"u"||typeof K<"u"&&typeof K.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",yu=t=>t.split("?")[0],wu=10,A_=S_();let P_=class{constructor(e){if(this.url=e,this.events=new gt.EventEmitter,this.registering=!1,!gu(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,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,i)=>{if(typeof this.socket>"u"){i(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Yt(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!gu(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,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"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((i,r)=>{const s=Hf.isReactNative()?void 0:{rejectUnauthorized:!$_(e)},n=new A_(e,[],s);D_()?n.onerror=o=>{const a=o;r(this.emitError(a.error))}:n.on("error",o=>{r(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),i(n)}})}onOpen(e){e.onmessage=i=>this.onPayload(i),e.onclose=i=>this.onClose(i),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 i=typeof e.data=="string"?Ni(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),s=r.message||r.toString(),n=kn(e,s);this.events.emit("payload",n)}parseError(e,i=this.url){return zf(e,yu(i),"WS")}resetMaxListeners(){this.events.getMaxListeners()>wu&&this.events.setMaxListeners(wu)}emitError(e){const i=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${yu(this.url)}`));return this.events.emit("register_error",i),i}};const Wf="wc",Gf=2,bn="core",kt=`${Wf}@2:${bn}:`,O_={name:bn,logger:"error"},C_={database:":memory:"},T_="crypto",mu="client_ed25519_seed",F_=L.ONE_DAY,R_="keychain",N_="0.3",U_="messages",B_="0.3",bu=L.SIX_HOURS,k_="publisher",Yf="irn",j_="error",Jf="wss://relay.walletconnect.org",L_="relayer",_e={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"},M_="_subscription",nt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},q_=.1,ha="2.21.4",le={link_mode:"link_mode",relay:"relay"},tn={inbound:"inbound",outbound:"outbound"},z_="0.3",H_="WALLETCONNECT_CLIENT_ID",vu="WALLETCONNECT_LINK_MODE_APPS",tt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},V_="subscription",K_="0.3",W_="pairing",G_="0.3",jr={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Si={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Y_="history",J_="0.3",Z_="expirer",at={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Q_="0.3",X_="verify-api",ex="https://verify.walletconnect.com",Zf="https://verify.walletconnect.org",is=Zf,tx=`${is}/v3`,ix=[ex,Zf],rx="echo",sx="https://echo.walletconnect.com",Ct={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"},Kt={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"},vt={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"},Ei={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"},Ii={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",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",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Lr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",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"},nx=.1,ox="event-client",ax=86400,cx="https://pulse.walletconnect.org/batch";function hx(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,v=0,E=f.length;v!==E&&f[v]===0;)v++,g++;for(var m=(E-v)*u+1>>>0,A=new Uint8Array(m);v!==E;){for(var $=f[v],k=0,B=m-1;($!==0||k<y)&&B!==-1;B--,k++)$+=256*A[B]>>>0,A[B]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");y=k,v++}for(var T=m-y;T!==m&&A[T]===0;)T++;for(var w=c.repeat(g);T<m;++T)w+=t.charAt(A[T]);return w}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,v=0;f[g]===c;)y++,g++;for(var E=(f.length-g)*h+1>>>0,m=new Uint8Array(E);f[g];){var A=i[f.charCodeAt(g)];if(A===255)return;for(var $=0,k=E-1;(A!==0||$<v)&&k!==-1;k--,$++)A+=a*m[k]>>>0,m[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");v=$,g++}if(f[g]!==" "){for(var B=E-v;B!==E&&m[B]===0;)B++;for(var T=new Uint8Array(y+(E-B)),w=y;B!==E;)T[w++]=m[B++];return T}}}function p(f){var g=d(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:p}}var ux=hx,lx=ux;const Qf=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")},dx=t=>new TextEncoder().encode(t),fx=t=>new TextDecoder().decode(t);class px{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class gx{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}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 Xf(this,e)}}class yx{constructor(e){this.decoders=e}or(e){return Xf(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Xf=(t,e)=>new yx({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class wx{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new px(e,i,r),this.decoder=new gx(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ln=({name:t,prefix:e,encode:i,decode:r})=>new wx(t,e,i,r),xs=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=lx(i,e);return Ln({prefix:t,name:e,encode:r,decode:n=>Qf(s(n))})},mx=(t,e,i,r)=>{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*i/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[t[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},bx=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Fe=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>Ln({prefix:e,name:t,encode(s){return bx(s,r,i)},decode(s){return mx(s,r,i,t)}}),vx=Ln({prefix:"\0",name:"identity",encode:t=>fx(t),decode:t=>dx(t)});var Ex=Object.freeze({__proto__:null,identity:vx});const Ix=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _x=Object.freeze({__proto__:null,base2:Ix});const xx=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var $x=Object.freeze({__proto__:null,base8:xx});const Sx=xs({prefix:"9",name:"base10",alphabet:"0123456789"});var Dx=Object.freeze({__proto__:null,base10:Sx});const Ax=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Px=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ox=Object.freeze({__proto__:null,base16:Ax,base16upper:Px});const Cx=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Tx=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fx=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rx=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nx=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ux=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bx=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kx=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jx=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Lx=Object.freeze({__proto__:null,base32:Cx,base32upper:Tx,base32pad:Fx,base32padupper:Rx,base32hex:Nx,base32hexupper:Ux,base32hexpad:Bx,base32hexpadupper:kx,base32z:jx});const Mx=xs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),qx=xs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zx=Object.freeze({__proto__:null,base36:Mx,base36upper:qx});const Hx=xs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vx=xs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Kx=Object.freeze({__proto__:null,base58btc:Hx,base58flickr:Vx});const Wx=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Gx=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yx=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Jx=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Zx=Object.freeze({__proto__:null,base64:Wx,base64pad:Gx,base64url:Yx,base64urlpad:Jx});const ep=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Qx=ep.reduce((t,e,i)=>(t[i]=e,t),[]),Xx=ep.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function e8(t){return t.reduce((e,i)=>(e+=Qx[i],e),"")}function t8(t){const e=[];for(const i of t){const r=Xx[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const i8=Ln({prefix:"🚀",name:"base256emoji",encode:e8,decode:t8});var r8=Object.freeze({__proto__:null,base256emoji:i8}),s8=tp,Eu=128,n8=127,o8=~n8,a8=Math.pow(2,31);function tp(t,e,i){e=e||[],i=i||0;for(var r=i;t>=a8;)e[i++]=t&255|Eu,t/=128;for(;t&o8;)e[i++]=t&255|Eu,t>>>=7;return e[i]=t|0,tp.bytes=i-r+1,e}var c8=ua,h8=128,Iu=127;function ua(t,r){var i=0,r=r||0,s=0,n=r,o,a=t.length;do{if(n>=a)throw ua.bytes=0,new RangeError("Could not decode varint");o=t[n++],i+=s<28?(o&Iu)<<s:(o&Iu)*Math.pow(2,s),s+=7}while(o>=h8);return ua.bytes=n-r,i}var u8=Math.pow(2,7),l8=Math.pow(2,14),d8=Math.pow(2,21),f8=Math.pow(2,28),p8=Math.pow(2,35),g8=Math.pow(2,42),y8=Math.pow(2,49),w8=Math.pow(2,56),m8=Math.pow(2,63),b8=function(t){return t<u8?1:t<l8?2:t<d8?3:t<f8?4:t<p8?5:t<g8?6:t<y8?7:t<w8?8:t<m8?9:10},v8={encode:s8,decode:c8,encodingLength:b8},ip=v8;const _u=(t,e,i=0)=>(ip.encode(t,e,i),e),xu=t=>ip.encodingLength(t),la=(t,e)=>{const i=e.byteLength,r=xu(t),s=r+xu(i),n=new Uint8Array(s+i);return _u(t,n,0),_u(i,n,r),n.set(e,s),new E8(t,i,e,n)};class E8{constructor(e,i,r,s){this.code=e,this.size=i,this.digest=r,this.bytes=s}}const rp=({name:t,code:e,encode:i})=>new I8(t,e,i);class I8{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?la(this.code,i):i.then(r=>la(this.code,r))}else throw Error("Unknown type, must be binary type")}}const sp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),_8=rp({name:"sha2-256",code:18,encode:sp("SHA-256")}),x8=rp({name:"sha2-512",code:19,encode:sp("SHA-512")});var $8=Object.freeze({__proto__:null,sha256:_8,sha512:x8});const np=0,S8="identity",op=Qf,D8=t=>la(np,op(t)),A8={code:np,name:S8,encode:op,digest:D8};var P8=Object.freeze({__proto__:null,identity:A8});new TextEncoder,new TextDecoder;const $u={...Ex,..._x,...$x,...Dx,...Ox,...Lx,...zx,...Kx,...Zx,...r8};({...$8,...P8});function ap(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function O8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?ap(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function cp(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Su=cp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Eo=cp("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=O8(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),C8={utf8:Su,"utf-8":Su,hex:$u.base16,latin1:Eo,ascii:Eo,binary:Eo,...$u};function T8(t,e="utf8"){const i=C8[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?ap(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}var F8=Object.defineProperty,R8=(t,e,i)=>e in t?F8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Pt=(t,e,i)=>R8(t,typeof e!="symbol"?e+"":e,i);class N8{constructor(e,i){this.core=e,this.logger=i,Pt(this,"keychain",new Map),Pt(this,"name",R_),Pt(this,"version",N_),Pt(this,"initialized",!1),Pt(this,"storagePrefix",kt),Pt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Pt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Pt(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),Pt(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:n}=j("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return s}),Pt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=qe(i,this.name)}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Go(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Yo(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var U8=Object.defineProperty,B8=(t,e,i)=>e in t?U8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ae=(t,e,i)=>B8(t,typeof e!="symbol"?e+"":e,i);class k8{constructor(e,i,r){this.core=e,this.logger=i,Ae(this,"name",T_),Ae(this,"keychain"),Ae(this,"randomSessionIdentifier",na()),Ae(this,"initialized",!1),Ae(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ae(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ae(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=th(s);return bd(n.publicKey)}),Ae(this,"generateKeyPair",()=>{this.isInitialized();const s=IE();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ae(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=th(n),a=this.randomSessionIdentifier;return await c1(a,s,F_,o)}),Ae(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=_E(a,n);return this.setSymKey(c,o)}),Ae(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||Qs(s);return await this.keychain.set(o,s),o}),Ae(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ae(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ae(this,"encode",async(s,n,o)=>{this.isInitialized();const a=Ff(o),c=Yt(n);if(qh(a))return SE(c,o==null?void 0:o.encoding);if(Mh(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(d,p)}const h=this.getSymKey(s),{type:u,senderPublicKey:l}=a;return xE({type:u,symKey:h,message:c,senderPublicKey:l,encoding:o==null?void 0:o.encoding})}),Ae(this,"decode",async(s,n,o)=>{this.isInitialized();const a=AE(n,o);if(qh(a)){const c=DE(n,o==null?void 0:o.encoding);return Ni(c)}if(Mh(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;s=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(s),h=$E({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return Ni(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ae(this,"getPayloadType",(s,n=xt)=>{const o=us({encoded:s,encoding:n});return Bi(o.type)}),Ae(this,"getPayloadSenderPublicKey",(s,n=xt)=>{const o=us({encoded:s,encoding:n});return o.senderPublicKey?Ze(o.senderPublicKey,Me):void 0}),this.core=e,this.logger=qe(i,this.name),this.keychain=r||new N8(this.core,this.logger)}get context(){return Qe(this.logger)}async setPrivateKey(e,i){return await this.keychain.set(e,i),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(mu)}catch{e=na(),await this.keychain.set(mu,e)}return T8(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var j8=Object.defineProperty,L8=Object.defineProperties,M8=Object.getOwnPropertyDescriptors,Du=Object.getOwnPropertySymbols,q8=Object.prototype.hasOwnProperty,z8=Object.prototype.propertyIsEnumerable,da=(t,e,i)=>e in t?j8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,H8=(t,e)=>{for(var i in e||(e={}))q8.call(e,i)&&da(t,i,e[i]);if(Du)for(var i of Du(e))z8.call(e,i)&&da(t,i,e[i]);return t},V8=(t,e)=>L8(t,M8(e)),Xe=(t,e,i)=>da(t,typeof e!="symbol"?e+"":e,i);class K8 extends JI{constructor(e,i){super(e,i),this.logger=e,this.core=i,Xe(this,"messages",new Map),Xe(this,"messagesWithoutClientAck",new Map),Xe(this,"name",U_),Xe(this,"version",B_),Xe(this,"initialized",!1),Xe(this,"storagePrefix",kt),Xe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);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(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),Xe(this,"set",async(r,s,n)=>{this.isInitialized();const o=Rt(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),n===tn.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,V8(H8({},c),{[o]:s}))}return await this.persist(),o}),Xe(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),Xe(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Xe(this,"has",(r,s)=>{this.isInitialized();const n=this.get(r),o=Rt(s);return typeof n[o]<"u"}),Xe(this,"ack",async(r,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=Rt(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),Xe(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=qe(e,this.name),this.core=i}get context(){return Qe(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,Go(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Go(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Yo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Yo(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var W8=Object.defineProperty,G8=Object.defineProperties,Y8=Object.getOwnPropertyDescriptors,Au=Object.getOwnPropertySymbols,J8=Object.prototype.hasOwnProperty,Z8=Object.prototype.propertyIsEnumerable,fa=(t,e,i)=>e in t?W8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,zs=(t,e)=>{for(var i in e||(e={}))J8.call(e,i)&&fa(t,i,e[i]);if(Au)for(var i of Au(e))Z8.call(e,i)&&fa(t,i,e[i]);return t},Io=(t,e)=>G8(t,Y8(e)),Et=(t,e,i)=>fa(t,typeof e!="symbol"?e+"":e,i);class Q8 extends ZI{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,Et(this,"events",new gt.EventEmitter),Et(this,"name",k_),Et(this,"queue",new Map),Et(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),Et(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),Et(this,"needsTransportRestart",!1),Et(this,"publish",async(r,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||bu,c=gn(n),h=(n==null?void 0:n.prompt)||!1,u=(n==null?void 0:n.tag)||0,l=(n==null?void 0:n.id)||Ti().toString(),d={topic:r,message:s,opts:{ttl:a,relay:c,prompt:h,tag:u,id:l,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},p=`Failed to publish payload, please try again. id:${l} tag:${u}`;try{const f=new Promise(async g=>{const y=({id:E})=>{d.opts.id===E&&(this.removeRequestFromQueue(E),this.relayer.events.removeListener(_e.publish,y),g(d))};this.relayer.events.on(_e.publish,y);const v=fi(new Promise((E,m)=>{this.rpcPublish({topic:r,message:s,ttl:a,prompt:h,tag:u,id:l,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(E).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),m(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${l} tag:${u}`);try{await v,this.events.removeListener(_e.publish,y)}catch(E){this.queue.set(l,Io(zs({},d),{attempt:1})),this.logger.warn(E,E==null?void 0:E.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,topic:r,message:s,opts:n}}),await fi(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(l)}}),Et(this,"on",(r,s)=>{this.events.on(r,s)}),Et(this,"once",(r,s)=>{this.events.once(r,s)}),Et(this,"off",(r,s)=>{this.events.off(r,s)}),Et(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=e,this.logger=qe(i,this.name),this.registerEventListeners()}get context(){return Qe(this.logger)}async rpcPublish(e){var i,r,s,n;const{topic:o,message:a,ttl:c=bu,prompt:h,tag:u,id:l,attestation:d,tvf:p}=e,f={method:Wr(gn().protocol).publish,params:zs({topic:o,message:a,ttl:c,prompt:h,tag:u,attestation:d},p),id:l};Oe((i=f.params)==null?void 0:i.prompt)&&((r=f.params)==null||delete r.prompt),Oe((s=f.params)==null?void 0:s.tag)&&((n=f.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const g=await this.relayer.request(f);return this.relayer.events.emit(_e.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,i)=>{const r=e.attempt+1;this.queue.set(i,Io(zs({},e),{attempt:r}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(Io(zs({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Li.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(_e.connection_stalled);return}this.checkQueue()}),this.relayer.on(_e.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var X8=Object.defineProperty,e$=(t,e,i)=>e in t?X8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Xi=(t,e,i)=>e$(t,typeof e!="symbol"?e+"":e,i);class t${constructor(){Xi(this,"map",new Map),Xi(this,"set",(e,i)=>{const r=this.get(e);this.exists(e,i)||this.map.set(e,[...r,i])}),Xi(this,"get",e=>this.map.get(e)||[]),Xi(this,"exists",(e,i)=>this.get(e).includes(i)),Xi(this,"delete",(e,i)=>{if(typeof i>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,i))return;const s=r.filter(n=>n!==i);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Xi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var i$=Object.defineProperty,r$=Object.defineProperties,s$=Object.getOwnPropertyDescriptors,Pu=Object.getOwnPropertySymbols,n$=Object.prototype.hasOwnProperty,o$=Object.prototype.propertyIsEnumerable,pa=(t,e,i)=>e in t?i$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Mr=(t,e)=>{for(var i in e||(e={}))n$.call(e,i)&&pa(t,i,e[i]);if(Pu)for(var i of Pu(e))o$.call(e,i)&&pa(t,i,e[i]);return t},_o=(t,e)=>r$(t,s$(e)),ae=(t,e,i)=>pa(t,typeof e!="symbol"?e+"":e,i);class a$ extends e_{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,ae(this,"subscriptions",new Map),ae(this,"topicMap",new t$),ae(this,"events",new gt.EventEmitter),ae(this,"name",V_),ae(this,"version",K_),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",kt),ae(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(r,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const n=gn(s),o={topic:r,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ae(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),ae(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),ae(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),ae(this,"on",(r,s)=>{this.events.on(r,s)}),ae(this,"once",(r,s)=>{this.events.once(r,s)}),ae(this,"off",(r,s)=>{this.events.off(r,s)}),ae(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Li.pulse,async()=>{await this.checkPending()}),this.events.on(tt.created,async r=>{const s=tt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(tt.deleted,async r=>{const s=tt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=e,this.logger=qe(i,this.name),this.clientId=""}get context(){return Qe(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,i){let r=!1;try{r=this.getSubscription(e).topic===i}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,i){const r=this.topicMap.get(e);await Promise.all(r.map(async s=>await this.unsubscribeById(e,s,i)))}async unsubscribeById(e,i,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}});try{const s=gn(r);await this.restartToComplete({topic:e,id:i,relay:s}),await this.rpcUnsubscribe(e,i,s);const n=de("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,i,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,i,r){var s;(!r||(r==null?void 0:r.transportType)===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:i});const n={method:Wr(i.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((r==null?void 0:r.transportType)===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},L.toMiliseconds(L.ONE_SECOND)),a;const c=new Promise(async u=>{const l=d=>{d.topic===e&&(this.events.removeListener(tt.created,l),u(d.id))};this.events.on(tt.created,l);try{const d=await fi(new Promise((p,f)=>{this.relayer.request(n).catch(g=>{this.logger.warn(g,g==null?void 0:g.message),f(g)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(tt.created,l),u(d)}catch{}}),h=await fi(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(_e.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const i=e[0].relay,r={method:Wr(i.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await fi(new Promise(s=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(_e.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const i=e[0].relay,r={method:Wr(i.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await fi(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(_e.connection_stalled)}return s}rpcUnsubscribe(e,i,r){const s={method:Wr(r.protocol).unsubscribe,params:{topic:e,id:i}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,i){this.setSubscription(e,_o(Mr({},i),{id:e})),this.pending.delete(i.topic)}onBatchSubscribe(e){e.length&&e.forEach(i=>{this.setSubscription(i.id,Mr({},i)),this.pending.delete(i.topic)})}async onUnsubscribe(e,i,r){this.events.removeAllListeners(i),this.hasSubscription(i,e)&&this.deleteSubscription(i,r),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,i){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:i}),this.addSubscription(e,i)}addSubscription(e,i){this.subscriptions.set(e,Mr({},i)),this.topicMap.set(i.topic,e),this.events.emit(tt.created,i)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const i=this.subscriptions.get(e);if(!i){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}deleteSubscription(e,i){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:i});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(tt.deleted,_o(Mr({},r),{reason:i}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(tt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],i=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<i;r++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(tt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:i}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(i)}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 i=>_o(Mr({},i),{id:await this.getSubscriptionId(i.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await zb(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=j("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 Rt(e+await this.getClientId())}}var c$=Object.defineProperty,Ou=Object.getOwnPropertySymbols,h$=Object.prototype.hasOwnProperty,u$=Object.prototype.propertyIsEnumerable,ga=(t,e,i)=>e in t?c$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Cu=(t,e)=>{for(var i in e||(e={}))h$.call(e,i)&&ga(t,i,e[i]);if(Ou)for(var i of Ou(e))u$.call(e,i)&&ga(t,i,e[i]);return t},te=(t,e,i)=>ga(t,typeof e!="symbol"?e+"":e,i);class l$ extends QI{constructor(e){super(e),te(this,"protocol","wc"),te(this,"version",2),te(this,"core"),te(this,"logger"),te(this,"events",new gt.EventEmitter),te(this,"provider"),te(this,"messages"),te(this,"subscriber"),te(this,"publisher"),te(this,"name",L_),te(this,"transportExplicitlyClosed",!1),te(this,"initialized",!1),te(this,"connectionAttemptInProgress",!1),te(this,"relayUrl"),te(this,"projectId"),te(this,"packageName"),te(this,"bundleId"),te(this,"hasExperiencedNetworkDisruption",!1),te(this,"pingTimeout"),te(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),te(this,"reconnectTimeout"),te(this,"connectPromise"),te(this,"reconnectInProgress",!1),te(this,"requestsInFlight",[]),te(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),te(this,"request",async i=>{var r,s;this.logger.debug("Publishing Request Payload");const n=i.id||Ti().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:i.method,topic:(r=i.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),te(this,"resetPingTimeout",()=>{ln()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,r,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),te(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),te(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(_e.connect)}),te(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),te(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(_e.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),te(this,"registerProviderListeners",()=>{this.provider.on(nt.payload,this.onPayloadHandler),this.provider.on(nt.connect,this.onConnectHandler),this.provider.on(nt.disconnect,this.onDisconnectHandler),this.provider.on(nt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?qe(e.logger,this.name):Is(Un({level:e.logger||j_})),this.messages=new K8(this.logger,e.core),this.subscriber=new a$(this,this.logger),this.publisher=new Q8(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Jf,this.projectId=e.projectId,Db()?this.packageName=hh():Ab()&&(this.bundleId=hh()),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 Qe(this.logger)}get connected(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,i,r){this.isInitialized(),await this.publisher.publish(e,i,r),await this.recordMessageEvent({topic:e,message:i,publishedAt:Date.now(),transportType:le.relay},tn.outbound)}async subscribe(e,i){var r,s,n;this.isInitialized(),(!(i!=null&&i.transportType)||(i==null?void 0:i.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=u=>{u.topic===e&&(this.subscriber.off(tt.created,h),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(tt.created,h)}),new Promise(async(u,l)=>{a=await this.subscriber.subscribe(e,Cu({internal:{throwOnFailedPublish:o}},i)).catch(d=>{o&&l(d)})||a,u()})]),a}async unsubscribe(e,i){this.isInitialized(),await this.subscriber.unsubscribe(e,i)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await fi(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(i,r)=>{await this.connect(e).then(i).catch(r).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 Xh())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 i=e.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${i.length} message events sorted`);for(const r of i)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${i.length} message events processed`)}async onLinkMessageEvent(e,i){const{topic:r}=e;if(!i.sessionExists){const s=me(L.FIVE_MINUTES),n={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(_e.message,e),await this.recordMessageEvent(e,tn.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let i=1;for(;i<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${i}...`),await this.createProvider(),await new Promise(async(r,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(nt.disconnect,n),await fi(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(nt.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(nt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(nt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const s=r;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: ${i}`);break}await new Promise(r=>setTimeout(r,L.toMiliseconds(i*1))),i++}}startPingTimeout(){var e,i,r,s,n;if(ln())try{(i=(e=this.provider)==null?void 0:e.connection)!=null&&i.socket&&((n=(s=(r=this.provider)==null?void 0:r.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 yt(new P_(Fb({sdkVersion:ha,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,i){const{topic:r,message:s}=e;await this.messages.set(r,s,i)}async shouldIgnoreMessageEvent(e){const{topic:i,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(i))return this.logger.warn(`Ignoring message for unknown topic ${i}`),!0;const s=this.messages.has(i,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ic(e)){if(!e.method.endsWith(M_))return;const i=e.params,{topic:r,message:s,publishedAt:n,attestation:o}=i.data,a={topic:r,message:s,publishedAt:n,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Cu({type:"event",event:i.id},a)),this.events.emit(i.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else jn(e)&&this.events.emit(_e.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,tn.inbound),this.events.emit(_e.message,e))}async acknowledgePayload(e){const i=Bn(e.id,!0);await this.provider.connection.send(i)}unregisterProviderListeners(){this.provider.off(nt.payload,this.onPayloadHandler),this.provider.off(nt.connect,this.onConnectHandler),this.provider.off(nt.disconnect,this.onDisconnectHandler),this.provider.off(nt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Xh();E3(async i=>{e!==i&&(e=i,i?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Li.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&x3())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(i){this.logger.warn(i,i==null?void 0:i.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(_e.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},L.toMiliseconds(q_)))))}isInitialized(){if(!this.initialized){const{message:e}=j("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 d$(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Tu(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Fu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const f$="[object RegExp]",p$="[object String]",g$="[object Number]",y$="[object Boolean]",Ru="[object Arguments]",w$="[object Symbol]",m$="[object Date]",b$="[object Map]",v$="[object Set]",E$="[object Array]",I$="[object Function]",_$="[object ArrayBuffer]",xo="[object Object]",x$="[object Error]",$$="[object DataView]",S$="[object Uint8Array]",D$="[object Uint8ClampedArray]",A$="[object Uint16Array]",P$="[object Uint32Array]",O$="[object BigUint64Array]",C$="[object Int8Array]",T$="[object Int16Array]",F$="[object Int32Array]",R$="[object BigInt64Array]",N$="[object Float32Array]",U$="[object Float64Array]";function B$(){}function Nu(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 k$(t,e,i){return Gr(t,e,void 0,void 0,void 0,void 0,i)}function Gr(t,e,i,r,s,n,o){const a=o(t,e,i,r,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 rs(t,e,n,o)}return rs(t,e,n,o)}function rs(t,e,i,r){if(Object.is(t,e))return!0;let s=Fu(t),n=Fu(e);if(s===Ru&&(s=xo),n===Ru&&(n=xo),s!==n)return!1;switch(s){case p$:return t.toString()===e.toString();case g$:{const c=t.valueOf(),h=e.valueOf();return d$(c,h)}case y$:case m$:case w$:return Object.is(t.valueOf(),e.valueOf());case f$:return t.source===e.source&&t.flags===e.flags;case I$:return t===e}i=i??new Map;const o=i.get(t),a=i.get(e);if(o!=null&&a!=null)return o===e;i.set(t,e),i.set(e,t);try{switch(s){case b$:{if(t.size!==e.size)return!1;for(const[c,h]of t.entries())if(!e.has(c)||!Gr(h,e.get(c),c,t,e,i,r))return!1;return!0}case v$:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),h=Array.from(e.values());for(let u=0;u<c.length;u++){const l=c[u],d=h.findIndex(p=>Gr(l,p,void 0,t,e,i,r));if(d===-1)return!1;h.splice(d,1)}return!0}case E$:case S$:case D$:case A$:case P$:case O$:case C$:case T$:case F$:case R$:case N$:case U$:{if(typeof X<"u"&&X.isBuffer(t)!==X.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Gr(t[c],e[c],c,t,e,i,r))return!1;return!0}case _$:return t.byteLength!==e.byteLength?!1:rs(new Uint8Array(t),new Uint8Array(e),i,r);case $$:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:rs(new Uint8Array(t),new Uint8Array(e),i,r);case x$:return t.name===e.name&&t.message===e.message;case xo:{if(!(rs(t.constructor,e.constructor,i,r)||Nu(t)&&Nu(e)))return!1;const c=[...Object.keys(t),...Tu(t)],h=[...Object.keys(e),...Tu(e)];if(c.length!==h.length)return!1;for(let u=0;u<c.length;u++){const l=c[u],d=t[l];if(!Object.hasOwn(e,l))return!1;const p=e[l];if(!Gr(d,p,l,t,e,i,r))return!1}return!0}default:return!1}}finally{i.delete(t),i.delete(e)}}function j$(t,e){return k$(t,e,B$)}var L$=Object.defineProperty,Uu=Object.getOwnPropertySymbols,M$=Object.prototype.hasOwnProperty,q$=Object.prototype.propertyIsEnumerable,ya=(t,e,i)=>e in t?L$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Bu=(t,e)=>{for(var i in e||(e={}))M$.call(e,i)&&ya(t,i,e[i]);if(Uu)for(var i of Uu(e))q$.call(e,i)&&ya(t,i,e[i]);return t},He=(t,e,i)=>ya(t,typeof e!="symbol"?e+"":e,i);class qi extends XI{constructor(e,i,r,s=kt,n=void 0){super(e,i,r,s),this.core=e,this.logger=i,this.name=r,He(this,"map",new Map),He(this,"version",z_),He(this,"cached",[]),He(this,"initialized",!1),He(this,"getKey"),He(this,"storagePrefix",kt),He(this,"recentlyDeleted",[]),He(this,"recentlyDeletedLimit",200),He(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):QE(o)?this.map.set(o.id,o):XE(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),He(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())}),He(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),He(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>j$(a[c],o[c]))):this.values)),He(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=Bu(Bu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),He(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=qe(i,this.name),this.storagePrefix=s,this.getKey=n}get context(){return Qe(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 i=this.map.get(e);if(!i){if(this.recentlyDeleted.includes(e)){const{message:s}=j("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return i}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:i}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var z$=Object.defineProperty,H$=(t,e,i)=>e in t?z$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Z=(t,e,i)=>H$(t,typeof e!="symbol"?e+"":e,i);class V${constructor(e,i){this.core=e,this.logger=i,Z(this,"name",W_),Z(this,"version",G_),Z(this,"events",new xa),Z(this,"pairings"),Z(this,"initialized",!1),Z(this,"storagePrefix",kt),Z(this,"ignoredPayloadTypes",[Gt]),Z(this,"registeredMethods",[]),Z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Z(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),Z(this,"create",async r=>{this.isInitialized();const s=na(),n=await this.core.crypto.setSymKey(s),o=me(L.FIVE_MINUTES),a={protocol:Yf},c={topic:n,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},h=Hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Si.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r==null?void 0:r.transportType}),{topic:n,uri:h}}),Z(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[Ct.pairing_started]}});this.isValidPair(r,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=zh(r.uri);s.props.properties.topic=n,s.addTrace(Ct.pairing_uri_validation_success),s.addTrace(Ct.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),s.addTrace(Ct.existing_pairing),u.active)throw s.setError(Kt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(Ct.pairing_not_expired)}const l=c||me(L.FIVE_MINUTES),d={topic:n,relay:a,expiry:l,active:!1,methods:h};this.core.expirer.set(n,l),await this.pairings.set(n,d),s.addTrace(Ct.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Si.create,d),s.addTrace(Ct.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(Ct.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Kt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw s.setError(Kt.subscribe_pairing_topic_failure),p}return s.addTrace(Ct.subscribe_pairing_topic_success),d}),Z(this,"activate",async({topic:r})=>{this.isInitialized();const s=me(L.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),Z(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=_i();this.events.once(oe("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),Z(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),Z(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),Z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Z(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",de("USER_DISCONNECTED")),await this.deletePairing(s))}),Z(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),Z(this,"sendRequest",async(r,s,n)=>{const o=pi(s,n),a=await this.core.crypto.encode(r,o),c=jr[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),Z(this,"sendResult",async(r,s,n)=>{const o=Bn(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,h=jr[c].res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),Z(this,"sendError",async(r,s,n)=>{const o=kn(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,h=jr[c]?jr[c].res:jr.unregistered_method.res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),Z(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,de("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),Z(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>ci(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),Z(this,"onRelayEventRequest",async r=>{const{topic:s,payload:n}=r;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)}}),Z(this,"onRelayEventResponse",async r=>{const{topic:s,payload:n}=r,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)}}),Z(this,"onPairingPingRequest",async(r,s)=>{const{id:n}=s;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(Si.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),Z(this,"onPairingPingResponse",(r,s)=>{const{id:n}=s;setTimeout(()=>{Ft(s)?this.events.emit(oe("pairing_ping",n),{}):ct(s)&&this.events.emit(oe("pairing_ping",n),{error:s.error})},500)}),Z(this,"onPairingDeleteRequest",async(r,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Si.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),Z(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=de("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),Z(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(de("WC_METHOD_UNSUPPORTED",r))}),Z(this,"isValidPair",(r,s)=>{var n;if(!We(r)){const{message:a}=j("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(Kt.malformed_pairing_uri),new Error(a)}if(!ZE(r.uri)){const{message:a}=j("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(Kt.malformed_pairing_uri),new Error(a)}const o=zh(r==null?void 0:r.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Kt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Kt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(Kt.pairing_expired);const{message:a}=j("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Z(this,"isValidPing",async r=>{if(!We(r)){const{message:n}=j("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Z(this,"isValidDisconnect",async r=>{if(!We(r)){const{message:n}=j("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Z(this,"isValidPairingTopic",async r=>{if(!ye(r,!1)){const{message:s}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(ci(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=j("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=e,this.logger=qe(i,this.name),this.pairings=new qi(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(_e.message,async e=>{const{topic:i,message:r,transportType:s}=e;if(this.pairings.keys.includes(i)&&s!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(i,r);ic(n)?(this.core.history.set(i,n),await this.onRelayEventRequest({topic:i,payload:n})):jn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:i,payload:n}),this.core.history.delete(i,n.id)),await this.core.relayer.messages.ack(i,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(at.expired,async e=>{const{topic:i}=qd(e.target);i&&this.pairings.keys.includes(i)&&(await this.deletePairing(i,!0),this.events.emit(Si.expire,{topic:i}))})}}var K$=Object.defineProperty,W$=(t,e,i)=>e in t?K$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Pe=(t,e,i)=>W$(t,typeof e!="symbol"?e+"":e,i);class G$ extends YI{constructor(e,i){super(e,i),this.core=e,this.logger=i,Pe(this,"records",new Map),Pe(this,"events",new gt.EventEmitter),Pe(this,"name",Y_),Pe(this,"version",J_),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"storagePrefix",kt),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Pe(this,"set",(r,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:n,expiry:me(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bt.created,o)}),Pe(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=ct(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(bt.updated,s))}),Pe(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),Pe(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===r){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(bt.deleted,n)}}),this.persist()}),Pe(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),Pe(this,"on",(r,s)=>{this.events.on(r,s)}),Pe(this,"once",(r,s)=>{this.events.once(r,s)}),Pe(this,"off",(r,s)=>{this.events.off(r,s)}),Pe(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=qe(i,this.name)}get context(){return Qe(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(i=>{if(typeof i.response<"u")return;const r={topic:i.topic,request:pi(i.request.method,i.request.params,i.id),chainId:i.chainId};return e.push(r)}),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 i=this.records.get(e);if(!i){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:i}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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(bt.created,e=>{const i=bt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(bt.updated,e=>{const i=bt.updated;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(bt.deleted,e=>{const i=bt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.core.heartbeat.on(Li.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(i=>{L.toMiliseconds(i.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${i.id}`),this.records.delete(i.id),this.events.emit(bt.deleted,i,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Y$=Object.defineProperty,J$=(t,e,i)=>e in t?Y$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,je=(t,e,i)=>J$(t,typeof e!="symbol"?e+"":e,i);class Z$ extends t_{constructor(e,i){super(e,i),this.core=e,this.logger=i,je(this,"expirations",new Map),je(this,"events",new gt.EventEmitter),je(this,"name",Z_),je(this,"version",Q_),je(this,"cached",[]),je(this,"initialized",!1),je(this,"storagePrefix",kt),je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),je(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),je(this,"set",(r,s)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(at.created,{target:n,expiration:o})}),je(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),je(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(at.deleted,{target:s,expiration:n})}}),je(this,"on",(r,s)=>{this.events.on(r,s)}),je(this,"once",(r,s)=>{this.events.once(r,s)}),je(this,"off",(r,s)=>{this.events.off(r,s)}),je(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=qe(i,this.name)}get context(){return Qe(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 Rb(e);if(typeof e=="number")return Nb(e);const{message:i}=j("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(i)}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(at.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:i}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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 i=this.expirations.get(e);if(!i){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return i}checkExpiry(e,i){const{expiry:r}=i;L.toMiliseconds(r)-Date.now()<=0&&this.expire(e,i)}expire(e,i){this.expirations.delete(e),this.events.emit(at.expired,{target:e,expiration:i})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,i)=>this.checkExpiry(i,e))}registerEventListeners(){this.core.heartbeat.on(Li.pulse,()=>this.checkExpirations()),this.events.on(at.created,e=>{const i=at.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(at.expired,e=>{const i=at.expired;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(at.deleted,e=>{const i=at.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var Q$=Object.defineProperty,X$=(t,e,i)=>e in t?Q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ge=(t,e,i)=>X$(t,typeof e!="symbol"?e+"":e,i);class eS extends i_{constructor(e,i,r){super(e,i,r),this.core=e,this.logger=i,this.store=r,ge(this,"name",X_),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",tx),ge(this,"storagePrefix",kt),ge(this,"version",Gf),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async s=>{if(!_r()||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 h=Fi(),u=this.startAbortTimer(L.ONE_SECOND*5),l=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",y),h.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const g=h.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",f,{signal:this.abortController.signal});const y=v=>{if(v.data&&typeof v.data=="string")try{const E=JSON.parse(v.data);if(E.type==="verify_attestation"){if(Ko(E.attestation).payload.id!==o)return;clearInterval(u),h.body.removeChild(g),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",y),d(E.attestation===null?"":E.attestation)}}catch(E){this.logger.warn(E)}};h.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",l),l}catch(h){this.logger.warn(h)}return""}),ge(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(Ko(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),ge(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(L.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}),ge(this,"getVerifyUrl",s=>{let n=s||is;return ix.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${is}`),n=is),n}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(L.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)}}),ge(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(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")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(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}),ge(this,"validateAttestation",(s,n)=>{const o=OE(s,n.publicKey),a={hasExpired:L.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=qe(i,this.name),this.abortController=new AbortController,this.isDevEnv=La(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var tS=Object.defineProperty,iS=(t,e,i)=>e in t?tS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ku=(t,e,i)=>iS(t,typeof e!="symbol"?e+"":e,i);class rS extends r_{constructor(e,i){super(e,i),this.projectId=e,this.logger=i,ku(this,"context",rx),ku(this,"registerDeviceToken",async r=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${sx}/${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=qe(i,this.context)}}var sS=Object.defineProperty,ju=Object.getOwnPropertySymbols,nS=Object.prototype.hasOwnProperty,oS=Object.prototype.propertyIsEnumerable,wa=(t,e,i)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,qr=(t,e)=>{for(var i in e||(e={}))nS.call(e,i)&&wa(t,i,e[i]);if(ju)for(var i of ju(e))oS.call(e,i)&&wa(t,i,e[i]);return t},ve=(t,e,i)=>wa(t,typeof e!="symbol"?e+"":e,i);class aS extends s_{constructor(e,i,r=!0){super(e,i,r),this.core=e,this.logger=i,ve(this,"context",ox),ve(this,"storagePrefix",kt),ve(this,"storageVersion",nx),ve(this,"events",new Map),ve(this,"shouldPersist",!1),ve(this,"init",async()=>{if(!La())try{const s={eventId:lh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ld(this.core.relayer.protocol,this.core.relayer.version,ha)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),ve(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,h=lh(),u=this.core.projectId||"",l=Date.now(),d=qr({eventId:h,timestamp:l,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,d),this.shouldPersist=!0),d}),ve(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 qr(qr({},a),this.setMethods(a.eventId))}),ve(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),ve(this,"setEventListeners",()=>{this.core.heartbeat.on(Li.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(s.timestamp)>ax&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),ve(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),ve(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)}),ve(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)}),ve(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ve(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,qr(qr({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),ve(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)}}),ve(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${cx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ha}${n}`,{method:"POST",body:JSON.stringify(s)})}),ve(this,"getAppDomain",()=>jd().url),this.logger=qe(i,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var cS=Object.defineProperty,Lu=Object.getOwnPropertySymbols,hS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,ma=(t,e,i)=>e in t?cS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Mu=(t,e)=>{for(var i in e||(e={}))hS.call(e,i)&&ma(t,i,e[i]);if(Lu)for(var i of Lu(e))uS.call(e,i)&&ma(t,i,e[i]);return t},ce=(t,e,i)=>ma(t,typeof e!="symbol"?e+"":e,i);let lS=class hp extends VI{constructor(e){var i;super(e),ce(this,"protocol",Wf),ce(this,"version",Gf),ce(this,"name",bn),ce(this,"relayUrl"),ce(this,"projectId"),ce(this,"customStoragePrefix"),ce(this,"events",new gt.EventEmitter),ce(this,"logger"),ce(this,"heartbeat"),ce(this,"relayer"),ce(this,"crypto"),ce(this,"storage"),ce(this,"history"),ce(this,"expirer"),ce(this,"pairing"),ce(this,"verify"),ce(this,"echoClient"),ce(this,"linkModeSupportedApps"),ce(this,"eventClient"),ce(this,"initialized",!1),ce(this,"logChunkController"),ce(this,"on",(a,c)=>this.events.on(a,c)),ce(this,"once",(a,c)=>this.events.once(a,c)),ce(this,"off",(a,c)=>this.events.off(a,c)),ce(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ce(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:h})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}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)||Jf,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Un({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:O_.logger,name:bn}),{logger:n,chunkLoggerController:o}=qI({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(i=this.logChunkController)!=null&&i.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=qe(n,this.name),this.heartbeat=new R3,this.crypto=new k8(this,this.logger,e==null?void 0:e.keychain),this.history=new G$(this,this.logger),this.expirer=new Z$(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new pI(Mu(Mu({},C_),e==null?void 0:e.storageOptions)),this.relayer=new l$({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new V$(this,this.logger),this.verify=new eS(this,this.logger,this.storage),this.echoClient=new rS(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new aS(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new hp(e);await i.initialize();const r=await i.crypto.getClientId();return await i.storage.setItem(H_,r),i}get context(){return Qe(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(vu,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(vu)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${e}`,r=`${i}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[i]}catch(i){console.warn("Failed to get global WalletConnect core",i);return}}setGlobalCore(e){var i;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((i=e.opts)==null?void 0:i.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof lt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const dS=lS,up="wc",lp=2,dp="client",rc=`${up}@${lp}:${dp}:`,$o={name:dp,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},qu="WALLETCONNECT_DEEPLINK_CHOICE",fS="proposal",zu="Proposal expired",pS="session",er=L.SEVEN_DAYS,gS="engine",Ee={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},So={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},Ot={idle:"IDLE",active:"ACTIVE"},yS={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:""}},wS="request",mS=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],bS="wc",vS="auth",ES="authKeys",IS="pairingTopics",_S="requests",Mn=`${bS}@${1.5}:${vS}:`,rn=`${Mn}:PUB_KEY`;var xS=Object.defineProperty,$S=Object.defineProperties,SS=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,DS=Object.prototype.hasOwnProperty,AS=Object.prototype.propertyIsEnumerable,ba=(t,e,i)=>e in t?xS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ue=(t,e)=>{for(var i in e||(e={}))DS.call(e,i)&&ba(t,i,e[i]);if(Hu)for(var i of Hu(e))AS.call(e,i)&&ba(t,i,e[i]);return t},Ve=(t,e)=>$S(t,SS(e)),F=(t,e,i)=>ba(t,typeof e!="symbol"?e+"":e,i);class PS extends c_{constructor(e){super(e),F(this,"name",gS),F(this,"events",new xa),F(this,"initialized",!1),F(this,"requestQueue",{state:Ot.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Ot.idle,queue:[]}),F(this,"emittedSessionRequests",new Hb({limit:500})),F(this,"requestQueueDelay",L.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(Ee)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Ve(ue({},i),{requiredNamespaces:i.requiredNamespaces||{},optionalNamespaces:i.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=KE(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=r;let u=s,l,d=!1;try{if(u){const k=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=k.active}}catch(k){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),k}if(!u||!d){const{topic:k,uri:B}=await this.client.core.pairing.create();u=k,l=B}if(!u){const{message:k}=j("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(k)}const p=await this.client.core.crypto.generateKeyPair(),f=Ee.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,g=me(f),y=Ve(ue(ue({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Yf}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Tt()}),v=oe("session_connect",y.id),{reject:E,resolve:m,done:A}=_i(f,zu),$=({id:k})=>{k===y.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(y.id),this.events.emit(v,{error:{message:zu,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(v,({error:k,session:B})=>{this.client.events.off("proposal_expire",$),k?E(k):B&&m(B)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:l,approval:A}}),F(this,"pair",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(i)}catch(r){throw this.client.logger.error("pair() failed"),r}}),F(this,"approve",async i=>{var r,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=i==null?void 0:i.id)==null?void 0:r.toString(),trace:[vt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(w){throw o.setError(Ei.no_internet_connection),w}try{await this.isValidProposalId(i==null?void 0:i.id)}catch(w){throw this.client.logger.error(`approve() -> proposal.get(${i==null?void 0:i.id}) failed`),o.setError(Ei.proposal_not_found),w}try{await this.isValidApprove(i)}catch(w){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ei.session_approve_namespace_validation_failure),w}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:u,scopedProperties:l,sessionConfig:d}=i,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:y,optionalNamespaces:v}=p;let E=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:f});E||(E=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:vt.session_approve_started,properties:{topic:f,trace:[vt.session_approve_started,vt.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),A=g.publicKey,$=await this.client.core.crypto.generateSharedKey(m,A),k=ue(ue(ue({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:m,metadata:this.client.metadata},expiry:me(er)},u&&{sessionProperties:u}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),B=le.relay;E.addTrace(vt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:B})}catch(w){throw E.setError(Ei.subscribe_session_topic_failure),w}E.addTrace(vt.subscribe_session_topic_success);const T=Ve(ue({},k),{topic:$,requiredNamespaces:y,optionalNamespaces:v,pairingTopic:f,acknowledged:!1,self:k.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:le.relay});await this.client.session.set($,T),E.addTrace(vt.store_session);try{E.addTrace(vt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:k,throwOnFailedPublish:!0}).catch(w=>{throw E==null||E.setError(Ei.session_settle_publish_failure),w}),E.addTrace(vt.session_settle_publish_success),E.addTrace(vt.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:m},throwOnFailedPublish:!0}).catch(w=>{throw E==null||E.setError(Ei.session_approve_publish_failure),w}),E.addTrace(vt.session_approve_publish_success)}catch(w){throw this.client.logger.error(w),this.client.session.delete($,de("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),w}return this.client.core.eventClient.deleteEvent({eventId:E.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,me(er)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),F(this,"reject",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(i)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:s}=i;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&await this.sendError({id:r,topic:n,error:s,rpcOpts:Ee.wc_sessionPropose.reject}),await this.deleteProposal(r)}),F(this,"update",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(i)}catch(l){throw this.client.logger.error("update() -> isValidUpdate() failed"),l}const{topic:r,namespaces:s}=i,{done:n,resolve:o,reject:a}=_i(),c=Tt(),h=Ti().toString(),u=this.client.session.get(r).namespaces;return this.events.once(oe("session_update",c),({error:l})=>{l?a(l):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(l=>{this.client.logger.error(l),this.client.session.update(r,{namespaces:u}),a(l)}),{acknowledged:n}}),F(this,"extend",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(i)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=i,s=Tt(),{done:n,resolve:o,reject:a}=_i();return this.events.once(oe("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,me(er)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),F(this,"request",async i=>{this.isInitialized();try{await this.isValidRequest(i)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:s,topic:n,expiry:o=Ee.wc_sessionRequest.req.ttl}=i,a=this.client.session.get(n);(a==null?void 0:a.transportType)===le.relay&&await this.confirmOnlineStateOrThrow();const c=Tt(),h=Ti().toString(),{done:u,resolve:l,reject:d}=_i(o,"Request expired. Please try again.");this.events.once(oe("session_request",c),({error:y,result:v})=>{y?d(y):l(v)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:p,params:{request:Ve(ue({},s),{expiryTimestamp:me(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),await u();const g={request:Ve(ue({},s),{expiryTimestamp:me(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(v=>d(v)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),y()}),new Promise(async y=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const E=await jb(this.client.core.storage,qu);await Ub({id:c,topic:n,wcDeepLink:E})}y()}),u()]).then(y=>y[2])}),F(this,"respond",async i=>{this.isInitialized(),await this.isValidRespond(i);const{topic:r,response:s}=i,{id:n}=s,o=this.client.session.get(r);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Ft(s)?await this.sendResult({id:n,topic:r,result:s.result,throwOnFailedPublish:!0,appLink:a}):ct(s)&&await this.sendError({id:n,topic:r,error:s.error,appLink:a}),this.cleanupAfterResponse(i)}),F(this,"ping",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(i)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=i;if(this.client.session.keys.includes(r)){const s=Tt(),n=Ti().toString(),{done:o,resolve:a,reject:c}=_i();this.events.once(oe("session_ping",s),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),F(this,"emit",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(i);const{topic:r,event:s,chainId:n}=i,o=Ti().toString(),a=Tt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(i);const{topic:r}=i;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:de("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=j("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),F(this,"find",i=>(this.isInitialized(),this.client.session.getAll().filter(r=>YE(r,i)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(i,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(i);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((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:h,domain:u,nonce:l,type:d,exp:p,nbf:f,methods:g=[],expiry:y}=i,v=[...i.resources||[]],{topic:E,uri:m}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:E,uri:m}});const A=await this.client.core.crypto.generateKeyPair(),$=Qs(A);if(await Promise.all([this.client.auth.authKeys.set(rn,{responseTopic:$,publicKey:A}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:E})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${E}`),g.length>0){const{namespace:S}=yr(a[0]);let R=t2(S,"request",g);Zs(v)&&(R=r2(R,v.pop())),v.push(R)}const k=y&&y>Ee.wc_sessionAuthenticate.req.ttl?y:Ee.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:d??"caip122",chains:a,statement:c,aud:h,domain:u,version:"1",nonce:l,iat:new Date().toISOString(),exp:p,nbf:f,resources:v},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:me(k)},T={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},w={requiredNamespaces:{},optionalNamespaces:T,relays:[{protocol:"irn"}],pairingTopic:E,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:me(Ee.wc_sessionPropose.req.ttl),id:Tt()},{done:O,resolve:_,reject:D}=_i(k,"Request expired"),C=Tt(),U=oe("session_connect",w.id),I=oe("session_request",C),b=async({error:S,session:R})=>{this.events.off(I,x),S?D(S):R&&_({session:R})},x=async S=>{var R,N,q;if(await this.deletePendingAuthRequest(C,{message:"fulfilled",code:0}),S.error){const J=de("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===J.code?void 0:(this.events.off(U,b),D(S.error.message))}await this.deleteProposal(w.id),this.events.off(U,b);const{cacaos:z,responder:H}=S.result,V=[],W=[];for(const J of z){await Ih({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),D(de("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:fe}=J,$e=Zs(fe.resources),mi=[Jo(fe.iss)],$s=dn(fe.iss);if($e){const Hi=_h($e),zn=xh($e);V.push(...Hi),mi.push(...zn)}for(const Hi of mi)W.push(`${Hi}:${$s}`)}const ne=await this.client.core.crypto.generateSharedKey(A,H.publicKey);let se;V.length>0&&(se={topic:ne,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:H,controller:H.publicKey,expiry:me(er),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:E,namespaces:Gh([...new Set(V)],[...new Set(W)]),transportType:o},await this.client.core.relayer.subscribe(ne,{transportType:o}),await this.client.session.set(ne,se),E&&await this.client.core.pairing.updateMetadata({topic:E,metadata:H.metadata}),se=this.client.session.get(ne)),(R=this.client.metadata.redirect)!=null&&R.linkMode&&(N=H.metadata.redirect)!=null&&N.linkMode&&(q=H.metadata.redirect)!=null&&q.universal&&r&&(this.client.core.addLinkModeSupportedApp(H.metadata.redirect.universal),this.client.session.update(ne,{transportType:le.link_mode})),_({auths:z,session:se})};this.events.once(U,b),this.events.once(I,x);let P;try{if(n){const S=pi("wc_sessionAuthenticate",B,C);this.client.core.history.set(E,S);const R=await this.client.core.crypto.encode("",S,{type:vs,encoding:di});P=js(r,E,R)}else await Promise.all([this.sendRequest({topic:E,method:"wc_sessionAuthenticate",params:B,expiry:i.expiry,throwOnFailedPublish:!0,clientRpcId:C}),this.sendRequest({topic:E,method:"wc_sessionPropose",params:w,expiry:Ee.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:w.id})])}catch(S){throw this.events.off(U,b),this.events.off(I,x),S}return await this.setProposal(w.id,w),await this.setAuthRequest(C,{request:Ve(ue({},B),{verifyContext:{}}),pairingTopic:E,transportType:o}),{uri:P??m,response:O}}),F(this,"approveSessionAuthenticate",async i=>{const{id:r,auths:s}=i,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Ii.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(Lr.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(Lr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),u=Qs(c),l={type:Gt,receiverPublicKey:c,senderPublicKey:h},d=[],p=[];for(const y of s){if(!await Ih({cacao:y,projectId:this.client.core.projectId})){n.setError(Lr.invalid_cacao);const $=de("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:$,encodeOpts:l}),new Error($.message)}n.addTrace(Ii.cacaos_verified);const{p:v}=y,E=Zs(v.resources),m=[Jo(v.iss)],A=dn(v.iss);if(E){const $=_h(E),k=xh(E);d.push(...$),m.push(...k)}for(const $ of m)p.push(`${$}:${A}`)}const f=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Ii.create_authenticated_session_topic);let g;if((d==null?void 0:d.length)>0){g={topic:f,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(er),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Gh([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(Ii.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(y){throw n.setError(Lr.subscribe_authenticated_session_topic_failure),y}n.addTrace(Ii.subscribe_authenticated_session_topic_success),await this.client.session.set(f,g),n.addTrace(Ii.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ii.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(Lr.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:g}}),F(this,"rejectSessionAuthenticate",async i=>{this.isInitialized();const{id:r,reason:s}=i,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Qs(o),h={type:Gt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:h,rpcOpts:Ee.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),F(this,"formatAuthMessage",i=>{this.isInitialized();const{request:r,iss:s}=i;return sf(r,s)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const i=this.relayMessageCache.shift();i&&await this.onRelayMessage(i)}catch(i){this.client.logger.error(i)}},50)}),F(this,"cleanupDuplicatePairings",async i=>{if(i.pairingTopic)try{const r=this.client.core.pairing.pairings.get(i.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)===i.peer.metadata.url&&n.topic&&n.topic!==r.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(r){this.client.logger.error(r)}}),F(this,"deleteSession",async i=>{var r;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=i,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,de("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(qu).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===s&&this.deletePendingSessionRequest(h.id,de("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Ot.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),F(this,"deleteProposal",async(i,r)=>{if(r)try{const s=this.client.proposal.get(i),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Ei.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(i,de("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"proposal")}),F(this,"deletePendingSessionRequest",async(i,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(i,r),s?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==i),s&&(this.sessionRequestQueue.state=Ot.idle,this.client.events.emit("session_request_expire",{id:i}))}),F(this,"deletePendingAuthRequest",async(i,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(i,r),s?Promise.resolve():this.client.core.expirer.del(i)])}),F(this,"setExpiry",async(i,r)=>{this.client.session.keys.includes(i)&&(this.client.core.expirer.set(i,r),await this.client.session.update(i,{expiry:r}))}),F(this,"setProposal",async(i,r)=>{this.client.core.expirer.set(i,me(Ee.wc_sessionPropose.req.ttl)),await this.client.proposal.set(i,r)}),F(this,"setAuthRequest",async(i,r)=>{const{request:s,pairingTopic:n,transportType:o=le.relay}=r;this.client.core.expirer.set(i,s.expiryTimestamp),await this.client.auth.requests.set(i,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:i,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async i=>{const{id:r,topic:s,params:n,verifyContext:o}=i,a=n.request.expiryTimestamp||me(Ee.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:n,verifyContext:o})}),F(this,"sendRequest",async i=>{const{topic:r,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:u,tvf:l}=i,d=pi(s,n,c);let p;const f=!!u;try{const v=f?di:xt;p=await this.client.core.crypto.encode(r,d,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),v}let g;if(mS.includes(s)){const v=Rt(JSON.stringify(d)),E=Rt(p);g=await this.client.core.verify.register({id:E,decryptedId:v})}const y=Ee[s].req;if(y.attestation=g,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(r,d),f){const v=js(u,r,p);await K.Linking.openURL(v,this.client.name)}else{const v=Ee[s].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Ve(ue({},l),{correlationId:d.id}),h?(v.internal=Ve(ue({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,v)):this.client.core.relayer.publish(r,p,v).catch(E=>this.client.logger.error(E))}return d.id}),F(this,"sendResult",async i=>{const{id:r,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=i,h=Bn(r,n);let u;const l=c&&typeof(K==null?void 0:K.Linking)<"u";try{const f=l?di:xt;u=await this.client.core.crypto.encode(s,h,Ve(ue({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),f}let d,p;try{d=await this.client.core.history.get(s,r);const f=d.request;try{p=this.getTVFParams(r,f.params,n)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),f}if(l){const f=js(c,s,u);await K.Linking.openURL(f,this.client.name)}else{const f=d.request.method,g=Ee[f].res;g.tvf=Ve(ue({},p),{correlationId:r}),o?(g.internal=Ve(ue({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(h)}),F(this,"sendError",async i=>{const{id:r,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=i,h=kn(r,n);let u;const l=c&&typeof(K==null?void 0:K.Linking)<"u";try{const p=l?di:xt;u=await this.client.core.crypto.encode(s,h,Ve(ue({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let d;try{d=await this.client.core.history.get(s,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),p}if(l){const p=js(c,s,u);await K.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||Ee[p].res;this.client.core.relayer.publish(s,u,f)}await this.client.core.history.resolve(h)}),F(this,"cleanup",async()=>{const i=[],r=[];this.client.session.getAll().forEach(s=>{let n=!1;ci(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&i.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{ci(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...i.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])}),F(this,"onProviderMessageEvent",async i=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(i):await this.onRelayMessage(i)}),F(this,"onRelayEventRequest",async i=>{this.requestQueue.queue.push(i),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ot.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=Ot.active;const i=this.requestQueue.queue.shift();if(i)try{await this.processRequest(i)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Ot.idle}),F(this,"processRequest",async i=>{const{topic:r,payload:s,attestation:n,transportType:o,encryptedId:a}=i,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async i=>{const{topic:r,payload:s,transportType:n}=i,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",i=>{const{topic:r}=i,{message:s}=j("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),F(this,"shouldIgnorePairingRequest",i=>{const{topic:r,requestMethod:s}=i,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async i=>{const{topic:r,payload:s,attestation:n,encryptedId:o}=i,{params:a,id:c}=s;try{const h=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h==null||h.setError(Kt.proposal_listener_not_found)),this.isValidConnect(ue({},s.params));const u=a.expiryTimestamp||me(Ee.wc_sessionPropose.req.ttl),l=ue({id:c,pairingTopic:r,expiryTimestamp:u,attestation:n,encryptedId:o},a);await this.setProposal(c,l);const d=await this.getVerifyContext({attestationId:n,hash:Rt(JSON.stringify(s)),encryptedId:o,metadata:l.proposer.metadata});h==null||h.addTrace(Ct.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:l,verifyContext:d})}catch(h){await this.sendError({id:c,topic:r,error:h,rpcOpts:Ee.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),F(this,"onSessionProposeResponse",async(i,r,s)=>{const{id:n}=r;if(Ft(r)){const{result:o}=r;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 h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const u=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:i,proposalId:n,publicKey:c});const l=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:i})}else if(ct(r)){await this.deleteProposal(n);const o=oe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),F(this,"onSessionSettleRequest",async(i,r)=>{const{id:s,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:u,scopedProperties:l,sessionConfig:d}=r.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===i);if(!p)return this.client.logger.error(`Pending session not found for topic ${i}`);const f=this.client.proposal.get(p.proposalId),g=Ve(ue(ue(ue({topic:i,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),{transportType:le.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(oe("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:i,result:!0})}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(i,r)=>{const{id:s}=r;Ft(r)?(await this.client.session.update(i,{acknowledged:!0}),this.events.emit(oe("session_approve",s),{})):ct(r)&&(await this.client.session.delete(i,de("USER_DISCONNECTED")),this.events.emit(oe("session_approve",s),{error:r.error}))}),F(this,"onSessionUpdateRequest",async(i,r)=>{const{params:s,id:n}=r;try{const o=`${i}_session_update`,a=kr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:i,error:de("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ue({topic:i},s));try{kr.set(o,n),await this.client.session.update(i,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:i,result:!0})}catch(c){throw kr.delete(o),c}this.client.events.emit("session_update",{id:n,topic:i,params:s})}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(i,r)=>r.toString().slice(0,-3)<i.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(i,r)=>{const{id:s}=r,n=oe("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ft(r)?this.events.emit(oe("session_update",s),{}):ct(r)&&this.events.emit(oe("session_update",s),{error:r.error})}),F(this,"onSessionExtendRequest",async(i,r)=>{const{id:s}=r;try{this.isValidExtend({topic:i}),await this.setExpiry(i,me(er)),await this.sendResult({id:s,topic:i,result:!0}),this.client.events.emit("session_extend",{id:s,topic:i})}catch(n){await this.sendError({id:s,topic:i,error:n}),this.client.logger.error(n)}}),F(this,"onSessionExtendResponse",(i,r)=>{const{id:s}=r,n=oe("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ft(r)?this.events.emit(oe("session_extend",s),{}):ct(r)&&this.events.emit(oe("session_extend",s),{error:r.error})}),F(this,"onSessionPingRequest",async(i,r)=>{const{id:s}=r;try{this.isValidPing({topic:i}),await this.sendResult({id:s,topic:i,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:i})}catch(n){await this.sendError({id:s,topic:i,error:n}),this.client.logger.error(n)}}),F(this,"onSessionPingResponse",(i,r)=>{const{id:s}=r,n=oe("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);Ft(r)?this.events.emit(oe("session_ping",s),{}):ct(r)&&this.events.emit(oe("session_ping",s),{error:r.error})},500)}),F(this,"onSessionDeleteRequest",async(i,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:i,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(_e.publish,async()=>{n(await this.deleteSession({topic:i,id:s}))})}),this.sendResult({id:s,topic:i,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:i,error:de("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),F(this,"onSessionRequest",async i=>{var r,s,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:u}=i,{id:l,params:d}=a;try{await this.isValidRequest(ue({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:Rt(JSON.stringify(pi("wc_sessionRequest",d,l))),encryptedId:h,metadata:p.peer.metadata,transportType:u}),g={id:l,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(g),u===le.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:l,topic:o,error:p}),this.client.logger.error(p)}}),F(this,"onSessionRequestResponse",(i,r)=>{const{id:s}=r,n=oe("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Ft(r)?this.events.emit(oe("session_request",s),{result:r.result}):ct(r)&&this.events.emit(oe("session_request",s),{error:r.error})}),F(this,"onSessionEventRequest",async(i,r)=>{const{id:s,params:n}=r;try{const o=`${i}_session_event_${n.event.name}`,a=kr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(ue({topic:i},n)),this.client.events.emit("session_event",{id:s,topic:i,params:n}),kr.set(o,s)}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(i,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:i,payload:r}),Ft(r)?this.events.emit(oe("session_request",s),{result:r.result}):ct(r)&&this.events.emit(oe("session_request",s),{error:r.error})}),F(this,"onSessionAuthenticateRequest",async i=>{var r;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=i;try{const{requester:h,authPayload:u,expiryTimestamp:l}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Rt(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),p={requester:h,pairingTopic:s,id:n.id,authPayload:u,verifyContext:d,expiryTimestamp:l};await this.setAuthRequest(n.id,{request:p,pairingTopic:s,transportType:c}),c===le.link_mode&&(r=h.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(h){this.client.logger.error(h);const u=n.params.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:Gt,receiverPublicKey:u,senderPublicKey:l};await this.sendError({id:n.id,topic:s,error:h,encodeOpts:p,rpcOpts:Ee.wc_sessionAuthenticate.autoReject,appLink:d})}}),F(this,"addSessionRequestToSessionRequestQueue",i=>{this.sessionRequestQueue.queue.push(i)}),F(this,"cleanupAfterResponse",i=>{this.deletePendingSessionRequest(i.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ot.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:i,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===i&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=oe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(oe("session_request",n.request.id),{error:r})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ot.active){this.client.logger.info("session request queue is already active.");return}const i=this.sessionRequestQueue.queue[0];if(!i){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(i)}catch(r){this.client.logger.error(r)}}),F(this,"emitSessionRequest",i=>{if(this.emittedSessionRequests.has(i.id)){this.client.logger.warn({id:i.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);return}this.sessionRequestQueue.state=Ot.active,this.emittedSessionRequests.add(i.id),this.client.events.emit("session_request",i)}),F(this,"onPairingCreated",i=>{if(i.methods&&this.expectedPairingMethodMap.set(i.topic,i.methods),i.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===i.topic);r&&this.onSessionProposeRequest({topic:i.topic,payload:pi("wc_sessionPropose",Ve(ue({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),F(this,"isValidConnect",async i=>{if(!We(i)){const{message:h}=j("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(i)}`);throw new Error(h)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=i;if(Oe(r)||await this.isValidPairingTopic(r),!a3(c,!0)){const{message:h}=j("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!Oe(s)&&Ut(s)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(s,"requiredNamespaces")}if(!Oe(n)&&Ut(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>h.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(h)}`)}}),F(this,"validateNamespaces",(i,r)=>{const s=o3(i,"connect()",r);if(s)throw new Error(s.message)}),F(this,"isValidApprove",async i=>{if(!We(i))throw new Error(j("MISSING_OR_INVALID",`approve() params: ${i}`).message);const{id:r,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=i;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),h=yo(s,"approve()");if(h)throw new Error(h.message);const u=Zh(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!ye(n,!0)){const{message:l}=j("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(l)}if(Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const l=new Set(Object.keys(s));if(!Object.keys(a).every(d=>l.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(l).join(", ")}`)}}),F(this,"isValidReject",async i=>{if(!We(i)){const{message:n}=j("MISSING_OR_INVALID",`reject() params: ${i}`);throw new Error(n)}const{id:r,reason:s}=i;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!h3(s)){const{message:n}=j("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),F(this,"isValidSessionSettleRequest",i=>{if(!We(i)){const{message:h}=j("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${i}`);throw new Error(h)}const{relay:r,controller:s,namespaces:n,expiry:o}=i;if(!Nf(r)){const{message:h}=j("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=e3(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=yo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ci(o)){const{message:h}=j("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),F(this,"isValidUpdate",async i=>{if(!We(i)){const{message:c}=j("MISSING_OR_INVALID",`update() params: ${i}`);throw new Error(c)}const{topic:r,namespaces:s}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=yo(s,"update()");if(o)throw new Error(o.message);const a=Zh(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async i=>{if(!We(i)){const{message:s}=j("MISSING_OR_INVALID",`extend() params: ${i}`);throw new Error(s)}const{topic:r}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),F(this,"isValidRequest",async i=>{if(!We(i)){const{message:c}=j("MISSING_OR_INVALID",`request() params: ${i}`);throw new Error(c)}const{topic:r,request:s,chainId:n,expiry:o}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Jh(a,n)){const{message:c}=j("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!u3(s)){const{message:c}=j("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!f3(a,n,s.method)){const{message:c}=j("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!w3(o,So)){const{message:c}=j("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${So.min} and ${So.max}`);throw new Error(c)}}),F(this,"isValidRespond",async i=>{var r;if(!We(i)){const{message:o}=j("MISSING_OR_INVALID",`respond() params: ${i}`);throw new Error(o)}const{topic:s,response:n}=i;try{await this.isValidSessionTopic(s)}catch(o){throw(r=i==null?void 0:i.response)!=null&&r.id&&this.cleanupAfterResponse(i),o}if(!l3(n)){const{message:o}=j("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),F(this,"isValidPing",async i=>{if(!We(i)){const{message:s}=j("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidEmit",async i=>{if(!We(i)){const{message:a}=j("MISSING_OR_INVALID",`emit() params: ${i}`);throw new Error(a)}const{topic:r,event:s,chainId:n}=i;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Jh(o,n)){const{message:a}=j("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!d3(s)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!p3(o,n,s.name)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async i=>{if(!We(i)){const{message:s}=j("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidAuthenticate",i=>{const{chains:r,uri:s,domain:n,nonce:o}=i;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ye(s,!1))throw new Error("uri is required parameter");if(!ye(n,!1))throw new Error("domain is required parameter");if(!ye(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>yr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=yr(r[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 i=>{const{attestationId:r,hash:s,encryptedId:n,metadata:o,transportType:a}=i,c={verified:{verifyUrl:o.verifyUrl||is,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 h=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(i,r)=>{Object.values(i).forEach((s,n)=>{if(s==null){const{message:o}=j("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(i)[n]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",i=>{const r=this.client.auth.requests.get(i);return typeof r=="object"?r:void 0}),F(this,"addToRecentlyDeleted",(i,r)=>{if(this.recentlyDeletedMap.set(i,r),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",i=>{const r=this.recentlyDeletedMap.get(i);if(r){const{message:s}=j("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${i}`);throw new Error(s)}}),F(this,"isLinkModeEnabled",(i,r)=>{var s,n,o,a,c,h,u,l,d;return!i||r!==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&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((u=i==null?void 0:i.redirect)==null?void 0:u.universal)!==void 0&&((l=i==null?void 0:i.redirect)==null?void 0:l.universal)!==""&&((d=i==null?void 0:i.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(i.redirect.universal)&&typeof(K==null?void 0:K.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(i,r)=>{var s;return this.isLinkModeEnabled(i,r)?(s=i==null?void 0:i.redirect)==null?void 0:s.universal:void 0}),F(this,"handleLinkModeMessage",({url:i})=>{if(!i||!i.includes("wc_ev")||!i.includes("topic"))return;const r=uh(i,"topic")||"",s=decodeURIComponent(uh(i,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:n})}),F(this,"registerLinkModeListeners",async()=>{var i;if(La()||wi()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const r=K==null?void 0:K.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),F(this,"getTVFParams",(i,r,s)=>{var n,o,a;if(!((n=r.request)!=null&&n.method))return{};const c={correlationId:i,rpcMethods:[r.request.method],chainId:r.chainId};try{const h=this.extractTxHashesFromResult(r.request,s);c.txHashes=h,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(h){this.client.logger.warn("Error getting TVF params",h)}return c}),F(this,"isValidContractData",i=>{var r;if(!i)return!1;try{const s=(i==null?void 0:i.data)||((r=i==null?void 0:i[0])==null?void 0:r.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",(i,r)=>{var s;try{if(!r)return[];const n=i.method,o=yS[n];if(n==="sui_signTransaction")return[jv(r.transactionBytes)];if(n==="near_signTransaction")return[mh(r)];if(n==="near_signTransactions")return r.map(c=>mh(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=r.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[T3({transaction:i.params.transactionPayload,signature:r.signature})];if(n==="algo_signTxn")return dt(r)?r.map(c=>bh(c)):[bh(r)];if(n==="cosmos_signDirect")return[Mv(r)];if(typeof r=="string")return[r];const a=r[o.key];if(dt(a))return n==="solana_signAllTransactions"?a.map(c=>kv(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn("Error extracting tx hashes from result",n)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,i=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,s]of Object.entries(i))for(const n of s)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(_e.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:i,message:r,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(rn)?this.client.auth.authKeys.get(rn):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(i,r,{receiverPublicKey:o,encoding:n===le.link_mode?di:xt});ic(a)?(this.client.core.history.set(i,a),await this.onRelayEventRequest({topic:i,payload:a,attestation:s,transportType:n,encryptedId:Rt(r)})):jn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:i,payload:a,transportType:n}),this.client.core.history.delete(i,a.id)):await this.onRelayEventUnknownPayload({topic:i,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(i,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(at.expired,async e=>{const{topic:i,id:r}=qd(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,j("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,j("EXPIRED"),!0);i?this.client.session.keys.includes(i)&&(await this.deleteSession({topic:i,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:i})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Si.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Si.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ye(e,!1)){const{message:i}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(i)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:i}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(i)}if(ci(this.client.core.pairing.pairings.get(e).expiry)){const{message:i}=j("EXPIRED",`pairing topic: ${e}`);throw new Error(i)}}async isValidSessionTopic(e){if(!ye(e,!1)){const{message:i}=j("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(i)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:i}=j("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(i)}if(ci(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:i}=j("EXPIRED",`session topic: ${e}`);throw new Error(i)}if(!this.client.core.crypto.keychain.has(e)){const{message:i}=j("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(i)}}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(ye(e,!1)){const{message:i}=j("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(i)}else{const{message:i}=j("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(i)}}async isValidProposalId(e){if(!c3(e)){const{message:i}=j("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(i)}if(!this.client.proposal.keys.includes(e)){const{message:i}=j("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(i)}if(ci(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:i}=j("EXPIRED",`proposal id: ${e}`);throw new Error(i)}}}class OS extends qi{constructor(e,i){super(e,i,fS,rc),this.core=e,this.logger=i}}let CS=class extends qi{constructor(e,i){super(e,i,pS,rc),this.core=e,this.logger=i}};class TS extends qi{constructor(e,i){super(e,i,wS,rc,r=>r.id),this.core=e,this.logger=i}}class FS extends qi{constructor(e,i){super(e,i,ES,Mn,()=>rn),this.core=e,this.logger=i}}class RS extends qi{constructor(e,i){super(e,i,IS,Mn),this.core=e,this.logger=i}}class NS extends qi{constructor(e,i){super(e,i,_S,Mn,r=>r.id),this.core=e,this.logger=i}}var US=Object.defineProperty,BS=(t,e,i)=>e in t?US(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Do=(t,e,i)=>BS(t,typeof e!="symbol"?e+"":e,i);class kS{constructor(e,i){this.core=e,this.logger=i,Do(this,"authKeys"),Do(this,"pairingTopics"),Do(this,"requests"),this.authKeys=new FS(this.core,this.logger),this.pairingTopics=new RS(this.core,this.logger),this.requests=new NS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var jS=Object.defineProperty,LS=(t,e,i)=>e in t?jS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Q=(t,e,i)=>LS(t,typeof e!="symbol"?e+"":e,i);let MS=class fp extends a_{constructor(e){super(e),Q(this,"protocol",up),Q(this,"version",lp),Q(this,"name",$o.name),Q(this,"metadata"),Q(this,"core"),Q(this,"logger"),Q(this,"events",new gt.EventEmitter),Q(this,"engine"),Q(this,"session"),Q(this,"proposal"),Q(this,"pendingRequest"),Q(this,"auth"),Q(this,"signConfig"),Q(this,"on",(r,s)=>this.events.on(r,s)),Q(this,"once",(r,s)=>this.events.once(r,s)),Q(this,"off",(r,s)=>this.events.off(r,s)),Q(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),Q(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),Q(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),Q(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(n){throw this.logger.error(n.message),n}}),Q(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||$o.name,this.metadata=Ob(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const i=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Is(Un({level:(e==null?void 0:e.logger)||$o.logger}));this.core=(e==null?void 0:e.core)||new dS(e),this.logger=qe(i,this.name),this.session=new CS(this.core,this.logger),this.proposal=new OS(this.core,this.logger),this.pendingRequest=new TS(this.core,this.logger),this.engine=new PS(this),this.auth=new kS(this.core,this.logger)}static async init(e){const i=new fp(e);return await i.initialize(),i}get context(){return Qe(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var qS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,Vu=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,KS=Object.prototype.propertyIsEnumerable,Ku=(t,e,i)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Wu=(t,e)=>{for(var i in e||(e={}))VS.call(e,i)&&Ku(t,i,e[i]);if(Vu)for(var i of Vu(e))KS.call(e,i)&&Ku(t,i,e[i]);return t},Gu=(t,e)=>zS(t,HS(e));const WS={Accept:"application/json","Content-Type":"application/json"},GS="POST",Yu={headers:WS,method:GS},Ju=10;let St=class{constructor(e,i=!1){if(this.url=e,this.disableProviderPing=i,this.events=new gt.EventEmitter,this.isAvailable=!1,this.registering=!1,!pu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}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 i=Yt(e),r=await(await fc(this.url,Gu(Wu({},Yu),{body:i}))).json();this.onPayload({data:r})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!pu(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,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"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const i=Yt({id:1,jsonrpc:"2.0",method:"test",params:[]});await fc(e,Gu(Wu({},Yu),{body:i}))}this.onOpen()}catch(i){const r=this.parseError(i);throw this.events.emit("register_error",r),this.onClose(),r}}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 i=typeof e.data=="string"?Ni(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),s=r.message||r.toString(),n=kn(e,s);this.events.emit("payload",n)}parseError(e,i=this.url){return zf(e,i,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Ju&&this.events.setMaxListeners(Ju)}};const Zu="error",YS="wss://relay.walletconnect.org",JS="wc",ZS="universal_provider",Hs=`${JS}@2:${ZS}:`,pp="https://rpc.walletconnect.org/v1/",fr="generic",QS=`${pp}bundler`,wt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function sc(t){return t==null||typeof t!="object"&&typeof t!="function"}function gp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function yp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XS="[object RegExp]",wp="[object String]",mp="[object Number]",bp="[object Boolean]",vp="[object Arguments]",eD="[object Symbol]",tD="[object Date]",iD="[object Map]",rD="[object Set]",sD="[object Array]",nD="[object ArrayBuffer]",oD="[object Object]",aD="[object DataView]",cD="[object Uint8Array]",hD="[object Uint8ClampedArray]",uD="[object Uint16Array]",lD="[object Uint32Array]",dD="[object Int8Array]",fD="[object Int16Array]",pD="[object Int32Array]",gD="[object Float32Array]",yD="[object Float64Array]";function nc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function wD(t,e){return gr(t,void 0,t,new Map,e)}function gr(t,e,i,r=new Map,s=void 0){const n=s==null?void 0:s(t,e,i,r);if(n!=null)return n;if(sc(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=gr(t[a],a,i,r,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;r.set(t,o);for(const[a,c]of t)o.set(a,gr(c,a,i,r,s));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(gr(a,void 0,i,r,s));return o}if(typeof X<"u"&&X.isBuffer(t))return t.subarray();if(nc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=gr(t[a],a,i,r,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 r.set(t,o),Di(o,t,i,r,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),Di(o,t,i,r,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Di(o,t,i,r,s),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Di(o,t,i,r,s),o}if(typeof t=="object"&&mD(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Di(o,t,i,r,s),o}return t}function Di(t,e,i=t,r,s){const n=[...Object.keys(e),...gp(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=gr(e[a],a,i,r,s))}}function mD(t){switch(yp(t)){case vp:case sD:case nD:case aD:case bp:case tD:case gD:case yD:case dD:case fD:case pD:case iD:case mp:case oD:case XS:case rD:case wp:case eD:case cD:case hD:case uD:case lD:return!0;default:return!1}}function bD(t,e){return wD(t,(i,r,s,n)=>{const o=e==null?void 0:e(i,r,s,n);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case mp:case wp:case bp:{const a=new t.constructor(t==null?void 0:t.valueOf());return Di(a,t),a}case vp:{const a={};return Di(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function Qu(t){return bD(t)}function Xu(t){return t!==null&&typeof t=="object"&&yp(t)==="[object Arguments]"}function el(t){return typeof t=="object"&&t!==null}function vD(){}function ED(t){return nc(t)}function ID(t){var i;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!((i=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&i.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function _D(t){if(sc(t))return t;if(Array.isArray(t)||nc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),i=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new i(t);if(t instanceof RegExp){const r=new i(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new i(t.buffer.slice(0));if(t instanceof Error){const r=new i(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new i([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function xD(t,...e){const i=e.slice(0,-1),r=e[e.length-1];let s=t;for(let n=0;n<i.length;n++){const o=i[n];s=va(s,o,r,new Map)}return s}function va(t,e,i,r){if(sc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return _D(r.get(e));if(r.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),...gp(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(Xu(a)&&(a={...a}),Xu(c)&&(c={...c}),typeof X<"u"&&X.isBuffer(a)&&(a=Qu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],l=Reflect.ownKeys(c);for(let d=0;d<l.length;d++){const p=l[d];u[p]=c[p]}c=u}else c=[];const h=i(c,a,o,t,e,r);h!=null?t[o]=h:Array.isArray(a)||el(c)&&el(a)?t[o]=va(c,a,i,r):c==null&&ID(a)?t[o]=va({},a,i,r):c==null&&ED(a)?t[o]=Qu(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function $D(t,...e){return xD(t,...e,vD)}var SD=Object.defineProperty,DD=Object.defineProperties,AD=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,PD=Object.prototype.hasOwnProperty,OD=Object.prototype.propertyIsEnumerable,il=(t,e,i)=>e in t?SD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Vs=(t,e)=>{for(var i in e||(e={}))PD.call(e,i)&&il(t,i,e[i]);if(tl)for(var i of tl(e))OD.call(e,i)&&il(t,i,e[i]);return t},CD=(t,e)=>DD(t,AD(e));function st(t,e,i){var r;const s=yr(t);return((r=e.rpcMap)==null?void 0:r[s.reference])||`${pp}?chainId=${s.namespace}:${s.reference}&projectId=${i}`}function zi(t){return t.includes(":")?t.split(":")[1]:t}function Ep(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function TD(t,e){const i=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!i.length)return[];const r=[];return i.forEach(s=>{const n=e.namespaces[s].accounts;r.push(...n)}),r}function Ks(t={},e={}){const i=rl(t),r=rl(e);return $D(i,r)}function rl(t){var e,i,r,s,n;const o={};if(!Ut(t))return o;for(const[a,c]of Object.entries(t)){const h=Rn(a)?[a]:c.chains,u=c.methods||[],l=c.events||[],d=c.rpcMap||{},p=pr(a);o[p]=CD(Vs(Vs({},o[p]),c),{chains:Nt(h,(e=o[p])==null?void 0:e.chains),methods:Nt(u,(i=o[p])==null?void 0:i.methods),events:Nt(l,(r=o[p])==null?void 0:r.events)}),(Ut(d)||Ut(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=Vs(Vs({},d),(n=o[p])==null?void 0:n.rpcMap))}return o}function sl(t){return t.includes(":")?t.split(":")[2]:t}function nl(t){const e={};for(const[i,r]of Object.entries(t)){const s=r.methods||[],n=r.events||[],o=r.accounts||[],a=Rn(i)?[i]:r.chains?r.chains:Ep(r.accounts);e[i]={chains:a,methods:s,events:n,accounts:o}}return e}function Ao(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const Ip={},re=t=>Ip[t],Po=(t,e)=>{Ip[t]=e};var FD=Object.defineProperty,ol=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,ND=Object.prototype.propertyIsEnumerable,al=(t,e,i)=>e in t?FD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,cl=(t,e)=>{for(var i in e||(e={}))RD.call(e,i)&&al(t,i,e[i]);if(ol)for(var i of ol(e))ND.call(e,i)&&al(t,i,e[i]);return t};const hl="eip155",UD=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],BD=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,Oo=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,ul=t=>Object.keys(t).filter(e=>UD.includes(e)).reduce((e,i)=>(e[i]=t[i],e),{}),kD=(t,e,i)=>{const{sessionProperties:r={},scopedProperties:s={}}=t,n={};if(!Ut(s)&&!Ut(r))return;const o=ul(r);for(const a of i){const c=BD(a);if(!c)continue;n[Oo(c)]=o;const h=s==null?void 0:s[`${hl}:${c}`];if(h){const u=h==null?void 0:h[`${hl}:${c}:${e}`];n[Oo(c)]=cl(cl({},n[Oo(c)]),ul(u||h))}}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 jD=Object.defineProperty,LD=(t,e,i)=>e in t?jD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,tr=(t,e,i)=>LD(t,typeof e!="symbol"?e+"":e,i);class MD{constructor(e){tr(this,"name","polkadot"),tr(this,"client"),tr(this,"httpProviders"),tr(this,"events"),tr(this,"namespace"),tr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=zi(i);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var qD=Object.defineProperty,zD=Object.defineProperties,HD=Object.getOwnPropertyDescriptors,ll=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,KD=Object.prototype.propertyIsEnumerable,Ea=(t,e,i)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,dl=(t,e)=>{for(var i in e||(e={}))VD.call(e,i)&&Ea(t,i,e[i]);if(ll)for(var i of ll(e))KD.call(e,i)&&Ea(t,i,e[i]);return t},fl=(t,e)=>zD(t,HD(e)),ir=(t,e,i)=>Ea(t,typeof e!="symbol"?e+"":e,i);class WD{constructor(e){ir(this,"name","eip155"),ir(this,"client"),ir(this,"chainId"),ir(this,"namespace"),ir(this,"httpProviders"),ir(this,"events"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(parseInt(e),i),this.chainId=parseInt(e),this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,i){const r=i||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=parseInt(zi(i));e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}async handleSwitchChain(e){var i,r;let s=e.request.params?(i=e.request.params[0])==null?void 0:i.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:(r=this.namespace.chains)==null?void 0:r[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 i,r,s,n,o;const a=(r=(i=e.request)==null?void 0:i.params)==null?void 0:r[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 h=this.client.session.get(e.topic),u=((o=h==null?void 0:h.sessionProperties)==null?void 0:o.capabilities)||{},l=`${a}${c.join(",")}`,d=u==null?void 0:u[l];if(d)return d;let p;try{p=kD(h,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(p)return p;const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:fl(dl({},h.sessionProperties||{}),{capabilities:fl(dl({},u||{}),{[l]:f})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return f}async getCallStatus(e){var i,r;const s=this.client.session.get(e.topic),n=(i=s.sessionProperties)==null?void 0:i.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,i){var r;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(pi("eth_getUserOperationReceipt",[(r=i.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,i){return`${QS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${i}`}}var GD=Object.defineProperty,YD=(t,e,i)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rr=(t,e,i)=>YD(t,typeof e!="symbol"?e+"":e,i);class JD{constructor(e){rr(this,"name","solana"),rr(this,"client"),rr(this,"httpProviders"),rr(this,"events"),rr(this,"namespace"),rr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=zi(i);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var ZD=Object.defineProperty,QD=(t,e,i)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,sr=(t,e,i)=>QD(t,typeof e!="symbol"?e+"":e,i);class XD{constructor(e){sr(this,"name","cosmos"),sr(this,"client"),sr(this,"httpProviders"),sr(this,"events"),sr(this,"namespace"),sr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=zi(i);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var e6=Object.defineProperty,t6=(t,e,i)=>e in t?e6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nr=(t,e,i)=>t6(t,typeof e!="symbol"?e+"":e,i);class i6{constructor(e){nr(this,"name","algorand"),nr(this,"client"),nr(this,"httpProviders"),nr(this,"events"),nr(this,"namespace"),nr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){if(!this.httpProviders[e]){const r=i||st(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new yt(new St(r,re("disableProviderPing")))}}var r6=Object.defineProperty,s6=(t,e,i)=>e in t?r6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,or=(t,e,i)=>s6(t,typeof e!="symbol"?e+"":e,i);class n6{constructor(e){or(this,"name","cip34"),or(this,"client"),or(this,"httpProviders"),or(this,"events"),or(this,"namespace"),or(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{const r=this.getCardanoRPCUrl(i),s=zi(i);e[s]=this.createHttpProvider(s,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}getCardanoRPCUrl(e){const i=this.namespace.rpcMap;if(i)return i[e]}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var o6=Object.defineProperty,a6=(t,e,i)=>e in t?o6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ar=(t,e,i)=>a6(t,typeof e!="symbol"?e+"":e,i);class c6{constructor(e){ar(this,"name","elrond"),ar(this,"client"),ar(this,"httpProviders"),ar(this,"events"),ar(this,"namespace"),ar(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=zi(i);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var h6=Object.defineProperty,u6=(t,e,i)=>e in t?h6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,cr=(t,e,i)=>u6(t,typeof e!="symbol"?e+"":e,i);class l6{constructor(e){cr(this,"name","multiversx"),cr(this,"client"),cr(this,"httpProviders"),cr(this,"events"),cr(this,"namespace"),cr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const s=zi(i);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var d6=Object.defineProperty,f6=(t,e,i)=>e in t?d6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,hr=(t,e,i)=>f6(t,typeof e!="symbol"?e+"":e,i);class p6{constructor(e){hr(this,"name","near"),hr(this,"client"),hr(this,"httpProviders"),hr(this,"events"),hr(this,"namespace"),hr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){if(this.chainId=e,!this.httpProviders[e]){const r=i||st(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace);return typeof r>"u"?void 0:new yt(new St(r,re("disableProviderPing")))}}var g6=Object.defineProperty,y6=(t,e,i)=>e in t?g6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ur=(t,e,i)=>y6(t,typeof e!="symbol"?e+"":e,i);class w6{constructor(e){ur(this,"name","tezos"),ur(this,"client"),ur(this,"httpProviders"),ur(this,"events"),ur(this,"namespace"),ur(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,i){if(this.chainId=e,!this.httpProviders[e]){const r=i||st(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{e[i]=this.createHttpProvider(i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace);return typeof r>"u"?void 0:new yt(new St(r))}}var m6=Object.defineProperty,b6=(t,e,i)=>e in t?m6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,lr=(t,e,i)=>b6(t,typeof e!="symbol"?e+"":e,i);class v6{constructor(e){lr(this,"name",fr),lr(this,"client"),lr(this,"httpProviders"),lr(this,"events"),lr(this,"namespace"),lr(this,"chainId"),this.namespace=e.namespace,this.events=re("events"),this.client=re("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i),this.chainId=e,this.events.emit(wt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){var e,i;const r={};return(i=(e=this.namespace)==null?void 0:e.accounts)==null||i.forEach(s=>{const n=yr(s);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),r}getHttpProvider(e){const i=this.httpProviders[e];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||st(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new yt(new St(r,re("disableProviderPing")))}}var E6=Object.defineProperty,I6=Object.defineProperties,_6=Object.getOwnPropertyDescriptors,pl=Object.getOwnPropertySymbols,x6=Object.prototype.hasOwnProperty,$6=Object.prototype.propertyIsEnumerable,Ia=(t,e,i)=>e in t?E6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ws=(t,e)=>{for(var i in e||(e={}))x6.call(e,i)&&Ia(t,i,e[i]);if(pl)for(var i of pl(e))$6.call(e,i)&&Ia(t,i,e[i]);return t},Co=(t,e)=>I6(t,_6(e)),ot=(t,e,i)=>Ia(t,typeof e!="symbol"?e+"":e,i);let S6=class _p{constructor(e){ot(this,"client"),ot(this,"namespaces"),ot(this,"optionalNamespaces"),ot(this,"sessionProperties"),ot(this,"scopedProperties"),ot(this,"events",new xa),ot(this,"rpcProviders",{}),ot(this,"session"),ot(this,"providerOpts"),ot(this,"logger"),ot(this,"uri"),ot(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Is(Un({level:(e==null?void 0:e.logger)||Zu})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const i=new _p(e);return await i.initialize(),i}async request(e,i,r){const[s,n]=this.validateChain(i);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:Ws({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,i,r,s){const n=new Date().getTime();this.request(e,r,s).then(o=>i(null,Bn(n,o))).catch(o=>i(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:de("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,i){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:s}=await this.client.authenticate(e,i);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await s();if(this.session=n.session,this.session){const o=nl(this.session.namespaces);this.namespaces=Ks(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}removeListener(e,i){this.events.removeListener(e,i)}off(e,i){this.events.off(e,i)}get isWalletConnect(){return!0}async pair(e){const{uri:i,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});i&&(this.uri=i,this.events.emit("display_uri",i));const s=await r();this.session=s;const n=nl(s.namespaces);return this.namespaces=Ks(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,i){try{if(!this.session)return;const[r,s]=this.validateChain(e),n=this.getProvider(r);n.name===fr?n.setDefaultChain(`${r}:${s}`,i):n.setDefaultChain(s,i)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const i=this.client.pairing.getAll();if(dt(i)){for(const r of i)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${i.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,i;if(this.client=this.providerOpts.client||await MS.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Zu,relayUrl:this.providerOpts.relayUrl||YS,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(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(i=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:i.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[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(i=>pr(i)))];Po("client",this.client),Po("events",this.events),Po("disableProviderPing",this.disableProviderPing),e.forEach(i=>{if(!this.session)return;const r=TD(i,this.session),s=Ep(r),n=Ks(this.namespaces,this.optionalNamespaces),o=Co(Ws({},n[i]),{accounts:r,chains:s});switch(i){case"eip155":this.rpcProviders[i]=new WD({namespace:o});break;case"algorand":this.rpcProviders[i]=new i6({namespace:o});break;case"solana":this.rpcProviders[i]=new JD({namespace:o});break;case"cosmos":this.rpcProviders[i]=new XD({namespace:o});break;case"polkadot":this.rpcProviders[i]=new MD({namespace:o});break;case"cip34":this.rpcProviders[i]=new n6({namespace:o});break;case"elrond":this.rpcProviders[i]=new c6({namespace:o});break;case"multiversx":this.rpcProviders[i]=new l6({namespace:o});break;case"near":this.rpcProviders[i]=new p6({namespace:o});break;case"tezos":this.rpcProviders[i]=new w6({namespace:o});break;default:this.rpcProviders[fr]?this.rpcProviders[fr].updateNamespace(o):this.rpcProviders[fr]=new v6({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var i;const{topic:r}=e;r===((i=this.session)==null?void 0:i.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var i;const{params:r,topic:s}=e;if(s!==((i=this.session)==null?void 0:i.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&dt(o)&&this.events.emit("accountsChanged",o.map(sl))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=pr(o),h=Ao(o)!==Ao(a)?`${c}:${Ao(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:i})=>{var r,s;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=i,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Co(Ws({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:i})}),this.client.on("session_delete",async e=>{var i;e.topic===((i=this.session)==null?void 0:i.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Co(Ws({},de("USER_DISCONNECTED")),{data:e.topic})))}),this.on(wt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[fr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var i;this.getProvider(e).updateNamespace((i=this.session)==null?void 0:i.namespaces[e])})}setNamespaces(e){const{namespaces:i={},optionalNamespaces:r={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=Ks(i,r),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[i,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[i,r];if(i&&!Object.keys(this.namespaces||{}).map(o=>pr(o)).includes(i))throw new Error(`Namespace '${i}' is not configured. Please call connect() first with namespace config.`);if(i&&r)return[i,r];const s=pr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,i=!1){if(!this.namespaces)return;const[r,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(r,s),this.events.emit("chainChanged",s);const n=this.getProvider(r).getDefaultChain();i||this.getProvider(r).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:i,newChainId:r}){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(sl);if(!dt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,i){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${i}`,s={chains:[],methods:[],events:[],defaultChain:i};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=i):this.namespaces[r]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,i){var r;const s=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${Hs}/${e}${s}`,i)}async getFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";return await this.client.core.storage.getItem(`${Hs}/${e}${r}`)}async deleteFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.removeItem(`${Hs}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const i=await this.client.core.storage.getKeys();for(const r of i)r.startsWith(Hs)&&await this.client.core.storage.removeItem(r)}catch(i){this.logger.warn("Failed to cleanup storage",i)}}};const D6=S6,A6="wc",P6="ethereum_provider",O6=`${A6}@2:${P6}:`,C6="https://rpc.walletconnect.org/v1/",vn=["eth_sendTransaction","personal_sign"],xp=["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"],En=["chainChanged","accountsChanged"],$p=["chainChanged","accountsChanged","message","disconnect","connect"],T6=async()=>{const{createAppKit:t}=await ml(()=>import("./core-f5e3f11a.js").then(e=>e.X),["assets/core-f5e3f11a.js","assets/index-23cd0f55.js","assets/index-6a75d29a.css"]);return t};var F6=Object.defineProperty,R6=Object.defineProperties,N6=Object.getOwnPropertyDescriptors,gl=Object.getOwnPropertySymbols,U6=Object.prototype.hasOwnProperty,B6=Object.prototype.propertyIsEnumerable,_a=(t,e,i)=>e in t?F6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xi=(t,e)=>{for(var i in e||(e={}))U6.call(e,i)&&_a(t,i,e[i]);if(gl)for(var i of gl(e))B6.call(e,i)&&_a(t,i,e[i]);return t},zr=(t,e)=>R6(t,N6(e)),et=(t,e,i)=>_a(t,typeof e!="symbol"?e+"":e,i);function In(t){return Number(t[0].split(":")[1])}function Gs(t){return`0x${t.toString(16)}`}function k6(t){const{chains:e,optionalChains:i,methods:r,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!dt(e))throw new Error("Invalid chains");const c={chains:e,methods:r||vn,events:n||En,rpcMap:xi({},e.length?{[In(e)]:a[In(e)]}:{})},h=n==null?void 0:n.filter(p=>!En.includes(p)),u=r==null?void 0:r.filter(p=>!vn.includes(p));if(!i&&!o&&!s&&!(h!=null&&h.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const l=(h==null?void 0:h.length)&&(u==null?void 0:u.length)||!i,d={chains:[...new Set(l?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:xp))],events:[...new Set(c.events.concat(o!=null&&o.length?o:$p))],rpcMap:a};return{required:e.length?c:void 0,optional:i.length?d:void 0}}class qn{constructor(){et(this,"events",new gt.EventEmitter),et(this,"namespace","eip155"),et(this,"accounts",[]),et(this,"signer"),et(this,"chainId",1),et(this,"modal"),et(this,"rpc"),et(this,"STORAGE_KEY",O6),et(this,"on",(e,i)=>(this.events.on(e,i),this)),et(this,"once",(e,i)=>(this.events.once(e,i),this)),et(this,"removeListener",(e,i)=>(this.events.removeListener(e,i),this)),et(this,"off",(e,i)=>(this.events.off(e,i),this)),et(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const i=new qn;return await i.initialize(e),i}async request(e,i){return await this.signer.request(e,this.formatChainId(this.chainId),i)}sendAsync(e,i,r){this.signer.sendAsync(e,i,this.formatChainId(this.chainId),r)}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 i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:s}=k6(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,u;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(u=this.modal)==null||u.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const l=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(zr(xi({namespaces:xi({},r&&{[this.namespace]:r})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:l})).then(d=>{a(d)}).catch(d=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=nh(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Gs(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async authenticate(e,i){var r;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,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(zr(xi({},e),{chains:this.rpc.chains}),i).then(u=>{o(u)}).catch(u=>{var l;(l=this.modal)==null||l.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=nh(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Gs(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.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:i}=e,{event:r}=i;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.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 i=parseInt(e);this.chainId=i,this.events.emit("chainChanged",Gs(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",zr(xi({},de("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 i=e.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));i.length&&(this.chainId=i[0],this.events.emit("chainChanged",Gs(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const i=this.parseChainId(e);this.chainId=i,this.switchEthereumChain(i)}}parseAccountId(e){const[i,r,s]=e.split(":");return{chainId:`${i}:${r}`,address:s}}setAccounts(e){this.accounts=e.filter(i=>this.parseChainId(this.parseAccountId(i).chainId)===this.chainId).map(i=>this.parseAccountId(i).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var i,r;const s=(i=e==null?void 0:e.chains)!=null?i:[],n=(r=e==null?void 0:e.optionalChains)!=null?r:[],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)||vn:[],c=s.length?(e==null?void 0:e.events)||En:[],h=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],l=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(p=>this.formatChainId(p)),optionalChains:n.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:h,optionalEvents:u,rpcMap:l,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,i){const r={};return e.forEach(s=>{r[s]=this.getRpcUrl(s,i)}),r}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?In(this.rpc.chains):In(this.rpc.optionalChains),this.signer=await D6.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 r=await T6(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return Y6}),n=s(zr(xi({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");i=r(zr(xi({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(r){throw console.warn(r),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(r){throw this.signer.logger.error(r),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:i,optionalChains:r,rpcMap:s}=e;i&&dt(i)&&(this.rpc.chains=i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),r&&dt(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r==null?void 0:r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,i){var r;return((r=this.rpc.rpcMap)==null?void 0:r[e])||`${C6}?chainId=eip155:${e}&projectId=${i||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),i=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:i==null?void 0:i.accounts),this.setAccounts(i==null?void 0:i.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(i=>this.signer.logger.warn(i))}}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(i=>this.parseAccount(i))}}const j6=qn;var L6=Object.defineProperty,M6=Object.defineProperties,q6=Object.getOwnPropertyDescriptors,yl=Object.getOwnPropertySymbols,z6=Object.prototype.hasOwnProperty,H6=Object.prototype.propertyIsEnumerable,wl=(t,e,i)=>e in t?L6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Sp=(t,e)=>{for(var i in e||(e={}))z6.call(e,i)&&wl(t,i,e[i]);if(yl)for(var i of yl(e))H6.call(e,i)&&wl(t,i,e[i]);return t},V6=(t,e)=>M6(t,q6(e));function K6(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 W6=t=>{const[e,i]=t.split(":");return Dp({id:i,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function G6(t){var e,i,r,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(W6).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(l=>{var d;return l.id===((d=t.defaultChain)==null?void 0:d.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:K6(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:h,metadata:V6(Sp({},t.metadata),{name:((i=t.metadata)==null?void 0:i.name)||"WalletConnect",description:((r=t.metadata)==null?void 0:r.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 l=[...(t.mobileWallets||[]).map(f=>({id:f.id,name:f.name,links:f.links})),...(t.desktopWallets||[]).map(f=>({id:f.id,name:f.name,links:{native:f.links.native,universal:f.links.universal}}))],d=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],p=l.filter(f=>!d.includes(f.id));p.length&&(u.customWallets=p)}return u}function Dp(t){return Sp({formatters:void 0,fees:void 0,serializers:void 0},t)}var Y6=Object.freeze({__proto__:null,convertWCMToAppKitOptions:G6,defineChain:Dp});const qA=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:j6,OPTIONAL_EVENTS:$p,OPTIONAL_METHODS:xp,REQUIRED_EVENTS:En,REQUIRED_METHODS:vn,default:qn},Symbol.toStringTag,{value:"Module"}));export{eA as $,qI as A,Li as B,nb as C,pi as D,qe as E,c1 as F,Ti as G,kn as H,ji as I,Ft as J,ct as K,Tt as L,St as M,a0 as N,Is as O,th as P,bd as Q,Q6 as R,Oc as S,Cl as T,os as U,t0 as V,Ol as W,c0 as X,X6 as Y,Z6 as Z,sn as _,X3 as a,tA as a0,qA as a1,eI as b,Bf as c,Ls as d,tI as e,Ni as f,ru as g,ih as h,Il as i,L as j,rI as k,Fi as l,$a as m,ps as n,Vp as o,El as p,Ko as q,Un as r,Yt as s,R3 as t,yt as u,P_ as v,ic as w,jn as x,Qe as y,Bn as z};