@dcl/governance-site 1.15.1-20105651460.commit-7620061 → 2.0.0

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.
@@ -1,39 +0,0 @@
1
- import{e as xt,g as kf,h as R0,i as Y,B as re,k as St,c as pi,x as pc,o as pu,_ as F0}from"./index-6c5c6262.js";var gu=globalThis&&globalThis.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))},N0=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),U0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),k0=function(){function t(e,r,i,n){this.name=e,this.version=r,this.os=i,this.bot=n,this.type="bot-device"}return t}(),j0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),L0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),M0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,q0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,yu=3,z0=[["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",M0]],wu=[["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 V0(t){return t?mu(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new L0:typeof navigator<"u"?mu(navigator.userAgent):W0()}function H0(t){return t!==""&&z0.reduce(function(e,r){var i=r[0],n=r[1];if(e)return e;var s=n.exec(t);return!!s&&[i,s]},!1)}function mu(t){var e=H0(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new j0;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length<yu&&(n=gu(gu([],n,!0),G0(yu-n.length),!0)):n=[];var s=n.join("."),o=K0(t),a=q0.exec(t);return a&&a[1]?new k0(r,s,o,a[1]):new N0(r,s,o)}function K0(t){for(var e=0,r=wu.length;e<r;e++){var i=wu[e],n=i[0],s=i[1],o=s.exec(t);if(o)return n}return null}function W0(){var t=typeof xt<"u"&&xt.version;return t?new U0(xt.version.slice(1)):null}function G0(t){for(var e=[],r=0;r<t;r++)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 ga=function(t,e){return ga=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},ga(t,e)};function Y0(t,e){ga(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ya=function(){return ya=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ya.apply(this,arguments)};function Z0(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function J0(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function X0(t,e){return function(r,i){e(r,i,t)}}function Q0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ey(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):n(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function ty(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,n=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],n=0}finally{i=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function ry(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function iy(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function wa(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jf(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function ny(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(jf(arguments[e]));return t}function sy(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function wn(t){return this instanceof wn?(this.v=t,this):new wn(t)}function oy(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof wn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ay(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:wn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function cy(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof wa=="function"?wa(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function uy(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ly(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function hy(t){return t&&t.__esModule?t:{default:t}}function fy(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function dy(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const py=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ya},__asyncDelegator:ay,__asyncGenerator:oy,__asyncValues:cy,__await:wn,__awaiter:ey,__classPrivateFieldGet:fy,__classPrivateFieldSet:dy,__createBinding:ry,__decorate:J0,__exportStar:iy,__extends:Y0,__generator:ty,__importDefault:hy,__importStar:ly,__makeTemplateObject:uy,__metadata:Q0,__param:X0,__read:jf,__rest:Z0,__spread:ny,__spreadArrays:sy,__values:wa},Symbol.toStringTag,{value:"Module"})),Ms=kf(py);var po={},zi={},bu;function gy(){if(bu)return zi;bu=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return zi.delay=t,zi}var Lr={},go={},Mr={},vu;function yy(){return vu||(vu=1,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.ONE_THOUSAND=Mr.ONE_HUNDRED=void 0,Mr.ONE_HUNDRED=100,Mr.ONE_THOUSAND=1e3),Mr}var yo={},Eu;function wy(){return Eu||(Eu=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}(yo)),yo}var xu;function Lf(){return xu||(xu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(yy(),t),e.__exportStar(wy(),t)}(go)),go}var _u;function my(){if(_u)return Lr;_u=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.fromMiliseconds=Lr.toMiliseconds=void 0;const t=Lf();function e(i){return i*t.ONE_THOUSAND}Lr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Lr.fromMiliseconds=r,Lr}var Iu;function by(){return Iu||(Iu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(gy(),t),e.__exportStar(my(),t)}(po)),po}var gi={},Su;function vy(){if(Su)return gi;Su=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const n=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:n})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return gi.Watch=t,gi.default=t,gi}var wo={},Vi={},$u;function Ey(){if($u)return Vi;$u=1,Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.IWatch=void 0;class t{}return Vi.IWatch=t,Vi}var Ou;function xy(){return Ou||(Ou=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Ms.__exportStar(Ey(),t)}(wo)),wo}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(by(),t),e.__exportStar(vy(),t),e.__exportStar(xy(),t),e.__exportStar(Lf(),t)})(L);var le={};Object.defineProperty(le,"__esModule",{value:!0});le.getLocalStorage=le.getLocalStorageOrThrow=le.getCrypto=le.getCryptoOrThrow=Mf=le.getLocation=le.getLocationOrThrow=gc=le.getNavigator=le.getNavigatorOrThrow=ii=le.getDocument=le.getDocumentOrThrow=le.getFromWindowOrThrow=le.getFromWindow=void 0;function ci(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}le.getFromWindow=ci;function ji(t){const e=ci(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}le.getFromWindowOrThrow=ji;function _y(){return ji("document")}le.getDocumentOrThrow=_y;function Iy(){return ci("document")}var ii=le.getDocument=Iy;function Sy(){return ji("navigator")}le.getNavigatorOrThrow=Sy;function $y(){return ci("navigator")}var gc=le.getNavigator=$y;function Oy(){return ji("location")}le.getLocationOrThrow=Oy;function Dy(){return ci("location")}var Mf=le.getLocation=Dy;function Ay(){return ji("crypto")}le.getCryptoOrThrow=Ay;function Py(){return ci("crypto")}le.getCrypto=Py;function Cy(){return ji("localStorage")}le.getLocalStorageOrThrow=Cy;function By(){return ci("localStorage")}le.getLocalStorage=By;var yc={};Object.defineProperty(yc,"__esModule",{value:!0});var qf=yc.getWindowMetadata=void 0;const Du=le;function Ty(){let t,e;try{t=Du.getDocumentOrThrow(),e=Du.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),f=[];for(let d=0;d<h.length;d++){const p=h[d],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const w=p.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let I=e.protocol+"//"+e.host;if(w.indexOf("/")===0)I+=w;else{const C=e.pathname.split("/");C.pop();const b=C.join("/");I+=b+"/"+w}f.push(I)}else if(w.indexOf("//")===0){const I=e.protocol+w;f.push(I)}else f.push(w)}}return f}function i(...h){const f=t.getElementsByTagName("meta");for(let d=0;d<f.length;d++){const p=f[d],g=["itemprop","property","name"].map(w=>p.getAttribute(w)).filter(w=>w?h.includes(w):!1);if(g.length&&g){const w=p.getAttribute("content");if(w)return w}}return""}function n(){let h=i("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return i("description","og:description","twitter:description","keywords")}const o=n(),a=s(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}qf=yc.getWindowMetadata=Ty;const Ry="0.1.1";function Fy(){return Ry}class de extends Error{constructor(e,r={}){const i=(()=>{var c;if(r.cause instanceof de){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),n=(()=>r.cause instanceof de&&r.cause.docsPath||r.docsPath)(),o=`https://oxlib.sh${n??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||n?["",i?`Details: ${i}`:void 0,n?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
15
- `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Fy()}`}),this.cause=r.cause,this.details=i,this.docs=o,this.docsPath=n,this.shortMessage=e}walk(e){return zf(this,e)}}function zf(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?zf(t.cause,e):e?null:t}const yi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ny(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ni(t,...e){if(!Ny(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 Uy(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mn(t.outputLen),mn(t.blockLen)}function Fi(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 Vf(t,e){ni(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ky(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ni(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function mo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Rt(t,e){return t<<32-e|t>>>e}const jy=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Ly(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function My(t){for(let e=0;e<t.length;e++)t[e]=Ly(t[e]);return t}const Au=jy?t=>t:My;function qy(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function qs(t){return typeof t=="string"&&(t=qy(t)),ni(t),t}function zy(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];ni(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}class wc{}function Hf(t){const e=i=>t().update(qs(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Vy(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")}function Hy(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}function Ky(t,e,r){return t&e^~t&r}function Wy(t,e,r){return t&e^t&r^e&r}class Gy extends wc{constructor(e,r,i,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=mo(this.buffer)}update(e){Fi(this),e=qs(e),ni(e);const{view:r,buffer:i,blockLen:n}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=mo(e);for(;n<=s-o;o+=n)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fi(this),Vf(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,Ni(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;Hy(i,n-8,BigInt(this.length*8),s),this.process(i,0);const a=mo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const pr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jn=BigInt(2**32-1),Pu=BigInt(32);function Yy(t,e=!1){return e?{h:Number(t&jn),l:Number(t>>Pu&jn)}:{h:Number(t>>Pu&jn)|0,l:Number(t&jn)|0}}function Zy(t,e=!1){const r=t.length;let i=new Uint32Array(r),n=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Yy(t[s],e);[i[s],n[s]]=[o,a]}return[i,n]}const Jy=(t,e,r)=>t<<r|e>>>32-r,Xy=(t,e,r)=>e<<r|t>>>32-r,Qy=(t,e,r)=>e<<r-32|t>>>64-r,ew=(t,e,r)=>t<<r-32|e>>>64-r,tw=BigInt(0),Hi=BigInt(1),rw=BigInt(2),iw=BigInt(7),nw=BigInt(256),sw=BigInt(113),Kf=[],Wf=[],Gf=[];for(let t=0,e=Hi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Kf.push(2*(5*i+r)),Wf.push((t+1)*(t+2)/2%64);let n=tw;for(let s=0;s<7;s++)e=(e<<Hi^(e>>iw)*sw)%nw,e&rw&&(n^=Hi<<(Hi<<BigInt(s))-Hi);Gf.push(n)}const Yf=Zy(Gf,!0),ow=Yf[0],aw=Yf[1],Cu=(t,e,r)=>r>32?Qy(t,e,r):Jy(t,e,r),Bu=(t,e,r)=>r>32?ew(t,e,r):Xy(t,e,r);function cw(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=Cu(u,l,1)^r[a],f=Bu(u,l,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let n=t[2],s=t[3];for(let o=0;o<24;o++){const a=Wf[o],c=Cu(n,s,a),u=Bu(n,s,a),l=Kf[o];n=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=ow[i],t[1]^=aw[i]}Ni(r)}class mc extends wc{constructor(e,r,i,n=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=n,this.rounds=s,mn(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ky(this.state)}clone(){return this._cloneInto()}keccak(){Au(this.state32),cw(this.state32,this.rounds),Au(this.state32),this.posOut=0,this.pos=0}update(e){Fi(this),e=qs(e),ni(e);const{blockLen:r,state:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);for(let a=0;a<o;a++)i[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:n}=this;e[i]^=r,r&128&&i===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Fi(this,!1),ni(e),this.finish();const r=this.state,{blockLen:i}=this;for(let n=0,s=e.length;n<s;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,s-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=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 mn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Vf(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,Ni(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new mc(r,i,n,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=i,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const uw=(t,e,r)=>Hf(()=>new mc(e,t,r)),lw=(()=>uw(1,136,256/8))(),hw=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]),gr=new Uint32Array(64);class fw extends Gy{constructor(e=32){super(64,e,8,!1),this.A=pr[0]|0,this.B=pr[1]|0,this.C=pr[2]|0,this.D=pr[3]|0,this.E=pr[4]|0,this.F=pr[5]|0,this.G=pr[6]|0,this.H=pr[7]|0}get(){const{A:e,B:r,C:i,D:n,E:s,F:o,G:a,H:c}=this;return[e,r,i,n,s,o,a,c]}set(e,r,i,n,s,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)gr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=gr[h-15],d=gr[h-2],p=Rt(f,7)^Rt(f,18)^f>>>3,g=Rt(d,17)^Rt(d,19)^d>>>10;gr[h]=g+gr[h-7]+p+gr[h-16]|0}let{A:i,B:n,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Rt(a,6)^Rt(a,11)^Rt(a,25),d=l+f+Ky(a,c,u)+hw[h]+gr[h]|0,g=(Rt(i,2)^Rt(i,13)^Rt(i,22))+Wy(i,n,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=n,n=i,i=d+g|0}i=i+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(i,n,s,o,a,c,u,l)}roundClean(){Ni(gr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ni(this.buffer)}}const dw=Hf(()=>new fw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bc=BigInt(0),ma=BigInt(1);function On(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function vc(t){if(!On(t))throw new Error("Uint8Array expected")}function bn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Ln(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Zf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?bc:BigInt("0x"+t)}const Jf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vn(t){if(vc(t),Jf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=pw[t[r]];return e}const Gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tu(t){if(t>=Gt._0&&t<=Gt._9)return t-Gt._0;if(t>=Gt.A&&t<=Gt.F)return t-(Gt.A-10);if(t>=Gt.a&&t<=Gt.f)return t-(Gt.a-10)}function ms(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Jf)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Tu(t.charCodeAt(s)),a=Tu(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}i[n]=o*16+a}return i}function ri(t){return Zf(vn(t))}function Xf(t){return vc(t),Zf(vn(Uint8Array.from(t).reverse()))}function Dn(t,e){return ms(t.toString(16).padStart(e*2,"0"))}function Qf(t,e){return Dn(t,e).reverse()}function mt(t,e,r){let i;if(typeof e=="string")try{i=ms(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(On(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}function bs(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];vc(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}const bo=t=>typeof t=="bigint"&&bc<=t;function Ec(t,e,r){return bo(t)&&bo(e)&&bo(r)&&e<=t&&t<r}function Ai(t,e,r,i){if(!Ec(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function gw(t){let e;for(e=0;t>bc;t>>=ma,e+=1);return e}const zs=t=>(ma<<BigInt(t))-ma,vo=t=>new Uint8Array(t),Ru=t=>Uint8Array.from(t);function yw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let i=vo(t),n=vo(t),s=0;const o=()=>{i.fill(1),n.fill(0),s=0},a=(...h)=>r(n,i,...h),c=(h=vo(0))=>{n=a(Ru([0]),h),i=a(),h.length!==0&&(n=a(Ru([1]),h),i=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){i=a();const d=i.slice();f.push(d),h+=i.length}return bs(...f)};return(h,f)=>{o(),c(h);let d;for(;!(d=f(u()));)c();return o(),d}}const ww={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"||On(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 Vs(t,e,r={}){const i=(n,s,o)=>{const a=ww[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[n];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(n)+" is invalid. Expected "+s+", got "+c)};for(const[n,s]of Object.entries(e))i(n,s,!1);for(const[n,s]of Object.entries(r))i(n,s,!0);return t}function Fu(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}function mw(t,e){if(ju(t)>e)throw new jw({givenSize:ju(t),maxSize:e})}const Yt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Nu(t){if(t>=Yt.zero&&t<=Yt.nine)return t-Yt.zero;if(t>=Yt.A&&t<=Yt.F)return t-(Yt.A-10);if(t>=Yt.a&&t<=Yt.f)return t-(Yt.a-10)}function bw(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;if(t.length>i)throw new Lw({size:t.length,targetSize:i,type:"Bytes"});const n=new Uint8Array(i);for(let s=0;s<i;s++){const o=r==="right";n[o?s:i-s-1]=t[o?s:t.length-s-1]}return n}function ed(t,e){if(Nr(t)>e)throw new Aw({givenSize:Nr(t),maxSize:e})}function vw(t,e){if(typeof e=="number"&&e>0&&e>Nr(t)-1)throw new id({offset:e,position:"start",size:Nr(t)})}function Ew(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Nr(t)!==r-e)throw new id({offset:r,position:"end",size:Nr(t)})}function td(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;const n=t.replace("0x","");if(n.length>i*2)throw new Pw({size:Math.ceil(n.length/2),targetSize:i,type:"Hex"});return`0x${n[r==="right"?"padEnd":"padStart"](i*2,"0")}`}const xw="#__bigint";function xc(t,e,r){return JSON.stringify(t,(i,n)=>typeof e=="function"?e(i,n):typeof n=="bigint"?n.toString()+xw:n,r)}const _w=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Iw(t,e={}){const{strict:r=!1}=e;if(!t)throw new Uu(t);if(typeof t!="string")throw new Uu(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new ku(t);if(!t.startsWith("0x"))throw new ku(t)}function Sw(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function _c(t){return t instanceof Uint8Array?vs(t):Array.isArray(t)?vs(new Uint8Array(t)):t}function vs(t,e={}){let r="";for(let n=0;n<t.length;n++)r+=_w[t[n]];const i=`0x${r}`;return typeof e.size=="number"?(ed(i,e.size),rd(i,e.size)):i}function Eo(t,e={}){const{signed:r,size:i}=e,n=BigInt(t);let s;i?r?s=(1n<<BigInt(i)*8n-1n)-1n:s=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&n>s||n<o){const u=typeof t=="bigint"?"n":"";throw new Dw({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:r,size:i,value:`${t}${u}`})}const c=`0x${(r&&n<0?(1n<<BigInt(i*8))+BigInt(n):n).toString(16)}`;return i?$w(c,i):c}function $w(t,e){return td(t,{dir:"left",size:e})}function rd(t,e){return td(t,{dir:"right",size:e})}function ir(t,e,r,i={}){const{strict:n}=i;vw(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&Ew(s,e,r),s}function Nr(t){return Math.ceil((t.length-2)/2)}function Ow(t,e={}){const{strict:r=!1}=e;try{return Iw(t,{strict:r}),!0}catch{return!1}}class Dw extends de{constructor({max:e,min:r,signed:i,size:n,value:s}){super(`Number \`${s}\` is not in safe${n?` ${n*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Uu extends de{constructor(e){super(`Value \`${typeof e=="object"?xc(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class ku extends de{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let Aw=class extends de{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class id extends de{constructor({offset:e,position:r,size:i}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let Pw=class extends de{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const Cw=new TextEncoder;function Bw(t){if(!(t instanceof Uint8Array)){if(!t)throw new Mn(t);if(typeof t!="object")throw new Mn(t);if(!("BYTES_PER_ELEMENT"in t))throw new Mn(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Mn(t)}}function Tw(t){return t instanceof Uint8Array?t:typeof t=="string"?Fw(t):Rw(t)}function Rw(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Fw(t,e={}){const{size:r}=e;let i=t;r&&(ed(t,r),i=rd(t,r));let n=i.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Nu(n.charCodeAt(c++)),l=Nu(n.charCodeAt(c++));if(u===void 0||l===void 0)throw new de(`Invalid byte sequence ("${n[c-2]}${n[c-1]}" in "${n}").`);o[a]=u*16+l}return o}function Nw(t,e={}){const{size:r}=e,i=Cw.encode(t);return typeof r=="number"?(mw(i,r),Uw(i,r)):i}function Uw(t,e){return bw(t,{dir:"right",size:e})}function ju(t){return t.length}function kw(t){try{return Bw(t),!0}catch{return!1}}class Mn extends de{constructor(e){super(`Value \`${typeof e=="object"?xc(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class jw extends de{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Lw extends de{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function nd(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,i=lw(Tw(t));return r==="Bytes"?i:vs(i)}class Mw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const qw={checksum:new Mw(8192)},xo=qw.checksum;function sd(t,e={}){const{compressed:r}=e,{prefix:i,x:n,y:s}=t;if(r===!1||typeof n=="bigint"&&typeof s=="bigint"){if(i!==4)throw new Lu({prefix:i,cause:new Gw});return}if(r===!0||typeof n=="bigint"&&typeof s>"u"){if(i!==3&&i!==2)throw new Lu({prefix:i,cause:new Ww});return}throw new Kw({publicKey:t})}function zw(t){const e=(()=>{if(Ow(t))return od(t);if(kw(t))return Vw(t);const{prefix:r,x:i,y:n}=t;return typeof i=="bigint"&&typeof n=="bigint"?{prefix:r??4,x:i,y:n}:{prefix:r,x:i}})();return sd(e),e}function Vw(t){return od(vs(t))}function od(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new Yw({publicKey:t});if(t.length===130){const i=BigInt(ir(t,0,32)),n=BigInt(ir(t,32,64));return{prefix:4,x:i,y:n}}if(t.length===132){const i=Number(ir(t,0,1)),n=BigInt(ir(t,1,33)),s=BigInt(ir(t,33,65));return{prefix:i,x:n,y:s}}const e=Number(ir(t,0,1)),r=BigInt(ir(t,1,33));return{prefix:e,x:r}}function Hw(t,e={}){sd(t);const{prefix:r,x:i,y:n}=t,{includePrefix:s=!0}=e;return Sw(s?Eo(r,{size:1}):"0x",Eo(i,{size:32}),typeof n=="bigint"?Eo(n,{size:32}):"0x")}class Kw extends de{constructor({publicKey:e}){super(`Value \`${xc(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Lu extends de{constructor({prefix:e,cause:r}){super(`Prefix "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Ww extends de{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Gw extends de{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Yw=class extends de{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Nr(_c(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Zw=/^0x[a-fA-F0-9]{40}$/;function ad(t,e={}){const{strict:r=!0}=e;if(!Zw.test(t))throw new Mu({address:t,cause:new Qw});if(r){if(t.toLowerCase()===t)return;if(cd(t)!==t)throw new Mu({address:t,cause:new em})}}function cd(t){if(xo.has(t))return xo.get(t);ad(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=nd(Nw(e),{as:"Bytes"}),i=e.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&i[s]&&(i[s]=i[s].toUpperCase()),(r[s>>1]&15)>=8&&i[s+1]&&(i[s+1]=i[s+1].toUpperCase());const n=`0x${i.join("")}`;return xo.set(t,n),n}function Jw(t,e={}){const{checksum:r=!1}=e;return ad(t),r?cd(t):t}function Xw(t,e={}){const r=nd(`0x${Hw(t).slice(4)}`).substring(26);return Jw(`0x${r}`,e)}class Mu extends de{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Qw extends de{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class em extends de{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class ud extends wc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Uy(e);const i=qs(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(i.length>n?e.create().update(i).digest():i);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Ni(s)}update(e){return Fi(this),this.iHash.update(e),this}digestInto(e){Fi(this),ni(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:n,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ld=(t,e,r)=>new ud(t,e).update(r).digest();ld.create=(t,e)=>new ud(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rt=BigInt(0),Ke=BigInt(1),Jr=BigInt(2),tm=BigInt(3),hd=BigInt(4),fd=BigInt(5),dd=BigInt(8);function Qe(t,e){const r=t%e;return r>=rt?r:e+r}function pt(t,e,r){let i=t;for(;e-- >rt;)i*=i,i%=r;return i}function ba(t,e){if(t===rt)throw new Error("invert: expected non-zero number");if(e<=rt)throw new Error("invert: expected positive modulus, got "+e);let r=Qe(t,e),i=e,n=rt,s=Ke;for(;r!==rt;){const a=i/r,c=i%r,u=n-s*a;i=r,r=c,n=s,s=u}if(i!==Ke)throw new Error("invert: does not exist");return Qe(n,e)}function pd(t,e){const r=(t.ORDER+Ke)/hd,i=t.pow(e,r);if(!t.eql(t.sqr(i),e))throw new Error("Cannot find square root");return i}function rm(t,e){const r=(t.ORDER-fd)/dd,i=t.mul(e,Jr),n=t.pow(i,r),s=t.mul(e,n),o=t.mul(t.mul(s,Jr),n),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function im(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ke,r=0;for(;e%Jr===rt;)e/=Jr,r++;let i=Jr;const n=Ic(t);for(;qu(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pd;let s=n.pow(i,e);const o=(e+Ke)/Jr;return function(c,u){if(c.is0(u))return u;if(qu(c,u)!==1)throw new Error("Cannot find square root");let l=r,h=c.mul(c.ONE,s),f=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let p=1,g=c.sqr(f);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const w=Ke<<BigInt(l-p-1),I=c.pow(h,w);l=p,h=c.sqr(I),f=c.mul(f,h),d=c.mul(d,I)}return d}}function nm(t){return t%hd===tm?pd:t%dd===fd?rm:im(t)}const sm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function om(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=sm.reduce((i,n)=>(i[n]="function",i),e);return Vs(t,r)}function am(t,e,r){if(r<rt)throw new Error("invalid exponent, negatives unsupported");if(r===rt)return t.ONE;if(r===Ke)return e;let i=t.ONE,n=e;for(;r>rt;)r&Ke&&(i=t.mul(i,n)),n=t.sqr(n),r>>=Ke;return i}function gd(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),s),i}function qu(t,e){const r=(t.ORDER-Ke)/Jr,i=t.pow(e,r),n=t.eql(i,t.ONE),s=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function yd(t,e){e!==void 0&&mn(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Ic(t,e,r=!1,i={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=yd(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:n,BYTES:s,MASK:zs(n),ZERO:rt,ONE:Ke,create:c=>Qe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return rt<=c&&c<t},is0:c=>c===rt,isOdd:c=>(c&Ke)===Ke,neg:c=>Qe(-c,t),eql:(c,u)=>c===u,sqr:c=>Qe(c*c,t),add:(c,u)=>Qe(c+u,t),sub:(c,u)=>Qe(c-u,t),mul:(c,u)=>Qe(c*u,t),pow:(c,u)=>am(a,c,u),div:(c,u)=>Qe(c*ba(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ba(c,t),sqrt:i.sqrt||(c=>(o||(o=nm(t)),o(a,c))),toBytes:c=>r?Qf(c,s):Dn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Xf(c):ri(c)},invertBatch:c=>gd(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function wd(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 md(t){const e=wd(t);return e+Math.ceil(e/2)}function cm(t,e,r=!1){const i=t.length,n=wd(e),s=md(e);if(i<16||i<s||i>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+i);const o=r?Xf(t):ri(t),a=Qe(o,e-Ke)+Ke;return r?Qf(a,n):Dn(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zu=BigInt(0),va=BigInt(1);function _o(t,e){const r=e.negate();return t?r:e}function bd(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){bd(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),n=2**t,s=zs(t),o=BigInt(t);return{windows:r,windowSize:i,mask:s,maxNumber:n,shiftBy:o}}function Vu(t,e,r){const{windowSize:i,mask:n,maxNumber:s,shiftBy:o}=r;let a=Number(t&n),c=t>>o;a>i&&(a-=s,c+=va);const u=e*i,l=u+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:d,offsetF:u}}function um(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function lm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const So=new WeakMap,vd=new WeakMap;function $o(t){return vd.get(t)||1}function hm(t,e){return{constTimeNegate:_o,hasPrecomputes(r){return $o(r)!==1},unsafeLadder(r,i,n=t.ZERO){let s=r;for(;i>zu;)i&va&&(n=n.add(s)),s=s.double(),i>>=va;return n},precomputeWindow(r,i){const{windows:n,windowSize:s}=Io(i,e),o=[];let a=r,c=a;for(let u=0;u<n;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,n){let s=t.ZERO,o=t.BASE;const a=Io(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:d,offsetF:p}=Vu(n,c,a);n=u,h?o=o.add(_o(d,i[p])):s=s.add(_o(f,i[l]))}return{p:s,f:o}},wNAFUnsafe(r,i,n,s=t.ZERO){const o=Io(r,e);for(let a=0;a<o.windows&&n!==zu;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=Vu(n,a,o);if(n=c,!l){const f=i[u];s=s.add(h?f.negate():f)}}return s},getPrecomputes(r,i,n){let s=So.get(i);return s||(s=this.precomputeWindow(i,r),r!==1&&So.set(i,n(s))),s},wNAFCached(r,i,n){const s=$o(r);return this.wNAF(s,this.getPrecomputes(s,r,n),i)},wNAFCachedUnsafe(r,i,n,s){const o=$o(r);return o===1?this.unsafeLadder(r,i,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,n),i,s)},setWindowSize(r,i){bd(i,e),vd.set(r,i),So.delete(r)}}}function fm(t,e,r,i){um(r,t),lm(i,e);const n=r.length,s=i.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=gw(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=zs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const w=i[g],I=Number(w>>BigInt(d)&u);l[I]=l[I].add(r[g])}let p=o;for(let g=l.length-1,w=o;g>0;g--)w=w.add(l[g]),p=p.add(w);if(f=f.add(p),d!==0)for(let g=0;g<c;g++)f=f.double()}return f}function Ed(t){return om(t.Fp),Vs(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Hu(t){t.lowS!==void 0&&bn("lowS",t.lowS),t.prehash!==void 0&&bn("prehash",t.prehash)}function dm(t){const e=Ed(t);Vs(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:i,a:n}=e;if(r){if(!i.eql(n,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class pm extends Error{constructor(e=""){super(e)}}const nr={Err:pm,_tlv:{encode:(t,e)=>{const{Err:r}=nr;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,n=Ln(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const s=i>127?Ln(n.length/2|128):"";return Ln(t)+s+n+e},decode(t,e){const{Err:r}=nr;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const n=e[i++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=nr;if(t<or)throw new e("integer: negative integers are not allowed");let r=Ln(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=nr;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 ri(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=nr,n=mt("signature",t),{v:s,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,s),{v:u,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=nr,i=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),s=i+n;return e.encode(48,s)}};function Oo(t,e){return vn(Dn(t,e))}const or=BigInt(0),De=BigInt(1);BigInt(2);const Do=BigInt(3),gm=BigInt(4);function ym(t){const e=dm(t),{Fp:r}=e,i=Ic(e.n,e.nBitLength),n=e.toBytes||((b,v,D)=>{const P=v.toAffine();return bs(Uint8Array.from([4]),r.toBytes(P.x),r.toBytes(P.y))}),s=e.fromBytes||(b=>{const v=b.subarray(1),D=r.fromBytes(v.subarray(0,r.BYTES)),P=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:D,y:P}});function o(b){const{a:v,b:D}=e,P=r.sqr(b),T=r.mul(P,b);return r.add(r.add(T,r.mul(b,v)),D)}function a(b,v){const D=r.sqr(v),P=o(b);return r.eql(D,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,Do),gm),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function l(b){return Ec(b,De,e.n)}function h(b){const{allowedPrivateKeyLengths:v,nByteLength:D,wrapPrivateKey:P,n:T}=e;if(v&&typeof b!="bigint"){if(On(b)&&(b=vn(b)),typeof b!="string"||!v.includes(b.length))throw new Error("invalid private key");b=b.padStart(D*2,"0")}let R;try{R=typeof b=="bigint"?b:ri(mt("private key",b,D))}catch{throw new Error("invalid private key, expected hex or "+D+" bytes, got "+typeof b)}return P&&(R=Qe(R,T)),Ai("private key",R,De,T),R}function f(b){if(!(b instanceof g))throw new Error("ProjectivePoint expected")}const d=Fu((b,v)=>{const{px:D,py:P,pz:T}=b;if(r.eql(T,r.ONE))return{x:D,y:P};const R=b.is0();v==null&&(v=R?r.ONE:r.inv(T));const A=r.mul(D,v),U=r.mul(P,v),j=r.mul(T,v);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(j,r.ONE))throw new Error("invZ was invalid");return{x:A,y:U}}),p=Fu(b=>{if(b.is0()){if(e.allowInfinityPoint&&!r.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:v,y:D}=b.toAffine();if(!r.isValid(v)||!r.isValid(D))throw new Error("bad point: x or y not FE");if(!a(v,D))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,D,P){if(v==null||!r.isValid(v))throw new Error("x required");if(D==null||!r.isValid(D)||r.is0(D))throw new Error("y required");if(P==null||!r.isValid(P))throw new Error("z required");this.px=v,this.py=D,this.pz=P,Object.freeze(this)}static fromAffine(v){const{x:D,y:P}=v||{};if(!v||!r.isValid(D)||!r.isValid(P))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const T=R=>r.eql(R,r.ZERO);return T(D)&&T(P)?g.ZERO:new g(D,P,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const D=gd(r,v.map(P=>P.pz));return v.map((P,T)=>P.toAffine(D[T])).map(g.fromAffine)}static fromHex(v){const D=g.fromAffine(s(mt("pointHex",v)));return D.assertValidity(),D}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,D){return fm(g,i,v,D)}_setWindowSize(v){C.setWindowSize(this,v)}assertValidity(){p(this)}hasEvenY(){const{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:D,py:P,pz:T}=this,{px:R,py:A,pz:U}=v,j=r.eql(r.mul(D,U),r.mul(R,T)),B=r.eql(r.mul(P,U),r.mul(A,T));return j&&B}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:v,b:D}=e,P=r.mul(D,Do),{px:T,py:R,pz:A}=this;let U=r.ZERO,j=r.ZERO,B=r.ZERO,_=r.mul(T,T),O=r.mul(R,R),m=r.mul(A,A),y=r.mul(T,R);return y=r.add(y,y),B=r.mul(T,A),B=r.add(B,B),U=r.mul(v,B),j=r.mul(P,m),j=r.add(U,j),U=r.sub(O,j),j=r.add(O,j),j=r.mul(U,j),U=r.mul(y,U),B=r.mul(P,B),m=r.mul(v,m),y=r.sub(_,m),y=r.mul(v,y),y=r.add(y,B),B=r.add(_,_),_=r.add(B,_),_=r.add(_,m),_=r.mul(_,y),j=r.add(j,_),m=r.mul(R,A),m=r.add(m,m),_=r.mul(m,y),U=r.sub(U,_),B=r.mul(m,O),B=r.add(B,B),B=r.add(B,B),new g(U,j,B)}add(v){f(v);const{px:D,py:P,pz:T}=this,{px:R,py:A,pz:U}=v;let j=r.ZERO,B=r.ZERO,_=r.ZERO;const O=e.a,m=r.mul(e.b,Do);let y=r.mul(D,R),x=r.mul(P,A),$=r.mul(T,U),E=r.add(D,P),S=r.add(R,A);E=r.mul(E,S),S=r.add(y,x),E=r.sub(E,S),S=r.add(D,T);let F=r.add(R,U);return S=r.mul(S,F),F=r.add(y,$),S=r.sub(S,F),F=r.add(P,T),j=r.add(A,U),F=r.mul(F,j),j=r.add(x,$),F=r.sub(F,j),_=r.mul(O,S),j=r.mul(m,$),_=r.add(j,_),j=r.sub(x,_),_=r.add(x,_),B=r.mul(j,_),x=r.add(y,y),x=r.add(x,y),$=r.mul(O,$),S=r.mul(m,S),x=r.add(x,$),$=r.sub(y,$),$=r.mul(O,$),S=r.add(S,$),y=r.mul(x,S),B=r.add(B,y),y=r.mul(F,S),j=r.mul(E,j),j=r.sub(j,y),y=r.mul(E,x),_=r.mul(F,_),_=r.add(_,y),new g(j,B,_)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return C.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:D,n:P}=e;Ai("scalar",v,or,P);const T=g.ZERO;if(v===or)return T;if(this.is0()||v===De)return this;if(!D||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:R,k1:A,k2neg:U,k2:j}=D.splitScalar(v),B=T,_=T,O=this;for(;A>or||j>or;)A&De&&(B=B.add(O)),j&De&&(_=_.add(O)),O=O.double(),A>>=De,j>>=De;return R&&(B=B.negate()),U&&(_=_.negate()),_=new g(r.mul(_.px,D.beta),_.py,_.pz),B.add(_)}multiply(v){const{endo:D,n:P}=e;Ai("scalar",v,De,P);let T,R;if(D){const{k1neg:A,k1:U,k2neg:j,k2:B}=D.splitScalar(v);let{p:_,f:O}=this.wNAF(U),{p:m,f:y}=this.wNAF(B);_=C.constTimeNegate(A,_),m=C.constTimeNegate(j,m),m=new g(r.mul(m.px,D.beta),m.py,m.pz),T=_.add(m),R=O.add(y)}else{const{p:A,f:U}=this.wNAF(v);T=A,R=U}return g.normalizeZ([T,R])[0]}multiplyAndAddUnsafe(v,D,P){const T=g.BASE,R=(U,j)=>j===or||j===De||!U.equals(T)?U.multiplyUnsafe(j):U.multiply(j),A=R(this,D).add(R(v,P));return A.is0()?void 0:A}toAffine(v){return d(this,v)}isTorsionFree(){const{h:v,isTorsionFree:D}=e;if(v===De)return!0;if(D)return D(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:D}=e;return v===De?this:D?D(g,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return bn("isCompressed",v),this.assertValidity(),n(g,this,v)}toHex(v=!0){return bn("isCompressed",v),vn(this.toRawBytes(v))}}g.BASE=new g(e.Gx,e.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:w,nBitLength:I}=e,C=hm(g,w?Math.ceil(I/2):I);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:l}}function wm(t){const e=Ed(t);return Vs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function mm(t){const e=wm(t),{Fp:r,n:i,nByteLength:n,nBitLength:s}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(m){return Qe(m,i)}function u(m){return ba(m,i)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:d}=ym({...e,toBytes(m,y,x){const $=y.toAffine(),E=r.toBytes($.x),S=bs;return bn("isCompressed",x),x?S(Uint8Array.from([y.hasEvenY()?2:3]),E):S(Uint8Array.from([4]),E,r.toBytes($.y))},fromBytes(m){const y=m.length,x=m[0],$=m.subarray(1);if(y===o&&(x===2||x===3)){const E=ri($);if(!Ec(E,De,r.ORDER))throw new Error("Point is not on curve");const S=f(E);let F;try{F=r.sqrt(S)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const N=(F&De)===De;return(x&1)===1!==N&&(F=r.neg(F)),{x:E,y:F}}else if(y===a&&x===4){const E=r.fromBytes($.subarray(0,r.BYTES)),S=r.fromBytes($.subarray(r.BYTES,2*r.BYTES));return{x:E,y:S}}else{const E=o,S=a;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+S+", got "+y)}}});function p(m){const y=i>>De;return m>y}function g(m){return p(m)?c(-m):m}const w=(m,y,x)=>ri(m.slice(y,x));class I{constructor(y,x,$){Ai("r",y,De,i),Ai("s",x,De,i),this.r=y,this.s=x,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(y){const x=n;return y=mt("compactSignature",y,x*2),new I(w(y,0,x),w(y,x,2*x))}static fromDER(y){const{r:x,s:$}=nr.toSig(mt("DER",y));return new I(x,$)}assertValidity(){}addRecoveryBit(y){return new I(this.r,this.s,y)}recoverPublicKey(y){const{r:x,s:$,recovery:E}=this,S=T(mt("msgHash",y));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");const F=E===2||E===3?x+e.n:x;if(F>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const N=E&1?"03":"02",H=l.fromHex(N+Oo(F,r.BYTES)),z=u(F),q=c(-S*z),K=c($*z),G=l.BASE.multiplyAndAddUnsafe(H,q,K);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new I(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ms(this.toDERHex())}toDERHex(){return nr.hexFromSig(this)}toCompactRawBytes(){return ms(this.toCompactHex())}toCompactHex(){const y=n;return Oo(this.r,y)+Oo(this.s,y)}}const C={isValidPrivateKey(m){try{return h(m),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const m=md(e.n);return cm(e.randomBytes(m),e.n)},precompute(m=8,y=l.BASE){return y._setWindowSize(m),y.multiply(BigInt(3)),y}};function b(m,y=!0){return l.fromPrivateKey(m).toRawBytes(y)}function v(m){if(typeof m=="bigint")return!1;if(m instanceof l)return!0;const x=mt("key",m).length,$=r.BYTES,E=$+1,S=2*$+1;if(!(e.allowedPrivateKeyLengths||n===E))return x===E||x===S}function D(m,y,x=!0){if(v(m)===!0)throw new Error("first arg must be private key");if(v(y)===!1)throw new Error("second arg must be public key");return l.fromHex(y).multiply(h(m)).toRawBytes(x)}const P=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const y=ri(m),x=m.length*8-s;return x>0?y>>BigInt(x):y},T=e.bits2int_modN||function(m){return c(P(m))},R=zs(s);function A(m){return Ai("num < 2^"+s,m,or,R),Dn(m,n)}function U(m,y,x=j){if(["recovered","canonical"].some(W=>W in x))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:E}=e;let{lowS:S,prehash:F,extraEntropy:N}=x;S==null&&(S=!0),m=mt("msgHash",m),Hu(x),F&&(m=mt("prehashed msgHash",$(m)));const H=T(m),z=h(y),q=[A(z),A(H)];if(N!=null&&N!==!1){const W=N===!0?E(r.BYTES):N;q.push(mt("extraEntropy",W))}const K=bs(...q),G=H;function X(W){const Q=P(W);if(!d(Q))return;const pe=u(Q),ve=l.BASE.multiply(Q).toAffine(),Ie=c(ve.x);if(Ie===or)return;const He=c(pe*c(G+Ie*z));if(He===or)return;let Wt=(ve.x===Ie?0:2)|Number(ve.y&De),dr=He;return S&&p(He)&&(dr=g(He),Wt^=1),new I(Ie,dr,Wt)}return{seed:K,k2sig:X}}const j={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function _(m,y,x=j){const{seed:$,k2sig:E}=U(m,y,x),S=e;return yw(S.hash.outputLen,S.nByteLength,S.hmac)($,E)}l.BASE._setWindowSize(8);function O(m,y,x,$=B){var Wt;const E=m;y=mt("msgHash",y),x=mt("publicKey",x);const{lowS:S,prehash:F,format:N}=$;if(Hu($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&N!=="compact"&&N!=="der")throw new Error("format must be compact or der");const H=typeof E=="string"||On(E),z=!H&&!N&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!H&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,K;try{if(z&&(q=new I(E.r,E.s)),H){try{N!=="compact"&&(q=I.fromDER(E))}catch(dr){if(!(dr instanceof nr.Err))throw dr}!q&&N!=="der"&&(q=I.fromCompact(E))}K=l.fromHex(x)}catch{return!1}if(!q||S&&q.hasHighS())return!1;F&&(y=e.hash(y));const{r:G,s:X}=q,W=T(y),Q=u(X),pe=c(W*Q),ve=c(G*Q),Ie=(Wt=l.BASE.multiplyAndAddUnsafe(K,pe,ve))==null?void 0:Wt.toAffine();return Ie?c(Ie.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:D,sign:_,verify:O,ProjectivePoint:l,Signature:I,utils:C}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bm(t){return{hash:t,hmac:(e,...r)=>ld(t,e,zy(...r)),randomBytes:Vy}}function vm(t,e){const r=i=>mm({...t,...bm(i)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const xd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ku=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Em=BigInt(0),xm=BigInt(1),Ea=BigInt(2),Wu=(t,e)=>(t+e/Ea)/e;function _m(t){const e=xd,r=BigInt(3),i=BigInt(6),n=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,h=pt(l,r,e)*l%e,f=pt(h,r,e)*l%e,d=pt(f,Ea,e)*u%e,p=pt(d,n,e)*d%e,g=pt(p,s,e)*p%e,w=pt(g,a,e)*g%e,I=pt(w,c,e)*w%e,C=pt(I,a,e)*g%e,b=pt(C,r,e)*l%e,v=pt(b,o,e)*p%e,D=pt(v,i,e)*u%e,P=pt(D,Ea,e);if(!xa.eql(xa.sqr(P),t))throw new Error("Cannot find square root");return P}const xa=Ic(xd,void 0,void 0,{sqrt:_m}),Im=vm({a:Em,b:BigInt(7),Fp:xa,n:Ku,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Ku,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-xm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=Wu(s*t,e),c=Wu(-i*t,e);let u=Qe(t-a*r-c*n,e),l=Qe(-a*i-c*s,e);const h=u>o,f=l>o;if(h&&(u=e-u),f&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}}},dw);function Sm(t){if(t.length!==130&&t.length!==132)throw new Om({signature:t});const e=BigInt(ir(t,0,32)),r=BigInt(ir(t,32,64)),i=(()=>{const n=+`0x${t.slice(130)}`;if(!Number.isNaN(n))try{return $m(n)}catch{throw new Dm({value:n})}})();return typeof i>"u"?{r:e,s:r}:{r:e,s:r,yParity:i}}function $m(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new Am({value:t})}class Om extends de{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Nr(_c(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Dm extends de{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class Am extends de{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Pm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _d(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Es(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Sc(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function _a(t){if(!Array.isArray(t))throw new Error("array expected")}function xs(t,e){if(!_d(!0,e))throw new Error(`${t}: array of strings expected`)}function Cm(t,e){if(!_d(!1,e))throw new Error(`${t}: array of numbers expected`)}function Bm(...t){const e=s=>s,r=(s,o)=>a=>s(o(a)),i=t.map(s=>s.encode).reduceRight(r,e),n=t.map(s=>s.decode).reduce(r,e);return{encode:i,decode:n}}function Tm(t){const e=typeof t=="string"?t.split(""):t,r=e.length;xs("alphabet",e);const i=new Map(e.map((n,s)=>[n,s]));return{encode:n=>(_a(n),n.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:n=>(_a(n),n.map(s=>{Es("alphabet.decode",s);const o=i.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function Rm(t=""){return Es("join",t),{encode:e=>(xs("join.decode",e),e.join(t)),decode:e=>(Es("join.decode",e),e.split(t))}}function Fm(t,e="="){return Sc(t),Es("padding",e),{encode(r){for(xs("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){xs("padding.decode",r);let i=r.length;if(i*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===e;i--)if((i-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}const Id=(t,e)=>e===0?t:Id(e,t%e),_s=(t,e)=>t+(e-Id(t,e)),Ao=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Gu(t,e,r,i){if(_a(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(_s(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${_s(e,r)}`);let n=0,s=0;const o=Ao[e],a=Ao[r]-1,c=[];for(const u of t){if(Sc(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(n=n<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=r;s-=r)c.push((n>>s-r&a)>>>0);const l=Ao[s];if(l===void 0)throw new Error("invalid carry");n&=l-1}if(n=n<<r-s&a,!i&&s>=e)throw new Error("Excess padding");if(!i&&n>0)throw new Error(`Non-zero padding: ${n}`);return i&&s>0&&c.push(n>>>0),c}function Nm(t,e=!1){if(Sc(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(_s(8,t)>32||_s(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Pm(r))throw new Error("radix2.encode input should be Uint8Array");return Gu(Array.from(r),8,t,!e)},decode:r=>(Cm("radix2.decode",r),Uint8Array.from(Gu(r,t,8,e)))}}const Um=Bm(Nm(5),Tm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Fm(5),Rm(""));function km(t){return Xw(jm(t))}function jm(t){const{payload:e,signature:r}=t,{r:i,s:n,yParity:s}=r,a=new Im.Signature(BigInt(i),BigInt(n)).addRecoveryBit(s).recoverPublicKey(_c(e).substring(2));return zw(a)}function Lm(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,i=t.charAt(0),n=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,f=0;const d=u.length;for(;f!==d&&u[f]===0;)f++,l++;const p=(d-f)*s+1>>>0,g=new Uint8Array(p);for(;f!==d;){let C=u[f],b=0;for(let v=p-1;(C!==0||b<h)&&v!==-1;v--,b++)C+=256*g[v]>>>0,g[v]=C%r>>>0,C=C/r>>>0;if(C!==0)throw new Error("Non-zero carry");h=b,f++}let w=p-h;for(;w!==p&&g[w]===0;)w++;let I=i.repeat(l);for(;w<p;++w)I+=t.charAt(g[w]);return I}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===i;)h++,l++;const d=(u.length-l)*n+1>>>0,p=new Uint8Array(d);for(;l<u.length;){const C=u.charCodeAt(l);if(C>255)return;let b=e[C];if(b===255)return;let v=0;for(let D=d-1;(b!==0||v<f)&&D!==-1;D--,v++)b+=r*p[D]>>>0,p[D]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=v,l++}let g=d-f;for(;g!==d&&p[g]===0;)g++;const w=new Uint8Array(h+(d-g));let I=h;for(;g!==d;)w[I++]=p[g++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Mm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const An=Lm(Mm);function qm(t){const e=t.length;let r=0,i=0;for(;i<e;){let n=t.charCodeAt(i++);if(n&4294967168)if(!(n&4294965248))r+=2;else{if(n>=55296&&n<=56319&&i<e){const s=t.charCodeAt(i);(s&64512)===56320&&(++i,n=((n&1023)<<10)+(s&1023)+65536)}n&4294901760?r+=4:r+=3}else{r++;continue}}return r}function zm(t,e,r){const i=t.length;let n=r,s=0;for(;s<i;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<i){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128):(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128)}else{e[n++]=o;continue}e[n++]=o&63|128}}const Vm=new TextEncoder,Hm=50;function Km(t,e,r){Vm.encodeInto(t,e.subarray(r))}function Wm(t,e,r){t.length>Hm?Km(t,e,r):zm(t,e,r)}const Gm=4096;function Sd(t,e,r){let i=e;const n=i+r,s=[];let o="";for(;i<n;){const a=t[i++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[i++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[i++]&63,u=t[i++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[i++]&63,u=t[i++]&63,l=t[i++]&63;let h=(a&7)<<18|c<<12|u<<6|l;h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|h&1023),s.push(h)}else s.push(a);s.length>=Gm&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Ym=new TextDecoder,Zm=200;function Jm(t,e,r){const i=t.subarray(e,e+r);return Ym.decode(i)}function Xm(t,e,r){return r>Zm?Jm(t,e,r):Sd(t,e,r)}class qn{constructor(e,r){this.type=e,this.data=r}}class lt extends Error{constructor(e){super(e);const r=Object.create(lt.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:lt.name})}}const Ki=4294967295;function Qm(t,e,r){const i=r/4294967296,n=r;t.setUint32(e,i),t.setUint32(e+4,n)}function $d(t,e,r){const i=Math.floor(r/4294967296),n=r;t.setUint32(e,i),t.setUint32(e+4,n)}function Od(t,e){const r=t.getInt32(e),i=t.getUint32(e+4);return r*4294967296+i}function e1(t,e){const r=t.getUint32(e),i=t.getUint32(e+4);return r*4294967296+i}const t1=-1,r1=4294967296-1,i1=17179869184-1;function n1({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=i1)if(e===0&&t<=r1){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,i=t&4294967295,n=new Uint8Array(8),s=new DataView(n.buffer);return s.setUint32(0,e<<2|r&3),s.setUint32(4,i),n}else{const r=new Uint8Array(12),i=new DataView(r.buffer);return i.setUint32(0,e),$d(i,4,t),r}}function s1(t){const e=t.getTime(),r=Math.floor(e/1e3),i=(e-r*1e3)*1e6,n=Math.floor(i/1e9);return{sec:r+n,nsec:i-n*1e9}}function o1(t){if(t instanceof Date){const e=s1(t);return n1(e)}else return null}function a1(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const r=e.getUint32(0),i=e.getUint32(4),n=(r&3)*4294967296+i,s=r>>>2;return{sec:n,nsec:s}}case 12:{const r=Od(e,4),i=e.getUint32(0);return{sec:r,nsec:i}}default:throw new lt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function c1(t){const e=a1(t);return new Date(e.sec*1e3+e.nsec/1e6)}const u1={type:t1,encode:o1,decode:c1};class Is{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(u1)}register({type:e,encode:r,decode:i}){if(e>=0)this.encoders[e]=r,this.decoders[e]=i;else{const n=-1-e;this.builtInEncoders[n]=r,this.builtInDecoders[n]=i}}tryToEncode(e,r){for(let i=0;i<this.builtInEncoders.length;i++){const n=this.builtInEncoders[i];if(n!=null){const s=n(e,r);if(s!=null){const o=-1-i;return new qn(o,s)}}}for(let i=0;i<this.encoders.length;i++){const n=this.encoders[i];if(n!=null){const s=n(e,r);if(s!=null){const o=i;return new qn(o,s)}}}return e instanceof qn?e:null}decode(e,r,i){const n=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return n?n(e,r,i):new qn(r,e)}}Is.defaultCodec=new Is;function l1(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ia(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):l1(t)?new Uint8Array(t):Uint8Array.from(t)}const h1=100,f1=2048;let d1=class Dd{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Is.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)??h1,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??f1,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 Dd({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),i=new Uint8Array(r),n=new DataView(r);i.set(this.bytes),this.view=n,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=qm(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Wm(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,r){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const i=Ia(e);this.writeU8a(i)}encodeArray(e,r){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const n of e)this.doEncode(n,r+1)}countWithoutUndefined(e,r){let i=0;for(const n of r)e[n]!==void 0&&i++;return i}encodeMap(e,r){const i=Object.keys(e);this.sortKeys&&i.sort();const n=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(const s of i){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),n=i.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(i);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Qm(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),$d(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 p1(t,e){return new d1(e).encodeSharedRef(t)}function Po(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const g1=16,y1=16;class w1{constructor(e=g1,r=y1){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,i){const n=this.caches[i-1];e:for(const s of n){const o=s.bytes;for(let a=0;a<i;a++)if(o[a]!==e[r+a])continue e;return s.str}return null}store(e,r){const i=this.caches[e.length-1],n={bytes:e,str:r};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=n:i.push(n)}decode(e,r,i){const n=this.find(e,r,i);if(n!=null)return this.hit++,n;this.miss++;const s=Sd(e,r,i),o=Uint8Array.prototype.slice.call(e,r,r+i);return this.store(o,s),s}}const Sa="array",hn="map_key",Ad="map_value",m1=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new lt("The type of key must be string or number but "+typeof t)};class b1{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=Sa,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=hn,r.readCount=0,r.size=e,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Sa){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===hn||e.type===Ad){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wi=-1,$c=new DataView(new ArrayBuffer(0)),v1=new Uint8Array($c.buffer);try{$c.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 Yu=new RangeError("Insufficient data"),E1=new w1;let x1=class Pd{constructor(e){this.totalPos=0,this.pos=0,this.view=$c,this.bytes=v1,this.headByte=Wi,this.stack=new b1,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Is.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)??Ki,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Ki,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Ki,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Ki,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Ki,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:E1,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??m1}clone(){return new Pd({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=Wi,this.stack.reset()}setBuffer(e){const r=Ia(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wi&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),i=Ia(e),n=new Uint8Array(r.length+i.length);n.set(r),n.set(i,r.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:i}=this;return new RangeError(`Extra ${r.byteLength-i} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,i;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:n,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Po(n)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let i=r,n=-1;for await(const s of e){if(r&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(n=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e<160){const n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else{const n=e-160;r=this.decodeString(n,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const n=this.lookU8();r=this.decodeString(n,1)}else if(e===218){const n=this.lookU16();r=this.decodeString(n,2)}else if(e===219){const n=this.lookU32();r=this.decodeString(n,4)}else if(e===220){const n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===221){const n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===222){const n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===223){const n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===196){const n=this.lookU8();r=this.decodeBinary(n,1)}else if(e===197){const n=this.lookU16();r=this.decodeBinary(n,2)}else if(e===198){const n=this.lookU32();r=this.decodeBinary(n,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const n=this.lookU8();r=this.decodeExtension(n,1)}else if(e===200){const n=this.lookU16();r=this.decodeExtension(n,2)}else if(e===201){const n=this.lookU32();r=this.decodeExtension(n,4)}else throw new lt(`Unrecognized type byte: ${Po(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const n=i.top();if(n.type===Sa)if(n.array[n.position]=r,n.position++,n.position===n.size)r=n.array,i.release(n);else continue e;else if(n.type===hn){if(r==="__proto__")throw new lt("The key __proto__ is not allowed");n.key=this.mapKeyConverter(r),n.type=Ad;continue e}else if(n.map[n.key]=r,n.readCount++,n.readCount===n.size)r=n.map,i.release(n);else{n.key=null,n.type=hn;continue e}}return r}}readHeadByte(){return this.headByte===Wi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wi}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 lt(`Unrecognized array type byte: ${Po(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new lt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new lt(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){var s;if(e>this.maxStrLength)throw new lt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw Yu;const i=this.pos+r;let n;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?n=this.keyDecoder.decode(this.bytes,i,e):n=Xm(this.bytes,i,e),this.pos+=r+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hn:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new lt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw Yu;const i=this.pos+r,n=this.bytes.subarray(i,i+e);return this.pos+=r+e,n}decodeExtension(e,r){if(e>this.maxExtLength)throw new lt(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+r),n=this.decodeBinary(e,r+1);return this.extensionCodec.decode(n,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=e1(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Od(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 _1(t,e){return new x1(e).decode(t)}const I1=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),S1=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function si(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return S1(t)}catch{return t}}function lr(t){return typeof t=="string"?t:I1(t)||""}function $1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Cd(t,...e){if(!$1(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 Zu(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 O1(t,e){Cd(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const wi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Co=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function D1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Bd(t){return typeof t=="string"&&(t=D1(t)),Cd(t),t}let A1=class{clone(){return this._cloneInto()}};function P1(t){const e=i=>t().update(Bd(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Td(t=32){if(wi&&typeof wi.getRandomValues=="function")return wi.getRandomValues(new Uint8Array(t));if(wi&&typeof wi.randomBytes=="function")return wi.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function C1(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}let B1=class extends A1{constructor(e,r,i,n){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){Zu(this);const{view:r,buffer:i,blockLen:n}=this;e=Bd(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=Co(e);for(;n<=s-o;o+=n)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zu(this),O1(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;C1(i,n-8,BigInt(this.length*8),s),this.process(i,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.length=n,e.pos=a,e.finished=s,e.destroyed=o,n%r&&e.buffer.set(i),e}};const zn=BigInt(2**32-1),$a=BigInt(32);function Rd(t,e=!1){return e?{h:Number(t&zn),l:Number(t>>$a&zn)}:{h:Number(t>>$a&zn)|0,l:Number(t&zn)|0}}function T1(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let n=0;n<t.length;n++){const{h:s,l:o}=Rd(t[n],e);[r[n],i[n]]=[s,o]}return[r,i]}const R1=(t,e)=>BigInt(t>>>0)<<$a|BigInt(e>>>0),F1=(t,e,r)=>t>>>r,N1=(t,e,r)=>t<<32-r|e>>>r,U1=(t,e,r)=>t>>>r|e<<32-r,k1=(t,e,r)=>t<<32-r|e>>>r,j1=(t,e,r)=>t<<64-r|e>>>r-32,L1=(t,e,r)=>t>>>r-32|e<<64-r,M1=(t,e)=>e,q1=(t,e)=>t,z1=(t,e,r)=>t<<r|e>>>32-r,V1=(t,e,r)=>e<<r|t>>>32-r,H1=(t,e,r)=>e<<r-32|t>>>64-r,K1=(t,e,r)=>t<<r-32|e>>>64-r;function W1(t,e,r,i){const n=(e>>>0)+(i>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}const G1=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Y1=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,Z1=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),J1=(t,e,r,i,n)=>e+r+i+n+(t/2**32|0)|0,X1=(t,e,r,i,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(n>>>0),Q1=(t,e,r,i,n,s)=>e+r+i+n+s+(t/2**32|0)|0,J={fromBig:Rd,split:T1,toBig:R1,shrSH:F1,shrSL:N1,rotrSH:U1,rotrSL:k1,rotrBH:j1,rotrBL:L1,rotr32H:M1,rotr32L:q1,rotlSH:z1,rotlSL:V1,rotlBH:H1,rotlBL:K1,add:W1,add3L:G1,add3H:Y1,add4L:Z1,add4H:J1,add5H:Q1,add5L:X1},[eb,tb]=(()=>J.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))))(),yr=new Uint32Array(80),wr=new Uint32Array(80);let rb=class extends B1{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:n,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=n|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,r){for(let b=0;b<16;b++,r+=4)yr[b]=e.getUint32(r),wr[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const v=yr[b-15]|0,D=wr[b-15]|0,P=J.rotrSH(v,D,1)^J.rotrSH(v,D,8)^J.shrSH(v,D,7),T=J.rotrSL(v,D,1)^J.rotrSL(v,D,8)^J.shrSL(v,D,7),R=yr[b-2]|0,A=wr[b-2]|0,U=J.rotrSH(R,A,19)^J.rotrBH(R,A,61)^J.shrSH(R,A,6),j=J.rotrSL(R,A,19)^J.rotrBL(R,A,61)^J.shrSL(R,A,6),B=J.add4L(T,j,wr[b-7],wr[b-16]),_=J.add4H(B,P,U,yr[b-7],yr[b-16]);yr[b]=_|0,wr[b]=B|0}let{Ah:i,Al:n,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:d,Fl:p,Gh:g,Gl:w,Hh:I,Hl:C}=this;for(let b=0;b<80;b++){const v=J.rotrSH(h,f,14)^J.rotrSH(h,f,18)^J.rotrBH(h,f,41),D=J.rotrSL(h,f,14)^J.rotrSL(h,f,18)^J.rotrBL(h,f,41),P=h&d^~h&g,T=f&p^~f&w,R=J.add5L(C,D,T,tb[b],wr[b]),A=J.add5H(R,I,v,P,eb[b],yr[b]),U=R|0,j=J.rotrSH(i,n,28)^J.rotrBH(i,n,34)^J.rotrBH(i,n,39),B=J.rotrSL(i,n,28)^J.rotrBL(i,n,34)^J.rotrBL(i,n,39),_=i&s^i&a^s&a,O=n&o^n&c^o&c;I=g|0,C=w|0,g=d|0,w=p|0,d=h|0,p=f|0,{h,l:f}=J.add(u|0,l|0,A|0,U|0),u=a|0,l=c|0,a=s|0,c=o|0,s=i|0,o=n|0;const m=J.add3L(U,B,O);i=J.add3H(m,A,j,_),n=m|0}({h:i,l:n}=J.add(this.Ah|0,this.Al|0,i|0,n|0)),{h:s,l:o}=J.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=J.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=J.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=J.add(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=J.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=J.add(this.Gh|0,this.Gl|0,g|0,w|0),{h:I,l:C}=J.add(this.Hh|0,this.Hl|0,I|0,C|0),this.set(i,n,s,o,a,c,u,l,h,f,d,p,g,w,I,C)}roundClean(){yr.fill(0),wr.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 ib=P1(()=>new rb);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oc=BigInt(0),Fd=BigInt(1),nb=BigInt(2);function Dc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ac(t){if(!Dc(t))throw new Error("Uint8Array expected")}function Bo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const sb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pc(t){Ac(t);let e="";for(let r=0;r<t.length;r++)e+=sb[t[r]];return e}function Nd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Oc:BigInt("0x"+t)}const Zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ju(t){if(t>=Zt._0&&t<=Zt._9)return t-Zt._0;if(t>=Zt.A&&t<=Zt.F)return t-(Zt.A-10);if(t>=Zt.a&&t<=Zt.f)return t-(Zt.a-10)}function Ud(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Ju(t.charCodeAt(s)),a=Ju(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}i[n]=o*16+a}return i}function ob(t){return Nd(Pc(t))}function ls(t){return Ac(t),Nd(Pc(Uint8Array.from(t).reverse()))}function kd(t,e){return Ud(t.toString(16).padStart(e*2,"0"))}function Oa(t,e){return kd(t,e).reverse()}function Jt(t,e,r){let i;if(typeof e=="string")try{i=Ud(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Dc(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}function Xu(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];Ac(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}const To=t=>typeof t=="bigint"&&Oc<=t;function ab(t,e,r){return To(t)&&To(e)&&To(r)&&e<=t&&t<r}function Gi(t,e,r,i){if(!ab(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function cb(t){let e;for(e=0;t>Oc;t>>=Fd,e+=1);return e}const ub=t=>(nb<<BigInt(t-1))-Fd,lb={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"||Dc(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 Cc(t,e,r={}){const i=(n,s,o)=>{const a=lb[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[n];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(n)+" is invalid. Expected "+s+", got "+c)};for(const[n,s]of Object.entries(e))i(n,s,!1);for(const[n,s]of Object.entries(r))i(n,s,!0);return t}function Qu(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}const Ae=BigInt(0),ge=BigInt(1),Gr=BigInt(2),hb=BigInt(3),Da=BigInt(4),el=BigInt(5),tl=BigInt(8);function xe(t,e){const r=t%e;return r>=Ae?r:e+r}function fb(t,e,r){if(e<Ae)throw new Error("invalid exponent, negatives unsupported");if(r<=Ae)throw new Error("invalid modulus");if(r===ge)return Ae;let i=ge;for(;e>Ae;)e&ge&&(i=i*t%r),t=t*t%r,e>>=ge;return i}function Ft(t,e,r){let i=t;for(;e-- >Ae;)i*=i,i%=r;return i}function rl(t,e){if(t===Ae)throw new Error("invert: expected non-zero number");if(e<=Ae)throw new Error("invert: expected positive modulus, got "+e);let r=xe(t,e),i=e,n=Ae,s=ge;for(;r!==Ae;){const o=i/r,a=i%r,c=n-s*o;i=r,r=a,n=s,s=c}if(i!==ge)throw new Error("invert: does not exist");return xe(n,e)}function db(t){const e=(t-ge)/Gr;let r,i,n;for(r=t-ge,i=0;r%Gr===Ae;r/=Gr,i++);for(n=Gr;n<t&&fb(n,e,t)!==t-ge;n++)if(n>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ge)/Da;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(r+ge)/Gr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,n),r),l=o.pow(a,s),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(h);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);const d=o.pow(u,ge<<BigInt(c-f-1));u=o.sqr(d),l=o.mul(l,d),h=o.mul(h,u),c=f}return l}}function pb(t){if(t%Da===hb){const e=(t+ge)/Da;return function(r,i){const n=r.pow(i,e);if(!r.eql(r.sqr(n),i))throw new Error("Cannot find square root");return n}}if(t%tl===el){const e=(t-el)/tl;return function(r,i){const n=r.mul(i,Gr),s=r.pow(n,e),o=r.mul(i,s),a=r.mul(r.mul(o,Gr),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return db(t)}const gb=(t,e)=>(xe(t,e)&ge)===ge,yb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function wb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=yb.reduce((i,n)=>(i[n]="function",i),e);return Cc(t,r)}function mb(t,e,r){if(r<Ae)throw new Error("invalid exponent, negatives unsupported");if(r===Ae)return t.ONE;if(r===ge)return e;let i=t.ONE,n=e;for(;r>Ae;)r&ge&&(i=t.mul(i,n)),n=t.sqr(n),r>>=ge;return i}function bb(t,e){const r=new Array(e.length),i=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),n=t.inv(i);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),n),r}function jd(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Ld(t,e,r=!1,i={}){if(t<=Ae)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=jd(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:n,BYTES:s,MASK:ub(n),ZERO:Ae,ONE:ge,create:c=>xe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ae<=c&&c<t},is0:c=>c===Ae,isOdd:c=>(c&ge)===ge,neg:c=>xe(-c,t),eql:(c,u)=>c===u,sqr:c=>xe(c*c,t),add:(c,u)=>xe(c+u,t),sub:(c,u)=>xe(c-u,t),mul:(c,u)=>xe(c*u,t),pow:(c,u)=>mb(a,c,u),div:(c,u)=>xe(c*rl(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>rl(c,t),sqrt:i.sqrt||(c=>(o||(o=pb(t)),o(a,c))),invertBatch:c=>bb(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Oa(c,s):kd(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?ls(c):ob(c)}});return Object.freeze(a)}const il=BigInt(0),Vn=BigInt(1);function Ro(t,e){const r=e.negate();return t?r:e}function Md(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){Md(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function vb(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Eb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const No=new WeakMap,qd=new WeakMap;function Uo(t){return qd.get(t)||1}function xb(t,e){return{constTimeNegate:Ro,hasPrecomputes(r){return Uo(r)!==1},unsafeLadder(r,i,n=t.ZERO){let s=r;for(;i>il;)i&Vn&&(n=n.add(s)),s=s.double(),i>>=Vn;return n},precomputeWindow(r,i){const{windows:n,windowSize:s}=Fo(i,e),o=[];let a=r,c=a;for(let u=0;u<n;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,n){const{windows:s,windowSize:o}=Fo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let f=0;f<s;f++){const d=f*o;let p=Number(n&u);n>>=h,p>o&&(p-=l,n+=Vn);const g=d,w=d+Math.abs(p)-1,I=f%2!==0,C=p<0;p===0?c=c.add(Ro(I,i[g])):a=a.add(Ro(C,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,n,s=t.ZERO){const{windows:o,windowSize:a}=Fo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(n===il)break;let d=Number(n&c);if(n>>=l,d>a&&(d-=u,n+=Vn),d===0)continue;let p=i[f+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(r,i,n){let s=No.get(i);return s||(s=this.precomputeWindow(i,r),r!==1&&No.set(i,n(s))),s},wNAFCached(r,i,n){const s=Uo(r);return this.wNAF(s,this.getPrecomputes(s,r,n),i)},wNAFCachedUnsafe(r,i,n,s){const o=Uo(r);return o===1?this.unsafeLadder(r,i,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,n),i,s)},setWindowSize(r,i){Md(i,e),qd.set(r,i),No.delete(r)}}}function _b(t,e,r,i){if(vb(r,t),Eb(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const n=t.ZERO,s=cb(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(n),u=Math.floor((e.BITS-1)/o)*o;let l=n;for(let h=u;h>=0;h-=o){c.fill(n);for(let d=0;d<i.length;d++){const p=i[d],g=Number(p>>BigInt(h)&BigInt(a));c[g]=c[g].add(r[d])}let f=n;for(let d=c.length-1,p=n;d>0;d--)p=p.add(c[d]),f=f.add(p);if(l=l.add(f),h!==0)for(let d=0;d<o;d++)l=l.double()}return l}function Ib(t){return wb(t.Fp),Cc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...jd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const $t=BigInt(0),Ye=BigInt(1),Hn=BigInt(2),Sb=BigInt(8),$b={zip215:!0};function Ob(t){const e=Ib(t);return Cc(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Db(t){const e=Ob(t),{Fp:r,n:i,prehash:n,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=Hn<<BigInt(a*8)-Ye,l=r.create,h=Ld(e.n,e.nBitLength),f=e.uvRatio||((m,y)=>{try{return{isValid:!0,value:r.sqrt(m*r.inv(y))}}catch{return{isValid:!1,value:$t}}}),d=e.adjustScalarBytes||(m=>m),p=e.domain||((m,y,x)=>{if(Bo("phflag",x),y.length||x)throw new Error("Contexts/pre-hash are not supported");return m});function g(m,y){Gi("coordinate "+m,y,$t,u)}function w(m){if(!(m instanceof b))throw new Error("ExtendedPoint expected")}const I=Qu((m,y)=>{const{ex:x,ey:$,ez:E}=m,S=m.is0();y==null&&(y=S?Sb:r.inv(E));const F=l(x*y),N=l($*y),H=l(E*y);if(S)return{x:$t,y:Ye};if(H!==Ye)throw new Error("invZ was invalid");return{x:F,y:N}}),C=Qu(m=>{const{a:y,d:x}=e;if(m.is0())throw new Error("bad point: ZERO");const{ex:$,ey:E,ez:S,et:F}=m,N=l($*$),H=l(E*E),z=l(S*S),q=l(z*z),K=l(N*y),G=l(z*l(K+H)),X=l(q+l(x*l(N*H)));if(G!==X)throw new Error("bad point: equation left != right (1)");const W=l($*E),Q=l(S*F);if(W!==Q)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(y,x,$,E){this.ex=y,this.ey=x,this.ez=$,this.et=E,g("x",y),g("y",x),g("z",$),g("t",E),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof b)throw new Error("extended point not allowed");const{x,y:$}=y||{};return g("x",x),g("y",$),new b(x,$,Ye,l(x*$))}static normalizeZ(y){const x=r.invertBatch(y.map($=>$.ez));return y.map(($,E)=>$.toAffine(x[E])).map(b.fromAffine)}static msm(y,x){return _b(b,h,y,x)}_setWindowSize(y){P.setWindowSize(this,y)}assertValidity(){C(this)}equals(y){w(y);const{ex:x,ey:$,ez:E}=this,{ex:S,ey:F,ez:N}=y,H=l(x*N),z=l(S*E),q=l($*N),K=l(F*E);return H===z&&q===K}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:y}=e,{ex:x,ey:$,ez:E}=this,S=l(x*x),F=l($*$),N=l(Hn*l(E*E)),H=l(y*S),z=x+$,q=l(l(z*z)-S-F),K=H+F,G=K-N,X=H-F,W=l(q*G),Q=l(K*X),pe=l(q*X),ve=l(G*K);return new b(W,Q,ve,pe)}add(y){w(y);const{a:x,d:$}=e,{ex:E,ey:S,ez:F,et:N}=this,{ex:H,ey:z,ez:q,et:K}=y;if(x===BigInt(-1)){const au=l((S-E)*(z+H)),cu=l((S+E)*(z-H)),fo=l(cu-au);if(fo===$t)return this.double();const uu=l(F*Hn*K),lu=l(N*Hn*q),hu=lu+uu,fu=cu+au,du=lu-uu,P0=l(hu*fo),C0=l(fu*du),B0=l(hu*du),T0=l(fo*fu);return new b(P0,C0,T0,B0)}const G=l(E*H),X=l(S*z),W=l(N*$*K),Q=l(F*q),pe=l((E+S)*(H+z)-G-X),ve=Q-W,Ie=Q+W,He=l(X-x*G),Wt=l(pe*ve),dr=l(Ie*He),D0=l(pe*He),A0=l(ve*Ie);return new b(Wt,dr,A0,D0)}subtract(y){return this.add(y.negate())}wNAF(y){return P.wNAFCached(this,y,b.normalizeZ)}multiply(y){const x=y;Gi("scalar",x,Ye,i);const{p:$,f:E}=this.wNAF(x);return b.normalizeZ([$,E])[0]}multiplyUnsafe(y,x=b.ZERO){const $=y;return Gi("scalar",$,$t,i),$===$t?D:this.is0()||$===Ye?this:P.wNAFCachedUnsafe(this,$,b.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,i).is0()}toAffine(y){return I(this,y)}clearCofactor(){const{h:y}=e;return y===Ye?this:this.multiplyUnsafe(y)}static fromHex(y,x=!1){const{d:$,a:E}=e,S=r.BYTES;y=Jt("pointHex",y,S),Bo("zip215",x);const F=y.slice(),N=y[S-1];F[S-1]=N&-129;const H=ls(F),z=x?u:r.ORDER;Gi("pointHex.y",H,$t,z);const q=l(H*H),K=l(q-Ye),G=l($*q-E);let{isValid:X,value:W}=f(K,G);if(!X)throw new Error("Point.fromHex: invalid y coordinate");const Q=(W&Ye)===Ye,pe=(N&128)!==0;if(!x&&W===$t&&pe)throw new Error("Point.fromHex: x=0 and x_0=1");return pe!==Q&&(W=l(-W)),b.fromAffine({x:W,y:H})}static fromPrivateKey(y){return A(y).point}toRawBytes(){const{x:y,y:x}=this.toAffine(),$=Oa(x,r.BYTES);return $[$.length-1]|=y&Ye?128:0,$}toHex(){return Pc(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,Ye,l(e.Gx*e.Gy)),b.ZERO=new b($t,Ye,Ye,$t);const{BASE:v,ZERO:D}=b,P=xb(b,a*8);function T(m){return xe(m,i)}function R(m){return T(ls(m))}function A(m){const y=r.BYTES;m=Jt("private key",m,y);const x=Jt("hashed private key",s(m),2*y),$=d(x.slice(0,y)),E=x.slice(y,2*y),S=R($),F=v.multiply(S),N=F.toRawBytes();return{head:$,prefix:E,scalar:S,point:F,pointBytes:N}}function U(m){return A(m).pointBytes}function j(m=new Uint8Array,...y){const x=Xu(...y);return R(s(p(x,Jt("context",m),!!n)))}function B(m,y,x={}){m=Jt("message",m),n&&(m=n(m));const{prefix:$,scalar:E,pointBytes:S}=A(y),F=j(x.context,$,m),N=v.multiply(F).toRawBytes(),H=j(x.context,N,S,m),z=T(F+H*E);Gi("signature.s",z,$t,i);const q=Xu(N,Oa(z,r.BYTES));return Jt("result",q,r.BYTES*2)}const _=$b;function O(m,y,x,$=_){const{context:E,zip215:S}=$,F=r.BYTES;m=Jt("signature",m,2*F),y=Jt("message",y),x=Jt("publicKey",x,F),S!==void 0&&Bo("zip215",S),n&&(y=n(y));const N=ls(m.slice(F,2*F));let H,z,q;try{H=b.fromHex(x,S),z=b.fromHex(m.slice(0,F),S),q=v.multiplyUnsafe(N)}catch{return!1}if(!S&&H.isSmallOrder())return!1;const K=j(E,z.toRawBytes(),H.toRawBytes(),y);return z.add(H.multiplyUnsafe(K)).subtract(q).clearCofactor().equals(b.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:U,sign:B,verify:O,ExtendedPoint:b,utils:{getExtendedPublicKey:A,randomPrivateKey:()=>o(r.BYTES),precompute(m=8,y=b.BASE){return y._setWindowSize(m),y.multiply(BigInt(3)),y}}}}BigInt(0),BigInt(1);const Bc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),nl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ab=BigInt(1),sl=BigInt(2);BigInt(3);const Pb=BigInt(5),Cb=BigInt(8);function Bb(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),s=Bc,o=t*t%s*t%s,a=Ft(o,sl,s)*o%s,c=Ft(a,Ab,s)*t%s,u=Ft(c,Pb,s)*c%s,l=Ft(u,e,s)*u%s,h=Ft(l,r,s)*l%s,f=Ft(h,i,s)*h%s,d=Ft(f,n,s)*f%s,p=Ft(d,n,s)*f%s,g=Ft(p,e,s)*u%s;return{pow_p_5_8:Ft(g,sl,s)*t%s,b2:o}}function Tb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Rb(t,e){const r=Bc,i=xe(e*e*e,r),n=xe(i*i*e,r),s=Bb(t*n).pow_p_5_8;let o=xe(t*i*s,r);const a=xe(e*o*o,r),c=o,u=xe(o*nl,r),l=a===t,h=a===xe(-t,r),f=a===xe(-t*nl,r);return l&&(o=c),(h||f)&&(o=u),gb(o,r)&&(o=xe(-o,r)),{isValid:l||h,value:o}}const Fb=(()=>Ld(Bc,void 0,!0))(),Nb=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Fb,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Cb,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ib,randomBytes:Td,adjustScalarBytes:Tb,uvRatio:Rb}))(),zd=(()=>Db(Nb))(),Ub="EdDSA",kb="JWT",Ss=".",Hs="base64url",Vd="utf8",Hd="utf8",jb=":",Lb="did",Mb="key",ol="base58btc",qb="z",zb="K36",Vb=32;function Tc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Kd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Tc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Wd(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const r=Kd(e);let i=0;for(const n of t)r.set(n,i),i+=n.length;return Tc(r)}function Hb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*l+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*u+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var Kb=Hb,Wb=Kb;const Gd=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")},Gb=t=>new TextEncoder().encode(t),Yb=t=>new TextDecoder().decode(t);let Zb=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Jb=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yd(this,e)}},Xb=class{constructor(e){this.decoders=e}or(e){return Yd(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Yd=(t,e)=>new Xb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Qb=class{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new Zb(e,r,i),this.decoder=new Jb(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ks=({name:t,prefix:e,encode:r,decode:i})=>new Qb(t,e,r,i),Pn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=Wb(r,e);return Ks({prefix:t,name:e,encode:i,decode:s=>Gd(n(s))})},ev=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},tv=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Fe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ks({prefix:e,name:t,encode(n){return tv(n,i,r)},decode(n){return ev(n,i,r,t)}}),rv=Ks({prefix:"\0",name:"identity",encode:t=>Yb(t),decode:t=>Gb(t)});var iv=Object.freeze({__proto__:null,identity:rv});const nv=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sv=Object.freeze({__proto__:null,base2:nv});const ov=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var av=Object.freeze({__proto__:null,base8:ov});const cv=Pn({prefix:"9",name:"base10",alphabet:"0123456789"});var uv=Object.freeze({__proto__:null,base10:cv});const lv=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),hv=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fv=Object.freeze({__proto__:null,base16:lv,base16upper:hv});const dv=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),pv=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),gv=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yv=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),wv=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),mv=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bv=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vv=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ev=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xv=Object.freeze({__proto__:null,base32:dv,base32upper:pv,base32pad:gv,base32padupper:yv,base32hex:wv,base32hexupper:mv,base32hexpad:bv,base32hexpadupper:vv,base32z:Ev});const _v=Pn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Iv=Pn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Sv=Object.freeze({__proto__:null,base36:_v,base36upper:Iv});const $v=Pn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ov=Pn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Dv=Object.freeze({__proto__:null,base58btc:$v,base58flickr:Ov});const Av=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Pv=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Cv=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bv=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Tv=Object.freeze({__proto__:null,base64:Av,base64pad:Pv,base64url:Cv,base64urlpad:Bv});const Zd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Rv=Zd.reduce((t,e,r)=>(t[r]=e,t),[]),Fv=Zd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Nv(t){return t.reduce((e,r)=>(e+=Rv[r],e),"")}function Uv(t){const e=[];for(const r of t){const i=Fv[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const kv=Ks({prefix:"🚀",name:"base256emoji",encode:Nv,decode:Uv});var jv=Object.freeze({__proto__:null,base256emoji:kv}),Lv=Jd,al=128,Mv=127,qv=~Mv,zv=Math.pow(2,31);function Jd(t,e,r){e=e||[],r=r||0;for(var i=r;t>=zv;)e[r++]=t&255|al,t/=128;for(;t&qv;)e[r++]=t&255|al,t>>>=7;return e[r]=t|0,Jd.bytes=r-i+1,e}var Vv=Aa,Hv=128,cl=127;function Aa(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Aa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&cl)<<n:(o&cl)*Math.pow(2,n),n+=7}while(o>=Hv);return Aa.bytes=s-i,r}var Kv=Math.pow(2,7),Wv=Math.pow(2,14),Gv=Math.pow(2,21),Yv=Math.pow(2,28),Zv=Math.pow(2,35),Jv=Math.pow(2,42),Xv=Math.pow(2,49),Qv=Math.pow(2,56),e2=Math.pow(2,63),t2=function(t){return t<Kv?1:t<Wv?2:t<Gv?3:t<Yv?4:t<Zv?5:t<Jv?6:t<Xv?7:t<Qv?8:t<e2?9:10},r2={encode:Lv,decode:Vv,encodingLength:t2},Xd=r2;const ul=(t,e,r=0)=>(Xd.encode(t,e,r),e),ll=t=>Xd.encodingLength(t),Pa=(t,e)=>{const r=e.byteLength,i=ll(t),n=i+ll(r),s=new Uint8Array(n+r);return ul(t,s,0),ul(r,s,i),s.set(e,n),new i2(t,r,e,s)};let i2=class{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}};const Qd=({name:t,code:e,encode:r})=>new n2(t,e,r);let n2=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Pa(this.code,r):r.then(i=>Pa(this.code,i))}else throw Error("Unknown type, must be binary type")}};const ep=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),s2=Qd({name:"sha2-256",code:18,encode:ep("SHA-256")}),o2=Qd({name:"sha2-512",code:19,encode:ep("SHA-512")});var a2=Object.freeze({__proto__:null,sha256:s2,sha512:o2});const tp=0,c2="identity",rp=Gd,u2=t=>Pa(tp,rp(t)),l2={code:tp,name:c2,encode:rp,digest:u2};var h2=Object.freeze({__proto__:null,identity:l2});new TextEncoder,new TextDecoder;const hl={...iv,...sv,...av,...uv,...fv,...xv,...Sv,...Dv,...Tv,...jv};({...a2,...h2});function ip(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const fl=ip("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ko=ip("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Kd(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),np={utf8:fl,"utf-8":fl,hex:hl.base16,latin1:ko,ascii:ko,binary:ko,...hl};function Ws(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function Li(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Tc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function dl(t){return si(Ws(Li(t,Hs),Vd))}function $s(t){return Ws(Li(lr(t),Vd),Hs)}function sp(t){const e=Li(zb,ol),r=qb+Ws(Wd([e,t]),ol);return[Lb,Mb,r].join(jb)}function f2(t){return Ws(t,Hs)}function d2(t){return Li(t,Hs)}function p2(t){return Li([$s(t.header),$s(t.payload)].join(Ss),Hd)}function g2(t){return[$s(t.header),$s(t.payload),f2(t.signature)].join(Ss)}function Ca(t){const e=t.split(Ss),r=dl(e[0]),i=dl(e[1]),n=d2(e[2]),s=Li(e.slice(0,2).join(Ss),Hd);return{header:r,payload:i,signature:n,data:s}}function pl(t=Td(Vb)){const e=zd.getPublicKey(t);return{secretKey:Wd([t,e]),publicKey:e}}async function y2(t,e,r,i,n=L.fromMiliseconds(Date.now())){const s={alg:Ub,typ:kb},o=sp(i.publicKey),a=n+r,c={iss:o,sub:t,aud:e,iat:n,exp:a},u=p2({header:s,payload:c}),l=zd.sign(u,i.secretKey.slice(0,32));return g2({header:s,payload:c,signature:l})}function Rc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function op(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Rc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fn(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const r=op(e);let i=0;for(const n of t)r.set(n,i),i+=n.length;return Rc(r)}function w2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*l+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*u+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var m2=w2,b2=m2;const v2=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")},E2=t=>new TextEncoder().encode(t),x2=t=>new TextDecoder().decode(t);class _2{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class I2{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ap(this,e)}}class S2{constructor(e){this.decoders=e}or(e){return ap(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ap=(t,e)=>new S2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class $2{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new _2(e,r,i),this.decoder=new I2(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Gs=({name:t,prefix:e,encode:r,decode:i})=>new $2(t,e,r,i),Cn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=b2(r,e);return Gs({prefix:t,name:e,encode:i,decode:s=>v2(n(s))})},O2=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},D2=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ne=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Gs({prefix:e,name:t,encode(n){return D2(n,i,r)},decode(n){return O2(n,i,r,t)}}),A2=Gs({prefix:"\0",name:"identity",encode:t=>x2(t),decode:t=>E2(t)}),P2=Object.freeze(Object.defineProperty({__proto__:null,identity:A2},Symbol.toStringTag,{value:"Module"})),C2=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),B2=Object.freeze(Object.defineProperty({__proto__:null,base2:C2},Symbol.toStringTag,{value:"Module"})),T2=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),R2=Object.freeze(Object.defineProperty({__proto__:null,base8:T2},Symbol.toStringTag,{value:"Module"})),F2=Cn({prefix:"9",name:"base10",alphabet:"0123456789"}),N2=Object.freeze(Object.defineProperty({__proto__:null,base10:F2},Symbol.toStringTag,{value:"Module"})),U2=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),k2=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),j2=Object.freeze(Object.defineProperty({__proto__:null,base16:U2,base16upper:k2},Symbol.toStringTag,{value:"Module"})),L2=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),M2=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),q2=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),z2=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V2=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),H2=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),K2=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W2=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G2=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Y2=Object.freeze(Object.defineProperty({__proto__:null,base32:L2,base32hex:V2,base32hexpad:K2,base32hexpadupper:W2,base32hexupper:H2,base32pad:q2,base32padupper:z2,base32upper:M2,base32z:G2},Symbol.toStringTag,{value:"Module"})),Z2=Cn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),J2=Cn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),X2=Object.freeze(Object.defineProperty({__proto__:null,base36:Z2,base36upper:J2},Symbol.toStringTag,{value:"Module"})),Q2=Cn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),eE=Cn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),tE=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Q2,base58flickr:eE},Symbol.toStringTag,{value:"Module"})),rE=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),iE=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nE=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),sE=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),oE=Object.freeze(Object.defineProperty({__proto__:null,base64:rE,base64pad:iE,base64url:nE,base64urlpad:sE},Symbol.toStringTag,{value:"Module"})),cp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),aE=cp.reduce((t,e,r)=>(t[r]=e,t),[]),cE=cp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function uE(t){return t.reduce((e,r)=>(e+=aE[r],e),"")}function lE(t){const e=[];for(const r of t){const i=cE[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const hE=Gs({prefix:"🚀",name:"base256emoji",encode:uE,decode:lE}),fE=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:hE},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const gl={...P2,...B2,...R2,...N2,...j2,...Y2,...X2,...tE,...oE,...fE};function up(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const yl=up("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),jo=up("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=op(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),lp={utf8:yl,"utf-8":yl,hex:gl.base16,latin1:jo,ascii:jo,binary:jo,...gl};function Et(t,e="utf8"){const r=lp[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Rc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function nt(t,e="utf8"){const r=lp[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const dE={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"}},pE="Input must be an string, Buffer or Uint8Array";function gE(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(pE);return e}function yE(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Kn(t){return(4294967296+t).toString(16).substring(1)}function wE(t,e,r){let i=`
16
- `+t+" = ";for(let n=0;n<e.length;n+=2){if(r===32)i+=Kn(e[n]).toUpperCase(),i+=" ",i+=Kn(e[n+1]).toUpperCase();else if(r===64)i+=Kn(e[n+1]).toUpperCase(),i+=Kn(e[n]).toUpperCase();else throw new Error("Invalid size "+r);n%6===4?i+=`
17
- `+new Array(t.length+4).join(" "):n<e.length-2&&(i+=" ")}console.log(i)}function mE(t,e,r){let i=new Date().getTime();const n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-i)+"ms"),i=s;for(let o=0;o<r;o++){const a=t(n),c=new Date().getTime(),u=c-i;i=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var hp={normalizeInput:gE,toHex:yE,debugPrint:wE,testSpeed:mE};const hs=hp;function Wn(t,e,r){const i=t[e]+t[r];let n=t[e+1]+t[r+1];i>=4294967296&&n++,t[e]=i,t[e+1]=n}function wl(t,e,r,i){let n=t[e]+r;r<0&&(n+=4294967296);let s=t[e+1]+i;n>=4294967296&&s++,t[e]=n,t[e+1]=s}function fp(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function mr(t,e,r,i,n,s){const o=an[n],a=an[n+1],c=an[s],u=an[s+1];Wn(Z,t,e),wl(Z,t,o,a);let l=Z[i]^Z[t],h=Z[i+1]^Z[t+1];Z[i]=h,Z[i+1]=l,Wn(Z,r,i),l=Z[e]^Z[r],h=Z[e+1]^Z[r+1],Z[e]=l>>>24^h<<8,Z[e+1]=h>>>24^l<<8,Wn(Z,t,e),wl(Z,t,c,u),l=Z[i]^Z[t],h=Z[i+1]^Z[t+1],Z[i]=l>>>16^h<<16,Z[i+1]=h>>>16^l<<16,Wn(Z,r,i),l=Z[e]^Z[r],h=Z[e+1]^Z[r+1],Z[e]=h>>>31^l<<1,Z[e+1]=l>>>31^h<<1}const dp=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),bE=[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],ke=new Uint8Array(bE.map(function(t){return t*2})),Z=new Uint32Array(32),an=new Uint32Array(32);function pp(t,e){let r=0;for(r=0;r<16;r++)Z[r]=t.h[r],Z[r+16]=dp[r];for(Z[24]=Z[24]^t.t,Z[25]=Z[25]^t.t/4294967296,e&&(Z[28]=~Z[28],Z[29]=~Z[29]),r=0;r<32;r++)an[r]=fp(t.b,4*r);for(r=0;r<12;r++)mr(0,8,16,24,ke[r*16+0],ke[r*16+1]),mr(2,10,18,26,ke[r*16+2],ke[r*16+3]),mr(4,12,20,28,ke[r*16+4],ke[r*16+5]),mr(6,14,22,30,ke[r*16+6],ke[r*16+7]),mr(0,10,20,30,ke[r*16+8],ke[r*16+9]),mr(2,12,22,24,ke[r*16+10],ke[r*16+11]),mr(4,14,16,26,ke[r*16+12],ke[r*16+13]),mr(6,8,18,28,ke[r*16+14],ke[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Z[r]^Z[r+16]}const br=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function gp(t,e,r,i){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(i&&i.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const n={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};br.fill(0),br[0]=t,e&&(br[1]=e.length),br[2]=1,br[3]=1,r&&br.set(r,32),i&&br.set(i,48);for(let s=0;s<16;s++)n.h[s]=dp[s]^fp(br,s*4);return e&&(Fc(n,e),n.c=128),n}function Fc(t,e){for(let r=0;r<e.length;r++)t.c===128&&(t.t+=t.c,pp(t,!1),t.c=0),t.b[t.c++]=e[r]}function yp(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;pp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3);return e}function wp(t,e,r,i,n){r=r||64,t=hs.normalizeInput(t),i&&(i=hs.normalizeInput(i)),n&&(n=hs.normalizeInput(n));const s=gp(r,e,i,n);return Fc(s,t),yp(s)}function vE(t,e,r,i,n){const s=wp(t,e,r,i,n);return hs.toHex(s)}var EE={blake2b:wp,blake2bHex:vE,blake2bInit:gp,blake2bUpdate:Fc,blake2bFinal:yp};const mp=hp;function xE(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vr(t,e,r,i,n,s){se[t]=se[t]+se[e]+n,se[i]=Gn(se[i]^se[t],16),se[r]=se[r]+se[i],se[e]=Gn(se[e]^se[r],12),se[t]=se[t]+se[e]+s,se[i]=Gn(se[i]^se[t],8),se[r]=se[r]+se[i],se[e]=Gn(se[e]^se[r],7)}function Gn(t,e){return t>>>e^t<<32-e}const bp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),je=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]),se=new Uint32Array(16),Pe=new Uint32Array(16);function vp(t,e){let r=0;for(r=0;r<8;r++)se[r]=t.h[r],se[r+8]=bp[r];for(se[12]^=t.t,se[13]^=t.t/4294967296,e&&(se[14]=~se[14]),r=0;r<16;r++)Pe[r]=xE(t.b,4*r);for(r=0;r<10;r++)vr(0,4,8,12,Pe[je[r*16+0]],Pe[je[r*16+1]]),vr(1,5,9,13,Pe[je[r*16+2]],Pe[je[r*16+3]]),vr(2,6,10,14,Pe[je[r*16+4]],Pe[je[r*16+5]]),vr(3,7,11,15,Pe[je[r*16+6]],Pe[je[r*16+7]]),vr(0,5,10,15,Pe[je[r*16+8]],Pe[je[r*16+9]]),vr(1,6,11,12,Pe[je[r*16+10]],Pe[je[r*16+11]]),vr(2,7,8,13,Pe[je[r*16+12]],Pe[je[r*16+13]]),vr(3,4,9,14,Pe[je[r*16+14]],Pe[je[r*16+15]]);for(r=0;r<8;r++)t.h[r]^=se[r]^se[r+8]}function Ep(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const r=e?e.length:0;if(e&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");const i={h:new Uint32Array(bp),b:new Uint8Array(64),c:0,t:0,outlen:t};return i.h[0]^=16842752^r<<8^t,r>0&&(Nc(i,e),i.c=64),i}function Nc(t,e){for(let r=0;r<e.length;r++)t.c===64&&(t.t+=t.c,vp(t,!1),t.c=0),t.b[t.c++]=e[r]}function xp(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;vp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3)&255;return e}function _p(t,e,r){r=r||32,t=mp.normalizeInput(t);const i=Ep(r,e);return Nc(i,t),xp(i)}function _E(t,e,r){const i=_p(t,e,r);return mp.toHex(i)}var IE={blake2s:_p,blake2sHex:_E,blake2sInit:Ep,blake2sUpdate:Nc,blake2sFinal:xp};const Yi=EE,Zi=IE;var SE={blake2b:Yi.blake2b,blake2bHex:Yi.blake2bHex,blake2bInit:Yi.blake2bInit,blake2bUpdate:Yi.blake2bUpdate,blake2bFinal:Yi.blake2bFinal,blake2s:Zi.blake2s,blake2sHex:Zi.blake2sHex,blake2sInit:Zi.blake2sInit,blake2sUpdate:Zi.blake2sUpdate,blake2sFinal:Zi.blake2sFinal},Ys={exports:{}};function $E(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var OE=DE;function DE(t,e,r){var i=r&&r.stringify||$E,n=1;if(typeof t=="object"&&t!==null){var s=e.length+n;if(s===1)return t;var o=new Array(s);o[0]=i(t);for(var a=1;a<s;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-n,h=-1,f=t&&t.length||0,d=0;d<f;){if(t.charCodeAt(d)===37&&d+1<f){switch(h=h>-1?h:0,t.charCodeAt(d+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<d&&(u+=t.slice(h,d)),u+=Number(e[l]),h=d+2,d++;break;case 105:if(l>=c||e[l]==null)break;h<d&&(u+=t.slice(h,d)),u+=Math.floor(Number(e[l])),h=d+2,d++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<d&&(u+=t.slice(h,d));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",h=d+2,d++;break}if(p==="function"){u+=e[l].name||"<anonymous>",h=d+2,d++;break}u+=i(e[l]),h=d+2,d++;break;case 115:if(l>=c)break;h<d&&(u+=t.slice(h,d)),u+=String(e[l]),h=d+2,d++;break;case 37:h<d&&(u+=t.slice(h,d)),u+="%",h=d+2,d++,l--;break}++l}++d}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const ml=OE;Ys.exports=hr;const En=zE().console||{},AE={mapHttpRequest:Yn,mapHttpResponse:Yn,wrapRequestSerializer:Lo,wrapResponseSerializer:Lo,wrapErrorSerializer:Lo,req:Yn,res:Yn,err:vl,errWithCause:vl};function Tr(t,e){return t==="silent"?1/0:e.levels.values[t]}const Uc=Symbol("pino.logFuncs"),Ba=Symbol("pino.hierarchy"),PE={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function bl(t,e){const r={logger:e,parent:t[Ba]};e[Ba]=r}function CE(t,e,r){const i={};e.forEach(n=>{i[n]=r[n]?r[n]:En[n]||En[PE[n]||"log"]||Pi}),t[Uc]=i}function BE(t,e){return Array.isArray(t)?t.filter(function(i){return i!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function hr(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||En;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},n=BE(t.browser.serialize,i);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof r=="function"&&a.forEach(function(g){r[g]=r}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",u=Object.create(r);u.log||(u.log=Pi),CE(u,a,r),bl({},u),Object.defineProperty(u,"levelVal",{get:h}),Object.defineProperty(u,"level",{get:f,set:d});const l={transmit:e,serialize:n,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:LE(t),messageKey:t.messageKey||"msg",onChild:t.onChild||Pi};u.levels=TE(t),u.level=c,u.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=Pi,u.serializers=i,u._serialize=n,u._stdErrSerialize=s,u.child=function(...g){return p.call(this,l,...g)},e&&(u._logEvent=Ta());function h(){return Tr(this.level,this)}function f(){return this._level}function d(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,qr(this,l,u,"error"),qr(this,l,u,"fatal"),qr(this,l,u,"warn"),qr(this,l,u,"info"),qr(this,l,u,"debug"),qr(this,l,u,"trace"),o.forEach(w=>{qr(this,l,u,w)})}function p(g,w,I){if(!w)throw new Error("missing bindings for child Pino");I=I||{},n&&w.serializers&&(I.serializers=w.serializers);const C=I.serializers;if(n&&C){var b=Object.assign({},i,C),v=t.browser.serialize===!0?Object.keys(b):n;delete w.serializers,kc([w],v,b,this._stdErrSerialize)}function D(T){this._childLevel=(T._childLevel|0)+1,this.bindings=w,b&&(this.serializers=b,this._serialize=v),e&&(this._logEvent=Ta([].concat(T._logEvent.bindings,w)))}D.prototype=this;const P=new D(this);return bl(this,P),P.child=function(...T){return p.call(this,g,...T)},P.level=I.level||this.level,g.onChild(P),P}return u}function TE(t){const e=t.customLevels||{},r=Object.assign({},hr.levels.values,e),i=Object.assign({},hr.levels.labels,RE(e));return{values:r,labels:i}}function RE(t){const e={};return Object.keys(t).forEach(function(r){e[t[r]]=r}),e}hr.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"}};hr.stdSerializers=AE;hr.stdTimeFunctions=Object.assign({},{nullTime:Ip,epochTime:Sp,unixTime:ME,isoTime:qE});function FE(t){const e=[];t.bindings&&e.push(t.bindings);let r=t[Ba];for(;r.parent;)r=r.parent,r.logger.bindings&&e.push(r.logger.bindings);return e.reverse()}function qr(t,e,r,i){if(Object.defineProperty(t,i,{value:Tr(t.level,r)>Tr(i,r)?Pi:r[Uc][i],writable:!0,enumerable:!0,configurable:!0}),t[i]===Pi){if(!e.transmit)return;const s=e.transmit.level||t.level,o=Tr(s,r);if(Tr(i,r)<o)return}t[i]=UE(t,e,r,i);const n=FE(t);n.length!==0&&(t[i]=NE(n,t[i]))}function NE(t,e){return function(){return e.apply(this,[...t,...arguments])}}function UE(t,e,r,i){return function(n){return function(){const o=e.timestamp(),a=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===En?En:this;for(var u=0;u<a.length;u++)a[u]=arguments[u];var l=!1;if(e.serialize&&(kc(a,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?n.call(c,...kE(this,i,a,o,e)):n.apply(c,a),e.transmit){const h=e.transmit.level||t._level,f=Tr(h,r),d=Tr(i,r);if(d<f)return;jE(this,{ts:o,methodLevel:i,methodValue:d,transmitLevel:h,transmitValue:r.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Tr(t._level,r)},a,l)}}}(t[Uc][i])}function kE(t,e,r,i,n){const{level:s,log:o=h=>h}=n.formatters||{},a=r.slice();let c=a[0];const u={};let l=(t._childLevel|0)+1;if(l<1&&(l=1),i&&(u.time=i),s){const h=s(e,t.levels.values[e]);Object.assign(u,h)}else u.level=t.levels.values[e];if(n.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[o(u),...a]}else{if(c!==null&&typeof c=="object"){for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?ml(a.shift(),a):void 0}else typeof c=="string"&&(c=ml(a.shift(),a));return c!==void 0&&(u[n.messageKey]=c),[o(u)]}}function kc(t,e,r,i){for(const n in t)if(i&&t[n]instanceof Error)t[n]=hr.stdSerializers.err(t[n]);else if(typeof t[n]=="object"&&!Array.isArray(t[n])&&e)for(const s in t[n])e.indexOf(s)>-1&&s in r&&(t[n][s]=r[s](t[n][s]))}function jE(t,e,r,i=!1){const n=e.send,s=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,u=t._logEvent.bindings;i||kc(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=r.filter(function(l){return u.indexOf(l)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,n(o,t._logEvent,c),t._logEvent=Ta(u)}function Ta(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function vl(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function LE(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ip:Sp}function Yn(){return{}}function Lo(t){return t}function Pi(){}function Ip(){return!1}function Sp(){return Date.now()}function ME(){return Math.round(Date.now()/1e3)}function qE(){return new Date(Date.now()).toISOString()}function zE(){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)||{}}}Ys.exports.default=hr;Ys.exports.pino=hr;var Ii=Ys.exports;const $p=R0(Ii),VE={level:"info"},Zs="custom_context",jc=1e3*1024;var HE=Object.defineProperty,KE=(t,e,r)=>e in t?HE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pr=(t,e,r)=>KE(t,typeof e!="symbol"?e+"":e,r);let WE=class{constructor(e){Pr(this,"nodeValue"),Pr(this,"sizeInBytes"),Pr(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},El=class{constructor(e){Pr(this,"lengthInNodes"),Pr(this,"sizeInBytes"),Pr(this,"head"),Pr(this,"tail"),Pr(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new WE(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}};var GE=Object.defineProperty,YE=(t,e,r)=>e in t?GE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zn=(t,e,r)=>YE(t,typeof e!="symbol"?e+"":e,r);let Op=class{constructor(e,r=jc){Zn(this,"logs"),Zn(this,"level"),Zn(this,"levelValue"),Zn(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Ii.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new El(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Ii.levels.values.error?console.error(e):r===Ii.levels.values.warn?console.warn(e):r===Ii.levels.values.debug?console.debug(e):r===Ii.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(lr({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new El(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(lr({extraMetadata:e})),new Blob(r,{type:"application/json"})}};var ZE=Object.defineProperty,JE=(t,e,r)=>e in t?ZE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,XE=(t,e,r)=>JE(t,typeof e!="symbol"?e+"":e,r);let QE=class{constructor(e,r=jc){XE(this,"baseChunkLogger"),this.baseChunkLogger=new Op(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}};var e3=Object.defineProperty,t3=(t,e,r)=>e in t?e3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,r3=(t,e,r)=>t3(t,typeof e!="symbol"?e+"":e,r);let i3=class{constructor(e,r=jc){r3(this,"baseChunkLogger"),this.baseChunkLogger=new Op(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var n3=Object.defineProperty,s3=Object.defineProperties,o3=Object.getOwnPropertyDescriptors,xl=Object.getOwnPropertySymbols,a3=Object.prototype.hasOwnProperty,c3=Object.prototype.propertyIsEnumerable,_l=(t,e,r)=>e in t?n3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Os=(t,e)=>{for(var r in e||(e={}))a3.call(e,r)&&_l(t,r,e[r]);if(xl)for(var r of xl(e))c3.call(e,r)&&_l(t,r,e[r]);return t},Ds=(t,e)=>s3(t,o3(e));function u3(t){return Ds(Os({},t),{level:(t==null?void 0:t.level)||VE.level})}function l3(t,e,r=Zs){return t[r]=e,t}function st(t,e=Zs){return t[e]||""}function h3(t,e,r=Zs){const i=st(t,r);return i.trim()?`${i}/${e}`:e}function dt(t,e,r=Zs){const i=h3(t,e,r),n=t.child({context:i});return l3(n,i,r)}function f3(t){var e,r;const i=new QE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:$p(Ds(Os({},t.opts),{level:"trace",browser:Ds(Os({},(r=t.opts)==null?void 0:r.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function d3(t){var e;const r=new i3((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:$p(Ds(Os({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function Dp(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?f3(t):d3(t)}const p3=":";function cr(t){const[e,r]=t.split(p3);return{namespace:e,reference:r}}function Il(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const n=t[i];r.push(...n.accounts)}),r}function Ap(t,e){return t.includes(":")?[t]:e.chains||[]}var g3=Object.defineProperty,y3=Object.defineProperties,w3=Object.getOwnPropertyDescriptors,Sl=Object.getOwnPropertySymbols,m3=Object.prototype.hasOwnProperty,b3=Object.prototype.propertyIsEnumerable,Ra=(t,e,r)=>e in t?g3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$l=(t,e)=>{for(var r in e||(e={}))m3.call(e,r)&&Ra(t,r,e[r]);if(Sl)for(var r of Sl(e))b3.call(e,r)&&Ra(t,r,e[r]);return t},v3=(t,e)=>y3(t,w3(e)),Ol=(t,e,r)=>Ra(t,typeof e!="symbol"?e+"":e,r);const E3="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},x3="js";function As(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}function kr(){return!ii()&&!!gc()&&navigator.product===E3}function _3(){return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="android"}function I3(){return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="ios"}function Mi(){return!As()&&!!gc()&&!!ii()}function Bn(){return kr()?ft.reactNative:As()?ft.node:Mi()?ft.browser:ft.unknown}function Dl(){var t;try{return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Application)<"u"?(t=Y.Application)==null?void 0:t.applicationId:void 0}catch{return}}function S3(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([i],[n])=>i.localeCompare(n)).forEach(([i,n])=>{n!=null&&r.set(i,String(n))}),r.toString()}function $3(t){var e,r;const i=Pp();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(n=>n!=="")),v3($l($l({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(n){return console.warn("Error populating app metadata",n),t||i}}function Pp(){return qf()||{name:"",description:"",url:"",icons:[""]}}function O3(){if(Bn()===ft.reactNative&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"){const{OS:r,Version:i}=Y.Platform;return[r,i].join("-")}const t=V0();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 D3(){var t;const e=Bn();return e===ft.browser?[e,((t=Mf())==null?void 0:t.host)||"unknown"].join(":"):e}function Cp(t,e,r){const i=O3(),n=D3();return[[t,e].join("-"),[x3,r].join("-"),i,n].join("/")}function A3({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=Cp(t,e,i),h={auth:n,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=S3(u[1]||"",h);return u[0]+"?"+f}function Xr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Fa(t){return Object.fromEntries(t.entries())}function Na(t){return new Map(Object.entries(t))}function Kr(t=L.FIVE_MINUTES,e){const r=L.toMiliseconds(t||L.FIVE_MINUTES);let i,n,s,o;return{resolve:a=>{s&&i&&(clearTimeout(s),i(a),o=Promise.resolve(a))},reject:a=>{s&&n&&(clearTimeout(s),n(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),i=a,n=c})}}function zt(t,e,r){return new Promise(async(i,n)=>{const s=setTimeout(()=>n(new Error(r)),e);try{const o=await t;i(o)}catch(o){n(o)}clearTimeout(s)})}function Bp(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 P3(t){return Bp("topic",t)}function C3(t){return Bp("id",t)}function Tp(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function we(t,e){return L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function qt(t){return Date.now()>=L.toMiliseconds(t)}function ae(t,e){return`${t}${e?`:${e}`:""}`}function Vt(t=[],e=[]){return[...new Set([...t,...e])]}async function B3({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const n=typeof r=="string"?JSON.parse(r):r,s=n==null?void 0:n.href;if(typeof s!="string")return;const o=T3(s,t,e),a=Bn();if(a===ft.browser){if(!((i=ii())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}R3(o)}else a===ft.reactNative&&typeof(Y==null?void 0:Y.Linking)<"u"&&await Y.Linking.openURL(o)}catch(n){console.error(n)}}function T3(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let n=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";n=`${n}${s}${k3(i,!0)}`}else n=`${n}/wc?${i}`;return n}function R3(t){let e="_self";U3()?e="_top":(N3()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function F3(t,e){let r="";try{if(Mi()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Al(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Pl(){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 Lc(){return typeof xt<"u"&&{}.IS_VITEST==="true"}function N3(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function U3(){try{return window.self!==window.top}catch{return!1}}function k3(t,e=!1){const r=re.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Rp(t){return re.from(t,"base64").toString("utf-8")}function j3(t){return new Promise(e=>setTimeout(e,t))}let L3=class{constructor({limit:e}){Ol(this,"limit"),Ol(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}};const Jn=BigInt(2**32-1),Cl=BigInt(32);function Fp(t,e=!1){return e?{h:Number(t&Jn),l:Number(t>>Cl&Jn)}:{h:Number(t>>Cl&Jn)|0,l:Number(t&Jn)|0}}function Np(t,e=!1){const r=t.length;let i=new Uint32Array(r),n=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Fp(t[s],e);[i[s],n[s]]=[o,a]}return[i,n]}const Bl=(t,e,r)=>t>>>r,Tl=(t,e,r)=>t<<32-r|e>>>r,Or=(t,e,r)=>t>>>r|e<<32-r,Dr=(t,e,r)=>t<<32-r|e>>>r,cn=(t,e,r)=>t<<64-r|e>>>r-32,un=(t,e,r)=>t>>>r-32|e<<64-r,M3=(t,e)=>e,q3=(t,e)=>t,z3=(t,e,r)=>t<<r|e>>>32-r,V3=(t,e,r)=>e<<r|t>>>32-r,H3=(t,e,r)=>e<<r-32|t>>>64-r,K3=(t,e,r)=>t<<r-32|e>>>64-r;function Pt(t,e,r,i){const n=(e>>>0)+(i>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}const Mc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),qc=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,W3=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),G3=(t,e,r,i,n)=>e+r+i+n+(t/2**32|0)|0,Y3=(t,e,r,i,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(n>>>0),Z3=(t,e,r,i,n,s)=>e+r+i+n+s+(t/2**32|0)|0,mi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Js(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function fr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Tt(t,...e){if(!Js(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 Xs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");fr(t.outputLen),fr(t.blockLen)}function Ur(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function zc(t,e){Tt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function xn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function It(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Mo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Nt(t,e){return t<<32-e|t>>>e}const Up=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const tr=Up?t=>t:t=>kp(t);function J3(t){for(let e=0;e<t.length;e++)t[e]=kp(t[e]);return t}const Ar=Up?t=>t:J3,jp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",X3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ci(t){if(Tt(t),jp)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=X3[t[r]];return e}const Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Rl(t){if(t>=Xt._0&&t<=Xt._9)return t-Xt._0;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function Ps(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(jp)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Rl(t.charCodeAt(s)),a=Rl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}i[n]=o*16+a}return i}function Lp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Bt(t){return typeof t=="string"&&(t=Lp(t)),Tt(t),t}function Cr(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];Tt(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}let Qs=class{};function Tn(t){const e=i=>t().update(Bt(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Q3(t){const e=(i,n)=>t(n).update(Bt(i)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}function ui(t=32){if(mi&&typeof mi.getRandomValues=="function")return mi.getRandomValues(new Uint8Array(t));if(mi&&typeof mi.randomBytes=="function")return Uint8Array.from(mi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const ex=BigInt(0),Ji=BigInt(1),tx=BigInt(2),rx=BigInt(7),ix=BigInt(256),nx=BigInt(113),Mp=[],qp=[],zp=[];for(let t=0,e=Ji,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Mp.push(2*(5*i+r)),qp.push((t+1)*(t+2)/2%64);let n=ex;for(let s=0;s<7;s++)e=(e<<Ji^(e>>rx)*nx)%ix,e&tx&&(n^=Ji<<(Ji<<BigInt(s))-Ji);zp.push(n)}const Vp=Np(zp,!0),sx=Vp[0],ox=Vp[1],Fl=(t,e,r)=>r>32?H3(t,e,r):z3(t,e,r),Nl=(t,e,r)=>r>32?K3(t,e,r):V3(t,e,r);function ax(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=r[c],l=r[c+1],h=Fl(u,l,1)^r[a],f=Nl(u,l,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let n=t[2],s=t[3];for(let o=0;o<24;o++){const a=qp[o],c=Fl(n,s,a),u=Nl(n,s,a),l=Mp[o];n=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=sx[i],t[1]^=ox[i]}It(r)}let cx=class Hp extends Qs{constructor(e,r,i,n=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=n,this.rounds=s,fr(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=xn(this.state)}clone(){return this._cloneInto()}keccak(){Ar(this.state32),ax(this.state32,this.rounds),Ar(this.state32),this.posOut=0,this.pos=0}update(e){Ur(this),e=Bt(e),Tt(e);const{blockLen:r,state:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);for(let a=0;a<o;a++)i[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:n}=this;e[i]^=r,r&128&&i===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ur(this,!1),Tt(e),this.finish();const r=this.state,{blockLen:i}=this;for(let n=0,s=e.length;n<s;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,s-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=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 fr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zc(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,It(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new Hp(r,i,n,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=i,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}};const ux=(t,e,r)=>Tn(()=>new cx(e,t,r)),lx=ux(1,136,256/8);function hx(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}function fx(t,e,r){return t&e^~t&r}function dx(t,e,r){return t&e^t&r^e&r}let Kp=class extends Qs{constructor(e,r,i,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Mo(this.buffer)}update(e){Ur(this),e=Bt(e),Tt(e);const{view:r,buffer:i,blockLen:n}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=Mo(e);for(;n<=s-o;o+=n)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ur(this),zc(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,It(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;hx(i,n-8,BigInt(this.length*8),s),this.process(i,0);const a=Mo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}};const Er=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),px=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]),xr=new Uint32Array(64);class gx extends Kp{constructor(e=32){super(64,e,8,!1),this.A=Er[0]|0,this.B=Er[1]|0,this.C=Er[2]|0,this.D=Er[3]|0,this.E=Er[4]|0,this.F=Er[5]|0,this.G=Er[6]|0,this.H=Er[7]|0}get(){const{A:e,B:r,C:i,D:n,E:s,F:o,G:a,H:c}=this;return[e,r,i,n,s,o,a,c]}set(e,r,i,n,s,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)xr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=xr[h-15],d=xr[h-2],p=Nt(f,7)^Nt(f,18)^f>>>3,g=Nt(d,17)^Nt(d,19)^d>>>10;xr[h]=g+xr[h-7]+p+xr[h-16]|0}let{A:i,B:n,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Nt(a,6)^Nt(a,11)^Nt(a,25),d=l+f+fx(a,c,u)+px[h]+xr[h]|0,p=(Nt(i,2)^Nt(i,13)^Nt(i,22))+dx(i,n,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=n,n=i,i=d+p|0}i=i+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(i,n,s,o,a,c,u,l)}roundClean(){It(xr)}destroy(){this.set(0,0,0,0,0,0,0,0),It(this.buffer)}}const Wp=Np(["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))),yx=Wp[0],wx=Wp[1],_r=new Uint32Array(80),Ir=new Uint32Array(80);let Vc=class extends Kp{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:r,Bh:i,Bl:n,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=n|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,r){for(let b=0;b<16;b++,r+=4)_r[b]=e.getUint32(r),Ir[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const v=_r[b-15]|0,D=Ir[b-15]|0,P=Or(v,D,1)^Or(v,D,8)^Bl(v,D,7),T=Dr(v,D,1)^Dr(v,D,8)^Tl(v,D,7),R=_r[b-2]|0,A=Ir[b-2]|0,U=Or(R,A,19)^cn(R,A,61)^Bl(R,A,6),j=Dr(R,A,19)^un(R,A,61)^Tl(R,A,6),B=W3(T,j,Ir[b-7],Ir[b-16]),_=G3(B,P,U,_r[b-7],_r[b-16]);_r[b]=_|0,Ir[b]=B|0}let{Ah:i,Al:n,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:d,Fl:p,Gh:g,Gl:w,Hh:I,Hl:C}=this;for(let b=0;b<80;b++){const v=Or(h,f,14)^Or(h,f,18)^cn(h,f,41),D=Dr(h,f,14)^Dr(h,f,18)^un(h,f,41),P=h&d^~h&g,T=f&p^~f&w,R=Y3(C,D,T,wx[b],Ir[b]),A=Z3(R,I,v,P,yx[b],_r[b]),U=R|0,j=Or(i,n,28)^cn(i,n,34)^cn(i,n,39),B=Dr(i,n,28)^un(i,n,34)^un(i,n,39),_=i&s^i&a^s&a,O=n&o^n&c^o&c;I=g|0,C=w|0,g=d|0,w=p|0,d=h|0,p=f|0,{h,l:f}=Pt(u|0,l|0,A|0,U|0),u=a|0,l=c|0,a=s|0,c=o|0,s=i|0,o=n|0;const m=Mc(U,B,O);i=qc(m,A,j,_),n=m|0}({h:i,l:n}=Pt(this.Ah|0,this.Al|0,i|0,n|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Pt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Pt(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=Pt(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=Pt(this.Gh|0,this.Gl|0,g|0,w|0),{h:I,l:C}=Pt(this.Hh|0,this.Hl|0,I|0,C|0),this.set(i,n,s,o,a,c,u,l,h,f,d,p,g,w,I,C)}roundClean(){It(_r,Ir)}destroy(){It(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class mx extends Vc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const qe=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class bx extends Vc{constructor(){super(32),this.Ah=qe[0]|0,this.Al=qe[1]|0,this.Bh=qe[2]|0,this.Bl=qe[3]|0,this.Ch=qe[4]|0,this.Cl=qe[5]|0,this.Dh=qe[6]|0,this.Dl=qe[7]|0,this.Eh=qe[8]|0,this.El=qe[9]|0,this.Fh=qe[10]|0,this.Fl=qe[11]|0,this.Gh=qe[12]|0,this.Gl=qe[13]|0,this.Hh=qe[14]|0,this.Hl=qe[15]|0}}const eo=Tn(()=>new gx),vx=Tn(()=>new Vc),Ex=Tn(()=>new mx),xx=Tn(()=>new bx),_x=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]),Ee=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),V=new Uint32Array(32);function Sr(t,e,r,i,n,s){const o=n[s],a=n[s+1];let c=V[2*t],u=V[2*t+1],l=V[2*e],h=V[2*e+1],f=V[2*r],d=V[2*r+1],p=V[2*i],g=V[2*i+1],w=Mc(c,l,o);u=qc(w,u,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:M3(g,p),Dl:q3(g)},{h:d,l:f}=Pt(d,f,g,p),{Bh:h,Bl:l}={Bh:h^d,Bl:l^f},{Bh:h,Bl:l}={Bh:Or(h,l,24),Bl:Dr(h,l,24)},V[2*t]=c,V[2*t+1]=u,V[2*e]=l,V[2*e+1]=h,V[2*r]=f,V[2*r+1]=d,V[2*i]=p,V[2*i+1]=g}function $r(t,e,r,i,n,s){const o=n[s],a=n[s+1];let c=V[2*t],u=V[2*t+1],l=V[2*e],h=V[2*e+1],f=V[2*r],d=V[2*r+1],p=V[2*i],g=V[2*i+1],w=Mc(c,l,o);u=qc(w,u,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:Or(g,p,16),Dl:Dr(g,p,16)},{h:d,l:f}=Pt(d,f,g,p),{Bh:h,Bl:l}={Bh:h^d,Bl:l^f},{Bh:h,Bl:l}={Bh:cn(h,l,63),Bl:un(h,l,63)},V[2*t]=c,V[2*t+1]=u,V[2*e]=l,V[2*e+1]=h,V[2*r]=f,V[2*r+1]=d,V[2*i]=p,V[2*i+1]=g}function Ix(t,e={},r,i,n){if(fr(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==n)throw new Error("personalization must be undefined or "+n)}class Sx extends Qs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,fr(e),fr(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=xn(this.buffer)}update(e){Ur(this),e=Bt(e),Tt(e);const{blockLen:r,buffer:i,buffer32:n}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===r&&(Ar(n),this.compress(n,0,!1),Ar(n),this.pos=0);const u=Math.min(r-this.pos,s-c),l=o+c;if(u===r&&!(l%4)&&c+u<s){const h=new Uint32Array(a,l,Math.floor((s-c)/4));Ar(h);for(let f=0;c+r<s;f+=n.length,c+=r)this.length+=r,this.compress(h,f,!1);Ar(h);continue}i.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){Ur(this),zc(e,this);const{pos:r,buffer32:i}=this;this.finished=!0,It(this.buffer.subarray(r)),Ar(i),this.compress(i,0,!0),Ar(i);const n=xn(e);this.get().forEach((s,o)=>n[o]=tr(s))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){const{buffer:r,length:i,finished:n,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=s,e.finished=n,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class $x extends Sx{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=Ee[0]|0,this.v0h=Ee[1]|0,this.v1l=Ee[2]|0,this.v1h=Ee[3]|0,this.v2l=Ee[4]|0,this.v2h=Ee[5]|0,this.v3l=Ee[6]|0,this.v3h=Ee[7]|0,this.v4l=Ee[8]|0,this.v4h=Ee[9]|0,this.v5l=Ee[10]|0,this.v5h=Ee[11]|0,this.v6l=Ee[12]|0,this.v6h=Ee[13]|0,this.v7l=Ee[14]|0,this.v7h=Ee[15]|0,Ix(r,e,64,16,16);let{key:i,personalization:n,salt:s}=e,o=0;if(i!==void 0&&(i=Bt(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Bt(s);const a=xn(s);this.v4l^=tr(a[0]),this.v4h^=tr(a[1]),this.v5l^=tr(a[2]),this.v5h^=tr(a[3])}if(n!==void 0){n=Bt(n);const a=xn(n);this.v6l^=tr(a[0]),this.v6h^=tr(a[1]),this.v7l^=tr(a[2]),this.v7h^=tr(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:i,v1h:n,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:h,v5h:f,v6l:d,v6h:p,v7l:g,v7h:w}=this;return[e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,u,l,h,f,d,p,g,w){this.v0l=e|0,this.v0h=r|0,this.v1l=i|0,this.v1h=n|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=h|0,this.v5h=f|0,this.v6l=d|0,this.v6h=p|0,this.v7l=g|0,this.v7h=w|0}compress(e,r,i){this.get().forEach((c,u)=>V[u]=c),V.set(Ee,16);let{h:n,l:s}=Fp(BigInt(this.length));V[24]=Ee[8]^s,V[25]=Ee[9]^n,i&&(V[28]=~V[28],V[29]=~V[29]);let o=0;const a=_x;for(let c=0;c<12;c++)Sr(0,4,8,12,e,r+2*a[o++]),$r(0,4,8,12,e,r+2*a[o++]),Sr(1,5,9,13,e,r+2*a[o++]),$r(1,5,9,13,e,r+2*a[o++]),Sr(2,6,10,14,e,r+2*a[o++]),$r(2,6,10,14,e,r+2*a[o++]),Sr(3,7,11,15,e,r+2*a[o++]),$r(3,7,11,15,e,r+2*a[o++]),Sr(0,5,10,15,e,r+2*a[o++]),$r(0,5,10,15,e,r+2*a[o++]),Sr(1,6,11,12,e,r+2*a[o++]),$r(1,6,11,12,e,r+2*a[o++]),Sr(2,7,8,13,e,r+2*a[o++]),$r(2,7,8,13,e,r+2*a[o++]),Sr(3,4,9,14,e,r+2*a[o++]),$r(3,4,9,14,e,r+2*a[o++]);this.v0l^=V[0]^V[16],this.v0h^=V[1]^V[17],this.v1l^=V[2]^V[18],this.v1h^=V[3]^V[19],this.v2l^=V[4]^V[20],this.v2h^=V[5]^V[21],this.v3l^=V[6]^V[22],this.v3h^=V[7]^V[23],this.v4l^=V[8]^V[24],this.v4h^=V[9]^V[25],this.v5l^=V[10]^V[26],this.v5h^=V[11]^V[27],this.v6l^=V[12]^V[28],this.v6h^=V[13]^V[29],this.v7l^=V[14]^V[30],this.v7h^=V[15]^V[31],It(V)}destroy(){this.destroyed=!0,It(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Ox=Q3(t=>new $x(t)),Dx="https://rpc.walletconnect.org/v1";function Gp(t){const e=`Ethereum Signed Message:
18
- ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+re.from(lx(r)).toString("hex")}async function Ax(t,e,r,i,n,s){switch(r.t){case"eip191":return await Px(t,e,r.s);case"eip1271":return await Cx(t,e,r.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Px(t,e,r){const i=Sm(r);return km({payload:Gp(e),signature:i}).toLowerCase()===t.toLowerCase()}async function Cx(t,e,r,i,n,s){const o=cr(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Gp(e)).substring(2),f=a+h+c+l+u,d=await fetch(`${s||Dx}/?chainId=${i}&projectId=${n}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Bx(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:p}=await d.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Bx(){return Date.now()+Math.floor(Math.random()*1e3)}function Tx(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const n=1+i*64;if(r.length<n)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const s=re.from(t,"base64").slice(1,65);return An.encode(s)}function Rx(t){const e=new Uint8Array(re.from(t,"base64")),r=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length);const n=Ox(i,{dkLen:32});return An.encode(n)}function Ul(t){const e=new Uint8Array(eo(Fx(t)));return An.encode(e)}function Fx(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 kl(t){const e=re.from(t,"base64"),r=_1(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const i=p1(r),n=re.from("TX"),s=re.concat([n,re.from(i)]),o=xx(s);return Um.encode(o).replace(/=+$/,"")}function qo(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),re.from(e)}function Nx(t){const e=re.from(t.signed.bodyBytes,"base64"),r=re.from(t.signed.authInfoBytes,"base64"),i=re.from(t.signature.signature,"base64"),n=[];n.push(re.from([10])),n.push(qo(e.length)),n.push(e),n.push(re.from([18])),n.push(qo(r.length)),n.push(r),n.push(re.from([26])),n.push(qo(i.length)),n.push(i);const s=re.concat(n),o=eo(s);return re.from(o).toString("hex").toUpperCase()}function Ux(t){var e,r;const i=[];try{if(typeof t=="string")return i.push(t),i;if(typeof t!="object")return i;t!=null&&t.id&&i.push(t.id);const n=(r=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:r.transactionHashes;n&&i.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return i}var kx=Object.defineProperty,jx=Object.defineProperties,Lx=Object.getOwnPropertyDescriptors,jl=Object.getOwnPropertySymbols,Mx=Object.prototype.hasOwnProperty,qx=Object.prototype.propertyIsEnumerable,Ll=(t,e,r)=>e in t?kx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zx=(t,e)=>{for(var r in e||(e={}))Mx.call(e,r)&&Ll(t,r,e[r]);if(jl)for(var r of jl(e))qx.call(e,r)&&Ll(t,r,e[r]);return t},Vx=(t,e)=>jx(t,Lx(e));const Yp="did:pkh:",Hx={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Kx=t=>t?Hx[t]||t:"",to=t=>t==null?void 0:t.split(":"),Wx=t=>{const e=t&&to(t);if(e)return t.includes(Yp)?e[3]:e[1]},Gx=t=>{const e=t&&to(t);if(e)return t.includes(Yp)?e[2]:e[0]},Ua=t=>{const e=t&&to(t);if(e)return e[2]+":"+e[3]},Cs=t=>{const e=t&&to(t);if(e)return e.pop()};async function Ml(t){const{cacao:e,projectId:r}=t,{s:i,p:n}=e,s=Zp(n,n.iss),o=Cs(n.iss);return await Ax(o,s,i,Ua(n.iss),r)}const Zp=(t,e)=>{const r=Gx(e);if(!r)throw new Error("Invalid issuer: "+e);const i=`${t.domain} wants you to sign in with your ${Kx(r)} account:`,n=Cs(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 o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${Wx(e)}`,u=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(w=>`
19
- - ${w}`).join("")}`:void 0,g=fs(t.resources);if(g){const w=_n(g);s=i_(s,w)}return[i,n,"",s,"",o,a,c,u,l,h,f,d,p].filter(w=>w!=null).join(`
20
- `)};function Yx(t){return re.from(JSON.stringify(t)).toString("base64")}function Zx(t){return JSON.parse(re.from(t,"base64").toString("utf-8"))}function oi(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(n=>{const s=i[n];if(!Array.isArray(s))throw new Error(`Ability limits ${n} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${o}`)})})})}function Jx(t,e,r,i={}){return r==null||r.sort((n,s)=>n.localeCompare(s)),{att:{[t]:Xx(e,r,i)}}}function Xx(t,e,r={}){e=e==null?void 0:e.sort((n,s)=>n.localeCompare(s));const i=e.map(n=>({[`${t}/${n}`]:[r]}));return Object.assign({},...i)}function Jp(t){return oi(t),`urn:recap:${Yx(t).replace(/=/g,"")}`}function _n(t){const e=Zx(t.replace("urn:recap:",""));return oi(e),e}function Qx(t,e,r){const i=Jx(t,e,r);return Jp(i)}function e_(t){return t&&t.includes("urn:recap:")}function t_(t,e){const r=_n(t),i=_n(e),n=r_(r,i);return Jp(n)}function r_(t,e){oi(t),oi(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),i={att:{}};return r.forEach(n=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[n])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[n])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;i.att[n]=Vx(zx({},i.att[n]),{[a]:((c=t.att[n])==null?void 0:c[a])||((u=e.att[n])==null?void 0:u[a])})})}),i}function i_(t="",e){oi(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let n=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(n++,`(${n}) '${h}': '${u[h].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const s=i.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function ql(t){var e;const r=_n(t);oi(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function zl(t){const e=_n(t);oi(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var s;(s=n==null?void 0:n[0])!=null&&s.chains&&r.push(n[0].chains)})}),[...new Set(r.flat())]}function fs(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return e_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Xp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ka(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function zo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function et(t,...e){if(!Xp(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Vl(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function n_(t,e){et(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Fr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ui(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function s_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const o_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function a_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ja(t){if(typeof t=="string")t=a_(t);else if(Xp(t))t=La(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function c_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function u_(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const l_=(t,e)=>{function r(i,...n){if(et(i),!o_)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=n[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?et(u):et(u,t.nonceLength)}const s=t.tagLength;s&&n[1]!==void 0&&et(n[1]);const o=e(i,...n),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");et(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,et(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(et(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function Hl(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!f_(e))throw new Error("invalid output, must be aligned");return e}function Kl(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}function h_(t,e,r){ka(r);const i=new Uint8Array(16),n=s_(i);return Kl(n,0,BigInt(e),r),Kl(n,8,BigInt(t),r),i}function f_(t){return t.byteOffset%4===0}function La(t){return Uint8Array.from(t)}const Qp=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),d_=Qp("expand 16-byte k"),p_=Qp("expand 32-byte k"),g_=Fr(d_),y_=Fr(p_);function ie(t,e){return t<<e|t>>>32-e}function Ma(t){return t.byteOffset%4===0}const Xn=64,w_=16,eg=2**32-1,Wl=new Uint32Array;function m_(t,e,r,i,n,s,o,a){const c=n.length,u=new Uint8Array(Xn),l=Fr(u),h=Ma(n)&&Ma(s),f=h?Fr(n):Wl,d=h?Fr(s):Wl;for(let p=0;p<c;o++){if(t(e,r,i,l,o,a),o>=eg)throw new Error("arx: counter overflow");const g=Math.min(Xn,c-p);if(h&&g===Xn){const w=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let I=0,C;I<w_;I++)C=w+I,d[C]=f[C]^l[I];p+=Xn;continue}for(let w=0,I;w<g;w++)I=p+w,s[I]=n[I]^u[w];p+=g}}function b_(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:n,counterRight:s,rounds:o}=c_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return zo(n),zo(o),ka(s),ka(r),(a,c,u,l,h=0)=>{et(a),et(c),et(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),et(l),zo(h),h<0||h>=eg)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const d=[];let p=a.length,g,w;if(p===32)d.push(g=La(a)),w=y_;else if(p===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),w=g_,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Ma(c)||d.push(c=La(c));const I=Fr(g);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(w,I,Fr(c.subarray(0,16)),I),c=c.subarray(16)}const C=16-n;if(C!==c.length)throw new Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){const v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,d.push(c)}const b=Fr(c);return m_(t,w,I,b,u,l,h,o),Ui(...d),l}}const Ce=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class v_{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=ja(e),et(e,32);const r=Ce(e,0),i=Ce(e,2),n=Ce(e,4),s=Ce(e,6),o=Ce(e,8),a=Ce(e,10),c=Ce(e,12),u=Ce(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>10|n<<6)&7939,this.r[3]=(n>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Ce(e,16+2*l)}process(e,r,i=!1){const n=i?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],d=o[6],p=o[7],g=o[8],w=o[9],I=Ce(e,r+0),C=Ce(e,r+2),b=Ce(e,r+4),v=Ce(e,r+6),D=Ce(e,r+8),P=Ce(e,r+10),T=Ce(e,r+12),R=Ce(e,r+14);let A=s[0]+(I&8191),U=s[1]+((I>>>13|C<<3)&8191),j=s[2]+((C>>>10|b<<6)&8191),B=s[3]+((b>>>7|v<<9)&8191),_=s[4]+((v>>>4|D<<12)&8191),O=s[5]+(D>>>1&8191),m=s[6]+((D>>>14|P<<2)&8191),y=s[7]+((P>>>11|T<<5)&8191),x=s[8]+((T>>>8|R<<8)&8191),$=s[9]+(R>>>5|n),E=0,S=E+A*a+U*(5*w)+j*(5*g)+B*(5*p)+_*(5*d);E=S>>>13,S&=8191,S+=O*(5*f)+m*(5*h)+y*(5*l)+x*(5*u)+$*(5*c),E+=S>>>13,S&=8191;let F=E+A*c+U*a+j*(5*w)+B*(5*g)+_*(5*p);E=F>>>13,F&=8191,F+=O*(5*d)+m*(5*f)+y*(5*h)+x*(5*l)+$*(5*u),E+=F>>>13,F&=8191;let N=E+A*u+U*c+j*a+B*(5*w)+_*(5*g);E=N>>>13,N&=8191,N+=O*(5*p)+m*(5*d)+y*(5*f)+x*(5*h)+$*(5*l),E+=N>>>13,N&=8191;let H=E+A*l+U*u+j*c+B*a+_*(5*w);E=H>>>13,H&=8191,H+=O*(5*g)+m*(5*p)+y*(5*d)+x*(5*f)+$*(5*h),E+=H>>>13,H&=8191;let z=E+A*h+U*l+j*u+B*c+_*a;E=z>>>13,z&=8191,z+=O*(5*w)+m*(5*g)+y*(5*p)+x*(5*d)+$*(5*f),E+=z>>>13,z&=8191;let q=E+A*f+U*h+j*l+B*u+_*c;E=q>>>13,q&=8191,q+=O*a+m*(5*w)+y*(5*g)+x*(5*p)+$*(5*d),E+=q>>>13,q&=8191;let K=E+A*d+U*f+j*h+B*l+_*u;E=K>>>13,K&=8191,K+=O*c+m*a+y*(5*w)+x*(5*g)+$*(5*p),E+=K>>>13,K&=8191;let G=E+A*p+U*d+j*f+B*h+_*l;E=G>>>13,G&=8191,G+=O*u+m*c+y*a+x*(5*w)+$*(5*g),E+=G>>>13,G&=8191;let X=E+A*g+U*p+j*d+B*f+_*h;E=X>>>13,X&=8191,X+=O*l+m*u+y*c+x*a+$*(5*w),E+=X>>>13,X&=8191;let W=E+A*w+U*g+j*p+B*d+_*f;E=W>>>13,W&=8191,W+=O*h+m*l+y*u+x*c+$*a,E+=W>>>13,W&=8191,E=(E<<2)+E|0,E=E+S|0,S=E&8191,E=E>>>13,F+=E,s[0]=S,s[1]=F,s[2]=N,s[3]=H,s[4]=z,s[5]=q,s[6]=K,s[7]=G,s[8]=X,s[9]=W}finalize(){const{h:e,pad:r}=this,i=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,i[0]=e[0]+5,n=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+n,n=i[a]>>>13,i[a]&=8191;i[9]-=8192;let s=(n^1)-1;for(let a=0;a<10;a++)i[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ui(i)}update(e){Vl(this),e=ja(e),et(e);const{buffer:r,blockLen:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(i-this.pos,n-s);if(o===i){for(;i<=n-s;s+=i)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Ui(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vl(this),n_(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:n}=this;if(n){for(r[n++]=1;n<16;n++)r[n]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=i[o]>>>0,e[s++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function E_(t){const e=(i,n)=>t(n).update(ja(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const x_=E_(t=>new v_(t));function __(t,e,r,i,n,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],d=e[3],p=e[4],g=e[5],w=e[6],I=e[7],C=n,b=r[0],v=r[1],D=r[2],P=o,T=a,R=c,A=u,U=l,j=h,B=f,_=d,O=p,m=g,y=w,x=I,$=C,E=b,S=v,F=D;for(let H=0;H<s;H+=2)P=P+U|0,$=ie($^P,16),O=O+$|0,U=ie(U^O,12),P=P+U|0,$=ie($^P,8),O=O+$|0,U=ie(U^O,7),T=T+j|0,E=ie(E^T,16),m=m+E|0,j=ie(j^m,12),T=T+j|0,E=ie(E^T,8),m=m+E|0,j=ie(j^m,7),R=R+B|0,S=ie(S^R,16),y=y+S|0,B=ie(B^y,12),R=R+B|0,S=ie(S^R,8),y=y+S|0,B=ie(B^y,7),A=A+_|0,F=ie(F^A,16),x=x+F|0,_=ie(_^x,12),A=A+_|0,F=ie(F^A,8),x=x+F|0,_=ie(_^x,7),P=P+j|0,F=ie(F^P,16),y=y+F|0,j=ie(j^y,12),P=P+j|0,F=ie(F^P,8),y=y+F|0,j=ie(j^y,7),T=T+B|0,$=ie($^T,16),x=x+$|0,B=ie(B^x,12),T=T+B|0,$=ie($^T,8),x=x+$|0,B=ie(B^x,7),R=R+_|0,E=ie(E^R,16),O=O+E|0,_=ie(_^O,12),R=R+_|0,E=ie(E^R,8),O=O+E|0,_=ie(_^O,7),A=A+U|0,S=ie(S^A,16),m=m+S|0,U=ie(U^m,12),A=A+U|0,S=ie(S^A,8),m=m+S|0,U=ie(U^m,7);let N=0;i[N++]=o+P|0,i[N++]=a+T|0,i[N++]=c+R|0,i[N++]=u+A|0,i[N++]=l+U|0,i[N++]=h+j|0,i[N++]=f+B|0,i[N++]=d+_|0,i[N++]=p+O|0,i[N++]=g+m|0,i[N++]=w+y|0,i[N++]=I+x|0,i[N++]=C+$|0,i[N++]=b+E|0,i[N++]=v+S|0,i[N++]=D+F|0}const I_=b_(__,{counterRight:!1,counterLength:4,allowShortKeys:!1}),S_=new Uint8Array(16),Gl=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(S_.subarray(r))},$_=new Uint8Array(32);function Yl(t,e,r,i,n){const s=t(e,r,$_),o=x_.create(s);n&&Gl(o,n),Gl(o,i);const a=h_(i.length,n?n.length:0,!0);o.update(a);const c=o.digest();return Ui(s,a),c}const O_=t=>(e,r,i)=>({encrypt(n,s){const o=n.length;s=Hl(o+16,s,!1),s.set(n);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Yl(t,e,r,a,i);return s.set(c,o),Ui(c),s},decrypt(n,s){s=Hl(n.length-16,s,!1);const o=n.subarray(0,-16),a=n.subarray(-16),c=Yl(t,e,r,o,i);if(!u_(a,c))throw new Error("invalid tag");return s.set(n.subarray(0,-16)),t(e,r,s,s,1),Ui(c),s}}),tg=l_({blockSize:64,nonceLength:12,tagLength:16},O_(I_));let rg=class extends Qs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Xs(e);const i=Bt(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(i.length>n?e.create().update(i).digest():i);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),It(s)}update(e){return Ur(this),this.iHash.update(e),this}digestInto(e){Ur(this),Tt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:n,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const ro=(t,e,r)=>new rg(t,e).update(r).digest();ro.create=(t,e)=>new rg(t,e);function D_(t,e,r){return Xs(t),r===void 0&&(r=new Uint8Array(t.outputLen)),ro(t,Bt(r),Bt(e))}const Vo=Uint8Array.from([0]),Zl=Uint8Array.of();function A_(t,e,r,i=32){Xs(t),fr(i);const n=t.outputLen;if(i>255*n)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/n);r===void 0&&(r=Zl);const o=new Uint8Array(s*n),a=ro.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Vo[0]=l+1,c.update(l===0?Zl:u).update(r).update(Vo).digestInto(u),o.set(u,n*l),a._cloneInto(c);return a.destroy(),c.destroy(),It(u,Vo),o.slice(0,i)}const P_=(t,e,r,i,n)=>A_(t,D_(t,e,r),i,n),io=eo,Hc=BigInt(0),qa=BigInt(1);function Bs(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Qr(t,e,r=""){const i=Js(t),n=t==null?void 0:t.length,s=e!==void 0;if(!i||s&&n!==e){const o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=i?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qn(t){const e=t.toString(16);return e.length&1?"0"+e:e}function ig(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Hc:BigInt("0x"+t)}function no(t){return ig(Ci(t))}function Ts(t){return Tt(t),ig(Ci(Uint8Array.from(t).reverse()))}function Kc(t,e){return Ps(t.toString(16).padStart(e*2,"0"))}function Wc(t,e){return Kc(t,e).reverse()}function Ve(t,e,r){let i;if(typeof e=="string")try{i=Ps(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Js(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}const Ho=t=>typeof t=="bigint"&&Hc<=t;function C_(t,e,r){return Ho(t)&&Ho(e)&&Ho(r)&&e<=t&&t<r}function za(t,e,r,i){if(!C_(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function ng(t){let e;for(e=0;t>Hc;t>>=qa,e+=1);return e}const Rn=t=>(qa<<BigInt(t))-qa;function B_(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const i=f=>new Uint8Array(f),n=f=>Uint8Array.of(f);let s=i(t),o=i(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...f)=>r(o,s,...f),l=(f=i(0))=>{o=u(n(0),f),s=u(),f.length!==0&&(o=u(n(1),f),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){s=u();const p=s.slice();d.push(p),f+=s.length}return Cr(...d)};return(f,d)=>{c(),l(f);let p;for(;!(p=d(h()));)l();return c(),p}}function so(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function i(n,s,o){const a=t[n];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${n}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([n,s])=>i(n,s,!1)),Object.entries(r).forEach(([n,s])=>i(n,s,!0))}function Jl(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}const it=BigInt(0),We=BigInt(1),ei=BigInt(2),sg=BigInt(3),og=BigInt(4),ag=BigInt(5),T_=BigInt(7),cg=BigInt(8),R_=BigInt(9),ug=BigInt(16);function ht(t,e){const r=t%e;return r>=it?r:e+r}function At(t,e,r){let i=t;for(;e-- >it;)i*=i,i%=r;return i}function Xl(t,e){if(t===it)throw new Error("invert: expected non-zero number");if(e<=it)throw new Error("invert: expected positive modulus, got "+e);let r=ht(t,e),i=e,n=it,s=We;for(;r!==it;){const o=i/r,a=i%r,c=n-s*o;i=r,r=a,n=s,s=c}if(i!==We)throw new Error("invert: does not exist");return ht(n,e)}function Gc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function lg(t,e){const r=(t.ORDER+We)/og,i=t.pow(e,r);return Gc(t,i,e),i}function F_(t,e){const r=(t.ORDER-ag)/cg,i=t.mul(e,ei),n=t.pow(i,r),s=t.mul(e,n),o=t.mul(t.mul(s,ei),n),a=t.mul(s,t.sub(o,t.ONE));return Gc(t,a,e),a}function N_(t){const e=jr(t),r=hg(t),i=r(e,e.neg(e.ONE)),n=r(e,i),s=r(e,e.neg(i)),o=(t+T_)/ug;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,i);const h=a.mul(u,n),f=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(h),c);u=a.cmov(u,l,d),l=a.cmov(f,h,p);const g=a.eql(a.sqr(l),c),w=a.cmov(u,l,g);return Gc(a,w,c),w}}function hg(t){if(t<sg)throw new Error("sqrt is not defined for small field");let e=t-We,r=0;for(;e%ei===it;)e/=ei,r++;let i=ei;const n=jr(t);for(;Ql(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return lg;let s=n.pow(i,e);const o=(e+We)/ei;return function(a,c){if(a.is0(c))return c;if(Ql(a,c)!==1)throw new Error("Cannot find square root");let u=r,l=a.mul(a.ONE,s),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let d=1,p=a.sqr(h);for(;!a.eql(p,a.ONE);)if(d++,p=a.sqr(p),d===u)throw new Error("Cannot find square root");const g=We<<BigInt(u-d-1),w=a.pow(l,g);u=d,l=a.sqr(w),h=a.mul(h,l),f=a.mul(f,w)}return f}}function U_(t){return t%og===sg?lg:t%cg===ag?F_:t%ug===R_?N_(t):hg(t)}const k_=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function j_(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=k_.reduce((i,n)=>(i[n]="function",i),e);return so(t,r),t}function L_(t,e,r){if(r<it)throw new Error("invalid exponent, negatives unsupported");if(r===it)return t.ONE;if(r===We)return e;let i=t.ONE,n=e;for(;r>it;)r&We&&(i=t.mul(i,n)),n=t.sqr(n),r>>=We;return i}function fg(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),s),i}function Ql(t,e){const r=(t.ORDER-We)/ei,i=t.pow(e,r),n=t.eql(i,t.ONE),s=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function dg(t,e){e!==void 0&&fr(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function jr(t,e,r=!1,i={}){if(t<=it)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,s,o=!1,a;if(typeof e=="object"&&e!=null){if(i.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(n=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(n=e),i.sqrt&&(s=i.sqrt);const{nBitLength:c,nByteLength:u}=dg(t,n);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:Rn(c),ZERO:it,ONE:We,allowedLengths:a,create:f=>ht(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return it<=f&&f<t},is0:f=>f===it,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&We)===We,neg:f=>ht(-f,t),eql:(f,d)=>f===d,sqr:f=>ht(f*f,t),add:(f,d)=>ht(f+d,t),sub:(f,d)=>ht(f-d,t),mul:(f,d)=>ht(f*d,t),pow:(f,d)=>L_(h,f,d),div:(f,d)=>ht(f*Xl(d,t),t),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Xl(f,t),sqrt:s||(f=>(l||(l=U_(t)),l(h,f))),toBytes:f=>r?Wc(f,u):Kc(f,u),fromBytes:(f,d=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const g=new Uint8Array(u);g.set(f,r?0:g.length-f.length),f=g}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let p=r?Ts(f):no(f);if(o&&(p=ht(p,t)),!d&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>fg(h,f),cmov:(f,d,p)=>p?d:f});return Object.freeze(h)}function pg(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 gg(t){const e=pg(t);return e+Math.ceil(e/2)}function M_(t,e,r=!1){const i=t.length,n=pg(e),s=gg(e);if(i<16||i<s||i>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+i);const o=r?Ts(t):no(t),a=ht(o,e-We)+We;return r?Wc(a,n):Kc(a,n)}const ki=BigInt(0),ti=BigInt(1);function Rs(t,e){const r=e.negate();return t?r:e}function Ko(t,e){const r=fg(t.Fp,e.map(i=>i.Z));return e.map((i,n)=>t.fromAffine(i.toAffine(r[n])))}function yg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Wo(t,e){yg(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),n=2**t,s=Rn(t),o=BigInt(t);return{windows:r,windowSize:i,mask:s,maxNumber:n,shiftBy:o}}function eh(t,e,r){const{windowSize:i,mask:n,maxNumber:s,shiftBy:o}=r;let a=Number(t&n),c=t>>o;a>i&&(a-=s,c+=ti);const u=e*i,l=u+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:d,offsetF:u}}function q_(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function z_(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Go=new WeakMap,wg=new WeakMap;function Yo(t){return wg.get(t)||1}function th(t){if(t!==ki)throw new Error("invalid wNAF")}class V_{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,i=this.ZERO){let n=e;for(;r>ki;)r&ti&&(i=i.add(n)),n=n.double(),r>>=ti;return i}precomputeWindow(e,r){const{windows:i,windowSize:n}=Wo(r,this.bits),s=[];let o=e,a=o;for(let c=0;c<i;c++){a=o,s.push(a);for(let u=1;u<n;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,r,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let n=this.ZERO,s=this.BASE;const o=Wo(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:f,offsetF:d}=eh(i,a,o);i=c,l?s=s.add(Rs(f,r[d])):n=n.add(Rs(h,r[u]))}return th(i),{p:n,f:s}}wNAFUnsafe(e,r,i,n=this.ZERO){const s=Wo(e,this.bits);for(let o=0;o<s.windows&&i!==ki;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=eh(i,o,s);if(i=a,!u){const h=r[c];n=n.add(l?h.negate():h)}}return th(i),n}getPrecomputes(e,r,i){let n=Go.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof i=="function"&&(n=i(n)),Go.set(r,n))),n}cached(e,r,i){const n=Yo(e);return this.wNAF(n,this.getPrecomputes(n,e,i),r)}unsafe(e,r,i,n){const s=Yo(e);return s===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),r,n)}createCache(e,r){yg(r,this.bits),wg.set(e,r),Go.delete(e)}hasCache(e){return Yo(e)!==1}}function H_(t,e,r,i){let n=e,s=t.ZERO,o=t.ZERO;for(;r>ki||i>ki;)r&ti&&(s=s.add(n)),i&ti&&(o=o.add(n)),n=n.double(),r>>=ti,i>>=ti;return{p1:s,p2:o}}function K_(t,e,r,i){q_(r,t),z_(i,e);const n=r.length,s=i.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=ng(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Rn(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const w=i[g],I=Number(w>>BigInt(d)&u);l[I]=l[I].add(r[g])}let p=o;for(let g=l.length-1,w=o;g>0;g--)w=w.add(l[g]),p=p.add(w);if(f=f.add(p),d!==0)for(let g=0;g<c;g++)f=f.double()}return f}function rh(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return j_(e),e}else return jr(t,{isLE:r})}function W_(t,e,r={},i){if(i===void 0&&(i=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>ki))throw new Error(`CURVE.${a} must be positive bigint`)}const n=rh(e.p,r.Fp,i),s=rh(e.n,r.Fn,i),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!n.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Lp("HashToScalar-");const Xi=BigInt(0),bi=BigInt(1),es=BigInt(2);function G_(t){return so(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function Y_(t){const e=G_(t),{P:r,type:i,adjustScalarBytes:n,powPminus2:s,randomBytes:o}=e,a=i==="x25519";if(!a&&i!=="x448")throw new Error("invalid type");const c=o||ui,u=a?255:448,l=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),d=a?es**BigInt(254):es**BigInt(447),p=a?BigInt(8)*es**BigInt(251)-bi:BigInt(4)*es**BigInt(445)-bi,g=d+p+bi,w=B=>ht(B,r),I=C(h);function C(B){return Wc(w(B),l)}function b(B){const _=Ve("u coordinate",B,l);return a&&(_[31]&=127),w(Ts(_))}function v(B){return Ts(n(Ve("scalar",B,l)))}function D(B,_){const O=R(b(_),v(B));if(O===Xi)throw new Error("invalid private or public key received");return C(O)}function P(B){return D(B,I)}function T(B,_,O){const m=w(B*(_-O));return _=w(_-m),O=w(O+m),{x_2:_,x_3:O}}function R(B,_){za("u",B,Xi,r),za("scalar",_,d,g);const O=_,m=B;let y=bi,x=Xi,$=B,E=bi,S=Xi;for(let N=BigInt(u-1);N>=Xi;N--){const H=O>>N&bi;S^=H,{x_2:y,x_3:$}=T(S,y,$),{x_2:x,x_3:E}=T(S,x,E),S=H;const z=y+x,q=w(z*z),K=y-x,G=w(K*K),X=q-G,W=$+E,Q=$-E,pe=w(Q*z),ve=w(W*K),Ie=pe+ve,He=pe-ve;$=w(Ie*Ie),E=w(m*w(He*He)),y=w(q*G),x=w(X*(q+w(f*X)))}({x_2:y,x_3:$}=T(S,y,$)),{x_2:x,x_3:E}=T(S,x,E);const F=s(x);return w(y*F)}const A={secretKey:l,publicKey:l,seed:l},U=(B=c(l))=>(Tt(B,A.seed),B);function j(B){const _=U(B);return{secretKey:_,publicKey:P(_)}}return{keygen:j,getSharedSecret:(B,_)=>D(B,_),getPublicKey:B=>P(B),scalarMult:D,scalarMultBase:P,utils:{randomSecretKey:U,randomPrivateKey:U},GuBytes:I.slice(),lengths:A}}const Z_=BigInt(1),ih=BigInt(2),J_=BigInt(3),X_=BigInt(5),Q_=BigInt(8),mg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),eI={p:mg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Q_,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function tI(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),s=mg,o=t*t%s*t%s,a=At(o,ih,s)*o%s,c=At(a,Z_,s)*t%s,u=At(c,X_,s)*c%s,l=At(u,e,s)*u%s,h=At(l,r,s)*l%s,f=At(h,i,s)*h%s,d=At(f,n,s)*f%s,p=At(d,n,s)*f%s,g=At(p,e,s)*u%s;return{pow_p_5_8:At(g,ih,s)*t%s,b2:o}}function rI(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const iI=jr(eI.p,{isLE:!0}),Va=(()=>{const t=iI.ORDER;return Y_({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:i}=tI(e);return ht(At(r,J_,t)*i,t)},adjustScalarBytes:rI})})(),nh=(t,e)=>(t+(t>=0?e:-e)/bg)/e;function nI(t,e,r){const[[i,n],[s,o]]=e,a=nh(o*t,r),c=nh(-n*t,r);let u=t-a*i-c*s,l=-a*n-c*o;const h=u<ar,f=l<ar;h&&(u=-u),f&&(l=-l);const d=Rn(Math.ceil(ng(r)/2))+Bi;if(u<ar||u>=d||l<ar||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}function Ha(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Zo(t,e){const r={};for(let i of Object.keys(e))r[i]=t[i]===void 0?e[i]:t[i];return Bs(r.lowS,"lowS"),Bs(r.prehash,"prehash"),r.format!==void 0&&Ha(r.format),r}class sI extends Error{constructor(e=""){super(e)}}const sr={Err:sI,_tlv:{encode:(t,e)=>{const{Err:r}=sr;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,n=Qn(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const s=i>127?Qn(n.length/2|128):"";return Qn(t)+s+n+e},decode(t,e){const{Err:r}=sr;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const n=e[i++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=sr;if(t<ar)throw new e("integer: negative integers are not allowed");let r=Qn(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=sr;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return no(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=sr,n=Ve("signature",t),{v:s,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,s),{v:u,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=sr,i=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),s=i+n;return e.encode(48,s)}},ar=BigInt(0),Bi=BigInt(1),bg=BigInt(2),ts=BigInt(3),oI=BigInt(4);function Si(t,e){const{BYTES:r}=t;let i;if(typeof e=="bigint")i=e;else{let n=Ve("private key",e);try{i=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function aI(t,e={}){const r=W_("weierstrass",t,e),{Fp:i,Fn:n}=r;let s=r.CURVE;const{h:o,n:a}=s;so(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!i.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Eg(i,n);function l(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,_,O){const{x:m,y}=_.toAffine(),x=i.toBytes(m);if(Bs(O,"isCompressed"),O){l();const $=!i.isOdd(y);return Cr(vg($),x)}else return Cr(Uint8Array.of(4),x,i.toBytes(y))}function f(B){Qr(B,void 0,"Point");const{publicKey:_,publicKeyUncompressed:O}=u,m=B.length,y=B[0],x=B.subarray(1);if(m===_&&(y===2||y===3)){const $=i.fromBytes(x);if(!i.isValid($))throw new Error("bad point: is not on curve, wrong x");const E=g($);let S;try{S=i.sqrt(E)}catch(N){const H=N instanceof Error?": "+N.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}l();const F=i.isOdd(S);return(y&1)===1!==F&&(S=i.neg(S)),{x:$,y:S}}else if(m===O&&y===4){const $=i.BYTES,E=i.fromBytes(x.subarray(0,$)),S=i.fromBytes(x.subarray($,$*2));if(!w(E,S))throw new Error("bad point: is not on curve");return{x:E,y:S}}else throw new Error(`bad point: got length ${m}, expected compressed=${_} or uncompressed=${O}`)}const d=e.toBytes||h,p=e.fromBytes||f;function g(B){const _=i.sqr(B),O=i.mul(_,B);return i.add(i.add(O,i.mul(B,s.a)),s.b)}function w(B,_){const O=i.sqr(_),m=g(B);return i.eql(O,m)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=i.mul(i.pow(s.a,ts),oI),C=i.mul(i.sqr(s.b),BigInt(27));if(i.is0(i.add(I,C)))throw new Error("bad curve params: a or b");function b(B,_,O=!1){if(!i.isValid(_)||O&&i.is0(_))throw new Error(`bad point coordinate ${B}`);return _}function v(B){if(!(B instanceof A))throw new Error("ProjectivePoint expected")}function D(B){if(!c||!c.basises)throw new Error("no endo");return nI(B,c.basises,n.ORDER)}const P=Jl((B,_)=>{const{X:O,Y:m,Z:y}=B;if(i.eql(y,i.ONE))return{x:O,y:m};const x=B.is0();_==null&&(_=x?i.ONE:i.inv(y));const $=i.mul(O,_),E=i.mul(m,_),S=i.mul(y,_);if(x)return{x:i.ZERO,y:i.ZERO};if(!i.eql(S,i.ONE))throw new Error("invZ was invalid");return{x:$,y:E}}),T=Jl(B=>{if(B.is0()){if(e.allowInfinityPoint&&!i.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:O}=B.toAffine();if(!i.isValid(_)||!i.isValid(O))throw new Error("bad point: x or y not field elements");if(!w(_,O))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(B,_,O,m,y){return O=new A(i.mul(O.X,B),O.Y,O.Z),_=Rs(m,_),O=Rs(y,O),_.add(O)}class A{constructor(_,O,m){this.X=b("x",_),this.Y=b("y",O,!0),this.Z=b("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(_){const{x:O,y:m}=_||{};if(!_||!i.isValid(O)||!i.isValid(m))throw new Error("invalid affine point");if(_ instanceof A)throw new Error("projective point not allowed");return i.is0(O)&&i.is0(m)?A.ZERO:new A(O,m,i.ONE)}static fromBytes(_){const O=A.fromAffine(p(Qr(_,void 0,"point")));return O.assertValidity(),O}static fromHex(_){return A.fromBytes(Ve("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,O=!0){return j.createCache(this,_),O||this.multiply(ts),this}assertValidity(){T(this)}hasEvenY(){const{y:_}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(_)}equals(_){v(_);const{X:O,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=_,S=i.eql(i.mul(O,E),i.mul(x,y)),F=i.eql(i.mul(m,E),i.mul($,y));return S&&F}negate(){return new A(this.X,i.neg(this.Y),this.Z)}double(){const{a:_,b:O}=s,m=i.mul(O,ts),{X:y,Y:x,Z:$}=this;let E=i.ZERO,S=i.ZERO,F=i.ZERO,N=i.mul(y,y),H=i.mul(x,x),z=i.mul($,$),q=i.mul(y,x);return q=i.add(q,q),F=i.mul(y,$),F=i.add(F,F),E=i.mul(_,F),S=i.mul(m,z),S=i.add(E,S),E=i.sub(H,S),S=i.add(H,S),S=i.mul(E,S),E=i.mul(q,E),F=i.mul(m,F),z=i.mul(_,z),q=i.sub(N,z),q=i.mul(_,q),q=i.add(q,F),F=i.add(N,N),N=i.add(F,N),N=i.add(N,z),N=i.mul(N,q),S=i.add(S,N),z=i.mul(x,$),z=i.add(z,z),N=i.mul(z,q),E=i.sub(E,N),F=i.mul(z,H),F=i.add(F,F),F=i.add(F,F),new A(E,S,F)}add(_){v(_);const{X:O,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=_;let S=i.ZERO,F=i.ZERO,N=i.ZERO;const H=s.a,z=i.mul(s.b,ts);let q=i.mul(O,x),K=i.mul(m,$),G=i.mul(y,E),X=i.add(O,m),W=i.add(x,$);X=i.mul(X,W),W=i.add(q,K),X=i.sub(X,W),W=i.add(O,y);let Q=i.add(x,E);return W=i.mul(W,Q),Q=i.add(q,G),W=i.sub(W,Q),Q=i.add(m,y),S=i.add($,E),Q=i.mul(Q,S),S=i.add(K,G),Q=i.sub(Q,S),N=i.mul(H,W),S=i.mul(z,G),N=i.add(S,N),S=i.sub(K,N),N=i.add(K,N),F=i.mul(S,N),K=i.add(q,q),K=i.add(K,q),G=i.mul(H,G),W=i.mul(z,W),K=i.add(K,G),G=i.sub(q,G),G=i.mul(H,G),W=i.add(W,G),q=i.mul(K,W),F=i.add(F,q),q=i.mul(Q,W),S=i.mul(X,S),S=i.sub(S,q),q=i.mul(X,K),N=i.mul(Q,N),N=i.add(N,q),new A(S,F,N)}subtract(_){return this.add(_.negate())}is0(){return this.equals(A.ZERO)}multiply(_){const{endo:O}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let m,y;const x=$=>j.cached(this,$,E=>Ko(A,E));if(O){const{k1neg:$,k1:E,k2neg:S,k2:F}=D(_),{p:N,f:H}=x(E),{p:z,f:q}=x(F);y=H.add(q),m=R(O.beta,N,z,$,S)}else{const{p:$,f:E}=x(_);m=$,y=E}return Ko(A,[m,y])[0]}multiplyUnsafe(_){const{endo:O}=e,m=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===ar||m.is0())return A.ZERO;if(_===Bi)return m;if(j.hasCache(this))return this.multiply(_);if(O){const{k1neg:y,k1:x,k2neg:$,k2:E}=D(_),{p1:S,p2:F}=H_(A,m,x,E);return R(O.beta,S,F,y,$)}else return j.unsafe(m,_)}multiplyAndAddUnsafe(_,O,m){const y=this.multiplyUnsafe(O).add(_.multiplyUnsafe(m));return y.is0()?void 0:y}toAffine(_){return P(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return o===Bi?!0:_?_(A,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return o===Bi?this:_?_(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(_=!0){return Bs(_,"isCompressed"),this.assertValidity(),d(A,this,_)}toHex(_=!0){return Ci(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Ko(A,_)}static msm(_,O){return K_(A,n,_,O)}static fromPrivateKey(_){return A.BASE.multiply(Si(n,_))}}A.BASE=new A(s.Gx,s.Gy,i.ONE),A.ZERO=new A(i.ZERO,i.ONE,i.ZERO),A.Fp=i,A.Fn=n;const U=n.BITS,j=new V_(A,e.endo?Math.ceil(U/2):U);return A.BASE.precompute(8),A}function vg(t){return Uint8Array.of(t?2:3)}function Eg(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function cI(t,e={}){const{Fn:r}=t,i=e.randomBytes||ui,n=Object.assign(Eg(t.Fp,r),{seed:gg(r.ORDER)});function s(f){try{return!!Si(r,f)}catch{return!1}}function o(f,d){const{publicKey:p,publicKeyUncompressed:g}=n;try{const w=f.length;return d===!0&&w!==p||d===!1&&w!==g?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=i(n.seed)){return M_(Qr(f,n.seed,"seed"),r.ORDER)}function c(f,d=!0){return t.BASE.multiply(Si(r,f)).toBytes(d)}function u(f){const d=a(f);return{secretKey:d,publicKey:c(d)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:d,publicKey:p,publicKeyUncompressed:g}=n;if(r.allowedLengths||d===p)return;const w=Ve("key",f).length;return w===p||w===g}function h(f,d,p=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");const g=Si(r,f);return t.fromHex(d).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:f=>Si(r,f),precompute(f=8,d=t.BASE){return d.precompute(f,!1)}},lengths:n})}function uI(t,e,r={}){Xs(e),so(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=r.randomBytes||ui,n=r.hmac||((O,...m)=>ro(e,O,Cr(...m))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d}=cI(t,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(O){const m=a>>Bi;return O>m}function I(O,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${O}: out of range 1..Point.Fn.ORDER`);return m}function C(O,m){Ha(m);const y=d.signature,x=m==="compact"?y:m==="recovered"?y+1:void 0;return Qr(O,x,`${m} signature`)}class b{constructor(m,y,x){this.r=I("r",m),this.s=I("s",y),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(m,y=g){C(m,y);let x;if(y==="der"){const{r:F,s:N}=sr.toSig(Qr(m));return new b(F,N)}y==="recovered"&&(x=m[0],y="compact",m=m.subarray(1));const $=o.BYTES,E=m.subarray(0,$),S=m.subarray($,$*2);return new b(o.fromBytes(E),o.fromBytes(S),x)}static fromHex(m,y){return this.fromBytes(Ps(m),y)}addRecoveryBit(m){return new b(this.r,this.s,m)}recoverPublicKey(m){const y=s.ORDER,{r:x,s:$,recovery:E}=this;if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");if(a*bg<y&&E>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=E===2||E===3?x+a:x;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const F=s.toBytes(S),N=t.fromBytes(Cr(vg((E&1)===0),F)),H=o.inv(S),z=D(Ve("msgHash",m)),q=o.create(-z*H),K=o.create($*H),G=t.BASE.multiplyUnsafe(q).add(N.multiplyUnsafe(K));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return w(this.s)}toBytes(m=g){if(Ha(m),m==="der")return Ps(sr.hexFromSig(this));const y=o.toBytes(this.r),x=o.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Cr(Uint8Array.of(this.recovery),y,x)}return Cr(y,x)}toHex(m){return Ci(this.toBytes(m))}assertValidity(){}static fromCompact(m){return b.fromBytes(Ve("sig",m),"compact")}static fromDER(m){return b.fromBytes(Ve("sig",m),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ci(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ci(this.toBytes("compact"))}}const v=r.bits2int||function(O){if(O.length>8192)throw new Error("input is too large");const m=no(O),y=O.length*8-c;return y>0?m>>BigInt(y):m},D=r.bits2int_modN||function(O){return o.create(v(O))},P=Rn(c);function T(O){return za("num < 2^"+c,O,ar,P),o.toBytes(O)}function R(O,m){return Qr(O,void 0,"message"),m?Qr(e(O),void 0,"prehashed message"):O}function A(O,m,y){if(["recovered","canonical"].some(K=>K in y))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:$,extraEntropy:E}=Zo(y,p);O=R(O,$);const S=D(O),F=Si(o,m),N=[T(F),T(S)];if(E!=null&&E!==!1){const K=E===!0?i(d.secretKey):E;N.push(Ve("extraEntropy",K))}const H=Cr(...N),z=S;function q(K){const G=v(K);if(!o.isValidNot0(G))return;const X=o.inv(G),W=t.BASE.multiply(G).toAffine(),Q=o.create(W.x);if(Q===ar)return;const pe=o.create(X*o.create(z+Q*F));if(pe===ar)return;let ve=(W.x===Q?0:2)|Number(W.y&Bi),Ie=pe;return x&&w(pe)&&(Ie=o.neg(pe),ve^=1),new b(Q,Ie,ve)}return{seed:H,k2sig:q}}function U(O,m,y={}){O=Ve("message",O);const{seed:x,k2sig:$}=A(O,m,y);return B_(e.outputLen,o.BYTES,n)(x,$)}function j(O){let m;const y=typeof O=="string"||Js(O),x=!y&&O!==null&&typeof O=="object"&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!y&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)m=new b(O.r,O.s);else if(y){try{m=b.fromBytes(Ve("sig",O),"der")}catch($){if(!($ instanceof sr.Err))throw $}if(!m)try{m=b.fromBytes(Ve("sig",O),"compact")}catch{return!1}}return m||!1}function B(O,m,y,x={}){const{lowS:$,prehash:E,format:S}=Zo(x,p);if(y=Ve("publicKey",y),m=R(Ve("message",m),E),"strict"in x)throw new Error("options.strict was renamed to lowS");const F=S===void 0?j(O):b.fromBytes(Ve("sig",O),S);if(F===!1)return!1;try{const N=t.fromBytes(y);if($&&F.hasHighS())return!1;const{r:H,s:z}=F,q=D(m),K=o.inv(z),G=o.create(q*K),X=o.create(H*K),W=t.BASE.multiplyUnsafe(G).add(N.multiplyUnsafe(X));return W.is0()?!1:o.create(W.x)===H}catch{return!1}}function _(O,m,y={}){const{prehash:x}=Zo(y,p);return m=R(m,x),b.fromBytes(O,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:d,Point:t,sign:U,verify:B,recoverPublicKey:_,Signature:b,hash:e})}function lI(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let i=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const n=jr(e.n,{BITS:t.nBitLength,allowedLengths:i,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:n,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function hI(t){const{CURVE:e,curveOpts:r}=lI(t),i={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:i}}function fI(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,dg(r.Fn.ORDER,r.Fn.BITS))})}function dI(t){const{CURVE:e,curveOpts:r,hash:i,ecdsaOpts:n}=hI(t),s=aI(e,r),o=uI(s,i,n);return fI(t,o)}function Ka(t,e){const r=i=>dI({...t,hash:i});return{...r(e),create:r}}const xg={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},_g={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ig={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},pI=jr(xg.p),gI=jr(_g.p),yI=jr(Ig.p),wI=Ka({...xg,Fp:pI,lowS:!1},eo);Ka({..._g,Fp:gI,lowS:!1},Ex),Ka({...Ig,Fp:yI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},vx);const mI=wI,Sg="base10",Ge="base16",tt="base64pad",Br="base64url",Fn="utf8",$g=0,ur=1,Nn=2,bI=0,sh=1,dn=12,Yc=32;function vI(){const t=Va.utils.randomPrivateKey(),e=Va.getPublicKey(t);return{privateKey:nt(t,Ge),publicKey:nt(e,Ge)}}function Wa(){const t=ui(Yc);return nt(t,Ge)}function EI(t,e){const r=Va.getSharedSecret(Et(t,Ge),Et(e,Ge)),i=P_(io,r,void 0,void 0,Yc);return nt(i,Ge)}function ds(t){const e=io(Et(t,Ge));return nt(e,Ge)}function bt(t){const e=io(Et(t,Fn));return nt(e,Ge)}function Og(t){return Et(`${t}`,Sg)}function ai(t){return Number(nt(t,Sg))}function Dg(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ag(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function xI(t){const e=Og(typeof t.type<"u"?t.type:$g);if(ai(e)===ur&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Et(t.senderPublicKey,Ge):void 0,i=typeof t.iv<"u"?Et(t.iv,Ge):ui(dn),n=Et(t.symKey,Ge),s=tg(n,i).encrypt(Et(t.message,Fn)),o=Pg({type:e,sealed:s,iv:i,senderPublicKey:r});return t.encoding===Br?Dg(o):o}function _I(t){const e=Et(t.symKey,Ge),{sealed:r,iv:i}=In({encoded:t.encoded,encoding:t.encoding}),n=tg(e,i).decrypt(r);if(n===null)throw new Error("Failed to decrypt");return nt(n,Fn)}function II(t,e){const r=Og(Nn),i=ui(dn),n=Et(t,Fn),s=Pg({type:r,sealed:n,iv:i});return e===Br?Dg(s):s}function SI(t,e){const{sealed:r}=In({encoded:t,encoding:e});return nt(r,Fn)}function Pg(t){if(ai(t.type)===Nn)return nt(fn([t.type,t.sealed]),tt);if(ai(t.type)===ur){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return nt(fn([t.type,t.senderPublicKey,t.iv,t.sealed]),tt)}return nt(fn([t.type,t.iv,t.sealed]),tt)}function In(t){const e=(t.encoding||tt)===Br?Ag(t.encoded):t.encoded,r=Et(e,tt),i=r.slice(bI,sh),n=sh;if(ai(i)===ur){const c=n+Yc,u=c+dn,l=r.slice(n,c),h=r.slice(c,u),f=r.slice(u);return{type:i,sealed:f,iv:h,senderPublicKey:l}}if(ai(i)===Nn){const c=r.slice(n),u=ui(dn);return{type:i,sealed:c,iv:u}}const s=n+dn,o=r.slice(n,s),a=r.slice(s);return{type:i,sealed:a,iv:o}}function $I(t,e){const r=In({encoded:t,encoding:e==null?void 0:e.encoding});return Cg({type:ai(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?nt(r.senderPublicKey,Ge):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Cg(t){const e=(t==null?void 0:t.type)||$g;if(e===ur){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 oh(t){return t.type===ur&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function ah(t){return t.type===Nn}function OI(t){const e=re.from(t.x,"base64"),r=re.from(t.y,"base64");return fn([new Uint8Array([4]),e,r])}function DI(t,e){const[r,i,n]=t.split("."),s=re.from(Ag(n),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${r}.${i}`,u=io(c),l=OI(e);if(!mI.verify(fn([o,a]),u,l))throw new Error("Invalid signature");return Ca(t).payload}const AI="irn";function Fs(t){return(t==null?void 0:t.relay)||{protocol:AI}}function $i(t){const e=dE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var PI=Object.defineProperty,CI=Object.defineProperties,BI=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,TI=Object.prototype.hasOwnProperty,RI=Object.prototype.propertyIsEnumerable,uh=(t,e,r)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Jo=(t,e)=>{for(var r in e||(e={}))TI.call(e,r)&&uh(t,r,e[r]);if(ch)for(var r of ch(e))RI.call(e,r)&&uh(t,r,e[r]);return t},FI=(t,e)=>CI(t,BI(e));function NI(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(n=>{if(n.startsWith(i)){const s=n.replace(i,""),o=t[n];r[s]=o}}),r}function lh(t){if(!t.includes("wc:")){const u=Rp(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),n=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:UI(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:NI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function UI(t){return t.startsWith("//")?t.substring(2):t}function kI(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(n=>{const s=n,o=r+e+s;t[s]&&(i[o]=t[s])}),i}function hh(t){const e=new URLSearchParams,r=Jo(Jo(FI(Jo({},kI(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(r).sort(([i],[n])=>i.localeCompare(n)).forEach(([i,n])=>{n!==void 0&&e.append(i,String(n))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function rs(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var jI=Object.defineProperty,LI=Object.defineProperties,MI=Object.getOwnPropertyDescriptors,fh=Object.getOwnPropertySymbols,qI=Object.prototype.hasOwnProperty,zI=Object.prototype.propertyIsEnumerable,dh=(t,e,r)=>e in t?jI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VI=(t,e)=>{for(var r in e||(e={}))qI.call(e,r)&&dh(t,r,e[r]);if(fh)for(var r of fh(e))zI.call(e,r)&&dh(t,r,e[r]);return t},HI=(t,e)=>LI(t,MI(e));function qi(t){const e=[];return t.forEach(r=>{const[i,n]=r.split(":");e.push(`${i}:${n}`)}),e}function Bg(t){const e=[];return Object.values(t).forEach(r=>{e.push(...qi(r.accounts))}),[...new Set(e)]}function KI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.methods)}),[...new Set(e)]}function WI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.events)}),[...new Set(e)]}function GI(t,e){const r=[];return Object.values(t).forEach(i=>{qi(i.accounts).includes(e)&&r.push(...i.methods)}),r}function YI(t,e){const r=[];return Object.values(t).forEach(i=>{qi(i.accounts).includes(e)&&r.push(...i.events)}),r}function oo(t){return t.includes(":")}function Oi(t){return oo(t)?t.split(":")[0]:t}function ph(t){var e,r,i;const n={};if(!Ht(t))return n;for(const[s,o]of Object.entries(t)){const a=oo(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=Oi(s);n[l]=HI(VI({},n[l]),{chains:Vt(a,(e=n[l])==null?void 0:e.chains),methods:Vt(c,(r=n[l])==null?void 0:r.methods),events:Vt(u,(i=n[l])==null?void 0:i.events)})}return n}function ZI(t){const e={};return t==null||t.forEach(r=>{var i;const[n,s]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[],methods:[]}),e[n].accounts.push(r),(i=e[n].chains)==null||i.push(`${n}:${s}`)}),e}function gh(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=ZI(e);for(const[i,n]of Object.entries(r))n.methods?n.methods=Vt(n.methods,t):n.methods=t,n.events=["chainChanged","accountsChanged"];return r}function JI(t,e){var r,i,n,s,o,a;const c=ph(t),u=ph(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:Vt((r=c[f])==null?void 0:r.chains,(i=u[f])==null?void 0:i.chains),methods:Vt((n=c[f])==null?void 0:n.methods,(s=u[f])==null?void 0:s.methods),events:Vt((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}const XI={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}},QI={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 M(t,e){const{message:r,code:i}=QI[t];return{message:e?`${r} ${e}`:r,code:i}}function fe(t,e){const{message:r,code:i}=XI[t];return{message:e?`${r} ${e}`:r,code:i}}function _t(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ht(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function be(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function Zc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function eS(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),n=Object.keys(r);let s=!0;return Xr(n,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=qi(a),h=r[o];(!Xr(Ap(o,h),l)||!Xr(h.methods,c)||!Xr(h.events,u))&&(s=!1)}),s):!1}function Ns(t){return be(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function tS(t){if(be(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Ns(r)}}return!1}function rS(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(be(t,!1)){if(e(t))return!0;const r=Rp(t);return e(r)}}catch{}return!1}function iS(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function nS(t){return t==null?void 0:t.topic}function sS(t,e){let r=null;return be(t==null?void 0:t.publicKey,!1)||(r=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function yh(t){let e=!0;return _t(t)?t.length&&(e=t.every(r=>be(r,!1))):e=!1,e}function oS(t,e,r){let i=null;return _t(e)&&e.length?e.forEach(n=>{i||Ns(n)||(i=fe("UNSUPPORTED_CHAINS",`${r}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):Ns(t)||(i=fe("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function aS(t,e,r){let i=null;return Object.entries(t).forEach(([n,s])=>{if(i)return;const o=oS(n,Ap(n,s),`${e} ${r}`);o&&(i=o)}),i}function cS(t,e){let r=null;return _t(t)?t.forEach(i=>{r||tS(i)||(r=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function uS(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=cS(i==null?void 0:i.accounts,`${e} namespace`);n&&(r=n)}),r}function lS(t,e){let r=null;return yh(t==null?void 0:t.methods)?yh(t==null?void 0:t.events)||(r=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function Tg(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=lS(i,`${e}, namespace`);n&&(r=n)}),r}function hS(t,e,r){let i=null;if(t&&Ht(t)){const n=Tg(t,e);n&&(i=n);const s=aS(t,e,r);s&&(i=s)}else i=M("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function Xo(t,e){let r=null;if(t&&Ht(t)){const i=Tg(t,e);i&&(r=i);const n=uS(t,e);n&&(r=n)}else r=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Rg(t){return be(t.protocol,!0)}function fS(t,e){let r=!1;return e&&!t?r=!0:t&&_t(t)&&t.length&&t.forEach(i=>{r=Rg(i)}),r}function dS(t){return typeof t=="number"}function Xe(t){return typeof t<"u"&&typeof t!==null}function pS(t){return!(!t||typeof t!="object"||!t.code||!Zc(t.code,!1)||!t.message||!be(t.message,!1))}function gS(t){return!(_e(t)||!be(t.method,!1))}function yS(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!Zc(t.id,!1)||!be(t.jsonrpc,!1))}function wS(t){return!(_e(t)||!be(t.name,!1))}function wh(t,e){return!(!Ns(e)||!Bg(t).includes(e))}function mS(t,e,r){return be(r,!1)?GI(t,e).includes(r):!1}function bS(t,e,r){return be(r,!1)?YI(t,e).includes(r):!1}function mh(t,e,r){let i=null;const n=vS(t),s=ES(e),o=Object.keys(n),a=Object.keys(s),c=bh(Object.keys(t)),u=bh(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
21
- Required: ${l.toString()}
22
- Received: ${Object.keys(e).toString()}`)),Xr(o,a)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
23
- Required: ${o.toString()}
24
- Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const f=qi(e[h].accounts);f.includes(h)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
25
- Required: ${h}
26
- Approved: ${f.toString()}`))}),o.forEach(h=>{i||(Xr(n[h].methods,s[h].methods)?Xr(n[h].events,s[h].events)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function vS(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(n=>{e[n]={methods:t[r].methods,events:t[r].events}})}),e}function bh(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function ES(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=qi(t[r].accounts);i==null||i.forEach(n=>{e[n]={accounts:t[r].accounts.filter(s=>s.includes(`${n}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function xS(t,e){return Zc(t,!1)&&t<=e.max&&t>=e.min}function vh(){const t=Bn();return new Promise(e=>{switch(t){case ft.browser:e(_S());break;case ft.reactNative:e(IS());break;case ft.node:e(SS());break;default:e(!0)}})}function _S(){return Mi()&&(navigator==null?void 0:navigator.onLine)}async function IS(){if(kr()&&typeof Y<"u"&&Y!=null&&Y.NetInfo){const t=await(Y==null?void 0:Y.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function SS(){return!0}function $S(t){switch(Bn()){case ft.browser:OS(t);break;case ft.reactNative:DS(t);break}}function OS(t){!kr()&&Mi()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function DS(t){var e;kr()&&typeof Y<"u"&&Y!=null&&Y.NetInfo&&((e=Y)==null||e.NetInfo.addEventListener(r=>t(r==null?void 0:r.isConnected)))}function AS(){var t;return Mi()&&ii()?((t=ii())==null?void 0:t.visibilityState)==="visible":!0}const Qo={};class Qi{static get(e){return Qo[e]}static set(e,r){Qo[e]=r}static delete(e){delete Qo[e]}}function PS(t){const e=An.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function CS({publicKey:t,signature:e,payload:r}){var i;const n=Ga(r.method),s=128|parseInt(((i=r.version)==null?void 0:i.toString())||"4"),o=RS(r.address),a=r.era==="00"?new Uint8Array([0]):Ga(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${TS(r.tip)}`),h=NS(l),f=new Uint8Array([0,...t,o,...e,...a,...u,...h,...n]),d=FS(f.length+1);return new Uint8Array([...d,s,...f])}function BS(t){const e=Ga(t),r=SE.blake2b(e,void 0,32);return"0x"+re.from(r).toString("hex")}function Ga(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function TS(t){return t.startsWith("0x")?t.slice(2):t}function RS(t){const e=An.decode(t)[0];return e===42?0:e===60?2:1}function FS(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 NS(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 US(t){const e=Uint8Array.from(re.from(t.signature,"hex")),r=PS(t.transaction.address),i=CS({publicKey:r,signature:e,payload:t.transaction}),n=re.from(i).toString("hex");return BS(n)}function Jc({logger:t,name:e}){const r=typeof t=="string"?Dp({opts:{level:t,name:e}}).logger:t;return r.level=typeof t=="string"?t:t.level,r}class li{}let kS=class extends li{constructor(e){super()}};const Eh=L.FIVE_SECONDS,hi={pulse:"heartbeat_pulse"};let jS=class Fg extends kS{constructor(e){super(e),this.events=new St.EventEmitter,this.interval=Eh,this.interval=(e==null?void 0:e.interval)||Eh}static async init(e){const r=new Fg(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(hi.pulse)}};const LS=/"(?:_|\\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*:/,MS=/"(?: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*:/,qS=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function zS(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){VS(t);return}return e}function VS(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function is(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!qS.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(LS.test(t)||MS.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,zS)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function HS(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Oe(t,...e){try{return HS(t(...e))}catch(r){return Promise.reject(r)}}function KS(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function WS(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ps(t){if(KS(t))return String(t);if(WS(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ps(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ya="base64:";function GS(t){return typeof t=="string"?t:Ya+JS(t)}function YS(t){return typeof t!="string"||!t.startsWith(Ya)?t:ZS(t.slice(Ya.length))}function ZS(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function JS(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Je(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function XS(...t){return Je(t.join(":"))}function ns(t){return t=Je(t),t?t+":":""}function QS(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function e8(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const t8="memory",r8=()=>{const t=new Map;return{name:t8,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function i8(t={}){const e={mounts:{"":t.driver||r8()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},i=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),n=(u,l)=>{if(e.watching){l=Je(l);for(const h of e.watchListeners)h(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await xh(e.mounts[u],n,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,d=p=>{let g=f.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},f.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",w=Je(g?p:p.key),I=g?void 0:p.value,C=g||!p.options?l:{...l,...p.options},b=r(w);d(b).items.push({key:w,value:I,relativeKey:b.relativeKey,options:C})}return Promise.all([...f.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=Je(u);const{relativeKey:h,driver:f}=r(u);return Oe(f.hasItem,h,l)},getItem(u,l={}){u=Je(u);const{relativeKey:h,driver:f}=r(u);return Oe(f.getItem,h,l).then(d=>is(d))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Oe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(d=>({key:XS(h.base,d.key),value:is(d.value)}))):Promise.all(h.items.map(f=>Oe(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:is(d)})))))},getItemRaw(u,l={}){u=Je(u);const{relativeKey:h,driver:f}=r(u);return f.getItemRaw?Oe(f.getItemRaw,h,l):Oe(f.getItem,h,l).then(d=>YS(d))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Je(u);const{relativeKey:f,driver:d}=r(u);d.setItem&&(await Oe(d.setItem,f,ps(l),h),d.watch||n("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Oe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:ps(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Oe(h.driver.setItem,f.relativeKey,ps(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Je(u);const{relativeKey:f,driver:d}=r(u);if(d.setItemRaw)await Oe(d.setItemRaw,f,l,h);else if(d.setItem)await Oe(d.setItem,f,GS(l),h);else return;d.watch||n("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Je(u);const{relativeKey:h,driver:f}=r(u);f.removeItem&&(await Oe(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Oe(f.removeItem,h+"$",l),f.watch||n("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Je(u);const{relativeKey:h,driver:f}=r(u),d=Object.create(null);if(f.getMeta&&Object.assign(d,await Oe(f.getMeta,h,l)),!l.nativeOnly){const p=await Oe(f.getItem,h+"$",l).then(g=>is(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){var w;u=ns(u);const h=i(u,!0);let f=[];const d=[];let p=!0;for(const I of h){(w=I.driver.flags)!=null&&w.maxDepth||(p=!1);const C=await Oe(I.driver.getKeys,I.relativeBase,l);for(const b of C){const v=I.mountpoint+Je(b);f.some(D=>v.startsWith(D))||d.push(v)}f=[I.mountpoint,...f.filter(b=>!b.startsWith(I.mountpoint))]}const g=l.maxDepth!==void 0&&!p;return d.filter(I=>(!g||QS(I,l.maxDepth))&&e8(I,u))},async clear(u,l={}){u=ns(u),await Promise.all(i(u,!1).map(async h=>{if(h.driver.clear)return Oe(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(d=>h.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>_h(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=ns(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(xh(l,n,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){var h,f;u=ns(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&((f=(h=e.unwatch)[u])==null||f.call(h),delete e.unwatch[u]),l&&await _h(e.mounts[u]),e.mountpoints=e.mountpoints.filter(d=>d!==u),delete e.mounts[u])},getMount(u=""){u=Je(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Je(u),i(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function xh(t,e,r){return t.watch?t.watch((i,n)=>e(i,r+n)):()=>{}}async function _h(t){typeof t.dispose=="function"&&await Oe(t.dispose)}function fi(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Ng(t,e){let r;const i=()=>{if(r)return r;const n=indexedDB.open(t);return n.onupgradeneeded=()=>n.result.createObjectStore(e),r=fi(n),r.then(s=>{s.onclose=()=>r=void 0},()=>{}),r};return(n,s)=>i().then(o=>s(o.transaction(e,n).objectStore(e)))}let ea;function Un(){return ea||(ea=Ng("keyval-store","keyval")),ea}function Ih(t,e=Un()){return e("readonly",r=>fi(r.get(t)))}function n8(t,e,r=Un()){return r("readwrite",i=>(i.put(e,t),fi(i.transaction)))}function s8(t,e=Un()){return e("readwrite",r=>(r.delete(t),fi(r.transaction)))}function o8(t=Un()){return t("readwrite",e=>(e.clear(),fi(e.transaction)))}function a8(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},fi(t.transaction)}function c8(t=Un()){return t("readonly",e=>{if(e.getAllKeys)return fi(e.getAllKeys());const r=[];return a8(e,i=>r.push(i.key)).then(()=>r)})}const u8="idb-keyval";var l8=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=n=>e+n;let i;return t.dbName&&t.storeName&&(i=Ng(t.dbName,t.storeName)),{name:u8,options:t,async hasItem(n){return!(typeof await Ih(r(n),i)>"u")},async getItem(n){return await Ih(r(n),i)??null},setItem(n,s){return n8(r(n),s,i)},removeItem(n){return s8(r(n),i)},getKeys(){return c8(i)},clear(){return o8(i)}}};const h8="WALLET_CONNECT_V2_INDEXED_DB",f8="keyvaluestorage";let d8=class{constructor(){this.indexedDb=i8({driver:l8({dbName:h8,storeName:f8})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,lr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ta=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Y<"u"?Y:typeof self<"u"?self:{},gs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ta<"u"&&ta.localStorage?gs.exports=ta.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function p8(t){var e;return[t[0],si((e=t[1])!=null?e:"")]}let g8=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(p8)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return si(r)}async setItem(e,r){this.localStorage.setItem(e,lr(r))}async removeItem(e){this.localStorage.removeItem(e)}};const y8="wc_storage_version",Sh=1,w8=async(t,e,r)=>{const i=y8,n=await e.getItem(i);if(n&&n>=Sh){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(i,Sh),r(e),m8(t,o)},m8=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let b8=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new g8;this.storage=e;try{const r=new d8;w8(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var v8=Object.defineProperty,E8=(t,e,r)=>e in t?v8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$h=(t,e,r)=>E8(t,typeof e!="symbol"?e+"":e,r);let x8=class extends li{constructor(e){super(),this.opts=e,$h(this,"protocol","wc"),$h(this,"version",2)}};var _8=Object.defineProperty,I8=(t,e,r)=>e in t?_8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,S8=(t,e,r)=>I8(t,typeof e!="symbol"?e+"":e,r);let $8=class extends li{constructor(e,r){super(),this.core=e,this.logger=r,S8(this,"records",new Map)}},O8=class{constructor(e,r){this.logger=e,this.core=r}},D8=class extends li{constructor(e,r){super(),this.relayer=e,this.logger=r}},A8=class extends li{constructor(e){super()}},P8=class{constructor(e,r,i,n){this.core=e,this.logger=r,this.name=i}},C8=class extends li{constructor(e,r){super(),this.relayer=e,this.logger=r}},B8=class extends li{constructor(e,r){super(),this.core=e,this.logger=r}},T8=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},R8=class{constructor(e,r){this.projectId=e,this.logger=r}},F8=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var N8=Object.defineProperty,U8=(t,e,r)=>e in t?N8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oh=(t,e,r)=>U8(t,typeof e!="symbol"?e+"":e,r);let k8=class{constructor(e){this.opts=e,Oh(this,"protocol","wc"),Oh(this,"version",2)}},j8=class{constructor(e){this.client=e}};const L8="PARSE_ERROR",M8="INVALID_REQUEST",q8="METHOD_NOT_FOUND",z8="INVALID_PARAMS",Ug="INTERNAL_ERROR",Xc="SERVER_ERROR",V8=[-32700,-32600,-32601,-32602,-32603],pn={[L8]:{code:-32700,message:"Parse error"},[M8]:{code:-32600,message:"Invalid Request"},[q8]:{code:-32601,message:"Method not found"},[z8]:{code:-32602,message:"Invalid params"},[Ug]:{code:-32603,message:"Internal error"},[Xc]:{code:-32e3,message:"Server error"}},kg=Xc;function H8(t){return V8.includes(t)}function Dh(t){return Object.keys(pn).includes(t)?pn[t]:pn[kg]}function K8(t){const e=Object.values(pn).find(r=>r.code===t);return e||pn[kg]}function jg(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Lg={};/*! *****************************************************************************
27
- Copyright (c) Microsoft Corporation.
28
-
29
- Permission to use, copy, modify, and/or distribute this software for any
30
- purpose with or without fee is hereby granted.
31
-
32
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
33
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
34
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
35
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
36
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
- PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var Za=function(t,e){return Za=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Za(t,e)};function W8(t,e){Za(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Ja=function(){return Ja=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Ja.apply(this,arguments)};function G8(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function Y8(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function Z8(t,e){return function(r,i){e(r,i,t)}}function J8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X8(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):n(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function Q8(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(s=u[0]&2?n.return:u[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,u[1])).done)return s;switch(n=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,n=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],n=0}finally{i=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function e$(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function t$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Xa(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Mg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function r$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Mg(arguments[e]));return t}function i$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function n$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function s$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function o$(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Xa=="function"?Xa(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function a$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function c$(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function u$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function h$(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const f$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Ja},__asyncDelegator:s$,__asyncGenerator:n$,__asyncValues:o$,__await:Sn,__awaiter:X8,__classPrivateFieldGet:l$,__classPrivateFieldSet:h$,__createBinding:e$,__decorate:Y8,__exportStar:t$,__extends:W8,__generator:Q8,__importDefault:u$,__importStar:c$,__makeTemplateObject:a$,__metadata:J8,__param:Z8,__read:Mg,__rest:G8,__spread:r$,__spreadArrays:i$,__values:Xa},Symbol.toStringTag,{value:"Module"})),d$=kf(f$);var Qt={},Ah;function p$(){if(Ah)return Qt;Ah=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pi===null||pi===void 0?void 0:pi.crypto)||(pi===null||pi===void 0?void 0:pi.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=r,Qt}var er={},Ph;function g$(){if(Ph)return er;Ph=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowser=er.isNode=er.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}er.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}er.isNode=e;function r(){return!t()&&!e()}return er.isBrowser=r,er}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=d$;e.__exportStar(p$(),t),e.__exportStar(g$(),t)})(Lg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ao(t,e,r){return{id:t,jsonrpc:"2.0",error:y$(e,r)}}function y$(t,e){return typeof t>"u"?Dh(Ug):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Xc)),{message:t})),typeof e<"u"&&(t.data=e),H8(t.code)&&(t=K8(t.code)),t)}class w${}class m$ extends w${constructor(){super()}}class b$ extends m${constructor(e){super()}}const v$="^https?:",E$="^wss?:";function x$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function qg(t,e){const r=x$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return qg(t,v$)}function Bh(t){return qg(t,E$)}function _$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function zg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Qc(t){return zg(t)&&"method"in t}function co(t){return zg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class eu extends b${constructor(e){super(e),this.events=new St.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),co(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)}}var ra,Th;function I$(){return Th||(Th=1,ra=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ra}const S$=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:I$(),$$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,O$=S$();let D$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(lr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=Lg.isReactNative()?void 0:{rejectUnauthorized:!_$(e)},s=new O$(e,[],n);$$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const Vg="wc",Hg=2,Us="core",Kt=`${Vg}@2:${Us}:`,A$={name:Us,logger:"error"},P$={database:":memory:"},C$="crypto",Nh="client_ed25519_seed",B$=L.ONE_DAY,T$="keychain",R$="0.3",F$="messages",N$="0.3",U$=L.SIX_HOURS,k$="publisher",Kg="irn",j$="error",Wg="wss://relay.walletconnect.org",L$="relayer",me={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",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},q$=.1,Qa="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},z$="0.3",V$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",ut={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},H$="subscription",K$="0.3",W$="pairing",G$="0.3",en={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}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Y$="history",Z$="0.3",J$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},X$="0.3",Q$="verify-api",e6="https://verify.walletconnect.com",Gg="https://verify.walletconnect.org",gn=Gg,t6=`${gn}/v3`,r6=[e6,Gg],i6="echo",n6="https://echo.walletconnect.com",jt={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"},rr={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"},Dt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},zr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Vr={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"},tn={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"},s6=.1,o6="event-client",a6=86400,c6="https://pulse.walletconnect.org/batch";function u6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=n}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*l+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*u+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var l6=u6,h6=l6;const Yg=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")},f6=t=>new TextEncoder().encode(t),d6=t=>new TextDecoder().decode(t);class p6{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class g6{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Zg(this,e)}}class y6{constructor(e){this.decoders=e}or(e){return Zg(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Zg=(t,e)=>new y6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class w6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new p6(e,r,i),this.decoder=new g6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const uo=({name:t,prefix:e,encode:r,decode:i})=>new w6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=h6(r,e);return uo({prefix:t,name:e,encode:i,decode:s=>Yg(n(s))})},m6=(t,e,r,i)=>{const n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=n[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},b6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>uo({prefix:e,name:t,encode(n){return b6(n,i,r)},decode(n){return m6(n,i,r,t)}}),v6=uo({prefix:"\0",name:"identity",encode:t=>d6(t),decode:t=>f6(t)});var E6=Object.freeze({__proto__:null,identity:v6});const x6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var _6=Object.freeze({__proto__:null,base2:x6});const I6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var S6=Object.freeze({__proto__:null,base8:I6});const $6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var O6=Object.freeze({__proto__:null,base10:$6});const D6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),A6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var P6=Object.freeze({__proto__:null,base16:D6,base16upper:A6});const C6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),B6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),R6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),F6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),N6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),U6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),k6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var L6=Object.freeze({__proto__:null,base32:C6,base32upper:B6,base32pad:T6,base32padupper:R6,base32hex:F6,base32hexupper:N6,base32hexpad:U6,base32hexpadupper:k6,base32z:j6});const M6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),q6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var z6=Object.freeze({__proto__:null,base36:M6,base36upper:q6});const V6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K6=Object.freeze({__proto__:null,base58btc:V6,base58flickr:H6});const W6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),G6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Y6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Z6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var J6=Object.freeze({__proto__:null,base64:W6,base64pad:G6,base64url:Y6,base64urlpad:Z6});const Jg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),X6=Jg.reduce((t,e,r)=>(t[r]=e,t),[]),Q6=Jg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function eO(t){return t.reduce((e,r)=>(e+=X6[r],e),"")}function tO(t){const e=[];for(const r of t){const i=Q6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const rO=uo({prefix:"🚀",name:"base256emoji",encode:eO,decode:tO});var iO=Object.freeze({__proto__:null,base256emoji:rO}),nO=Xg,kh=128,sO=127,oO=~sO,aO=Math.pow(2,31);function Xg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=aO;)e[r++]=t&255|kh,t/=128;for(;t&oO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Xg.bytes=r-i+1,e}var cO=ec,uO=128,jh=127;function ec(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw ec.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=uO);return ec.bytes=s-i,r}var lO=Math.pow(2,7),hO=Math.pow(2,14),fO=Math.pow(2,21),dO=Math.pow(2,28),pO=Math.pow(2,35),gO=Math.pow(2,42),yO=Math.pow(2,49),wO=Math.pow(2,56),mO=Math.pow(2,63),bO=function(t){return t<lO?1:t<hO?2:t<fO?3:t<dO?4:t<pO?5:t<gO?6:t<yO?7:t<wO?8:t<mO?9:10},vO={encode:nO,decode:cO,encodingLength:bO},Qg=vO;const Lh=(t,e,r=0)=>(Qg.encode(t,e,r),e),Mh=t=>Qg.encodingLength(t),tc=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new EO(t,r,e,s)};class EO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const e0=({name:t,code:e,encode:r})=>new xO(t,e,r);class xO{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?tc(this.code,r):r.then(i=>tc(this.code,i))}else throw Error("Unknown type, must be binary type")}}const t0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),_O=e0({name:"sha2-256",code:18,encode:t0("SHA-256")}),IO=e0({name:"sha2-512",code:19,encode:t0("SHA-512")});var SO=Object.freeze({__proto__:null,sha256:_O,sha512:IO});const r0=0,$O="identity",i0=Yg,OO=t=>tc(r0,i0(t)),DO={code:r0,name:$O,encode:i0,digest:OO};var AO=Object.freeze({__proto__:null,identity:DO});new TextEncoder,new TextDecoder;const qh={...E6,..._6,...S6,...O6,...P6,...L6,...z6,...K6,...J6,...iO};({...SO,...AO});function n0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function PO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?n0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function s0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=s0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ia=s0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=PO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),CO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ia,ascii:ia,binary:ia,...qh};function BO(t,e="utf8"){const r=CO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?n0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var TO=Object.defineProperty,RO=(t,e,r)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>RO(t,typeof e!="symbol"?e+"":e,r);class FO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",T$),Ut(this,"version",R$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var NO=Object.defineProperty,UO=(t,e,r)=>e in t?NO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>UO(t,typeof e!="symbol"?e+"":e,r);class kO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",C$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Wa()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=pl(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=vI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=pl(s),a=this.randomSessionIdentifier;return await y2(a,n,B$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=EI(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=Cg(o),c=lr(s);if(ah(a))return II(c,o==null?void 0:o.encoding);if(oh(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const u=this.getSymKey(n),{type:l,senderPublicKey:h}=a;return xI({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=$I(s,o);if(ah(a)){const c=SI(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;n=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(n),u=_I({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return ai(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new FO(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nh)}catch{e=Wa(),await this.keychain.set(Nh,e)}return BO(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var jO=Object.defineProperty,LO=Object.defineProperties,MO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,qO=Object.prototype.hasOwnProperty,zO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?jO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,VO=(t,e)=>{for(var r in e||(e={}))qO.call(e,r)&&rc(t,r,e[r]);if(Vh)for(var r of Vh(e))zO.call(e,r)&&rc(t,r,e[r]);return t},HO=(t,e)=>LO(t,MO(e)),ot=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class KO extends O8{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",F$),ot(this,"version",N$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,HO(VO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}get context(){return st(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,Fa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Fa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Na(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Na(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WO=Object.defineProperty,GO=Object.defineProperties,YO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,ZO=Object.prototype.hasOwnProperty,JO=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?WO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vi=(t,e)=>{for(var r in e||(e={}))ZO.call(e,r)&&ic(t,r,e[r]);if(Hh)for(var r of Hh(e))JO.call(e,r)&&ic(t,r,e[r]);return t},Kh=(t,e)=>GO(t,YO(e)),yt=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class XO extends D8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",k$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(i,n,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||U$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vi({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((c=w.params)==null?void 0:c.tag)&&((u=w.params)==null||delete u.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const D=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await D,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:i,message:n,opts:s}}),await zt(C,this.publishTimeout,I)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(l=s==null?void 0:s.internal)!=null&&l.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:u,opts:l={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=l,I=l.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:vi(Kh(vi({},u),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,l).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{request:v,opts:l,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:I,payload:u,opts:l}}),await zt(P,this.publishTimeout,D)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l==null?void 0:l.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(me.publish,vi(vi({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const n=e.attempt+1;this.queue.set(r,Kh(vi({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var QO=Object.defineProperty,eD=(t,e,r)=>e in t?QO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e,r)=>eD(t,typeof e!="symbol"?e+"":e,r);class tD{constructor(){Ei(this,"map",new Map),Ei(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Ei(this,"get",e=>this.map.get(e)||[]),Ei(this,"exists",(e,r)=>this.get(e).includes(r)),Ei(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Ei(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var rD=Object.defineProperty,iD=Object.defineProperties,nD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,sD=Object.prototype.hasOwnProperty,oD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))sD.call(e,r)&&nc(t,r,e[r]);if(Wh)for(var r of Wh(e))oD.call(e,r)&&nc(t,r,e[r]);return t},na=(t,e)=>iD(t,nD(e)),ce=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class aD extends C8{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new tD),ce(this,"events",new St.EventEmitter),ce(this,"name",H$),ce(this,"version",K$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,n);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hi.pulse,async()=>{await this.checkPending()}),this.events.on(ut.created,async i=>{const n=ut.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(ut.deleted,async i=>{const n=ut.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,this.name),this.clientId=""}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:$i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const u=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(ut.created,f),h(d.id))};this.events.on(ut.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(ut.created,f),h(d)}catch{}}),l=await zt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await zt(new Promise(n=>{this.relayer.request(i).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,r,i){const n={method:$i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,na(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(ut.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(ut.deleted,na(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ut.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(ut.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>na(rn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await j3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=M("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 bt(e+await this.getClientId())}}var cD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?cD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&sc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&sc(t,r,e[r]);return t},ne=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class hD extends A8{constructor(e){var r;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",L$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Jc({logger:(r=e.logger)!=null?r:j$,name:this.name}),this.messages=new KO(this.logger,e.core),this.subscriber=new aD(this,this.logger),this.publisher=new XO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Wg,_3()?this.packageName=Dl():I3()&&(this.bundleId=Dl()),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 st(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r==null?void 0:r.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(ut.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(ut.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await vh())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const n=i;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.connection)==null?void 0:n.socket)==null||s.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 eu(new D$(A3({sdkVersion:Qa,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Qc(e)){if(!e.method.endsWith(M$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else co(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const r=$n(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await vh();$S(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(hi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&AS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(me.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}=M("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 fD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const dD="[object RegExp]",pD="[object String]",gD="[object Number]",yD="[object Boolean]",Xh="[object Arguments]",wD="[object Symbol]",mD="[object Date]",bD="[object Map]",vD="[object Set]",ED="[object Array]",xD="[object Function]",_D="[object ArrayBuffer]",sa="[object Object]",ID="[object Error]",SD="[object DataView]",$D="[object Uint8Array]",OD="[object Uint8ClampedArray]",DD="[object Uint16Array]",AD="[object Uint32Array]",PD="[object BigUint64Array]",CD="[object Int8Array]",BD="[object Int16Array]",TD="[object Int32Array]",RD="[object BigInt64Array]",FD="[object Float32Array]",ND="[object Float64Array]";function UD(){}function Qh(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 kD(t,e,r){return ln(t,e,void 0,void 0,void 0,void 0,r)}function ln(t,e,r,i,n,s,o){const a=o(t,e,r,i,n,s);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 yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=sa),s===Xh&&(s=sa),n!==s)return!1;switch(n){case pD:return t.toString()===e.toString();case gD:{const c=t.valueOf(),u=e.valueOf();return fD(c,u)}case yD:case mD:case wD:return Object.is(t.valueOf(),e.valueOf());case dD:return t.source===e.source&&t.flags===e.flags;case xD:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case bD:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ln(u,e.get(c),c,t,e,r,i))return!1;return!0}case vD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(d=>ln(h,d,void 0,t,e,r,i));if(f===-1)return!1;u.splice(f,1)}return!0}case ED:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:case ND:{if(typeof re<"u"&&re.isBuffer(t)!==re.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!ln(t[c],e[c],c,t,e,r,i))return!1;return!0}case _D:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case SD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.name===e.name&&t.message===e.message;case sa:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],u=[...Object.keys(e),...Zh(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!ln(f,d,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function jD(t,e){return kD(t,e,UD)}var LD=Object.defineProperty,ef=Object.getOwnPropertySymbols,MD=Object.prototype.hasOwnProperty,qD=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?LD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))MD.call(e,r)&&oc(t,r,e[r]);if(ef)for(var r of ef(e))qD.call(e,r)&&oc(t,r,e[r]);return t},Ze=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class di extends P8{constructor(e,r,i,n=Kt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",z$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):iS(o)?this.map.set(o.id,o):nS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>jD(a[c],o[c]))):this.values)),Ze(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=tf(tf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(r,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zD=Object.defineProperty,VD=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>VD(t,typeof e!="symbol"?e+"":e,r);class HD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",W$),ee(this,"version",G$),ee(this,"events",new pc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[ur]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Wa(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Kg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:u}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=lh(i.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),n.addTrace(jt.existing_pairing),l.active)throw n.setError(rr.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(rr.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(rr.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c].res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=ao(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,u=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,u),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async i=>{const{topic:n,payload:s}=i,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!rS(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(rr.malformed_pairing_uri),new Error(a)}const o=lh(i==null?void 0:i.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(rr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(rr.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new di(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Qc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):co(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Tp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var KD=Object.defineProperty,WD=(t,e,r)=>e in t?KD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>WD(t,typeof e!="symbol"?e+"":e,r);class GD extends $8{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",Y$),Be(this,"version",Z$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Ct(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(hi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YD=Object.defineProperty,ZD=(t,e,r)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class JD extends B8{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",J$),ze(this,"version",X$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,this.name)}get context(){return st(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 P3(e);if(typeof e=="number")return C3(e);const{message:r}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(hi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XD=Object.defineProperty,QD=(t,e,r)=>e in t?XD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r);class eA extends T8{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",Q$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",t6),ye(this,"storagePrefix",Kt),ye(this,"version",Hg),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mi()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=ii(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Ca(C.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};u.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(u){this.logger.warn(u)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Ca(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return r6.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=DI(n,s.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=dt(r,this.name),this.abortController=new AbortController,this.isDevEnv=Lc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var tA=Object.defineProperty,rA=(t,e,r)=>e in t?tA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>rA(t,typeof e!="symbol"?e+"":e,r);class iA extends R8{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",i6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${n6}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(r,this.context)}}var nA=Object.defineProperty,nf=Object.getOwnPropertySymbols,sA=Object.prototype.hasOwnProperty,oA=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))sA.call(e,r)&&ac(t,r,e[r]);if(nf)for(var r of nf(e))oA.call(e,r)&&ac(t,r,e[r]);return t},$e=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);class aA extends F8{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",o6),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",s6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Lc())try{const n={eventId:Pl(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Cp(this.core.relayer.protocol,this.core.relayer.version,Qa)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,u=Pl(),l=this.core.projectId||"",h=Date.now(),f=nn({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>a6&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),$e(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${c6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Qa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Pp().url),this.logger=dt(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var cA=Object.defineProperty,sf=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?cA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&cc(t,r,e[r]);if(sf)for(var r of sf(e))lA.call(e,r)&&cc(t,r,e[r]);return t},ue=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);let hA=class o0 extends x8{constructor(e){var r;super(e),ue(this,"protocol",Vg),ue(this,"version",Hg),ue(this,"name",Us),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new St.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Wg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=u3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:A$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Dp({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=dt(s,this.name),this.heartbeat=new jS,this.crypto=new kO(this,this.logger,e==null?void 0:e.keychain),this.history=new GD(this,this.logger),this.expirer=new JD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new b8(of(of({},P$),e==null?void 0:e.storageOptions)),this.relayer=new hD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new HD(this,this.logger),this.verify=new eA(this,this.logger,this.storage),this.echoClient=new iA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new aA(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new o0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(V$,i),r}get context(){return st(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(Uh,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(Uh)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const fA=hA,a0="wc",c0=2,u0="client",tu=`${a0}@${c0}:${u0}:`,oa={name:u0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",dA="proposal",cf="Proposal expired",pA="session",xi=L.SEVEN_DAYS,gA="engine",Te={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}}},aa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},yA={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:""}},wA="request",mA=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],bA="wc",vA="auth",EA="authKeys",xA="pairingTopics",_A="requests",lo=`${bA}@${1.5}:${vA}:`,ws=`${lo}:PUB_KEY`;var IA=Object.defineProperty,SA=Object.defineProperties,$A=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,OA=Object.prototype.hasOwnProperty,DA=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?IA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))OA.call(e,r)&&uc(t,r,e[r]);if(uf)for(var r of uf(e))DA.call(e,r)&&uc(t,r,e[r]);return t},Re=(t,e)=>SA(t,$A(e)),k=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class AA extends j8{constructor(e){super(e),k(this,"name",gA),k(this,"events",new pc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new L3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(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(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=JI(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:h,walletPay:f}=n,d=((i=h==null?void 0:h[0])==null?void 0:i.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Kg}],proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?D(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xi)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Dt.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Dt.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xi)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),u=Rr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,we(xi)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),u=Rr().toString(),{done:l,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await l();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await F3(this.client.core.storage,af);await B3({id:c,topic:s,wcDeepLink:C})}w()}),l()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,u=this.client.session.get(o);u.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(Dt.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>eS(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=r,I=[...r.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=cr(a[0]);let S=Qx(E,"request",g);fs(I)&&(S=t_(S,I.pop())),I.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:I},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Ml({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Ua(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=ql(pe),Wt=zl(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${Ie}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&i&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ds(c),h={type:ur,receiverPublicKey:c,senderPublicKey:u},f=[],d=[];for(const w of n){if(!await Ml({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Ua(I.iss)],v=Cs(I.iss);if(C){const D=ql(C),P=zl(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Vr.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xi),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:n,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),u={type:ur,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:n,encodeOpts:u,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Zp(i,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==i.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(af).catch(u=>this.client.logger.warn(u)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===n).map(u=>this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!l;try{const C=g?Br:tt;p=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let w;if(mA.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(l,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),u?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(s.id,n),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),l=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(i,l,{encoding:tt});this.client.core.history.set(i,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=$n(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,i);const p=f.request;try{d=this.getTVFParams(i,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${i}) failed`),p}if(h){const p=rs(c,n,l);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:i}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,l,g)):this.client.core.relayer.publish(n,l,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),k(this,"sendError",async r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=ao(i,s);let l;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br:tt;l=await this.client.core.crypto.encode(n,u,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(c,n,l);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,l,p)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(rr.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const l=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});u==null||u.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(vt(i)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(xi)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),l===he.link_mode&&(i=d.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:n,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:ur,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:u,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),k(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!fS(c,!0)){const{message:u}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(n&&!_e(n)&&Ht(n)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!_e(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),k(this,"validateNamespaces",(r,i)=>{const n=hS(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=Xo(n,"approve()");if(u)throw new Error(u.message);const l=mh(c.requiredNamespaces,n,"approve()");if(l)throw new Error(l.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!pS(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:u}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Rg(i)){const{message:u}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=sS(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Xo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:u}=M("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Xo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!gS(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!mS(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!yS(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!wS(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!bS(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>cr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=cr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,u,l,h,f;return!r||i!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=r==null?void 0:r.redirect)==null?void 0:l.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Al(r,"topic")||"",n=decodeURIComponent(Al(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(Lc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Bg(r.namespaces),n=KI(r.namespaces),s=WI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const u=this.extractTxHashesFromResult(i.request,n);c.txHashes=u,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn(u,"Error getting TVF params")}return c}),k(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=yA[s];if(s==="sui_signTransaction")return[Rx(i.transactionBytes)];if(s==="near_signTransaction")return[Ul(i)];if(s==="near_signTransactions")return i.map(c=>Ul(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[US({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>kl(c)):[kl(i)];if(s==="cosmos_signDirect")return[Nx(i)];if(s==="wallet_sendCalls")return Ux(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Tx(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Qc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):co(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:r,id:i}=Tp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(be(e,!1)){const{message:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!dS(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!xS(e,aa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${aa.min} and ${aa.max}`);throw new Error(r)}}}class PA extends di{constructor(e,r){super(e,r,dA,tu),this.core=e,this.logger=r}}let CA=class extends di{constructor(e,r){super(e,r,pA,tu),this.core=e,this.logger=r}};class BA extends di{constructor(e,r){super(e,r,wA,tu,i=>i.id),this.core=e,this.logger=r}}class TA extends di{constructor(e,r){super(e,r,EA,lo,()=>ws),this.core=e,this.logger=r}}class RA extends di{constructor(e,r){super(e,r,xA,lo),this.core=e,this.logger=r}}class FA extends di{constructor(e,r){super(e,r,_A,lo,i=>i.id),this.core=e,this.logger=r}}var NA=Object.defineProperty,UA=(t,e,r)=>e in t?NA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ca=(t,e,r)=>UA(t,typeof e!="symbol"?e+"":e,r);class kA{constructor(e,r){this.core=e,this.logger=r,ca(this,"authKeys"),ca(this,"pairingTopics"),ca(this,"requests"),this.authKeys=new TA(this.core,this.logger),this.pairingTopics=new RA(this.core,this.logger),this.requests=new FA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var jA=Object.defineProperty,LA=(t,e,r)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>LA(t,typeof e!="symbol"?e+"":e,r);class ru extends k8{constructor(e){super(e),te(this,"protocol",a0),te(this,"version",c0),te(this,"name",oa.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||oa.name,this.metadata=$3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Jc({logger:(e==null?void 0:e.logger)||oa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new fA(e),this.session=new CA(this.core,this.logger),this.proposal=new PA(this.core,this.logger),this.pendingRequest=new BA(this.core,this.logger),this.engine=new AA(this),this.auth=new kA(this.core,this.logger)}static async init(e){const r=new ru(e);return await r.initialize(),r}get context(){return st(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const MA=ru;var qA=Object.defineProperty,zA=Object.defineProperties,VA=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,KA=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?qA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))HA.call(e,r)&&hf(t,r,e[r]);if(lf)for(var r of lf(e))KA.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>zA(t,VA(e));const WA={Accept:"application/json","Content-Type":"application/json"},GA="POST",pf={headers:WA,method:GA},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=lr(e),i=await(await pu(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=lr({id:1,jsonrpc:"2.0",method:"test",params:[]});await pu(e,df(ff({},pf),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=ao(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return jg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function iu(t){return t==null||typeof t!="object"&&typeof t!="function"}function h0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function f0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const YA="[object RegExp]",d0="[object String]",p0="[object Number]",g0="[object Boolean]",y0="[object Arguments]",ZA="[object Symbol]",JA="[object Date]",XA="[object Map]",QA="[object Set]",e4="[object Array]",t4="[object ArrayBuffer]",r4="[object Object]",i4="[object DataView]",n4="[object Uint8Array]",s4="[object Uint8ClampedArray]",o4="[object Uint16Array]",a4="[object Uint32Array]",c4="[object Int8Array]",u4="[object Int16Array]",l4="[object Int32Array]",h4="[object Float32Array]",f4="[object Float64Array]";function nu(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function d4(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(iu(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(nu(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&p4(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...h0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function p4(t){switch(f0(t)){case y0:case e4:case t4:case i4:case g0:case JA:case h4:case f4:case c4:case u4:case l4:case XA:case p0:case r4:case YA:case QA:case d0:case ZA:case n4:case s4:case o4:case a4:return!0;default:return!1}}function g4(t,e){return d4(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case p0:case d0:case g0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case y0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return g4(t)}function wf(t){return t!==null&&typeof t=="object"&&f0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function y4(){}function w4(t){return nu(t)}function m4(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function b4(t){if(iu(t))return t;if(Array.isArray(t)||nu(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function v4(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(iu(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return b4(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...h0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];l[d]=c[d]}c=l}else c=[];const u=r(c,a,o,t,e,i);u!=null?t[o]=u:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&m4(a)?t[o]=lc({},a,r,i):c==null&&w4(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function E4(t,...e){return v4(t,...e,y4)}const bf="error",x4="wss://relay.walletconnect.org",_4="wc",w0="universal_provider",ss=`${_4}@2:${w0}:`,m0="https://rpc.walletconnect.org/v1/",b0="generic",I4=`${m0}bundler`,Ti="call_status",S4=86400,su={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var $4=Object.defineProperty,O4=Object.defineProperties,D4=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,A4=Object.prototype.hasOwnProperty,P4=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?$4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))A4.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))P4.call(e,r)&&Ef(t,r,e[r]);return t},C4=(t,e)=>O4(t,D4(e));function v0(t,e,r){var i;const n=cr(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${m0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function B4(t){return t.includes(":")?t.split(":")[1]:t}function E0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function T4(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return E4(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const u=oo(a)?[a]:c.chains,l=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Oi(a);o[d]=C4(os(os({},o[d]),c),{chains:Vt(u,(e=o[d])==null?void 0:e.chains),methods:Vt(l,(r=o[d])==null?void 0:r.methods),events:Vt(h,(i=o[d])==null?void 0:i.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=oo(r)?[r]:i.chains?i.chains:E0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ua(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function R4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const x0={},Ri=t=>x0[t],la=(t,e)=>{x0[t]=e};var F4=Object.defineProperty,$f=Object.getOwnPropertySymbols,N4=Object.prototype.hasOwnProperty,U4=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))N4.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))U4.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",k4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],j4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ha=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>k4.includes(e)).reduce((e,r)=>(e[r]=L4(t[r]),e),{}),L4=t=>typeof t=="string"&&R4(t)?JSON.parse(t):t,M4=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(i))return;const o=Pf(i);for(const a of r){const c=j4(a);if(!c)continue;s[ha(c)]=o;const u=n==null?void 0:n[`${Af}:${c}`];if(u){const l=u==null?void 0:u[`${Af}:${c}:${e}`];s[ha(c)]=Df(Df({},s[ha(c)]),Pf(l||u))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var q4=Object.defineProperty,z4=(t,e,r)=>e in t?q4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V4=(t,e,r)=>z4(t,typeof e!="symbol"?e+"":e,r);let fa,H4=class _0{constructor(e){V4(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return fa||(fa=new _0(e)),fa}};var K4=Object.defineProperty,W4=Object.defineProperties,G4=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,Y4=Object.prototype.hasOwnProperty,Z4=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?K4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J4=(t,e)=>{for(var r in e||(e={}))Y4.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))Z4.call(e,r)&&Bf(t,r,e[r]);return t},X4=(t,e)=>W4(t,G4(e));async function Q4(t,e){const r=cr(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>eP(r.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),u=s.some(h=>(h==null?void 0:h.status)==="0x0");let l;return o?l=100:a?l=200:c?l=500:u&&(l=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:l}}async function eP(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function tP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,X4(J4({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(S4)}}))}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function iP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await rP({resultId:t,storage:e})}var nP=Object.defineProperty,sP=Object.defineProperties,oP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,aP=Object.prototype.hasOwnProperty,cP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?nP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,da=(t,e)=>{for(var r in e||(e={}))aP.call(e,r)&&hc(t,r,e[r]);if(Tf)for(var r of Tf(e))cP.call(e,r)&&hc(t,r,e[r]);return t},pa=(t,e)=>sP(t,oP(e)),Hr=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class uP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=H4.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(su.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,r){const i=r||v0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(B4(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=pa(da({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),l=((o=u==null?void 0:u.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=l==null?void 0:l[h];if(f)return f;let d;try{d=M4(u,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:pa(da({},u.sessionProperties||{}),{capabilities:pa(da({},l||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(o){const u=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(u,e)}catch(l){console.warn("Failed to fetch call status from bundler",l,u)}}const a=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(u){console.warn("Failed to fetch call status from custom bundler",u,a)}const c=await iP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await Q4(c,this.getHttpProvider.bind(this))}catch(u){console.warn("Failed to fetch call status from stored send calls",u,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${I4}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},u=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,l=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!u||!(l!=null&&l.length)||await tP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,hP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_i=(t,e,r)=>hP(t,typeof e!="symbol"?e+"":e,r);class fP{constructor(e){_i(this,"name",b0),_i(this,"client"),_i(this,"httpProviders"),_i(this,"events"),_i(this,"namespace"),_i(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(su.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return cr(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{var s,o;const a=cr(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,c)}),i}getHttpProvider(e){const r=cr(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||v0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new eu(new l0(i,Ri("disableProviderPing")))}}var dP=Object.defineProperty,pP=Object.defineProperties,gP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,yP=Object.prototype.hasOwnProperty,wP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?dP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))yP.call(e,r)&&fc(t,r,e[r]);if(Rf)for(var r of Rf(e))wP.call(e,r)&&fc(t,r,e[r]);return t},cs=(t,e)=>pP(t,gP(e)),at=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);class ou{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new pc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Jc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:w0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new ou(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:fe("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(o.namespaces);return this.namespaces=as(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!_t(r))return;for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,r;if(this.client=this.providerOpts.client||await MA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||x4,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(r=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=T4(r,this.session);if((i==null?void 0:i.length)===0)return;const n=E0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new uP({namespace:o});break;default:this.rpcProviders[r]=new fP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),u=ua(o)!==ua(a)?`${c}:${ua(a)}`:o;this.onChainChanged({currentCaipChainId:u})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(su.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[b0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(If);if(!_t(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const mP=ou,bP="wc",vP="ethereum_provider",EP=`${bP}@2:${vP}:`,xP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],I0=["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"],js=["chainChanged","accountsChanged"],S0=["chainChanged","accountsChanged","message","disconnect","connect"],_P=async()=>{const{createAppKit:t}=await F0(()=>import("./core-85d4a2c0.js").then(e=>e.ad),["assets/core-85d4a2c0.js","assets/index-6c5c6262.js","assets/index-3632219d.css"]);return t};var IP=Object.defineProperty,SP=Object.defineProperties,$P=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,OP=Object.prototype.hasOwnProperty,DP=Object.prototype.propertyIsEnumerable,dc=(t,e,r)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))OP.call(e,r)&&dc(t,r,e[r]);if(Ff)for(var r of Ff(e))DP.call(e,r)&&dc(t,r,e[r]);return t},on=(t,e)=>SP(t,$P(e)),ct=(t,e,r)=>dc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function us(t){return`0x${t.toString(16)}`}function AP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},u=s==null?void 0:s.filter(d=>!js.includes(d)),l=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!o&&!n&&!(u!=null&&u.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const h=(u==null?void 0:u.length)&&(l==null?void 0:l.length)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:I0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:S0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class ho{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",EP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new ho;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=AP(this.rpc);try{const s=await new Promise(async(a,c)=>{var u,l;this.rpc.showQrModal&&((u=this.modal)==null||u.open(),(l=this.modal)==null||l.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(on(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,u;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(u=this.modal)==null||u.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wr({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),s=n.session;if(s){const o=Il(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:us(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",us(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",on(Wr({},fe("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",us(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],u=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:u,optionalEvents:l,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await mP.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 n=await _P(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return LP}),o=s(on(Wr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${xP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const PP=ho;var CP=Object.defineProperty,BP=Object.defineProperties,TP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,RP=Object.prototype.hasOwnProperty,FP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?CP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$0=(t,e)=>{for(var r in e||(e={}))RP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))FP.call(e,r)&&Uf(t,r,e[r]);return t},NP=(t,e)=>BP(t,TP(e));function UP(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 kP=t=>{const[e,r]=t.split(":");return O0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function jP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(kP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const u=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:UP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:u,metadata:NP($0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(l.customWallets=d)}return l}function O0(t){return $0({formatters:void 0,fees:void 0,serializers:void 0},t)}var LP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:jP,defineChain:O0});const P5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:PP,OPTIONAL_EVENTS:S0,OPTIONAL_METHODS:I0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:ho},Symbol.toStringTag,{value:"Module"}));export{D$ as A,Qc as B,dE as C,u3 as D,co as E,$n as F,hi as G,Ct as H,li as I,y2 as J,Rr as K,ao as L,Mt as M,vt as N,Lt as O,pl as P,sp as Q,l0 as R,P5 as S,dt as X,Dp as Y,n8 as a,s8 as b,Ng as c,is as d,o8 as e,si as f,Ih as g,qf as h,L as i,Et as j,c8 as k,ii as l,gc as m,An as n,_1 as o,p1 as p,SE as q,V0 as r,lr as s,nt as t,Mf as u,fn as v,Ca as w,st as x,jS as y,eu as z};