@dcl-regenesislabs/mobile-hub 1.0.0-20717816491.commit-17f8927 → 1.0.0-20717992871.commit-9714473
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{basic-D4vJRBfa.js → basic-CmGH1qe7.js} +1 -1
- package/assets/{core-Ds-5UYKM.js → core-rAd4NtOZ.js} +4 -4
- package/assets/{features-BgzVlStz.js → features-Ck8kzp6S.js} +1 -1
- package/assets/{fortmatic-B79B8GDv.js → fortmatic-Cxq1Pqgt.js} +1 -1
- package/assets/{index-RgK09Bbj.js → index-Bg43zjvj.js} +1 -1
- package/assets/index-D4KucuwH.js +23 -0
- package/assets/{index-CcElmyXG.js → index-DV4XZBk2.js} +1 -1
- package/assets/{index-B88UDh6R.js → index-DY0nRecQ.js} +1 -1
- package/assets/{index-Cf-uY5dQ.js → index-Df9PG87w.js} +3 -3
- package/assets/{w3m-modal-xfuWMvke.js → w3m-modal-CODOfQ7e.js} +1 -1
- package/index.html +3 -3
- package/package.json +3 -3
- package/assets/index-CEmkvSJ-.js +0 -23
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-
|
|
2
|
-
import{g as Of,e as wt,c as Ut,x as ec,a as ay,_ as cy}from"./index-CEmkvSJ-.js";var Zc=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},ly=(function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t})(),uy=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t})(),hy=(function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t})(),fy=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})(),dy=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})(),py=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,gy=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Jc=3,yy=[["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",py]],Xc=[["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 wy(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new dy:typeof navigator<"u"?by(navigator.userAgent):Ey()}function my(t){return t!==""&&yy.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function by(t){var e=my(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new fy;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<Jc&&(s=Zc(Zc([],s,!0),xy(Jc-s.length),!0)):s=[];var n=s.join("."),o=vy(t),a=gy.exec(t);return a&&a[1]?new hy(r,n,o,a[1]):new ly(r,n,o)}function vy(t){for(var e=0,r=Xc.length;e<r;e++){var i=Xc[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function Ey(){var t=typeof process<"u"&&process.version;return t?new uy(process.version.slice(1)):null}function xy(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var Wn={};var ea=function(t,e){return ea=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},ea(t,e)};function _y(t,e){ea(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ta=function(){return ta=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ta.apply(this,arguments)};function Iy(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function Sy(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function Oy(t,e){return function(r,i){e(r,i,t)}}function Dy(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function $y(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function Ay(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Py(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function By(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ra(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 Df(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function Cy(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Df(arguments[e]));return t}function Ty(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function es(t){return this instanceof es?(this.v=t,this):new es(t)}function Ry(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(p){return new Promise(function(d,y){n.push([f,p,d,y])>1||a(f,p)})})}function a(f,p){try{c(i[f](p))}catch(d){h(n[0][3],d)}}function c(f){f.value instanceof es?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function Uy(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:es(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function Ny(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 ra=="function"?ra(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function ky(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function jy(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 Fy(t){return t&&t.__esModule?t:{default:t}}function Ly(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function My(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 qy=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ta},__asyncDelegator:Uy,__asyncGenerator:Ry,__asyncValues:Ny,__await:es,__awaiter:$y,__classPrivateFieldGet:Ly,__classPrivateFieldSet:My,__createBinding:Py,__decorate:Sy,__exportStar:By,__extends:_y,__generator:Ay,__importDefault:Fy,__importStar:jy,__makeTemplateObject:ky,__metadata:Dy,__param:Oy,__read:Df,__rest:Iy,__spread:Cy,__spreadArrays:Ty,__values:ra},Symbol.toStringTag,{value:"Module"})),xn=Of(qy);var Gn={},Ai={},Qc;function zy(){if(Qc)return Ai;Qc=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Ai.delay=t,Ai}var Pr={},Yn={},Br={},el;function Vy(){return el||(el=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.ONE_THOUSAND=Br.ONE_HUNDRED=void 0,Br.ONE_HUNDRED=100,Br.ONE_THOUSAND=1e3),Br}var Zn={},tl;function Hy(){return tl||(tl=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})(Zn)),Zn}var rl;function $f(){return rl||(rl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(Vy(),t),e.__exportStar(Hy(),t)})(Yn)),Yn}var il;function Ky(){if(il)return Pr;il=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.fromMiliseconds=Pr.toMiliseconds=void 0;const t=$f();function e(i){return i*t.ONE_THOUSAND}Pr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Pr.fromMiliseconds=r,Pr}var sl;function Wy(){return sl||(sl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(zy(),t),e.__exportStar(Ky(),t)})(Gn)),Gn}var ii={},nl;function Gy(){if(nl)return ii;nl=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return ii.Watch=t,ii.default=t,ii}var Jn={},Pi={},ol;function Yy(){if(ol)return Pi;ol=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.IWatch=void 0;class t{}return Pi.IWatch=t,Pi}var al;function Zy(){return al||(al=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),xn.__exportStar(Yy(),t)})(Jn)),Jn}var cl;function Jy(){return cl||(cl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(Wy(),t),e.__exportStar(Gy(),t),e.__exportStar(Zy(),t),e.__exportStar($f(),t)})(Wn)),Wn}var q=Jy(),se={},ll;function Af(){if(ll)return se;ll=1,Object.defineProperty(se,"__esModule",{value:!0}),se.getLocalStorage=se.getLocalStorageOrThrow=se.getCrypto=se.getCryptoOrThrow=se.getLocation=se.getLocationOrThrow=se.getNavigator=se.getNavigatorOrThrow=se.getDocument=se.getDocumentOrThrow=se.getFromWindowOrThrow=se.getFromWindow=void 0;function t(f){let p;return typeof window<"u"&&typeof window[f]<"u"&&(p=window[f]),p}se.getFromWindow=t;function e(f){const p=t(f);if(!p)throw new Error(`${f} is not defined in Window`);return p}se.getFromWindowOrThrow=e;function r(){return e("document")}se.getDocumentOrThrow=r;function i(){return t("document")}se.getDocument=i;function s(){return e("navigator")}se.getNavigatorOrThrow=s;function n(){return t("navigator")}se.getNavigator=n;function o(){return e("location")}se.getLocationOrThrow=o;function a(){return t("location")}se.getLocation=a;function c(){return e("crypto")}se.getCryptoOrThrow=c;function l(){return t("crypto")}se.getCrypto=l;function u(){return e("localStorage")}se.getLocalStorageOrThrow=u;function h(){return t("localStorage")}return se.getLocalStorage=h,se}var nr=Af(),Bi={},ul;function Xy(){if(ul)return Bi;ul=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.getWindowMetadata=void 0;const t=Af();function e(){let r,i;try{r=t.getDocumentOrThrow(),i=t.getLocationOrThrow()}catch{return null}function s(){const p=r.getElementsByTagName("link"),d=[];for(let y=0;y<p.length;y++){const m=p[y],v=m.getAttribute("rel");if(v&&v.toLowerCase().indexOf("icon")>-1){const I=m.getAttribute("href");if(I)if(I.toLowerCase().indexOf("https:")===-1&&I.toLowerCase().indexOf("http:")===-1&&I.indexOf("//")!==0){let b=i.protocol+"//"+i.host;if(I.indexOf("/")===0)b+=I;else{const E=i.pathname.split("/");E.pop();const $=E.join("/");b+=$+"/"+I}d.push(b)}else if(I.indexOf("//")===0){const b=i.protocol+I;d.push(b)}else d.push(I)}}return d}function n(...p){const d=r.getElementsByTagName("meta");for(let y=0;y<d.length;y++){const m=d[y],v=["itemprop","property","name"].map(I=>m.getAttribute(I)).filter(I=>I?p.includes(I):!1);if(v.length&&v){const I=m.getAttribute("content");if(I)return I}}return""}function o(){let p=n("name","og:site_name","og:title","twitter:title");return p||(p=r.title),p}function a(){return n("description","og:description","twitter:description","keywords")}const c=o(),l=a(),u=i.origin,h=s();return{description:l,url:u,icons:h,name:c}}return Bi.getWindowMetadata=e,Bi}var Qy=Xy();const e0="0.1.1";function t0(){return e0}class le extends Error{constructor(e,r={}){const i=(()=>{if(r.cause instanceof le){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:r.cause?.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-rAd4NtOZ.js","assets/index-D4KucuwH.js","assets/index-CcyN_bjy.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{g as Of,e as wt,c as Ut,x as ec,a as ay,_ as cy}from"./index-D4KucuwH.js";var Zc=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},ly=(function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t})(),uy=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t})(),hy=(function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t})(),fy=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})(),dy=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})(),py=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,gy=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Jc=3,yy=[["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",py]],Xc=[["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 wy(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new dy:typeof navigator<"u"?by(navigator.userAgent):Ey()}function my(t){return t!==""&&yy.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function by(t){var e=my(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new fy;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<Jc&&(s=Zc(Zc([],s,!0),xy(Jc-s.length),!0)):s=[];var n=s.join("."),o=vy(t),a=gy.exec(t);return a&&a[1]?new hy(r,n,o,a[1]):new ly(r,n,o)}function vy(t){for(var e=0,r=Xc.length;e<r;e++){var i=Xc[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function Ey(){var t=typeof process<"u"&&process.version;return t?new uy(process.version.slice(1)):null}function xy(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var Wn={};var ea=function(t,e){return ea=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},ea(t,e)};function _y(t,e){ea(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ta=function(){return ta=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ta.apply(this,arguments)};function Iy(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function Sy(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function Oy(t,e){return function(r,i){e(r,i,t)}}function Dy(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function $y(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function Ay(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Py(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function By(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ra(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 Df(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function Cy(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Df(arguments[e]));return t}function Ty(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function es(t){return this instanceof es?(this.v=t,this):new es(t)}function Ry(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(p){return new Promise(function(d,y){n.push([f,p,d,y])>1||a(f,p)})})}function a(f,p){try{c(i[f](p))}catch(d){h(n[0][3],d)}}function c(f){f.value instanceof es?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function Uy(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:es(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function Ny(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 ra=="function"?ra(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function ky(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function jy(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 Fy(t){return t&&t.__esModule?t:{default:t}}function Ly(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function My(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 qy=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ta},__asyncDelegator:Uy,__asyncGenerator:Ry,__asyncValues:Ny,__await:es,__awaiter:$y,__classPrivateFieldGet:Ly,__classPrivateFieldSet:My,__createBinding:Py,__decorate:Sy,__exportStar:By,__extends:_y,__generator:Ay,__importDefault:Fy,__importStar:jy,__makeTemplateObject:ky,__metadata:Dy,__param:Oy,__read:Df,__rest:Iy,__spread:Cy,__spreadArrays:Ty,__values:ra},Symbol.toStringTag,{value:"Module"})),xn=Of(qy);var Gn={},Ai={},Qc;function zy(){if(Qc)return Ai;Qc=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Ai.delay=t,Ai}var Pr={},Yn={},Br={},el;function Vy(){return el||(el=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.ONE_THOUSAND=Br.ONE_HUNDRED=void 0,Br.ONE_HUNDRED=100,Br.ONE_THOUSAND=1e3),Br}var Zn={},tl;function Hy(){return tl||(tl=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})(Zn)),Zn}var rl;function $f(){return rl||(rl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(Vy(),t),e.__exportStar(Hy(),t)})(Yn)),Yn}var il;function Ky(){if(il)return Pr;il=1,Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.fromMiliseconds=Pr.toMiliseconds=void 0;const t=$f();function e(i){return i*t.ONE_THOUSAND}Pr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Pr.fromMiliseconds=r,Pr}var sl;function Wy(){return sl||(sl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(zy(),t),e.__exportStar(Ky(),t)})(Gn)),Gn}var ii={},nl;function Gy(){if(nl)return ii;nl=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return ii.Watch=t,ii.default=t,ii}var Jn={},Pi={},ol;function Yy(){if(ol)return Pi;ol=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.IWatch=void 0;class t{}return Pi.IWatch=t,Pi}var al;function Zy(){return al||(al=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),xn.__exportStar(Yy(),t)})(Jn)),Jn}var cl;function Jy(){return cl||(cl=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=xn;e.__exportStar(Wy(),t),e.__exportStar(Gy(),t),e.__exportStar(Zy(),t),e.__exportStar($f(),t)})(Wn)),Wn}var q=Jy(),se={},ll;function Af(){if(ll)return se;ll=1,Object.defineProperty(se,"__esModule",{value:!0}),se.getLocalStorage=se.getLocalStorageOrThrow=se.getCrypto=se.getCryptoOrThrow=se.getLocation=se.getLocationOrThrow=se.getNavigator=se.getNavigatorOrThrow=se.getDocument=se.getDocumentOrThrow=se.getFromWindowOrThrow=se.getFromWindow=void 0;function t(f){let p;return typeof window<"u"&&typeof window[f]<"u"&&(p=window[f]),p}se.getFromWindow=t;function e(f){const p=t(f);if(!p)throw new Error(`${f} is not defined in Window`);return p}se.getFromWindowOrThrow=e;function r(){return e("document")}se.getDocumentOrThrow=r;function i(){return t("document")}se.getDocument=i;function s(){return e("navigator")}se.getNavigatorOrThrow=s;function n(){return t("navigator")}se.getNavigator=n;function o(){return e("location")}se.getLocationOrThrow=o;function a(){return t("location")}se.getLocation=a;function c(){return e("crypto")}se.getCryptoOrThrow=c;function l(){return t("crypto")}se.getCrypto=l;function u(){return e("localStorage")}se.getLocalStorageOrThrow=u;function h(){return t("localStorage")}return se.getLocalStorage=h,se}var nr=Af(),Bi={},ul;function Xy(){if(ul)return Bi;ul=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.getWindowMetadata=void 0;const t=Af();function e(){let r,i;try{r=t.getDocumentOrThrow(),i=t.getLocationOrThrow()}catch{return null}function s(){const p=r.getElementsByTagName("link"),d=[];for(let y=0;y<p.length;y++){const m=p[y],v=m.getAttribute("rel");if(v&&v.toLowerCase().indexOf("icon")>-1){const I=m.getAttribute("href");if(I)if(I.toLowerCase().indexOf("https:")===-1&&I.toLowerCase().indexOf("http:")===-1&&I.indexOf("//")!==0){let b=i.protocol+"//"+i.host;if(I.indexOf("/")===0)b+=I;else{const E=i.pathname.split("/");E.pop();const $=E.join("/");b+=$+"/"+I}d.push(b)}else if(I.indexOf("//")===0){const b=i.protocol+I;d.push(b)}else d.push(I)}}return d}function n(...p){const d=r.getElementsByTagName("meta");for(let y=0;y<d.length;y++){const m=d[y],v=["itemprop","property","name"].map(I=>m.getAttribute(I)).filter(I=>I?p.includes(I):!1);if(v.length&&v){const I=m.getAttribute("content");if(I)return I}}return""}function o(){let p=n("name","og:site_name","og:title","twitter:title");return p||(p=r.title),p}function a(){return n("description","og:description","twitter:description","keywords")}const c=o(),l=a(),u=i.origin,h=s();return{description:l,url:u,icons:h,name:c}}return Bi.getWindowMetadata=e,Bi}var Qy=Xy();const e0="0.1.1";function t0(){return e0}class le extends Error{constructor(e,r={}){const i=(()=>{if(r.cause instanceof le){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:r.cause?.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
3
3
|
`);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@${t0()}`}),this.cause=r.cause,this.details=i,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return Pf(this,e)}}function Pf(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Pf(t.cause,e):e?null:t}const si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function r0(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ts(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Wr(t,...e){if(!r0(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 i0(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ts(t.outputLen),ts(t.blockLen)}function xi(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 Bf(t,e){Wr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function s0(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function _i(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Xn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Dt(t,e){return t<<32-e|t>>>e}const n0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function a0(t){for(let e=0;e<t.length;e++)t[e]=o0(t[e]);return t}const hl=n0?t=>t:a0;function c0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function _n(t){return typeof t=="string"&&(t=c0(t)),Wr(t),t}function l0(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Wr(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class tc{}function Cf(t){const e=i=>t().update(_n(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function u0(t=32){if(si&&typeof si.getRandomValues=="function")return si.getRandomValues(new Uint8Array(t));if(si&&typeof si.randomBytes=="function")return Uint8Array.from(si.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function h0(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function f0(t,e,r){return t&e^~t&r}function d0(t,e,r){return t&e^t&r^e&r}class p0 extends tc{constructor(e,r,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Xn(this.buffer)}update(e){xi(this),e=_n(e),Wr(e);const{view:r,buffer:i,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Xn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){xi(this),Bf(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,_i(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;h0(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Xn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const ar=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_s=BigInt(2**32-1),fl=BigInt(32);function g0(t,e=!1){return e?{h:Number(t&_s),l:Number(t>>fl&_s)}:{h:Number(t>>fl&_s)|0,l:Number(t&_s)|0}}function y0(t,e=!1){const r=t.length;let i=new Uint32Array(r),s=new Uint32Array(r);for(let n=0;n<r;n++){const{h:o,l:a}=g0(t[n],e);[i[n],s[n]]=[o,a]}return[i,s]}const w0=(t,e,r)=>t<<r|e>>>32-r,m0=(t,e,r)=>e<<r|t>>>32-r,b0=(t,e,r)=>e<<r-32|t>>>64-r,v0=(t,e,r)=>t<<r-32|e>>>64-r,E0=BigInt(0),Ci=BigInt(1),x0=BigInt(2),_0=BigInt(7),I0=BigInt(256),S0=BigInt(113),Tf=[],Rf=[],Uf=[];for(let t=0,e=Ci,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Tf.push(2*(5*i+r)),Rf.push((t+1)*(t+2)/2%64);let s=E0;for(let n=0;n<7;n++)e=(e<<Ci^(e>>_0)*S0)%I0,e&x0&&(s^=Ci<<(Ci<<BigInt(n))-Ci);Uf.push(s)}const Nf=y0(Uf,!0),O0=Nf[0],D0=Nf[1],dl=(t,e,r)=>r>32?b0(t,e,r):w0(t,e,r),pl=(t,e,r)=>r>32?v0(t,e,r):m0(t,e,r);function $0(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=dl(l,u,1)^r[a],f=pl(l,u,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Rf[o],c=dl(s,n,a),l=pl(s,n,a),u=Tf[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=O0[i],t[1]^=D0[i]}_i(r)}class rc extends tc{constructor(e,r,i,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,ts(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=s0(this.state)}clone(){return this._cloneInto()}keccak(){hl(this.state32),$0(this.state32,this.rounds),hl(this.state32),this.posOut=0,this.pos=0}update(e){xi(this),e=_n(e),Wr(e);const{blockLen:r,state:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,(r&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){xi(this,!1),Wr(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ts(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Bf(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,_i(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new rc(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const A0=(t,e,r)=>Cf(()=>new rc(e,t,r)),P0=A0(1,136,256/8),B0=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]),cr=new Uint32Array(64);class C0 extends p0{constructor(e=32){super(64,e,8,!1),this.A=ar[0]|0,this.B=ar[1]|0,this.C=ar[2]|0,this.D=ar[3]|0,this.E=ar[4]|0,this.F=ar[5]|0,this.G=ar[6]|0,this.H=ar[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)cr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=cr[h-15],p=cr[h-2],d=Dt(f,7)^Dt(f,18)^f>>>3,y=Dt(p,17)^Dt(p,19)^p>>>10;cr[h]=y+cr[h-7]+d+cr[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=Dt(a,6)^Dt(a,11)^Dt(a,25),p=u+f+f0(a,c,l)+B0[h]+cr[h]|0,y=(Dt(i,2)^Dt(i,13)^Dt(i,22))+d0(i,s,n)|0;u=l,l=c,c=a,a=o+p|0,o=n,n=s,s=i,i=p+y|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,s,n,o,a,c,l,u)}roundClean(){_i(cr)}destroy(){this.set(0,0,0,0,0,0,0,0),_i(this.buffer)}}const T0=Cf(()=>new C0);const ic=BigInt(0),ia=BigInt(1);function us(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sc(t){if(!us(t))throw new Error("Uint8Array expected")}function rs(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Is(t){const e=t.toString(16);return e.length&1?"0"+e:e}function kf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ic:BigInt("0x"+t)}const jf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",R0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function is(t){if(sc(t),jf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=R0[t[r]];return e}const qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function gl(t){if(t>=qt._0&&t<=qt._9)return t-qt._0;if(t>=qt.A&&t<=qt.F)return t-(qt.A-10);if(t>=qt.a&&t<=qt.f)return t-(qt.a-10)}function Qs(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 s=0,n=0;s<r;s++,n+=2){const o=gl(t.charCodeAt(n)),a=gl(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function Kr(t){return kf(is(t))}function Ff(t){return sc(t),kf(is(Uint8Array.from(t).reverse()))}function hs(t,e){return Qs(t.toString(16).padStart(e*2,"0"))}function Lf(t,e){return hs(t,e).reverse()}function ht(t,e,r){let i;if(typeof e=="string")try{i=Qs(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(us(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function en(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];sc(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const Qn=t=>typeof t=="bigint"&&ic<=t;function nc(t,e,r){return Qn(t)&&Qn(e)&&Qn(r)&&e<=t&&t<r}function yi(t,e,r,i){if(!nc(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function U0(t){let e;for(e=0;t>ic;t>>=ia,e+=1);return e}const In=t=>(ia<<BigInt(t))-ia,eo=t=>new Uint8Array(t),yl=t=>Uint8Array.from(t);function N0(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=eo(t),s=eo(t),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...h)=>r(s,i,...h),c=(h=eo(0))=>{s=a(yl([0]),h),i=a(),h.length!==0&&(s=a(yl([1]),h),i=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){i=a();const p=i.slice();f.push(p),h+=i.length}return en(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(l()));)c();return o(),p}}const k0={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"||us(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 Sn(t,e,r={}){const i=(s,n,o)=>{const a=k0[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function wl(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}function j0(t,e){if(El(t)>e)throw new nw({givenSize:El(t),maxSize:e})}const zt={zero:48,nine:57,A:65,F:70,a:97,f:102};function ml(t){if(t>=zt.zero&&t<=zt.nine)return t-zt.zero;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 F0(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;if(t.length>i)throw new ow({size:t.length,targetSize:i,type:"Bytes"});const s=new Uint8Array(i);for(let n=0;n<i;n++){const o=r==="right";s[o?n:i-n-1]=t[o?n:t.length-n-1]}return s}function Mf(t,e){if(Or(t)>e)throw new Y0({givenSize:Or(t),maxSize:e})}function L0(t,e){if(typeof e=="number"&&e>0&&e>Or(t)-1)throw new Vf({offset:e,position:"start",size:Or(t)})}function M0(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Or(t)!==r-e)throw new Vf({offset:r,position:"end",size:Or(t)})}function qf(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;const s=t.replace("0x","");if(s.length>i*2)throw new Z0({size:Math.ceil(s.length/2),targetSize:i,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](i*2,"0")}`}const q0="#__bigint";function oc(t,e,r){return JSON.stringify(t,(i,s)=>typeof s=="bigint"?s.toString()+q0:s,r)}const z0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function V0(t,e={}){const{strict:r=!1}=e;if(!t)throw new bl(t);if(typeof t!="string")throw new bl(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new vl(t);if(!t.startsWith("0x"))throw new vl(t)}function H0(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function ac(t){return t instanceof Uint8Array?tn(t):Array.isArray(t)?tn(new Uint8Array(t)):t}function tn(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=z0[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(Mf(i,e.size),zf(i,e.size)):i}function to(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const l=typeof t=="bigint"?"n":"";throw new G0({max:n?`${n}${l}`:void 0,min:`${o}${l}`,signed:r,size:i,value:`${t}${l}`})}const c=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?K0(c,i):c}function K0(t,e){return qf(t,{dir:"left",size:e})}function zf(t,e){return qf(t,{dir:"right",size:e})}function Jt(t,e,r,i={}){const{strict:s}=i;L0(t,e);const n=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&M0(n,e,r),n}function Or(t){return Math.ceil((t.length-2)/2)}function W0(t,e={}){const{strict:r=!1}=e;try{return V0(t,{strict:r}),!0}catch{return!1}}class G0 extends le{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number \`${n}\` is not in safe${s?` ${s*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class bl extends le{constructor(e){super(`Value \`${typeof e=="object"?oc(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 vl extends le{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 Y0=class extends le{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 Vf extends le{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 Z0=class extends le{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 J0=new TextEncoder;function X0(t){if(!(t instanceof Uint8Array)){if(!t)throw new Ss(t);if(typeof t!="object")throw new Ss(t);if(!("BYTES_PER_ELEMENT"in t))throw new Ss(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Ss(t)}}function Q0(t){return t instanceof Uint8Array?t:typeof t=="string"?tw(t):ew(t)}function ew(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function tw(t,e={}){const{size:r}=e;let i=t;r&&(Mf(t,r),i=zf(t,r));let s=i.slice(2);s.length%2&&(s=`0${s}`);const n=s.length/2,o=new Uint8Array(n);for(let a=0,c=0;a<n;a++){const l=ml(s.charCodeAt(c++)),u=ml(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new le(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function rw(t,e={}){const{size:r}=e,i=J0.encode(t);return typeof r=="number"?(j0(i,r),iw(i,r)):i}function iw(t,e){return F0(t,{dir:"right",size:e})}function El(t){return t.length}function sw(t){try{return X0(t),!0}catch{return!1}}class Ss extends le{constructor(e){super(`Value \`${typeof e=="object"?oc(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 nw extends le{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 ow extends le{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 Hf(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,i=P0(Q0(t));return r==="Bytes"?i:tn(i)}class aw 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 cw={checksum:new aw(8192)},ro=cw.checksum;function Kf(t,e={}){const{compressed:r}=e,{prefix:i,x:s,y:n}=t;if(r===!1||typeof s=="bigint"&&typeof n=="bigint"){if(i!==4)throw new xl({prefix:i,cause:new pw});return}if(r===!0||typeof s=="bigint"&&typeof n>"u"){if(i!==3&&i!==2)throw new xl({prefix:i,cause:new dw});return}throw new fw({publicKey:t})}function lw(t){const e=(()=>{if(W0(t))return Wf(t);if(sw(t))return uw(t);const{prefix:r,x:i,y:s}=t;return typeof i=="bigint"&&typeof s=="bigint"?{prefix:r??4,x:i,y:s}:{prefix:r,x:i}})();return Kf(e),e}function uw(t){return Wf(tn(t))}function Wf(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new gw({publicKey:t});if(t.length===130){const i=BigInt(Jt(t,0,32)),s=BigInt(Jt(t,32,64));return{prefix:4,x:i,y:s}}if(t.length===132){const i=Number(Jt(t,0,1)),s=BigInt(Jt(t,1,33)),n=BigInt(Jt(t,33,65));return{prefix:i,x:s,y:n}}const e=Number(Jt(t,0,1)),r=BigInt(Jt(t,1,33));return{prefix:e,x:r}}function hw(t,e={}){Kf(t);const{prefix:r,x:i,y:s}=t,{includePrefix:n=!0}=e;return H0(n?to(r,{size:1}):"0x",to(i,{size:32}),typeof s=="bigint"?to(s,{size:32}):"0x")}class fw extends le{constructor({publicKey:e}){super(`Value \`${oc(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 xl extends le{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 dw extends le{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 pw extends le{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let gw=class extends le{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 ${Or(ac(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const yw=/^0x[a-fA-F0-9]{40}$/;function Gf(t,e={}){const{strict:r=!0}=e;if(!yw.test(t))throw new _l({address:t,cause:new bw});if(r){if(t.toLowerCase()===t)return;if(Yf(t)!==t)throw new _l({address:t,cause:new vw})}}function Yf(t){if(ro.has(t))return ro.get(t);Gf(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Hf(rw(e),{as:"Bytes"}),i=e.split("");for(let n=0;n<40;n+=2)r[n>>1]>>4>=8&&i[n]&&(i[n]=i[n].toUpperCase()),(r[n>>1]&15)>=8&&i[n+1]&&(i[n+1]=i[n+1].toUpperCase());const s=`0x${i.join("")}`;return ro.set(t,s),s}function ww(t,e={}){const{checksum:r=!1}=e;return Gf(t),r?Yf(t):t}function mw(t,e={}){const r=Hf(`0x${hw(t).slice(4)}`).substring(26);return ww(`0x${r}`,e)}class _l extends le{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 bw extends le{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 vw extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class Zf extends tc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,i0(e);const i=_n(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),_i(n)}update(e){return xi(this),this.iHash.update(e),this}digestInto(e){xi(this),Wr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Jf=(t,e,r)=>new Zf(t,e).update(r).digest();Jf.create=(t,e)=>new Zf(t,e);const Ye=BigInt(0),Fe=BigInt(1),Mr=BigInt(2),Ew=BigInt(3),Xf=BigInt(4),Qf=BigInt(5),ed=BigInt(8);function Ke(t,e){const r=t%e;return r>=Ye?r:e+r}function at(t,e,r){let i=t;for(;e-- >Ye;)i*=i,i%=r;return i}function sa(t,e){if(t===Ye)throw new Error("invert: expected non-zero number");if(e<=Ye)throw new Error("invert: expected positive modulus, got "+e);let r=Ke(t,e),i=e,s=Ye,n=Fe;for(;r!==Ye;){const a=i/r,c=i%r,l=s-n*a;i=r,r=c,s=n,n=l}if(i!==Fe)throw new Error("invert: does not exist");return Ke(s,e)}function td(t,e){const r=(t.ORDER+Fe)/Xf,i=t.pow(e,r);if(!t.eql(t.sqr(i),e))throw new Error("Cannot find square root");return i}function xw(t,e){const r=(t.ORDER-Qf)/ed,i=t.mul(e,Mr),s=t.pow(i,r),n=t.mul(e,s),o=t.mul(t.mul(n,Mr),s),a=t.mul(n,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function _w(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Fe,r=0;for(;e%Mr===Ye;)e/=Mr,r++;let i=Mr;const s=cc(t);for(;Il(s,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return td;let n=s.pow(i,e);const o=(e+Fe)/Mr;return function(c,l){if(c.is0(l))return l;if(Il(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,n),f=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,y=c.sqr(f);for(;!c.eql(y,c.ONE);)if(d++,y=c.sqr(y),d===u)throw new Error("Cannot find square root");const m=Fe<<BigInt(u-d-1),v=c.pow(h,m);u=d,h=c.sqr(v),f=c.mul(f,h),p=c.mul(p,v)}return p}}function Iw(t){return t%Xf===Ew?td:t%ed===Qf?xw:_w(t)}const Sw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ow(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Sw.reduce((i,s)=>(i[s]="function",i),e);return Sn(t,r)}function Dw(t,e,r){if(r<Ye)throw new Error("invalid exponent, negatives unsupported");if(r===Ye)return t.ONE;if(r===Fe)return e;let i=t.ONE,s=e;for(;r>Ye;)r&Fe&&(i=t.mul(i,s)),s=t.sqr(s),r>>=Fe;return i}function rd(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),n),i}function Il(t,e){const r=(t.ORDER-Fe)/Mr,i=t.pow(e,r),s=t.eql(i,t.ONE),n=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function id(t,e){e!==void 0&&ts(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function cc(t,e,r=!1,i={}){if(t<=Ye)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=id(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:In(s),ZERO:Ye,ONE:Fe,create:c=>Ke(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ye<=c&&c<t},is0:c=>c===Ye,isOdd:c=>(c&Fe)===Fe,neg:c=>Ke(-c,t),eql:(c,l)=>c===l,sqr:c=>Ke(c*c,t),add:(c,l)=>Ke(c+l,t),sub:(c,l)=>Ke(c-l,t),mul:(c,l)=>Ke(c*l,t),pow:(c,l)=>Dw(a,c,l),div:(c,l)=>Ke(c*sa(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>sa(c,t),sqrt:i.sqrt||(c=>(o||(o=Iw(t)),o(a,c))),toBytes:c=>r?Lf(c,n):hs(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?Ff(c):Kr(c)},invertBatch:c=>rd(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function sd(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 nd(t){const e=sd(t);return e+Math.ceil(e/2)}function $w(t,e,r=!1){const i=t.length,s=sd(e),n=nd(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?Ff(t):Kr(t),a=Ke(o,e-Fe)+Fe;return r?Lf(a,s):hs(a,s)}const Sl=BigInt(0),na=BigInt(1);function io(t,e){const r=e.negate();return t?r:e}function od(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function so(t,e){od(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),s=2**t,n=In(t),o=BigInt(t);return{windows:r,windowSize:i,mask:n,maxNumber:s,shiftBy:o}}function Ol(t,e,r){const{windowSize:i,mask:s,maxNumber:n,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>i&&(a-=n,c+=na);const l=e*i,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}function Aw(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 Pw(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,ad=new WeakMap;function oo(t){return ad.get(t)||1}function Bw(t,e){return{constTimeNegate:io,hasPrecomputes(r){return oo(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Sl;)i&na&&(s=s.add(n)),n=n.double(),i>>=na;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=so(i,e),o=[];let a=r,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){let n=t.ZERO,o=t.BASE;const a=so(r,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:d}=Ol(s,c,a);s=l,h?o=o.add(io(p,i[d])):n=n.add(io(f,i[u]))}return{p:n,f:o}},wNAFUnsafe(r,i,s,n=t.ZERO){const o=so(r,e);for(let a=0;a<o.windows&&s!==Sl;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=Ol(s,a,o);if(s=c,!u){const f=i[l];n=n.add(h?f.negate():f)}}return n},getPrecomputes(r,i,s){let n=no.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&no.set(i,s(n))),n},wNAFCached(r,i,s){const n=oo(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=oo(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){od(i,e),ad.set(r,i),no.delete(r)}}}function Cw(t,e,r,i){Aw(r,t),Pw(i,e);const s=r.length,n=i.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=U0(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=In(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){u.fill(o);for(let y=0;y<n;y++){const m=i[y],v=Number(m>>BigInt(p)&l);u[v]=u[v].add(r[y])}let d=o;for(let y=u.length-1,m=o;y>0;y--)m=m.add(u[y]),d=d.add(m);if(f=f.add(d),p!==0)for(let y=0;y<c;y++)f=f.double()}return f}function cd(t){return Ow(t.Fp),Sn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...id(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Dl(t){t.lowS!==void 0&&rs("lowS",t.lowS),t.prehash!==void 0&&rs("prehash",t.prehash)}function Tw(t){const e=cd(t);Sn(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:i,a:s}=e;if(r){if(!i.eql(s,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class Rw extends Error{constructor(e=""){super(e)}}const Xt={Err:Rw,_tlv:{encode:(t,e)=>{const{Err:r}=Xt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=Is(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?Is(s.length/2|128):"";return Is(t)+n+s+e},decode(t,e){const{Err:r}=Xt;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=Xt;if(t<er)throw new e("integer: negative integers are not allowed");let r=Is(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}=Xt;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 Kr(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=Xt,s=ht("signature",t),{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:l,l:u}=i.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=Xt,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}};function ao(t,e){return is(hs(t,e))}const er=BigInt(0),_e=BigInt(1);BigInt(2);const co=BigInt(3),Uw=BigInt(4);function Nw(t){const e=Tw(t),{Fp:r}=e,i=cc(e.n,e.nBitLength),s=e.toBytes||((b,E,$)=>{const B=E.toAffine();return en(Uint8Array.from([4]),r.toBytes(B.x),r.toBytes(B.y))}),n=e.fromBytes||(b=>{const E=b.subarray(1),$=r.fromBytes(E.subarray(0,r.BYTES)),B=r.fromBytes(E.subarray(r.BYTES,2*r.BYTES));return{x:$,y:B}});function o(b){const{a:E,b:$}=e,B=r.sqr(b),T=r.mul(B,b);return r.add(r.add(T,r.mul(b,E)),$)}function a(b,E){const $=r.sqr(E),B=o(b);return r.eql($,B)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,co),Uw),l=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,l)))throw new Error("bad curve params: a or b");function u(b){return nc(b,_e,e.n)}function h(b){const{allowedPrivateKeyLengths:E,nByteLength:$,wrapPrivateKey:B,n:T}=e;if(E&&typeof b!="bigint"){if(us(b)&&(b=is(b)),typeof b!="string"||!E.includes(b.length))throw new Error("invalid private key");b=b.padStart($*2,"0")}let R;try{R=typeof b=="bigint"?b:Kr(ht("private key",b,$))}catch{throw new Error("invalid private key, expected hex or "+$+" bytes, got "+typeof b)}return B&&(R=Ke(R,T)),yi("private key",R,_e,T),R}function f(b){if(!(b instanceof y))throw new Error("ProjectivePoint expected")}const p=wl((b,E)=>{const{px:$,py:B,pz:T}=b;if(r.eql(T,r.ONE))return{x:$,y:B};const R=b.is0();E==null&&(E=R?r.ONE:r.inv(T));const A=r.mul($,E),j=r.mul(B,E),N=r.mul(T,E);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(N,r.ONE))throw new Error("invZ was invalid");return{x:A,y:j}}),d=wl(b=>{if(b.is0()){if(e.allowInfinityPoint&&!r.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:E,y:$}=b.toAffine();if(!r.isValid(E)||!r.isValid($))throw new Error("bad point: x or y not FE");if(!a(E,$))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class y{constructor(E,$,B){if(E==null||!r.isValid(E))throw new Error("x required");if($==null||!r.isValid($)||r.is0($))throw new Error("y required");if(B==null||!r.isValid(B))throw new Error("z required");this.px=E,this.py=$,this.pz=B,Object.freeze(this)}static fromAffine(E){const{x:$,y:B}=E||{};if(!E||!r.isValid($)||!r.isValid(B))throw new Error("invalid affine point");if(E instanceof y)throw new Error("projective point not allowed");const T=R=>r.eql(R,r.ZERO);return T($)&&T(B)?y.ZERO:new y($,B,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(E){const $=rd(r,E.map(B=>B.pz));return E.map((B,T)=>B.toAffine($[T])).map(y.fromAffine)}static fromHex(E){const $=y.fromAffine(n(ht("pointHex",E)));return $.assertValidity(),$}static fromPrivateKey(E){return y.BASE.multiply(h(E))}static msm(E,$){return Cw(y,i,E,$)}_setWindowSize(E){I.setWindowSize(this,E)}assertValidity(){d(this)}hasEvenY(){const{y:E}=this.toAffine();if(r.isOdd)return!r.isOdd(E);throw new Error("Field doesn't support isOdd")}equals(E){f(E);const{px:$,py:B,pz:T}=this,{px:R,py:A,pz:j}=E,N=r.eql(r.mul($,j),r.mul(R,T)),C=r.eql(r.mul(B,j),r.mul(A,T));return N&&C}negate(){return new y(this.px,r.neg(this.py),this.pz)}double(){const{a:E,b:$}=e,B=r.mul($,co),{px:T,py:R,pz:A}=this;let j=r.ZERO,N=r.ZERO,C=r.ZERO,O=r.mul(T,T),P=r.mul(R,R),g=r.mul(A,A),w=r.mul(T,R);return w=r.add(w,w),C=r.mul(T,A),C=r.add(C,C),j=r.mul(E,C),N=r.mul(B,g),N=r.add(j,N),j=r.sub(P,N),N=r.add(P,N),N=r.mul(j,N),j=r.mul(w,j),C=r.mul(B,C),g=r.mul(E,g),w=r.sub(O,g),w=r.mul(E,w),w=r.add(w,C),C=r.add(O,O),O=r.add(C,O),O=r.add(O,g),O=r.mul(O,w),N=r.add(N,O),g=r.mul(R,A),g=r.add(g,g),O=r.mul(g,w),j=r.sub(j,O),C=r.mul(g,P),C=r.add(C,C),C=r.add(C,C),new y(j,N,C)}add(E){f(E);const{px:$,py:B,pz:T}=this,{px:R,py:A,pz:j}=E;let N=r.ZERO,C=r.ZERO,O=r.ZERO;const P=e.a,g=r.mul(e.b,co);let w=r.mul($,R),x=r.mul(B,A),D=r.mul(T,j),_=r.add($,B),S=r.add(R,A);_=r.mul(_,S),S=r.add(w,x),_=r.sub(_,S),S=r.add($,T);let U=r.add(R,j);return S=r.mul(S,U),U=r.add(w,D),S=r.sub(S,U),U=r.add(B,T),N=r.add(A,j),U=r.mul(U,N),N=r.add(x,D),U=r.sub(U,N),O=r.mul(P,S),N=r.mul(g,D),O=r.add(N,O),N=r.sub(x,O),O=r.add(x,O),C=r.mul(N,O),x=r.add(w,w),x=r.add(x,w),D=r.mul(P,D),S=r.mul(g,S),x=r.add(x,D),D=r.sub(w,D),D=r.mul(P,D),S=r.add(S,D),w=r.mul(x,S),C=r.add(C,w),w=r.mul(U,S),N=r.mul(_,N),N=r.sub(N,w),w=r.mul(_,x),O=r.mul(U,O),O=r.add(O,w),new y(N,C,O)}subtract(E){return this.add(E.negate())}is0(){return this.equals(y.ZERO)}wNAF(E){return I.wNAFCached(this,E,y.normalizeZ)}multiplyUnsafe(E){const{endo:$,n:B}=e;yi("scalar",E,er,B);const T=y.ZERO;if(E===er)return T;if(this.is0()||E===_e)return this;if(!$||I.hasPrecomputes(this))return I.wNAFCachedUnsafe(this,E,y.normalizeZ);let{k1neg:R,k1:A,k2neg:j,k2:N}=$.splitScalar(E),C=T,O=T,P=this;for(;A>er||N>er;)A&_e&&(C=C.add(P)),N&_e&&(O=O.add(P)),P=P.double(),A>>=_e,N>>=_e;return R&&(C=C.negate()),j&&(O=O.negate()),O=new y(r.mul(O.px,$.beta),O.py,O.pz),C.add(O)}multiply(E){const{endo:$,n:B}=e;yi("scalar",E,_e,B);let T,R;if($){const{k1neg:A,k1:j,k2neg:N,k2:C}=$.splitScalar(E);let{p:O,f:P}=this.wNAF(j),{p:g,f:w}=this.wNAF(C);O=I.constTimeNegate(A,O),g=I.constTimeNegate(N,g),g=new y(r.mul(g.px,$.beta),g.py,g.pz),T=O.add(g),R=P.add(w)}else{const{p:A,f:j}=this.wNAF(E);T=A,R=j}return y.normalizeZ([T,R])[0]}multiplyAndAddUnsafe(E,$,B){const T=y.BASE,R=(j,N)=>N===er||N===_e||!j.equals(T)?j.multiplyUnsafe(N):j.multiply(N),A=R(this,$).add(R(E,B));return A.is0()?void 0:A}toAffine(E){return p(this,E)}isTorsionFree(){const{h:E,isTorsionFree:$}=e;if(E===_e)return!0;if($)return $(y,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:E,clearCofactor:$}=e;return E===_e?this:$?$(y,this):this.multiplyUnsafe(e.h)}toRawBytes(E=!0){return rs("isCompressed",E),this.assertValidity(),s(y,this,E)}toHex(E=!0){return rs("isCompressed",E),is(this.toRawBytes(E))}}y.BASE=new y(e.Gx,e.Gy,r.ONE),y.ZERO=new y(r.ZERO,r.ONE,r.ZERO);const{endo:m,nBitLength:v}=e,I=Bw(y,m?Math.ceil(v/2):v);return{CURVE:e,ProjectivePoint:y,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function kw(t){const e=cd(t);return Sn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function jw(t){const e=kw(t),{Fp:r,n:i,nByteLength:s,nBitLength:n}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(g){return Ke(g,i)}function l(g){return sa(g,i)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=Nw({...e,toBytes(g,w,x){const D=w.toAffine(),_=r.toBytes(D.x),S=en;return rs("isCompressed",x),x?S(Uint8Array.from([w.hasEvenY()?2:3]),_):S(Uint8Array.from([4]),_,r.toBytes(D.y))},fromBytes(g){const w=g.length,x=g[0],D=g.subarray(1);if(w===o&&(x===2||x===3)){const _=Kr(D);if(!nc(_,_e,r.ORDER))throw new Error("Point is not on curve");const S=f(_);let U;try{U=r.sqrt(S)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const k=(U&_e)===_e;return(x&1)===1!==k&&(U=r.neg(U)),{x:_,y:U}}else if(w===a&&x===4){const _=r.fromBytes(D.subarray(0,r.BYTES)),S=r.fromBytes(D.subarray(r.BYTES,2*r.BYTES));return{x:_,y:S}}else{const _=o,S=a;throw new Error("invalid Point, expected length of "+_+", or uncompressed "+S+", got "+w)}}});function d(g){const w=i>>_e;return g>w}function y(g){return d(g)?c(-g):g}const m=(g,w,x)=>Kr(g.slice(w,x));class v{constructor(w,x,D){yi("r",w,_e,i),yi("s",x,_e,i),this.r=w,this.s=x,D!=null&&(this.recovery=D),Object.freeze(this)}static fromCompact(w){const x=s;return w=ht("compactSignature",w,x*2),new v(m(w,0,x),m(w,x,2*x))}static fromDER(w){const{r:x,s:D}=Xt.toSig(ht("DER",w));return new v(x,D)}assertValidity(){}addRecoveryBit(w){return new v(this.r,this.s,w)}recoverPublicKey(w){const{r:x,s:D,recovery:_}=this,S=T(ht("msgHash",w));if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");const U=_===2||_===3?x+e.n:x;if(U>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(_&1)===0?"02":"03",V=u.fromHex(k+ao(U,r.BYTES)),L=l(U),M=c(-S*L),K=c(D*L),G=u.BASE.multiplyAndAddUnsafe(V,M,K);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Qs(this.toDERHex())}toDERHex(){return Xt.hexFromSig(this)}toCompactRawBytes(){return Qs(this.toCompactHex())}toCompactHex(){const w=s;return ao(this.r,w)+ao(this.s,w)}}const I={isValidPrivateKey(g){try{return h(g),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const g=nd(e.n);return $w(e.randomBytes(g),e.n)},precompute(g=8,w=u.BASE){return w._setWindowSize(g),w.multiply(BigInt(3)),w}};function b(g,w=!0){return u.fromPrivateKey(g).toRawBytes(w)}function E(g){if(typeof g=="bigint")return!1;if(g instanceof u)return!0;const x=ht("key",g).length,D=r.BYTES,_=D+1,S=2*D+1;if(!(e.allowedPrivateKeyLengths||s===_))return x===_||x===S}function $(g,w,x=!0){if(E(g)===!0)throw new Error("first arg must be private key");if(E(w)===!1)throw new Error("second arg must be public key");return u.fromHex(w).multiply(h(g)).toRawBytes(x)}const B=e.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const w=Kr(g),x=g.length*8-n;return x>0?w>>BigInt(x):w},T=e.bits2int_modN||function(g){return c(B(g))},R=In(n);function A(g){return yi("num < 2^"+n,g,er,R),hs(g,s)}function j(g,w,x=N){if(["recovered","canonical"].some(W=>W in x))throw new Error("sign() legacy options not supported");const{hash:D,randomBytes:_}=e;let{lowS:S,prehash:U,extraEntropy:k}=x;S==null&&(S=!0),g=ht("msgHash",g),Dl(x),U&&(g=ht("prehashed msgHash",D(g)));const V=T(g),L=h(w),M=[A(L),A(V)];if(k!=null&&k!==!1){const W=k===!0?_(r.BYTES):k;M.push(ht("extraEntropy",W))}const K=en(...M),G=V;function Z(W){const J=B(W);if(!p(J))return;const ue=l(J),ye=u.BASE.multiply(J).toAffine(),be=c(ye.x);if(be===er)return;const je=c(ue*c(G+be*L));if(je===er)return;let Ot=(ye.x===be?0:2)|Number(ye.y&_e),xs=je;return S&&d(je)&&(xs=y(je),Ot^=1),new v(be,xs,Ot)}return{seed:K,k2sig:Z}}const N={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function O(g,w,x=N){const{seed:D,k2sig:_}=j(g,w,x),S=e;return N0(S.hash.outputLen,S.nByteLength,S.hmac)(D,_)}u.BASE._setWindowSize(8);function P(g,w,x,D=C){const _=g;w=ht("msgHash",w),x=ht("publicKey",x);const{lowS:S,prehash:U,format:k}=D;if(Dl(D),"strict"in D)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const V=typeof _=="string"||us(_),L=!V&&!k&&typeof _=="object"&&_!==null&&typeof _.r=="bigint"&&typeof _.s=="bigint";if(!V&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,K;try{if(L&&(M=new v(_.r,_.s)),V){try{k!=="compact"&&(M=v.fromDER(_))}catch(Ot){if(!(Ot instanceof Xt.Err))throw Ot}!M&&k!=="der"&&(M=v.fromCompact(_))}K=u.fromHex(x)}catch{return!1}if(!M||S&&M.hasHighS())return!1;U&&(w=e.hash(w));const{r:G,s:Z}=M,W=T(w),J=l(Z),ue=c(W*J),ye=c(G*J),be=u.BASE.multiplyAndAddUnsafe(K,ue,ye)?.toAffine();return be?c(be.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:$,sign:O,verify:P,ProjectivePoint:u,Signature:v,utils:I}}function Fw(t){return{hash:t,hmac:(e,...r)=>Jf(t,e,l0(...r)),randomBytes:u0}}function Lw(t,e){const r=i=>jw({...t,...Fw(i)});return{...r(e),create:r}}const ld=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),$l=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Mw=BigInt(0),qw=BigInt(1),oa=BigInt(2),Al=(t,e)=>(t+e/oa)/e;function zw(t){const e=ld,r=BigInt(3),i=BigInt(6),s=BigInt(11),n=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=at(u,r,e)*u%e,f=at(h,r,e)*u%e,p=at(f,oa,e)*l%e,d=at(p,s,e)*p%e,y=at(d,n,e)*d%e,m=at(y,a,e)*y%e,v=at(m,c,e)*m%e,I=at(v,a,e)*y%e,b=at(I,r,e)*u%e,E=at(b,o,e)*d%e,$=at(E,i,e)*l%e,B=at($,oa,e);if(!aa.eql(aa.sqr(B),t))throw new Error("Cannot find square root");return B}const aa=cc(ld,void 0,void 0,{sqrt:zw}),Vw=Lw({a:Mw,b:BigInt(7),Fp:aa,n:$l,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=$l,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-qw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=r,o=BigInt("0x100000000000000000000000000000000"),a=Al(n*t,e),c=Al(-i*t,e);let l=Ke(t-a*r-c*s,e),u=Ke(-a*i-c*n,e);const h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}}},T0);function Hw(t){if(t.length!==130&&t.length!==132)throw new Ww({signature:t});const e=BigInt(Jt(t,0,32)),r=BigInt(Jt(t,32,64)),i=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return Kw(s)}catch{throw new Gw({value:s})}})();return typeof i>"u"?{r:e,s:r}:{r:e,s:r,yParity:i}}function Kw(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 Yw({value:t})}class Ww extends le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Or(ac(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Gw extends le{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 Yw extends le{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function Zw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ud(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 rn(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function lc(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function ca(t){if(!Array.isArray(t))throw new Error("array expected")}function sn(t,e){if(!ud(!0,e))throw new Error(`${t}: array of strings expected`)}function Jw(t,e){if(!ud(!1,e))throw new Error(`${t}: array of numbers expected`)}function Xw(...t){const e=n=>n,r=(n,o)=>a=>n(o(a)),i=t.map(n=>n.encode).reduceRight(r,e),s=t.map(n=>n.decode).reduce(r,e);return{encode:i,decode:s}}function Qw(t){const e=typeof t=="string"?t.split(""):t,r=e.length;sn("alphabet",e);const i=new Map(e.map((s,n)=>[s,n]));return{encode:s=>(ca(s),s.map(n=>{if(!Number.isSafeInteger(n)||n<0||n>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);return e[n]})),decode:s=>(ca(s),s.map(n=>{rn("alphabet.decode",n);const o=i.get(n);if(o===void 0)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return o}))}}function em(t=""){return rn("join",t),{encode:e=>(sn("join.decode",e),e.join(t)),decode:e=>(rn("join.decode",e),e.split(t))}}function tm(t,e="="){return lc(t),rn("padding",e),{encode(r){for(sn("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){sn("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 hd=(t,e)=>e===0?t:hd(e,t%e),nn=(t,e)=>t+(e-hd(t,e)),lo=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Pl(t,e,r,i){if(ca(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(nn(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${nn(e,r)}`);let s=0,n=0;const o=lo[e],a=lo[r]-1,c=[];for(const l of t){if(lc(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<<e|l,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=r;n-=r)c.push((s>>n-r&a)>>>0);const u=lo[n];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<<r-n&a,!i&&n>=e)throw new Error("Excess padding");if(!i&&s>0)throw new Error(`Non-zero padding: ${s}`);return i&&n>0&&c.push(s>>>0),c}function rm(t,e=!1){if(lc(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(nn(8,t)>32||nn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Zw(r))throw new Error("radix2.encode input should be Uint8Array");return Pl(Array.from(r),8,t,!e)},decode:r=>(Jw("radix2.decode",r),Uint8Array.from(Pl(r,t,8,e)))}}const im=Xw(rm(5),Qw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),tm(5),em(""));function sm(t){return mw(nm(t))}function nm(t){const{payload:e,signature:r}=t,{r:i,s,yParity:n}=r,a=new Vw.Signature(BigInt(i),BigInt(s)).addRecoveryBit(n).recoverPublicKey(ac(e).substring(2));return lw(a)}function om(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,f=0;const p=l.length;for(;f!==p&&l[f]===0;)f++,u++;const d=(p-f)*n+1>>>0,y=new Uint8Array(d);for(;f!==p;){let I=l[f],b=0;for(let E=d-1;(I!==0||b<h)&&E!==-1;E--,b++)I+=256*y[E]>>>0,y[E]=I%r>>>0,I=I/r>>>0;if(I!==0)throw new Error("Non-zero carry");h=b,f++}let m=d-h;for(;m!==d&&y[m]===0;)m++;let v=i.repeat(u);for(;m<d;++m)v+=t.charAt(y[m]);return v}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,f=0;for(;l[u]===i;)h++,u++;const p=(l.length-u)*s+1>>>0,d=new Uint8Array(p);for(;u<l.length;){const I=l.charCodeAt(u);if(I>255)return;let b=e[I];if(b===255)return;let E=0;for(let $=p-1;(b!==0||E<f)&&$!==-1;$--,E++)b+=r*d[$]>>>0,d[$]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=E,u++}let y=p-f;for(;y!==p&&d[y]===0;)y++;const m=new Uint8Array(h+(p-y));let v=h;for(;y!==p;)m[v++]=d[y++];return m}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var am="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const fs=om(am);function cm(t){const e=t.length;let r=0,i=0;for(;i<e;){let s=t.charCodeAt(i++);if((s&4294967168)===0){r++;continue}else if((s&4294965248)===0)r+=2;else{if(s>=55296&&s<=56319&&i<e){const n=t.charCodeAt(i);(n&64512)===56320&&(++i,s=((s&1023)<<10)+(n&1023)+65536)}(s&4294901760)===0?r+=3:r+=4}}return r}function lm(t,e,r){const i=t.length;let s=r,n=0;for(;n<i;){let o=t.charCodeAt(n++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&n<i){const a=t.charCodeAt(n);(a&64512)===56320&&(++n,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const um=new TextEncoder,hm=50;function fm(t,e,r){um.encodeInto(t,e.subarray(r))}function dm(t,e,r){t.length>hm?fm(t,e,r):lm(t,e,r)}const pm=4096;function fd(t,e,r){let i=e;const s=i+r,n=[];let o="";for(;i<s;){const a=t[i++];if((a&128)===0)n.push(a);else if((a&224)===192){const c=t[i++]&63;n.push((a&31)<<6|c)}else if((a&240)===224){const c=t[i++]&63,l=t[i++]&63;n.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[i++]&63,l=t[i++]&63,u=t[i++]&63;let h=(a&7)<<18|c<<12|l<<6|u;h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|h&1023),n.push(h)}else n.push(a);n.length>=pm&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const gm=new TextDecoder,ym=200;function wm(t,e,r){const i=t.subarray(e,e+r);return gm.decode(i)}function mm(t,e,r){return r>ym?wm(t,e,r):fd(t,e,r)}class Os{constructor(e,r){this.type=e,this.data=r}}class it extends Error{constructor(e){super(e);const r=Object.create(it.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:it.name})}}const Ti=4294967295;function bm(t,e,r){const i=r/4294967296,s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function dd(t,e,r){const i=Math.floor(r/4294967296),s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function pd(t,e){const r=t.getInt32(e),i=t.getUint32(e+4);return r*4294967296+i}function vm(t,e){const r=t.getUint32(e),i=t.getUint32(e+4);return r*4294967296+i}const Em=-1,xm=4294967296-1,_m=17179869184-1;function Im({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=_m)if(e===0&&t<=xm){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,i=t&4294967295,s=new Uint8Array(8),n=new DataView(s.buffer);return n.setUint32(0,e<<2|r&3),n.setUint32(4,i),s}else{const r=new Uint8Array(12),i=new DataView(r.buffer);return i.setUint32(0,e),dd(i,4,t),r}}function Sm(t){const e=t.getTime(),r=Math.floor(e/1e3),i=(e-r*1e3)*1e6,s=Math.floor(i/1e9);return{sec:r+s,nsec:i-s*1e9}}function Om(t){if(t instanceof Date){const e=Sm(t);return Im(e)}else return null}function Dm(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const r=e.getUint32(0),i=e.getUint32(4),s=(r&3)*4294967296+i,n=r>>>2;return{sec:s,nsec:n}}case 12:{const r=pd(e,4),i=e.getUint32(0);return{sec:r,nsec:i}}default:throw new it(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function $m(t){const e=Dm(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Am={type:Em,encode:Om,decode:$m};class on{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Am)}register({type:e,encode:r,decode:i}){if(e>=0)this.encoders[e]=r,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=r,this.builtInDecoders[s]=i}}tryToEncode(e,r){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=-1-i;return new Os(o,n)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=i;return new Os(o,n)}}}return e instanceof Os?e:null}decode(e,r,i){const s=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return s?s(e,r,i):new Os(r,e)}}on.defaultCodec=new on;function Pm(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function la(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Pm(t)?new Uint8Array(t):Uint8Array.from(t)}const Bm=100,Cm=2048;let Tm=class gd{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??on.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Bm,this.initialBufferSize=e?.initialBufferSize??Cm,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new gd({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),i=new Uint8Array(r),s=new DataView(r);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=cm(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),dm(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=la(e);this.writeU8a(i)}encodeArray(e,r){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const s of e)this.doEncode(s,r+1)}countWithoutUndefined(e,r){let i=0;for(const s of r)e[s]!==void 0&&i++;return i}encodeMap(e,r){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const n of i){const o=e[n];this.ignoreUndefined&&o===void 0||(this.encodeString(n),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),s=i.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(i);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),bm(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),dd(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 Rm(t,e){return new Tm(e).encodeSharedRef(t)}function uo(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const Um=16,Nm=16;class km{constructor(e=Um,r=Nm){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,i){const s=this.caches[i-1];e:for(const n of s){const o=n.bytes;for(let a=0;a<i;a++)if(o[a]!==e[r+a])continue e;return n.str}return null}store(e,r){const i=this.caches[e.length-1],s={bytes:e,str:r};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,r,i){const s=this.find(e,r,i);if(s!=null)return this.hit++,s;this.miss++;const n=fd(e,r,i),o=Uint8Array.prototype.slice.call(e,r,r+i);return this.store(o,n),n}}const ua="array",Gi="map_key",yd="map_value",jm=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new it("The type of key must be string or number but "+typeof t)};class Fm{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=ua,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=Gi,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===ua){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Gi||e.type===yd){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 Ri=-1,uc=new DataView(new ArrayBuffer(0)),Lm=new Uint8Array(uc.buffer);try{uc.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 Bl=new RangeError("Insufficient data"),Mm=new km;let qm=class wd{constructor(e){this.totalPos=0,this.pos=0,this.view=uc,this.bytes=Lm,this.headByte=Ri,this.stack=new Fm,this.entered=!1,this.extensionCodec=e?.extensionCodec??on.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ti,this.maxBinLength=e?.maxBinLength??Ti,this.maxArrayLength=e?.maxArrayLength??Ti,this.maxMapLength=e?.maxMapLength??Ti,this.maxExtLength=e?.maxExtLength??Ti,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Mm,this.mapKeyConverter=e?.mapKeyConverter??jm}clone(){return new wd({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=Ri,this.stack.reset()}setBuffer(e){const r=la(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Ri&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),i=la(e),s=new Uint8Array(r.length+i.length);s.set(r),s.set(i,r.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:i}=this;return new RangeError(`Extra ${r.byteLength-i} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,i;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:s,pos:n,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${uo(s)} at ${o} (${n} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let i=r,s=-1;for await(const n of e){if(r&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else{const s=e-160;r=this.decodeString(s,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const s=this.lookU8();r=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();r=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();r=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===196){const s=this.lookU8();r=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();r=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();r=this.decodeBinary(s,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();r=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();r=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();r=this.decodeExtension(s,4)}else throw new it(`Unrecognized type byte: ${uo(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const s=i.top();if(s.type===ua)if(s.array[s.position]=r,s.position++,s.position===s.size)r=s.array,i.release(s);else continue e;else if(s.type===Gi){if(r==="__proto__")throw new it("The key __proto__ is not allowed");s.key=this.mapKeyConverter(r),s.type=yd;continue e}else if(s.map[s.key]=r,s.readCount++,s.readCount===s.size)r=s.map,i.release(s);else{s.key=null,s.type=Gi;continue e}}return r}}readHeadByte(){return this.headByte===Ri&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Ri}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new it(`Unrecognized array type byte: ${uo(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new it(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new it(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new it(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw Bl;const i=this.pos+r;let s;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?s=this.keyDecoder.decode(this.bytes,i,e):s=mm(this.bytes,i,e),this.pos+=r+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Gi:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new it(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw Bl;const i=this.pos+r,s=this.bytes.subarray(i,i+e);return this.pos+=r+e,s}decodeExtension(e,r){if(e>this.maxExtLength)throw new it(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+r),s=this.decodeBinary(e,r+1);return this.extensionCodec.decode(s,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=vm(this.view,this.pos);return this.pos+=8,e}readI64(){const e=pd(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 zm(t,e){return new qm(e).decode(t)}const Vm=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Hm=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Gr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Hm(t)}catch{return t}}function Yr(t){return typeof t=="string"?t:Vm(t)||""}function Km(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function md(t,...e){if(!Km(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 Cl(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 Wm(t,e){md(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const ni=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;const ho=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Gm(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=Gm(t)),md(t),t}let Ym=class{clone(){return this._cloneInto()}};function Zm(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 vd(t=32){if(ni&&typeof ni.getRandomValues=="function")return ni.getRandomValues(new Uint8Array(t));if(ni&&typeof ni.randomBytes=="function")return ni.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Jm(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}let Xm=class extends Ym{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ho(this.buffer)}update(e){Cl(this);const{view:r,buffer:i,blockLen:s}=this;e=bd(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=ho(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Cl(this),Wm(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;Jm(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=ho(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const Ds=BigInt(2**32-1),ha=BigInt(32);function Ed(t,e=!1){return e?{h:Number(t&Ds),l:Number(t>>ha&Ds)}:{h:Number(t>>ha&Ds)|0,l:Number(t&Ds)|0}}function Qm(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Ed(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const eb=(t,e)=>BigInt(t>>>0)<<ha|BigInt(e>>>0),tb=(t,e,r)=>t>>>r,rb=(t,e,r)=>t<<32-r|e>>>r,ib=(t,e,r)=>t>>>r|e<<32-r,sb=(t,e,r)=>t<<32-r|e>>>r,nb=(t,e,r)=>t<<64-r|e>>>r-32,ob=(t,e,r)=>t>>>r-32|e<<64-r,ab=(t,e)=>e,cb=(t,e)=>t,lb=(t,e,r)=>t<<r|e>>>32-r,ub=(t,e,r)=>e<<r|t>>>32-r,hb=(t,e,r)=>e<<r-32|t>>>64-r,fb=(t,e,r)=>t<<r-32|e>>>64-r;function db(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const pb=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),gb=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,yb=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),wb=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,mb=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),bb=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,Y={fromBig:Ed,split:Qm,toBig:eb,shrSH:tb,shrSL:rb,rotrSH:ib,rotrSL:sb,rotrBH:nb,rotrBL:ob,rotr32H:ab,rotr32L:cb,rotlSH:lb,rotlSL:ub,rotlBH:hb,rotlBL:fb,add:db,add3L:pb,add3H:gb,add4L:yb,add4H:wb,add5H:bb,add5L:mb},[vb,Eb]=Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),lr=new Uint32Array(80),ur=new Uint32Array(80);let xb=class extends Xm{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=m|0}process(e,r){for(let b=0;b<16;b++,r+=4)lr[b]=e.getUint32(r),ur[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const E=lr[b-15]|0,$=ur[b-15]|0,B=Y.rotrSH(E,$,1)^Y.rotrSH(E,$,8)^Y.shrSH(E,$,7),T=Y.rotrSL(E,$,1)^Y.rotrSL(E,$,8)^Y.shrSL(E,$,7),R=lr[b-2]|0,A=ur[b-2]|0,j=Y.rotrSH(R,A,19)^Y.rotrBH(R,A,61)^Y.shrSH(R,A,6),N=Y.rotrSL(R,A,19)^Y.rotrBL(R,A,61)^Y.shrSL(R,A,6),C=Y.add4L(T,N,ur[b-7],ur[b-16]),O=Y.add4H(C,B,j,lr[b-7],lr[b-16]);lr[b]=O|0,ur[b]=C|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:m,Hh:v,Hl:I}=this;for(let b=0;b<80;b++){const E=Y.rotrSH(h,f,14)^Y.rotrSH(h,f,18)^Y.rotrBH(h,f,41),$=Y.rotrSL(h,f,14)^Y.rotrSL(h,f,18)^Y.rotrBL(h,f,41),B=h&p^~h&y,T=f&d^~f&m,R=Y.add5L(I,$,T,Eb[b],ur[b]),A=Y.add5H(R,v,E,B,vb[b],lr[b]),j=R|0,N=Y.rotrSH(i,s,28)^Y.rotrBH(i,s,34)^Y.rotrBH(i,s,39),C=Y.rotrSL(i,s,28)^Y.rotrBL(i,s,34)^Y.rotrBL(i,s,39),O=i&n^i&a^n&a,P=s&o^s&c^o&c;v=y|0,I=m|0,y=p|0,m=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(l|0,u|0,A|0,j|0),l=a|0,u=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=Y.add3L(j,C,P);i=Y.add3H(g,A,N,O),s=g|0}({h:i,l:s}=Y.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=Y.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Y.add(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=Y.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Y.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:m}=Y.add(this.Gh|0,this.Gl|0,y|0,m|0),{h:v,l:I}=Y.add(this.Hh|0,this.Hl|0,v|0,I|0),this.set(i,s,n,o,a,c,l,u,h,f,p,d,y,m,v,I)}roundClean(){lr.fill(0),ur.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 _b=Zm(()=>new xb);const hc=BigInt(0),xd=BigInt(1),Ib=BigInt(2);function fc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function dc(t){if(!fc(t))throw new Error("Uint8Array expected")}function fo(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){dc(t);let e="";for(let r=0;r<t.length;r++)e+=Sb[t[r]];return e}function _d(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?hc:BigInt("0x"+t)}const Vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tl(t){if(t>=Vt._0&&t<=Vt._9)return t-Vt._0;if(t>=Vt.A&&t<=Vt.F)return t-(Vt.A-10);if(t>=Vt.a&&t<=Vt.f)return t-(Vt.a-10)}function Id(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Tl(t.charCodeAt(n)),a=Tl(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function Ob(t){return _d(pc(t))}function Ks(t){return dc(t),_d(pc(Uint8Array.from(t).reverse()))}function Sd(t,e){return Id(t.toString(16).padStart(e*2,"0"))}function fa(t,e){return Sd(t,e).reverse()}function Ht(t,e,r){let i;if(typeof e=="string")try{i=Id(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(fc(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Rl(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];dc(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const po=t=>typeof t=="bigint"&&hc<=t;function Db(t,e,r){return po(t)&&po(e)&&po(r)&&e<=t&&t<r}function Ui(t,e,r,i){if(!Db(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function $b(t){let e;for(e=0;t>hc;t>>=xd,e+=1);return e}const Ab=t=>(Ib<<BigInt(t-1))-xd,Pb={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"||fc(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 gc(t,e,r={}){const i=(s,n,o)=>{const a=Pb[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function Ul(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const Se=BigInt(0),he=BigInt(1),jr=BigInt(2),Bb=BigInt(3),da=BigInt(4),Nl=BigInt(5),kl=BigInt(8);function me(t,e){const r=t%e;return r>=Se?r:e+r}function Cb(t,e,r){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(r<=Se)throw new Error("invalid modulus");if(r===he)return Se;let i=he;for(;e>Se;)e&he&&(i=i*t%r),t=t*t%r,e>>=he;return i}function $t(t,e,r){let i=t;for(;e-- >Se;)i*=i,i%=r;return i}function jl(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let r=me(t,e),i=e,s=Se,n=he;for(;r!==Se;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==he)throw new Error("invert: does not exist");return me(s,e)}function Tb(t){const e=(t-he)/jr;let r,i,s;for(r=t-he,i=0;r%jr===Se;r/=jr,i++);for(s=jr;s<t&&Cb(s,e,t)!==t-he;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+he)/da;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(r+he)/jr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,l=o.pow(o.mul(o.ONE,s),r),u=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(l,he<<BigInt(c-f-1));l=o.sqr(p),u=o.mul(u,p),h=o.mul(h,l),c=f}return u}}function Rb(t){if(t%da===Bb){const e=(t+he)/da;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%kl===Nl){const e=(t-Nl)/kl;return function(r,i){const s=r.mul(i,jr),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,jr),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Tb(t)}const Ub=(t,e)=>(me(t,e)&he)===he,Nb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function kb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Nb.reduce((i,s)=>(i[s]="function",i),e);return gc(t,r)}function jb(t,e,r){if(r<Se)throw new Error("invalid exponent, negatives unsupported");if(r===Se)return t.ONE;if(r===he)return e;let i=t.ONE,s=e;for(;r>Se;)r&he&&(i=t.mul(i,s)),s=t.sqr(s),r>>=he;return i}function Fb(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Od(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Dd(t,e,r=!1,i={}){if(t<=Se)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Od(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Ab(s),ZERO:Se,ONE:he,create:c=>me(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<t},is0:c=>c===Se,isOdd:c=>(c&he)===he,neg:c=>me(-c,t),eql:(c,l)=>c===l,sqr:c=>me(c*c,t),add:(c,l)=>me(c+l,t),sub:(c,l)=>me(c-l,t),mul:(c,l)=>me(c*l,t),pow:(c,l)=>jb(a,c,l),div:(c,l)=>me(c*jl(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>jl(c,t),sqrt:i.sqrt||(c=>(o||(o=Rb(t)),o(a,c))),invertBatch:c=>Fb(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>r?fa(c,n):Sd(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?Ks(c):Ob(c)}});return Object.freeze(a)}const Fl=BigInt(0),$s=BigInt(1);function go(t,e){const r=e.negate();return t?r:e}function $d(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function yo(t,e){$d(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function Lb(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 Mb(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 wo=new WeakMap,Ad=new WeakMap;function mo(t){return Ad.get(t)||1}function qb(t,e){return{constTimeNegate:go,hasPrecomputes(r){return mo(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Fl;)i&$s&&(s=s.add(n)),n=n.double(),i>>=$s;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=yo(i,e),o=[];let a=r,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=yo(r,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**r-1),u=2**r,h=BigInt(r);for(let f=0;f<n;f++){const p=f*o;let d=Number(s&l);s>>=h,d>o&&(d-=u,s+=$s);const y=p,m=p+Math.abs(d)-1,v=f%2!==0,I=d<0;d===0?c=c.add(go(v,i[y])):a=a.add(go(I,i[m]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=yo(r,e),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(s===Fl)break;let p=Number(s&c);if(s>>=u,p>a&&(p-=l,s+=$s),p===0)continue;let d=i[f+Math.abs(p)-1];p<0&&(d=d.negate()),n=n.add(d)}return n},getPrecomputes(r,i,s){let n=wo.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&wo.set(i,s(n))),n},wNAFCached(r,i,s){const n=mo(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=mo(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){$d(i,e),Ad.set(r,i),wo.delete(r)}}}function zb(t,e,r,i){if(Lb(r,t),Mb(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=$b(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),l=Math.floor((e.BITS-1)/o)*o;let u=s;for(let h=l;h>=0;h-=o){c.fill(s);for(let p=0;p<i.length;p++){const d=i[p],y=Number(d>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let f=s;for(let p=c.length-1,d=s;p>0;p--)d=d.add(c[p]),f=f.add(d);if(u=u.add(f),h!==0)for(let p=0;p<o;p++)u=u.double()}return u}function Vb(t){return kb(t.Fp),gc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Od(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const mt=BigInt(0),qe=BigInt(1),As=BigInt(2),Hb=BigInt(8),Kb={zip215:!0};function Wb(t){const e=Vb(t);return gc(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Gb(t){const e=Wb(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,l=As<<BigInt(a*8)-qe,u=r.create,h=Dd(e.n,e.nBitLength),f=e.uvRatio||((g,w)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(w))}}catch{return{isValid:!1,value:mt}}}),p=e.adjustScalarBytes||(g=>g),d=e.domain||((g,w,x)=>{if(fo("phflag",x),w.length||x)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,w){Ui("coordinate "+g,w,mt,l)}function m(g){if(!(g instanceof b))throw new Error("ExtendedPoint expected")}const v=Ul((g,w)=>{const{ex:x,ey:D,ez:_}=g,S=g.is0();w==null&&(w=S?Hb:r.inv(_));const U=u(x*w),k=u(D*w),V=u(_*w);if(S)return{x:mt,y:qe};if(V!==qe)throw new Error("invZ was invalid");return{x:U,y:k}}),I=Ul(g=>{const{a:w,d:x}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:D,ey:_,ez:S,et:U}=g,k=u(D*D),V=u(_*_),L=u(S*S),M=u(L*L),K=u(k*w),G=u(L*u(K+V)),Z=u(M+u(x*u(k*V)));if(G!==Z)throw new Error("bad point: equation left != right (1)");const W=u(D*_),J=u(S*U);if(W!==J)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(w,x,D,_){this.ex=w,this.ey=x,this.ez=D,this.et=_,y("x",w),y("y",x),y("z",D),y("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof b)throw new Error("extended point not allowed");const{x,y:D}=w||{};return y("x",x),y("y",D),new b(x,D,qe,u(x*D))}static normalizeZ(w){const x=r.invertBatch(w.map(D=>D.ez));return w.map((D,_)=>D.toAffine(x[_])).map(b.fromAffine)}static msm(w,x){return zb(b,h,w,x)}_setWindowSize(w){B.setWindowSize(this,w)}assertValidity(){I(this)}equals(w){m(w);const{ex:x,ey:D,ez:_}=this,{ex:S,ey:U,ez:k}=w,V=u(x*k),L=u(S*_),M=u(D*k),K=u(U*_);return V===L&&M===K}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:w}=e,{ex:x,ey:D,ez:_}=this,S=u(x*x),U=u(D*D),k=u(As*u(_*_)),V=u(w*S),L=x+D,M=u(u(L*L)-S-U),K=V+U,G=K-k,Z=V-U,W=u(M*G),J=u(K*Z),ue=u(M*Z),ye=u(G*K);return new b(W,J,ye,ue)}add(w){m(w);const{a:x,d:D}=e,{ex:_,ey:S,ez:U,et:k}=this,{ex:V,ey:L,ez:M,et:K}=w;if(x===BigInt(-1)){const zc=u((S-_)*(L+V)),Vc=u((S+_)*(L-V)),Kn=u(Vc-zc);if(Kn===mt)return this.double();const Hc=u(U*As*K),Kc=u(k*As*M),Wc=Kc+Hc,Gc=Vc+zc,Yc=Kc-Hc,iy=u(Wc*Kn),sy=u(Gc*Yc),ny=u(Wc*Yc),oy=u(Kn*Gc);return new b(iy,sy,oy,ny)}const G=u(_*V),Z=u(S*L),W=u(k*D*K),J=u(U*M),ue=u((_+S)*(V+L)-G-Z),ye=J-W,be=J+W,je=u(Z-x*G),Ot=u(ue*ye),xs=u(be*je),ty=u(ue*je),ry=u(ye*be);return new b(Ot,xs,ry,ty)}subtract(w){return this.add(w.negate())}wNAF(w){return B.wNAFCached(this,w,b.normalizeZ)}multiply(w){const x=w;Ui("scalar",x,qe,i);const{p:D,f:_}=this.wNAF(x);return b.normalizeZ([D,_])[0]}multiplyUnsafe(w,x=b.ZERO){const D=w;return Ui("scalar",D,mt,i),D===mt?$:this.is0()||D===qe?this:B.wNAFCachedUnsafe(this,D,b.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,i).is0()}toAffine(w){return v(this,w)}clearCofactor(){const{h:w}=e;return w===qe?this:this.multiplyUnsafe(w)}static fromHex(w,x=!1){const{d:D,a:_}=e,S=r.BYTES;w=Ht("pointHex",w,S),fo("zip215",x);const U=w.slice(),k=w[S-1];U[S-1]=k&-129;const V=Ks(U),L=x?l:r.ORDER;Ui("pointHex.y",V,mt,L);const M=u(V*V),K=u(M-qe),G=u(D*M-_);let{isValid:Z,value:W}=f(K,G);if(!Z)throw new Error("Point.fromHex: invalid y coordinate");const J=(W&qe)===qe,ue=(k&128)!==0;if(!x&&W===mt&&ue)throw new Error("Point.fromHex: x=0 and x_0=1");return ue!==J&&(W=u(-W)),b.fromAffine({x:W,y:V})}static fromPrivateKey(w){return A(w).point}toRawBytes(){const{x:w,y:x}=this.toAffine(),D=fa(x,r.BYTES);return D[D.length-1]|=w&qe?128:0,D}toHex(){return pc(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,qe,u(e.Gx*e.Gy)),b.ZERO=new b(mt,qe,qe,mt);const{BASE:E,ZERO:$}=b,B=qb(b,a*8);function T(g){return me(g,i)}function R(g){return T(Ks(g))}function A(g){const w=r.BYTES;g=Ht("private key",g,w);const x=Ht("hashed private key",n(g),2*w),D=p(x.slice(0,w)),_=x.slice(w,2*w),S=R(D),U=E.multiply(S),k=U.toRawBytes();return{head:D,prefix:_,scalar:S,point:U,pointBytes:k}}function j(g){return A(g).pointBytes}function N(g=new Uint8Array,...w){const x=Rl(...w);return R(n(d(x,Ht("context",g),!!s)))}function C(g,w,x={}){g=Ht("message",g),s&&(g=s(g));const{prefix:D,scalar:_,pointBytes:S}=A(w),U=N(x.context,D,g),k=E.multiply(U).toRawBytes(),V=N(x.context,k,S,g),L=T(U+V*_);Ui("signature.s",L,mt,i);const M=Rl(k,fa(L,r.BYTES));return Ht("result",M,r.BYTES*2)}const O=Kb;function P(g,w,x,D=O){const{context:_,zip215:S}=D,U=r.BYTES;g=Ht("signature",g,2*U),w=Ht("message",w),x=Ht("publicKey",x,U),S!==void 0&&fo("zip215",S),s&&(w=s(w));const k=Ks(g.slice(U,2*U));let V,L,M;try{V=b.fromHex(x,S),L=b.fromHex(g.slice(0,U),S),M=E.multiplyUnsafe(k)}catch{return!1}if(!S&&V.isSmallOrder())return!1;const K=N(_,L.toRawBytes(),V.toRawBytes(),w);return L.add(V.multiplyUnsafe(K)).subtract(M).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:C,verify:P,ExtendedPoint:b,utils:{getExtendedPublicKey:A,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,w=b.BASE){return w._setWindowSize(g),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const yc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ll=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Yb=BigInt(1),Ml=BigInt(2);BigInt(3);const Zb=BigInt(5),Jb=BigInt(8);function Xb(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=yc,o=t*t%n*t%n,a=$t(o,Ml,n)*o%n,c=$t(a,Yb,n)*t%n,l=$t(c,Zb,n)*c%n,u=$t(l,e,n)*l%n,h=$t(u,r,n)*u%n,f=$t(h,i,n)*h%n,p=$t(f,s,n)*f%n,d=$t(p,s,n)*f%n,y=$t(d,e,n)*l%n;return{pow_p_5_8:$t(y,Ml,n)*t%n,b2:o}}function Qb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function e1(t,e){const r=yc,i=me(e*e*e,r),s=me(i*i*e,r),n=Xb(t*s).pow_p_5_8;let o=me(t*i*n,r);const a=me(e*o*o,r),c=o,l=me(o*Ll,r),u=a===t,h=a===me(-t,r),f=a===me(-t*Ll,r);return u&&(o=c),(h||f)&&(o=l),Ub(o,r)&&(o=me(-o,r)),{isValid:u||h,value:o}}const t1=Dd(yc,void 0,!0),r1={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:t1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Jb,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_b,randomBytes:vd,adjustScalarBytes:Qb,uvRatio:e1},Pd=Gb(r1),i1="EdDSA",s1="JWT",an=".",On="base64url",Bd="utf8",Cd="utf8",n1=":",o1="did",a1="key",ql="base58btc",c1="z",l1="K36",u1=32;function wc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Td(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?wc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Rd(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Td(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return wc(r)}function h1(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,m=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,y++;for(var b=(I-v)*u+1>>>0,E=new Uint8Array(b);v!==I;){for(var $=d[v],B=0,T=b-1;($!==0||B<m)&&T!==-1;T--,B++)$+=256*E[T]>>>0,E[T]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");m=B,v++}for(var R=b-m;R!==b&&E[R]===0;)R++;for(var A=c.repeat(y);R<b;++R)A+=t.charAt(E[R]);return A}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var m=0,v=0;d[y]===c;)m++,y++;for(var I=(d.length-y)*l+1>>>0,b=new Uint8Array(I);d[y];){var E=r[d.charCodeAt(y)];if(E===255)return;for(var $=0,B=I-1;(E!==0||$<v)&&B!==-1;B--,$++)E+=a*b[B]>>>0,b[B]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");v=$,y++}if(d[y]!==" "){for(var T=I-v;T!==I&&b[T]===0;)T++;for(var R=new Uint8Array(m+(I-T)),A=m;T!==I;)R[A++]=b[T++];return R}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var f1=h1,d1=f1;const Ud=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")},p1=t=>new TextEncoder().encode(t),g1=t=>new TextDecoder().decode(t);let y1=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")}},w1=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 Nd(this,e)}},m1=class{constructor(e){this.decoders=e}or(e){return Nd(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 Nd=(t,e)=>new m1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let b1=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new y1(e,r,i),this.decoder=new w1(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Dn=({name:t,prefix:e,encode:r,decode:i})=>new b1(t,e,r,i),ds=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=d1(r,e);return Dn({prefix:t,name:e,encode:i,decode:n=>Ud(s(n))})},v1=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},E1=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Dn({prefix:e,name:t,encode(s){return E1(s,i,r)},decode(s){return v1(s,i,r,t)}}),x1=Dn({prefix:"\0",name:"identity",encode:t=>g1(t),decode:t=>p1(t)});var _1=Object.freeze({__proto__:null,identity:x1});const I1=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var S1=Object.freeze({__proto__:null,base2:I1});const O1=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var D1=Object.freeze({__proto__:null,base8:O1});const $1=ds({prefix:"9",name:"base10",alphabet:"0123456789"});var A1=Object.freeze({__proto__:null,base10:$1});const P1=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),B1=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var C1=Object.freeze({__proto__:null,base16:P1,base16upper:B1});const T1=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),R1=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),U1=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),N1=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),k1=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),j1=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),F1=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L1=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),M1=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var q1=Object.freeze({__proto__:null,base32:T1,base32upper:R1,base32pad:U1,base32padupper:N1,base32hex:k1,base32hexupper:j1,base32hexpad:F1,base32hexpadupper:L1,base32z:M1});const z1=ds({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),V1=ds({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var H1=Object.freeze({__proto__:null,base36:z1,base36upper:V1});const K1=ds({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),W1=ds({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var G1=Object.freeze({__proto__:null,base58btc:K1,base58flickr:W1});const Y1=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Z1=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J1=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),X1=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Q1=Object.freeze({__proto__:null,base64:Y1,base64pad:Z1,base64url:J1,base64urlpad:X1});const kd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ev=kd.reduce((t,e,r)=>(t[r]=e,t),[]),tv=kd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function rv(t){return t.reduce((e,r)=>(e+=ev[r],e),"")}function iv(t){const e=[];for(const r of t){const i=tv[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const sv=Dn({prefix:"🚀",name:"base256emoji",encode:rv,decode:iv});var nv=Object.freeze({__proto__:null,base256emoji:sv}),ov=jd,zl=128,av=-128,cv=Math.pow(2,31);function jd(t,e,r){e=e||[],r=r||0;for(var i=r;t>=cv;)e[r++]=t&255|zl,t/=128;for(;t&av;)e[r++]=t&255|zl,t>>>=7;return e[r]=t|0,jd.bytes=r-i+1,e}var lv=pa,uv=128,Vl=127;function pa(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw pa.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Vl)<<s:(o&Vl)*Math.pow(2,s),s+=7}while(o>=uv);return pa.bytes=n-i,r}var hv=Math.pow(2,7),fv=Math.pow(2,14),dv=Math.pow(2,21),pv=Math.pow(2,28),gv=Math.pow(2,35),yv=Math.pow(2,42),wv=Math.pow(2,49),mv=Math.pow(2,56),bv=Math.pow(2,63),vv=function(t){return t<hv?1:t<fv?2:t<dv?3:t<pv?4:t<gv?5:t<yv?6:t<wv?7:t<mv?8:t<bv?9:10},Ev={encode:ov,decode:lv,encodingLength:vv},Fd=Ev;const Hl=(t,e,r=0)=>(Fd.encode(t,e,r),e),Kl=t=>Fd.encodingLength(t),ga=(t,e)=>{const r=e.byteLength,i=Kl(t),s=i+Kl(r),n=new Uint8Array(s+r);return Hl(t,n,0),Hl(r,n,i),n.set(e,s),new xv(t,r,e,n)};let xv=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const Ld=({name:t,code:e,encode:r})=>new _v(t,e,r);let _v=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?ga(this.code,r):r.then(i=>ga(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Md=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Iv=Ld({name:"sha2-256",code:18,encode:Md("SHA-256")}),Sv=Ld({name:"sha2-512",code:19,encode:Md("SHA-512")});var Ov=Object.freeze({__proto__:null,sha256:Iv,sha512:Sv});const qd=0,Dv="identity",zd=Ud,$v=t=>ga(qd,zd(t)),Av={code:qd,name:Dv,encode:zd,digest:$v};var Pv=Object.freeze({__proto__:null,identity:Av});new TextEncoder,new TextDecoder;const Wl={..._1,...S1,...D1,...A1,...C1,...q1,...H1,...G1,...Q1,...nv};({...Ov,...Pv});function Vd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Gl=Vd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),bo=Vd("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=Td(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Hd={utf8:Gl,"utf-8":Gl,hex:Wl.base16,latin1:bo,ascii:bo,binary:bo,...Wl};function $n(t,e="utf8"){const r=Hd[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 Oi(t,e="utf8"){const r=Hd[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?wc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Yl(t){return Gr($n(Oi(t,On),Bd))}function cn(t){return $n(Oi(Yr(t),Bd),On)}function Kd(t){const e=Oi(l1,ql),r=c1+$n(Rd([e,t]),ql);return[o1,a1,r].join(n1)}function Bv(t){return $n(t,On)}function Cv(t){return Oi(t,On)}function Tv(t){return Oi([cn(t.header),cn(t.payload)].join(an),Cd)}function Rv(t){return[cn(t.header),cn(t.payload),Bv(t.signature)].join(an)}function ya(t){const e=t.split(an),r=Yl(e[0]),i=Yl(e[1]),s=Cv(e[2]),n=Oi(e.slice(0,2).join(an),Cd);return{header:r,payload:i,signature:s,data:n}}function Zl(t=vd(u1)){const e=Pd.getPublicKey(t);return{secretKey:Rd([t,e]),publicKey:e}}async function Uv(t,e,r,i,s=q.fromMiliseconds(Date.now())){const n={alg:i1,typ:s1},o=Kd(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},l=Tv({header:n,payload:c}),u=Pd.sign(l,i.secretKey.slice(0,32));return Rv({header:n,payload:c,signature:u})}function mc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Wd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?mc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Yi(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Wd(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return mc(r)}function Nv(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,m=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,y++;for(var b=(I-v)*u+1>>>0,E=new Uint8Array(b);v!==I;){for(var $=d[v],B=0,T=b-1;($!==0||B<m)&&T!==-1;T--,B++)$+=256*E[T]>>>0,E[T]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");m=B,v++}for(var R=b-m;R!==b&&E[R]===0;)R++;for(var A=c.repeat(y);R<b;++R)A+=t.charAt(E[R]);return A}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var m=0,v=0;d[y]===c;)m++,y++;for(var I=(d.length-y)*l+1>>>0,b=new Uint8Array(I);d[y];){var E=r[d.charCodeAt(y)];if(E===255)return;for(var $=0,B=I-1;(E!==0||$<v)&&B!==-1;B--,$++)E+=a*b[B]>>>0,b[B]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");v=$,y++}if(d[y]!==" "){for(var T=I-v;T!==I&&b[T]===0;)T++;for(var R=new Uint8Array(m+(I-T)),A=m;T!==I;)R[A++]=b[T++];return R}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var kv=Nv,jv=kv;const Fv=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")},Lv=t=>new TextEncoder().encode(t),Mv=t=>new TextDecoder().decode(t);class qv{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 zv{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 Gd(this,e)}}class Vv{constructor(e){this.decoders=e}or(e){return Gd(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 Gd=(t,e)=>new Vv({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Hv{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new qv(e,r,i),this.decoder=new zv(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const An=({name:t,prefix:e,encode:r,decode:i})=>new Hv(t,e,r,i),ps=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=jv(r,e);return An({prefix:t,name:e,encode:i,decode:n=>Fv(s(n))})},Kv=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Wv=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Be=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>An({prefix:e,name:t,encode(s){return Wv(s,i,r)},decode(s){return Kv(s,i,r,t)}}),Gv=An({prefix:"\0",name:"identity",encode:t=>Mv(t),decode:t=>Lv(t)}),Yv=Object.freeze(Object.defineProperty({__proto__:null,identity:Gv},Symbol.toStringTag,{value:"Module"})),Zv=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Jv=Object.freeze(Object.defineProperty({__proto__:null,base2:Zv},Symbol.toStringTag,{value:"Module"})),Xv=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Qv=Object.freeze(Object.defineProperty({__proto__:null,base8:Xv},Symbol.toStringTag,{value:"Module"})),e2=ps({prefix:"9",name:"base10",alphabet:"0123456789"}),t2=Object.freeze(Object.defineProperty({__proto__:null,base10:e2},Symbol.toStringTag,{value:"Module"})),r2=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),i2=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),s2=Object.freeze(Object.defineProperty({__proto__:null,base16:r2,base16upper:i2},Symbol.toStringTag,{value:"Module"})),n2=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),o2=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),a2=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),c2=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),l2=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),u2=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),h2=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),f2=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),d2=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),p2=Object.freeze(Object.defineProperty({__proto__:null,base32:n2,base32hex:l2,base32hexpad:h2,base32hexpadupper:f2,base32hexupper:u2,base32pad:a2,base32padupper:c2,base32upper:o2,base32z:d2},Symbol.toStringTag,{value:"Module"})),g2=ps({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),y2=ps({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),w2=Object.freeze(Object.defineProperty({__proto__:null,base36:g2,base36upper:y2},Symbol.toStringTag,{value:"Module"})),m2=ps({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),b2=ps({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),v2=Object.freeze(Object.defineProperty({__proto__:null,base58btc:m2,base58flickr:b2},Symbol.toStringTag,{value:"Module"})),E2=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),x2=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_2=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),I2=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),S2=Object.freeze(Object.defineProperty({__proto__:null,base64:E2,base64pad:x2,base64url:_2,base64urlpad:I2},Symbol.toStringTag,{value:"Module"})),Yd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),O2=Yd.reduce((t,e,r)=>(t[r]=e,t),[]),D2=Yd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function $2(t){return t.reduce((e,r)=>(e+=O2[r],e),"")}function A2(t){const e=[];for(const r of t){const i=D2[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const P2=An({prefix:"🚀",name:"base256emoji",encode:$2,decode:A2}),B2=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:P2},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Jl={...Yv,...Jv,...Qv,...t2,...s2,...p2,...w2,...v2,...S2,...B2};function Zd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Xl=Zd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),vo=Zd("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=Wd(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Jd={utf8:Xl,"utf-8":Xl,hex:Jl.base16,latin1:vo,ascii:vo,binary:vo,...Jl};function pt(t,e="utf8"){const r=Jd[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?mc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Je(t,e="utf8"){const r=Jd[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 C2={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"}};var Eo,Ql;function Xd(){if(Ql)return Eo;Ql=1;const t="Input must be an string, Buffer or Uint8Array";function e(o){let a;if(o instanceof Uint8Array)a=o;else if(typeof o=="string")a=new TextEncoder().encode(o);else throw new Error(t);return a}function r(o){return Array.prototype.map.call(o,function(a){return(a<16?"0":"")+a.toString(16)}).join("")}function i(o){return(4294967296+o).toString(16).substring(1)}function s(o,a,c){let l=`
|
|
4
4
|
`+o+" = ";for(let u=0;u<a.length;u+=2){if(c===32)l+=i(a[u]).toUpperCase(),l+=" ",l+=i(a[u+1]).toUpperCase();else if(c===64)l+=i(a[u+1]).toUpperCase(),l+=i(a[u]).toUpperCase();else throw new Error("Invalid size "+c);u%6===4?l+=`
|
|
5
5
|
`+new Array(o.length+4).join(" "):u<a.length-2&&(l+=" ")}console.log(l)}function n(o,a,c){let l=new Date().getTime();const u=new Uint8Array(a);for(let f=0;f<a;f++)u[f]=f%256;const h=new Date().getTime();console.log("Generated random input in "+(h-l)+"ms"),l=h;for(let f=0;f<c;f++){const p=o(u),d=new Date().getTime(),y=d-l;l=d,console.log("Hashed in "+y+"ms: "+p.substring(0,20)+"..."),console.log(Math.round(a/(1<<20)/(y/1e3)*100)/100+" MB PER SECOND")}}return Eo={normalizeInput:e,toHex:r,debugPrint:s,testSpeed:n},Eo}var xo,eu;function T2(){if(eu)return xo;eu=1;const t=Xd();function e(v,I,b){const E=v[I]+v[b];let $=v[I+1]+v[b+1];E>=4294967296&&$++,v[I]=E,v[I+1]=$}function r(v,I,b,E){let $=v[I]+b;b<0&&($+=4294967296);let B=v[I+1]+E;$>=4294967296&&B++,v[I]=$,v[I+1]=B}function i(v,I){return v[I]^v[I+1]<<8^v[I+2]<<16^v[I+3]<<24}function s(v,I,b,E,$,B){const T=l[$],R=l[$+1],A=l[B],j=l[B+1];e(c,v,I),r(c,v,T,R);let N=c[E]^c[v],C=c[E+1]^c[v+1];c[E]=C,c[E+1]=N,e(c,b,E),N=c[I]^c[b],C=c[I+1]^c[b+1],c[I]=N>>>24^C<<8,c[I+1]=C>>>24^N<<8,e(c,v,I),r(c,v,A,j),N=c[E]^c[v],C=c[E+1]^c[v+1],c[E]=N>>>16^C<<16,c[E+1]=C>>>16^N<<16,e(c,b,E),N=c[I]^c[b],C=c[I+1]^c[b+1],c[I]=C>>>31^N<<1,c[I+1]=N>>>31^C<<1}const n=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),o=[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],a=new Uint8Array(o.map(function(v){return v*2})),c=new Uint32Array(32),l=new Uint32Array(32);function u(v,I){let b=0;for(b=0;b<16;b++)c[b]=v.h[b],c[b+16]=n[b];for(c[24]=c[24]^v.t,c[25]=c[25]^v.t/4294967296,I&&(c[28]=~c[28],c[29]=~c[29]),b=0;b<32;b++)l[b]=i(v.b,4*b);for(b=0;b<12;b++)s(0,8,16,24,a[b*16+0],a[b*16+1]),s(2,10,18,26,a[b*16+2],a[b*16+3]),s(4,12,20,28,a[b*16+4],a[b*16+5]),s(6,14,22,30,a[b*16+6],a[b*16+7]),s(0,10,20,30,a[b*16+8],a[b*16+9]),s(2,12,22,24,a[b*16+10],a[b*16+11]),s(4,14,16,26,a[b*16+12],a[b*16+13]),s(6,8,18,28,a[b*16+14],a[b*16+15]);for(b=0;b<16;b++)v.h[b]=v.h[b]^c[b]^c[b+16]}const h=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 f(v,I,b,E){if(v===0||v>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(I&&I.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(b&&b.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(E&&E.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const $={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:v};h.fill(0),h[0]=v,I&&(h[1]=I.length),h[2]=1,h[3]=1,b&&h.set(b,32),E&&h.set(E,48);for(let B=0;B<16;B++)$.h[B]=n[B]^i(h,B*4);return I&&(p($,I),$.c=128),$}function p(v,I){for(let b=0;b<I.length;b++)v.c===128&&(v.t+=v.c,u(v,!1),v.c=0),v.b[v.c++]=I[b]}function d(v){for(v.t+=v.c;v.c<128;)v.b[v.c++]=0;u(v,!0);const I=new Uint8Array(v.outlen);for(let b=0;b<v.outlen;b++)I[b]=v.h[b>>2]>>8*(b&3);return I}function y(v,I,b,E,$){b=b||64,v=t.normalizeInput(v),E&&(E=t.normalizeInput(E)),$&&($=t.normalizeInput($));const B=f(b,I,E,$);return p(B,v),d(B)}function m(v,I,b,E,$){const B=y(v,I,b,E,$);return t.toHex(B)}return xo={blake2b:y,blake2bHex:m,blake2bInit:f,blake2bUpdate:p,blake2bFinal:d},xo}var _o,tu;function R2(){if(tu)return _o;tu=1;const t=Xd();function e(d,y){return d[y]^d[y+1]<<8^d[y+2]<<16^d[y+3]<<24}function r(d,y,m,v,I,b){o[d]=o[d]+o[y]+I,o[v]=i(o[v]^o[d],16),o[m]=o[m]+o[v],o[y]=i(o[y]^o[m],12),o[d]=o[d]+o[y]+b,o[v]=i(o[v]^o[d],8),o[m]=o[m]+o[v],o[y]=i(o[y]^o[m],7)}function i(d,y){return d>>>y^d<<32-y}const s=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=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]),o=new Uint32Array(16),a=new Uint32Array(16);function c(d,y){let m=0;for(m=0;m<8;m++)o[m]=d.h[m],o[m+8]=s[m];for(o[12]^=d.t,o[13]^=d.t/4294967296,y&&(o[14]=~o[14]),m=0;m<16;m++)a[m]=e(d.b,4*m);for(m=0;m<10;m++)r(0,4,8,12,a[n[m*16+0]],a[n[m*16+1]]),r(1,5,9,13,a[n[m*16+2]],a[n[m*16+3]]),r(2,6,10,14,a[n[m*16+4]],a[n[m*16+5]]),r(3,7,11,15,a[n[m*16+6]],a[n[m*16+7]]),r(0,5,10,15,a[n[m*16+8]],a[n[m*16+9]]),r(1,6,11,12,a[n[m*16+10]],a[n[m*16+11]]),r(2,7,8,13,a[n[m*16+12]],a[n[m*16+13]]),r(3,4,9,14,a[n[m*16+14]],a[n[m*16+15]]);for(m=0;m<8;m++)d.h[m]^=o[m]^o[m+8]}function l(d,y){if(!(d>0&&d<=32))throw new Error("Incorrect output length, should be in [1, 32]");const m=y?y.length:0;if(y&&!(m>0&&m<=32))throw new Error("Incorrect key length, should be in [1, 32]");const v={h:new Uint32Array(s),b:new Uint8Array(64),c:0,t:0,outlen:d};return v.h[0]^=16842752^m<<8^d,m>0&&(u(v,y),v.c=64),v}function u(d,y){for(let m=0;m<y.length;m++)d.c===64&&(d.t+=d.c,c(d,!1),d.c=0),d.b[d.c++]=y[m]}function h(d){for(d.t+=d.c;d.c<64;)d.b[d.c++]=0;c(d,!0);const y=new Uint8Array(d.outlen);for(let m=0;m<d.outlen;m++)y[m]=d.h[m>>2]>>8*(m&3)&255;return y}function f(d,y,m){m=m||32,d=t.normalizeInput(d);const v=l(m,y);return u(v,d),h(v)}function p(d,y,m){const v=f(d,y,m);return t.toHex(v)}return _o={blake2s:f,blake2sHex:p,blake2sInit:l,blake2sUpdate:u,blake2sFinal:h},_o}var Io,ru;function U2(){if(ru)return Io;ru=1;const t=T2(),e=R2();return Io={blake2b:t.blake2b,blake2bHex:t.blake2bHex,blake2bInit:t.blake2bInit,blake2bUpdate:t.blake2bUpdate,blake2bFinal:t.blake2bFinal,blake2s:e.blake2s,blake2sHex:e.blake2sHex,blake2sInit:e.blake2sInit,blake2sUpdate:e.blake2sUpdate,blake2sFinal:e.blake2sFinal},Io}var N2=U2(),kt={exports:{}};function k2(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var j2=F2;function F2(t,e,r){var i=r&&r.stringify||k2,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=i(t);for(var a=1;a<n;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-s,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Number(e[u]),h=p+2,p++;break;case 105:if(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Math.floor(Number(e[u])),h=p+2,p++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;h<p&&(l+=t.slice(h,p));var d=typeof e[u];if(d==="string"){l+="'"+e[u]+"'",h=p+2,p++;break}if(d==="function"){l+=e[u].name||"<anonymous>",h=p+2,p++;break}l+=i(e[u]),h=p+2,p++;break;case 115:if(u>=c)break;h<p&&(l+=t.slice(h,p)),l+=String(e[u]),h=p+2,p++;break;case 37:h<p&&(l+=t.slice(h,p)),l+="%",h=p+2,p++,u--;break}++u}++p}return h===-1?t:(h<f&&(l+=t.slice(h)),l)}const iu=j2;kt.exports=rr;const ss=eE().console||{},L2={mapHttpRequest:Ps,mapHttpResponse:Ps,wrapRequestSerializer:So,wrapResponseSerializer:So,wrapErrorSerializer:So,req:Ps,res:Ps,err:nu,errWithCause:nu};function _r(t,e){return t==="silent"?1/0:e.levels.values[t]}const bc=Symbol("pino.logFuncs"),wa=Symbol("pino.hierarchy"),M2={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function su(t,e){const r={logger:e,parent:t[wa]};e[wa]=r}function q2(t,e,r){const i={};e.forEach(s=>{i[s]=r[s]?r[s]:ss[s]||ss[M2[s]||"log"]||wi}),t[bc]=i}function z2(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function rr(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||ss;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},s=z2(t.browser.serialize,i);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof r=="function"&&a.forEach(function(y){r[y]=r}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(r);l.log||(l.log=wi),q2(l,a,r),su({},l),Object.defineProperty(l,"levelVal",{get:h}),Object.defineProperty(l,"level",{get:f,set:p});const u={transmit:e,serialize:s,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:J2(t),messageKey:t.messageKey||"msg",onChild:t.onChild||wi};l.levels=V2(t),l.level=c,l.isLevelEnabled=function(y){return this.levels.values[y]?this.levels.values[y]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=wi,l.serializers=i,l._serialize=s,l._stdErrSerialize=n,l.child=function(...y){return d.call(this,u,...y)},e&&(l._logEvent=ma());function h(){return _r(this.level,this)}function f(){return this._level}function p(y){if(y!=="silent"&&!this.levels.values[y])throw Error("unknown level "+y);this._level=y,Cr(this,u,l,"error"),Cr(this,u,l,"fatal"),Cr(this,u,l,"warn"),Cr(this,u,l,"info"),Cr(this,u,l,"debug"),Cr(this,u,l,"trace"),o.forEach(m=>{Cr(this,u,l,m)})}function d(y,m,v){if(!m)throw new Error("missing bindings for child Pino");v=v||{},s&&m.serializers&&(v.serializers=m.serializers);const I=v.serializers;if(s&&I){var b=Object.assign({},i,I),E=t.browser.serialize===!0?Object.keys(b):s;delete m.serializers,vc([m],E,b,this._stdErrSerialize)}function $(T){this._childLevel=(T._childLevel|0)+1,this.bindings=m,b&&(this.serializers=b,this._serialize=E),e&&(this._logEvent=ma([].concat(T._logEvent.bindings,m)))}$.prototype=this;const B=new $(this);return su(this,B),B.child=function(...T){return d.call(this,y,...T)},B.level=v.level||this.level,y.onChild(B),B}return l}function V2(t){const e=t.customLevels||{},r=Object.assign({},rr.levels.values,e),i=Object.assign({},rr.levels.labels,H2(e));return{values:r,labels:i}}function H2(t){const e={};return Object.keys(t).forEach(function(r){e[t[r]]=r}),e}rr.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"}},rr.stdSerializers=L2,rr.stdTimeFunctions=Object.assign({},{nullTime:Qd,epochTime:ep,unixTime:X2,isoTime:Q2});function K2(t){const e=[];t.bindings&&e.push(t.bindings);let r=t[wa];for(;r.parent;)r=r.parent,r.logger.bindings&&e.push(r.logger.bindings);return e.reverse()}function Cr(t,e,r,i){if(Object.defineProperty(t,i,{value:_r(t.level,r)>_r(i,r)?wi:r[bc][i],writable:!0,enumerable:!0,configurable:!0}),t[i]===wi){if(!e.transmit)return;const n=e.transmit.level||t.level,o=_r(n,r);if(_r(i,r)<o)return}t[i]=G2(t,e,r,i);const s=K2(t);s.length!==0&&(t[i]=W2(s,t[i]))}function W2(t,e){return function(){return e.apply(this,[...t,...arguments])}}function G2(t,e,r,i){return(function(s){return function(){const n=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ss?ss:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(e.serialize&&(vc(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?s.call(a,...Y2(this,i,o,n,e)):s.apply(a,o),e.transmit){const u=e.transmit.level||t._level,h=_r(u,r),f=_r(i,r);if(f<h)return;Z2(this,{ts:n,methodLevel:i,methodValue:f,transmitValue:r.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:_r(t._level,r)},o,l)}}})(t[bc][i])}function Y2(t,e,r,i,s){const{level:n,log:o=h=>h}=s.formatters||{},a=r.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),i&&(l.time=i),n){const h=n(e,t.levels.values[e]);Object.assign(l,h)}else l.level=t.levels.values[e];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?iu(a.shift(),a):void 0}else typeof c=="string"&&(c=iu(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function vc(t,e,r,i){for(const s in t)if(i&&t[s]instanceof Error)t[s]=rr.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s])&&e)for(const n in t[s])e.indexOf(n)>-1&&n in r&&(t[s][n]=r[n](t[s][n]))}function Z2(t,e,r,i=!1){const s=e.send,n=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;i||vc(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=n,t._logEvent.messages=r.filter(function(u){return l.indexOf(u)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,s(o,t._logEvent,c),t._logEvent=ma(l)}function ma(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function nu(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 J2(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Qd:ep}function Ps(){return{}}function So(t){return t}function wi(){}function Qd(){return!1}function ep(){return Date.now()}function X2(){return Math.round(Date.now()/1e3)}function Q2(){return new Date(Date.now()).toISOString()}function eE(){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)||{}}}kt.exports.default=rr;kt.exports.pino=rr;const tE={level:"info"},Pn="custom_context",Ec=1e3*1024;var rE=Object.defineProperty,iE=(t,e,r)=>e in t?rE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vr=(t,e,r)=>iE(t,typeof e!="symbol"?e+"":e,r);let sE=class{constructor(e){vr(this,"nodeValue"),vr(this,"sizeInBytes"),vr(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}},ou=class{constructor(e){vr(this,"lengthInNodes"),vr(this,"sizeInBytes"),vr(this,"head"),vr(this,"tail"),vr(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new sE(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}};const nE=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r);function au(t){return typeof t=="string"?t:nE(t)||""}var oE=Object.defineProperty,aE=(t,e,r)=>e in t?oE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Bs=(t,e,r)=>aE(t,typeof e!="symbol"?e+"":e,r);let tp=class{constructor(e,r=Ec){Bs(this,"logs"),Bs(this,"level"),Bs(this,"levelValue"),Bs(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=kt.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new ou(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===kt.exports.levels.values.error?console.error(e):r===kt.exports.levels.values.warn?console.warn(e):r===kt.exports.levels.values.debug?console.debug(e):r===kt.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(au({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 ou(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(au({extraMetadata:e})),new Blob(r,{type:"application/json"})}};var cE=Object.defineProperty,lE=(t,e,r)=>e in t?cE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,uE=(t,e,r)=>lE(t,e+"",r);let hE=class{constructor(e,r=Ec){uE(this,"baseChunkLogger"),this.baseChunkLogger=new tp(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 fE=Object.defineProperty,dE=(t,e,r)=>e in t?fE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pE=(t,e,r)=>dE(t,e+"",r);let gE=class{constructor(e,r=Ec){pE(this,"baseChunkLogger"),this.baseChunkLogger=new tp(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 yE=Object.defineProperty,wE=Object.defineProperties,mE=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,bE=Object.prototype.hasOwnProperty,vE=Object.prototype.propertyIsEnumerable,lu=(t,e,r)=>e in t?yE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ln=(t,e)=>{for(var r in e||(e={}))bE.call(e,r)&&lu(t,r,e[r]);if(cu)for(var r of cu(e))vE.call(e,r)&&lu(t,r,e[r]);return t},un=(t,e)=>wE(t,mE(e));function EE(t){return un(ln({},t),{level:t?.level||tE.level})}function xE(t,e,r=Pn){return t[r]=e,t}function Xe(t,e=Pn){return t[e]||""}function _E(t,e,r=Pn){const i=Xe(t,r);return i.trim()?`${i}/${e}`:e}function ot(t,e,r=Pn){const i=_E(t,e,r),s=t.child({context:i});return xE(s,i,r)}function IE(t){var e,r;const i=new hE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt.exports(un(ln({},t.opts),{level:"trace",browser:un(ln({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function SE(t){var e;const r=new gE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt.exports(un(ln({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function rp(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?IE(t):SE(t)}var OE={};const DE=":";function ir(t){const[e,r]=t.split(DE);return{namespace:e,reference:r}}function uu(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function ip(t,e){return t.includes(":")?[t]:e.chains||[]}var $E=Object.defineProperty,AE=Object.defineProperties,PE=Object.getOwnPropertyDescriptors,hu=Object.getOwnPropertySymbols,BE=Object.prototype.hasOwnProperty,CE=Object.prototype.propertyIsEnumerable,ba=(t,e,r)=>e in t?$E(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fu=(t,e)=>{for(var r in e||(e={}))BE.call(e,r)&&ba(t,r,e[r]);if(hu)for(var r of hu(e))CE.call(e,r)&&ba(t,r,e[r]);return t},TE=(t,e)=>AE(t,PE(e)),du=(t,e,r)=>ba(t,typeof e!="symbol"?e+"":e,r);const RE="ReactNative",nt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},UE="js";function hn(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function $r(){return!nr.getDocument()&&!!nr.getNavigator()&&navigator.product===RE}function NE(){return $r()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function kE(){return $r()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Di(){return!hn()&&!!nr.getNavigator()&&!!nr.getDocument()}function gs(){return $r()?nt.reactNative:hn()?nt.node:Di()?nt.browser:nt.unknown}function pu(){var t;try{return $r()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function jE(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([i],[s])=>i.localeCompare(s)).forEach(([i,s])=>{s!=null&&r.set(i,String(s))}),r.toString()}function FE(t){var e,r;const i=sp();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?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),TE(fu(fu({},i),t),{url:t?.url||i.url,name:t?.name||i.name,description:t?.description||i.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function sp(){return Qy.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function LE(){if(gs()===nt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=wy();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 ME(){var t;const e=gs();return e===nt.browser?[e,((t=nr.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function np(t,e,r){const i=LE(),s=ME();return[[t,e].join("-"),[UE,r].join("-"),i,s].join("/")}function qE({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=r.split("?"),u=np(t,e,i),h={auth:s,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},f=jE(l[1]||"",h);return l[0]+"?"+f}function qr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function va(t){return Object.fromEntries(t.entries())}function Ea(t){return new Map(Object.entries(t))}function Nr(t=q.FIVE_MINUTES,e){const r=q.toMiliseconds(t||q.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},r),i=a,s=c})}}function jt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function op(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function zE(t){return op("topic",t)}function VE(t){return op("id",t)}function ap(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 de(t,e){return q.fromMiliseconds(Date.now()+q.toMiliseconds(t))}function Nt(t){return Date.now()>=q.toMiliseconds(t)}function ie(t,e){return`${t}${e?`:${e}`:""}`}function Ft(t=[],e=[]){return[...new Set([...t,...e])]}async function HE({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s?.href;if(typeof n!="string")return;const o=KE(n,t,e),a=gs();if(a===nt.browser){if(!((i=nr.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}WE(o)}else a===nt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function KE(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${JE(i,!0)}`}else s=`${s}/wc?${i}`;return s}function WE(t){let e="_self";ZE()?e="_top":(YE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function GE(t,e){let r="";try{if(Di()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function gu(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function yu(){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 xc(){return typeof process<"u"&&OE.IS_VITEST==="true"}function YE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ZE(){try{return window.self!==window.top}catch{return!1}}function JE(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function cp(t){return Buffer.from(t,"base64").toString("utf-8")}function XE(t){return new Promise(e=>setTimeout(e,t))}let QE=class{constructor({limit:e}){du(this,"limit"),du(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 Cs=BigInt(2**32-1),wu=BigInt(32);function lp(t,e=!1){return e?{h:Number(t&Cs),l:Number(t>>wu&Cs)}:{h:Number(t>>wu&Cs)|0,l:Number(t&Cs)|0}}function up(t,e=!1){const r=t.length;let i=new Uint32Array(r),s=new Uint32Array(r);for(let n=0;n<r;n++){const{h:o,l:a}=lp(t[n],e);[i[n],s[n]]=[o,a]}return[i,s]}const mu=(t,e,r)=>t>>>r,bu=(t,e,r)=>t<<32-r|e>>>r,wr=(t,e,r)=>t>>>r|e<<32-r,mr=(t,e,r)=>t<<32-r|e>>>r,Hi=(t,e,r)=>t<<64-r|e>>>r-32,Ki=(t,e,r)=>t>>>r-32|e<<64-r,ex=(t,e)=>e,tx=(t,e)=>t,rx=(t,e,r)=>t<<r|e>>>32-r,ix=(t,e,r)=>e<<r|t>>>32-r,sx=(t,e,r)=>e<<r-32|t>>>64-r,nx=(t,e,r)=>t<<r-32|e>>>64-r;function xt(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const _c=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ic=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,ox=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),ax=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,cx=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),lx=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,oi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Bn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function or(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function St(t,...e){if(!Bn(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 Cn(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");or(t.outputLen),or(t.blockLen)}function Dr(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 Sc(t,e){St(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ns(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function yt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Oo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function At(t,e){return t<<32-e|t>>>e}const hp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Yt=hp?t=>t:t=>fp(t);function ux(t){for(let e=0;e<t.length;e++)t[e]=fp(t[e]);return t}const br=hp?t=>t:ux,dp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function mi(t){if(St(t),dp)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=hx[t[r]];return e}const Kt={_0:48,_9:57,A:65,F:70,a:97,f:102};function vu(t){if(t>=Kt._0&&t<=Kt._9)return t-Kt._0;if(t>=Kt.A&&t<=Kt.F)return t-(Kt.A-10);if(t>=Kt.a&&t<=Kt.f)return t-(Kt.a-10)}function fn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(dp)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=vu(t.charCodeAt(n)),a=vu(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function pp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function It(t){return typeof t=="string"&&(t=pp(t)),St(t),t}function Er(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];St(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Tn=class{};function ys(t){const e=i=>t().update(It(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function fx(t){const e=(i,s)=>t(s).update(It(i)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}function Xr(t=32){if(oi&&typeof oi.getRandomValues=="function")return oi.getRandomValues(new Uint8Array(t));if(oi&&typeof oi.randomBytes=="function")return Uint8Array.from(oi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const dx=BigInt(0),Ni=BigInt(1),px=BigInt(2),gx=BigInt(7),yx=BigInt(256),wx=BigInt(113),gp=[],yp=[],wp=[];for(let t=0,e=Ni,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],gp.push(2*(5*i+r)),yp.push((t+1)*(t+2)/2%64);let s=dx;for(let n=0;n<7;n++)e=(e<<Ni^(e>>gx)*wx)%yx,e&px&&(s^=Ni<<(Ni<<BigInt(n))-Ni);wp.push(s)}const mp=up(wp,!0),mx=mp[0],bx=mp[1],Eu=(t,e,r)=>r>32?sx(t,e,r):rx(t,e,r),xu=(t,e,r)=>r>32?nx(t,e,r):ix(t,e,r);function vx(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Eu(l,u,1)^r[a],f=xu(l,u,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=yp[o],c=Eu(s,n,a),l=xu(s,n,a),u=gp[o];s=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=mx[i],t[1]^=bx[i]}yt(r)}let Ex=class bp extends Tn{constructor(e,r,i,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,or(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ns(this.state)}clone(){return this._cloneInto()}keccak(){br(this.state32),vx(this.state32,this.rounds),br(this.state32),this.posOut=0,this.pos=0}update(e){Dr(this),e=It(e),St(e);const{blockLen:r,state:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,(r&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Dr(this,!1),St(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return or(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Sc(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,yt(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new bp(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const xx=(t,e,r)=>ys(()=>new Ex(e,t,r)),_x=xx(1,136,256/8);function Ix(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function Sx(t,e,r){return t&e^~t&r}function Ox(t,e,r){return t&e^t&r^e&r}let vp=class extends Tn{constructor(e,r,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Oo(this.buffer)}update(e){Dr(this),e=It(e),St(e);const{view:r,buffer:i,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Oo(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Dr(this),Sc(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,yt(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;Ix(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Oo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}};const hr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Te=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Re=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Dx=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]),fr=new Uint32Array(64);class $x extends vp{constructor(e=32){super(64,e,8,!1),this.A=hr[0]|0,this.B=hr[1]|0,this.C=hr[2]|0,this.D=hr[3]|0,this.E=hr[4]|0,this.F=hr[5]|0,this.G=hr[6]|0,this.H=hr[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)fr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=fr[h-15],p=fr[h-2],d=At(f,7)^At(f,18)^f>>>3,y=At(p,17)^At(p,19)^p>>>10;fr[h]=y+fr[h-7]+d+fr[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=At(a,6)^At(a,11)^At(a,25),p=u+f+Sx(a,c,l)+Dx[h]+fr[h]|0,d=(At(i,2)^At(i,13)^At(i,22))+Ox(i,s,n)|0;u=l,l=c,c=a,a=o+p|0,o=n,n=s,s=i,i=p+d|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(i,s,n,o,a,c,l,u)}roundClean(){yt(fr)}destroy(){this.set(0,0,0,0,0,0,0,0),yt(this.buffer)}}const Ep=up(["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))),Ax=Ep[0],Px=Ep[1],dr=new Uint32Array(80),pr=new Uint32Array(80);let Oc=class extends vp{constructor(e=64){super(128,e,16,!1),this.Ah=Re[0]|0,this.Al=Re[1]|0,this.Bh=Re[2]|0,this.Bl=Re[3]|0,this.Ch=Re[4]|0,this.Cl=Re[5]|0,this.Dh=Re[6]|0,this.Dl=Re[7]|0,this.Eh=Re[8]|0,this.El=Re[9]|0,this.Fh=Re[10]|0,this.Fl=Re[11]|0,this.Gh=Re[12]|0,this.Gl=Re[13]|0,this.Hh=Re[14]|0,this.Hl=Re[15]|0}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=m|0}process(e,r){for(let b=0;b<16;b++,r+=4)dr[b]=e.getUint32(r),pr[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const E=dr[b-15]|0,$=pr[b-15]|0,B=wr(E,$,1)^wr(E,$,8)^mu(E,$,7),T=mr(E,$,1)^mr(E,$,8)^bu(E,$,7),R=dr[b-2]|0,A=pr[b-2]|0,j=wr(R,A,19)^Hi(R,A,61)^mu(R,A,6),N=mr(R,A,19)^Ki(R,A,61)^bu(R,A,6),C=ox(T,N,pr[b-7],pr[b-16]),O=ax(C,B,j,dr[b-7],dr[b-16]);dr[b]=O|0,pr[b]=C|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:m,Hh:v,Hl:I}=this;for(let b=0;b<80;b++){const E=wr(h,f,14)^wr(h,f,18)^Hi(h,f,41),$=mr(h,f,14)^mr(h,f,18)^Ki(h,f,41),B=h&p^~h&y,T=f&d^~f&m,R=cx(I,$,T,Px[b],pr[b]),A=lx(R,v,E,B,Ax[b],dr[b]),j=R|0,N=wr(i,s,28)^Hi(i,s,34)^Hi(i,s,39),C=mr(i,s,28)^Ki(i,s,34)^Ki(i,s,39),O=i&n^i&a^n&a,P=s&o^s&c^o&c;v=y|0,I=m|0,y=p|0,m=d|0,p=h|0,d=f|0,{h,l:f}=xt(l|0,u|0,A|0,j|0),l=a|0,u=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=_c(j,C,P);i=Ic(g,A,N,O),s=g|0}({h:i,l:s}=xt(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=xt(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=xt(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=xt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=xt(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:m}=xt(this.Gh|0,this.Gl|0,y|0,m|0),{h:v,l:I}=xt(this.Hh|0,this.Hl|0,v|0,I|0),this.set(i,s,n,o,a,c,l,u,h,f,p,d,y,m,v,I)}roundClean(){yt(dr,pr)}destroy(){yt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class Bx extends Oc{constructor(){super(48),this.Ah=Te[0]|0,this.Al=Te[1]|0,this.Bh=Te[2]|0,this.Bl=Te[3]|0,this.Ch=Te[4]|0,this.Cl=Te[5]|0,this.Dh=Te[6]|0,this.Dl=Te[7]|0,this.Eh=Te[8]|0,this.El=Te[9]|0,this.Fh=Te[10]|0,this.Fl=Te[11]|0,this.Gh=Te[12]|0,this.Gl=Te[13]|0,this.Hh=Te[14]|0,this.Hl=Te[15]|0}}const Ue=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Cx extends Oc{constructor(){super(32),this.Ah=Ue[0]|0,this.Al=Ue[1]|0,this.Bh=Ue[2]|0,this.Bl=Ue[3]|0,this.Ch=Ue[4]|0,this.Cl=Ue[5]|0,this.Dh=Ue[6]|0,this.Dl=Ue[7]|0,this.Eh=Ue[8]|0,this.El=Ue[9]|0,this.Fh=Ue[10]|0,this.Fl=Ue[11]|0,this.Gh=Ue[12]|0,this.Gl=Ue[13]|0,this.Hh=Ue[14]|0,this.Hl=Ue[15]|0}}const Rn=ys(()=>new $x),Tx=ys(()=>new Oc),Rx=ys(()=>new Bx),Ux=ys(()=>new Cx),Nx=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),we=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);function gr(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=H[2*t],l=H[2*t+1],u=H[2*e],h=H[2*e+1],f=H[2*r],p=H[2*r+1],d=H[2*i],y=H[2*i+1],m=_c(c,u,o);l=Ic(m,l,h,a),c=m|0,{Dh:y,Dl:d}={Dh:y^l,Dl:d^c},{Dh:y,Dl:d}={Dh:ex(y,d),Dl:tx(y)},{h:p,l:f}=xt(p,f,y,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:wr(h,u,24),Bl:mr(h,u,24)},H[2*t]=c,H[2*t+1]=l,H[2*e]=u,H[2*e+1]=h,H[2*r]=f,H[2*r+1]=p,H[2*i]=d,H[2*i+1]=y}function yr(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=H[2*t],l=H[2*t+1],u=H[2*e],h=H[2*e+1],f=H[2*r],p=H[2*r+1],d=H[2*i],y=H[2*i+1],m=_c(c,u,o);l=Ic(m,l,h,a),c=m|0,{Dh:y,Dl:d}={Dh:y^l,Dl:d^c},{Dh:y,Dl:d}={Dh:wr(y,d,16),Dl:mr(y,d,16)},{h:p,l:f}=xt(p,f,y,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:Hi(h,u,63),Bl:Ki(h,u,63)},H[2*t]=c,H[2*t+1]=l,H[2*e]=u,H[2*e+1]=h,H[2*r]=f,H[2*r+1]=p,H[2*i]=d,H[2*i+1]=y}function kx(t,e={},r,i,s){if(or(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=e;if(n!==void 0&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class jx extends Tn{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,or(e),or(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=ns(this.buffer)}update(e){Dr(this),e=It(e),St(e);const{blockLen:r,buffer:i,buffer32:s}=this,n=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<n;){this.pos===r&&(br(s),this.compress(s,0,!1),br(s),this.pos=0);const l=Math.min(r-this.pos,n-c),u=o+c;if(l===r&&!(u%4)&&c+l<n){const h=new Uint32Array(a,u,Math.floor((n-c)/4));br(h);for(let f=0;c+r<n;f+=s.length,c+=r)this.length+=r,this.compress(h,f,!1);br(h);continue}i.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Dr(this),Sc(e,this);const{pos:r,buffer32:i}=this;this.finished=!0,yt(this.buffer.subarray(r)),br(i),this.compress(i,0,!0),br(i);const s=ns(e);this.get().forEach((n,o)=>s[o]=Yt(n))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){const{buffer:r,length:i,finished:s,destroyed:n,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=n,e.finished=s,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Fx extends jx{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=we[0]|0,this.v0h=we[1]|0,this.v1l=we[2]|0,this.v1h=we[3]|0,this.v2l=we[4]|0,this.v2h=we[5]|0,this.v3l=we[6]|0,this.v3h=we[7]|0,this.v4l=we[8]|0,this.v4h=we[9]|0,this.v5l=we[10]|0,this.v5h=we[11]|0,this.v6l=we[12]|0,this.v6h=we[13]|0,this.v7l=we[14]|0,this.v7h=we[15]|0,kx(r,e,64,16,16);let{key:i,personalization:s,salt:n}=e,o=0;if(i!==void 0&&(i=It(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,n!==void 0){n=It(n);const a=ns(n);this.v4l^=Yt(a[0]),this.v4h^=Yt(a[1]),this.v5l^=Yt(a[2]),this.v5h^=Yt(a[3])}if(s!==void 0){s=It(s);const a=ns(s);this.v6l^=Yt(a[0]),this.v6h^=Yt(a[1]),this.v7l^=Yt(a[2]),this.v7h^=Yt(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:i,v1h:s,v2l:n,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:h,v5h:f,v6l:p,v6h:d,v7l:y,v7h:m}=this;return[e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m]}set(e,r,i,s,n,o,a,c,l,u,h,f,p,d,y,m){this.v0l=e|0,this.v0h=r|0,this.v1l=i|0,this.v1h=s|0,this.v2l=n|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=h|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=y|0,this.v7h=m|0}compress(e,r,i){this.get().forEach((c,l)=>H[l]=c),H.set(we,16);let{h:s,l:n}=lp(BigInt(this.length));H[24]=we[8]^n,H[25]=we[9]^s,i&&(H[28]=~H[28],H[29]=~H[29]);let o=0;const a=Nx;for(let c=0;c<12;c++)gr(0,4,8,12,e,r+2*a[o++]),yr(0,4,8,12,e,r+2*a[o++]),gr(1,5,9,13,e,r+2*a[o++]),yr(1,5,9,13,e,r+2*a[o++]),gr(2,6,10,14,e,r+2*a[o++]),yr(2,6,10,14,e,r+2*a[o++]),gr(3,7,11,15,e,r+2*a[o++]),yr(3,7,11,15,e,r+2*a[o++]),gr(0,5,10,15,e,r+2*a[o++]),yr(0,5,10,15,e,r+2*a[o++]),gr(1,6,11,12,e,r+2*a[o++]),yr(1,6,11,12,e,r+2*a[o++]),gr(2,7,8,13,e,r+2*a[o++]),yr(2,7,8,13,e,r+2*a[o++]),gr(3,4,9,14,e,r+2*a[o++]),yr(3,4,9,14,e,r+2*a[o++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],yt(H)}destroy(){this.destroyed=!0,yt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Lx=fx(t=>new Fx(t)),Mx="https://rpc.walletconnect.org/v1";function xp(t){const e=`Ethereum Signed Message:
|
|
@@ -12,4 +12,4 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(_x(r)).toStr
|
|
|
12
12
|
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const f=$i(e[h].accounts);f.includes(h)||(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
13
13
|
Required: ${h}
|
|
14
14
|
Approved: ${f.toString()}`))}),o.forEach(h=>{i||(qr(s[h].methods,n[h].methods)?qr(s[h].events,n[h].events)||(i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=z("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function CI(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(s=>{e[s]={methods:t[r].methods,events:t[r].events}})}),e}function nh(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function TI(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:$i(t[r].accounts)?.forEach(s=>{e[s]={accounts:t[r].accounts.filter(n=>n.includes(`${s}:`)),methods:t[r].methods,events:t[r].events}})}),e}function RI(t,e){return Cc(t)&&t<=e.max&&t>=e.min}function oh(){const t=gs();return new Promise(e=>{switch(t){case nt.browser:e(UI());break;case nt.reactNative:e(NI());break;case nt.node:e(kI());break;default:e(!0)}})}function UI(){return Di()&&navigator?.onLine}async function NI(){return $r()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function kI(){return!0}function jI(t){switch(gs()){case nt.browser:FI(t);break;case nt.reactNative:LI(t);break}}function FI(t){!$r()&&Di()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function LI(t){$r()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function MI(){var t;return Di()&&nr.getDocument()?((t=nr.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const jo={};class ji{static get(e){return jo[e]}static set(e,r){jo[e]=r}static delete(e){delete jo[e]}}function qI(t){const e=fs.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function zI({publicKey:t,signature:e,payload:r}){var i;const s=Ta(r.method),n=128|parseInt(((i=r.version)==null?void 0:i.toString())||"4"),o=KI(r.address),a=r.era==="00"?new Uint8Array([0]):Ta(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${HI(r.tip)}`),h=GI(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...s]),p=WI(f.length+1);return new Uint8Array([...p,n,...f])}function VI(t){const e=Ta(t),r=N2.blake2b(e,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function Ta(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function HI(t){return t.startsWith("0x")?t.slice(2):t}function KI(t){const e=fs.decode(t)[0];return e===42?0:e===60?2:1}function WI(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 GI(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 YI(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),r=qI(t.transaction.address),i=zI({publicKey:r,signature:e,payload:t.transaction}),s=Buffer.from(i).toString("hex");return VI(s)}function Tc({logger:t,name:e}){const r=typeof t=="string"?rp({opts:{level:t,name:e}}).logger:t;return r.level=typeof t=="string"?t:t.level,r}class Qr{}let ZI=class extends Qr{constructor(e){super()}};const ah=q.FIVE_SECONDS,ei={pulse:"heartbeat_pulse"};let JI=class lg extends ZI{constructor(e){super(e),this.events=new wt.EventEmitter,this.interval=ah,this.interval=e?.interval||ah}static async init(e){const r=new lg(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),q.toMiliseconds(this.interval))}pulse(){this.events.emit(ei.pulse)}};const XI=/"(?:_|\\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*:/,QI=/"(?: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*:/,eS=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function tS(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){rS(t);return}return e}function rS(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function js(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(!eS.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(XI.test(t)||QI.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,tS)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function iS(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return iS(t(...e))}catch(r){return Promise.reject(r)}}function sS(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function nS(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Ys(t){if(sS(t))return String(t);if(nS(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Ys(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ra="base64:";function oS(t){return typeof t=="string"?t:Ra+lS(t)}function aS(t){return typeof t!="string"||!t.startsWith(Ra)?t:cS(t.slice(Ra.length))}function cS(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function lS(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ve(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function uS(...t){return Ve(t.join(":"))}function Fs(t){return t=Ve(t),t?t+":":""}function hS(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 fS(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const dS="memory",pS=()=>{const t=new Map;return{name:dS,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 gS(t={}){const e={mounts:{"":t.driver||pS()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},i=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(l,u)=>{if(e.watching){u=Ve(u);for(const h of e.watchListeners)h(l,u)}},n=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await ch(e.mounts[l],s,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const f=new Map,p=d=>{let y=f.get(d.base);return y||(y={driver:d.driver,base:d.base,items:[]},f.set(d.base,y)),y};for(const d of l){const y=typeof d=="string",m=Ve(y?d:d.key),v=y?void 0:d.value,I=y||!d.options?u:{...u,...d.options},b=r(m);p(b).items.push({key:m,value:v,relativeKey:b.relativeKey,options:I})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(l,u={}){l=Ve(l);const{relativeKey:h,driver:f}=r(l);return xe(f.hasItem,h,u)},getItem(l,u={}){l=Ve(l);const{relativeKey:h,driver:f}=r(l);return xe(f.getItem,h,u).then(p=>js(p))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?xe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(p=>({key:uS(h.base,p.key),value:js(p.value)}))):Promise.all(h.items.map(f=>xe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:js(p)})))))},getItemRaw(l,u={}){l=Ve(l);const{relativeKey:h,driver:f}=r(l);return f.getItemRaw?xe(f.getItemRaw,h,u):xe(f.getItem,h,u).then(p=>aS(p))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Ve(l);const{relativeKey:f,driver:p}=r(l);p.setItem&&(await xe(p.setItem,f,Ys(u),h),p.watch||s("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return xe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Ys(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>xe(h.driver.setItem,f.relativeKey,Ys(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Ve(l);const{relativeKey:f,driver:p}=r(l);if(p.setItemRaw)await xe(p.setItemRaw,f,u,h);else if(p.setItem)await xe(p.setItem,f,oS(u),h);else return;p.watch||s("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Ve(l);const{relativeKey:h,driver:f}=r(l);f.removeItem&&(await xe(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await xe(f.removeItem,h+"$",u),f.watch||s("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Ve(l);const{relativeKey:h,driver:f}=r(l),p=Object.create(null);if(f.getMeta&&Object.assign(p,await xe(f.getMeta,h,u)),!u.nativeOnly){const d=await xe(f.getItem,h+"$",u).then(y=>js(y));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=Fs(l);const h=i(l,!0);let f=[];const p=[];let d=!0;for(const m of h){m.driver.flags?.maxDepth||(d=!1);const v=await xe(m.driver.getKeys,m.relativeBase,u);for(const I of v){const b=m.mountpoint+Ve(I);f.some(E=>b.startsWith(E))||p.push(b)}f=[m.mountpoint,...f.filter(I=>!I.startsWith(m.mountpoint))]}const y=u.maxDepth!==void 0&&!d;return p.filter(m=>(!y||hS(m,u.maxDepth))&&fS(m,l))},async clear(l,u={}){l=Fs(l),await Promise.all(i(l,!1).map(async h=>{if(h.driver.clear)return xe(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(p=>h.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>lh(l)))},async watch(l){return await n(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=Fs(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(ch(u,s,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){l=Fs(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await lh(e.mounts[l]),e.mountpoints=e.mountpoints.filter(h=>h!==l),delete e.mounts[l])},getMount(l=""){l=Ve(l)+":";const u=r(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Ve(l),i(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function ch(t,e,r){return t.watch?t.watch((i,s)=>e(i,r+s)):()=>{}}async function lh(t){typeof t.dispose=="function"&&await xe(t.dispose)}function ti(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function ug(t,e){let r;const i=()=>{if(r)return r;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),r=ti(s),r.then(n=>{n.onclose=()=>r=void 0},()=>{}),r};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Fo;function vs(){return Fo||(Fo=ug("keyval-store","keyval")),Fo}function uh(t,e=vs()){return e("readonly",r=>ti(r.get(t)))}function yS(t,e,r=vs()){return r("readwrite",i=>(i.put(e,t),ti(i.transaction)))}function wS(t,e=vs()){return e("readwrite",r=>(r.delete(t),ti(r.transaction)))}function mS(t=vs()){return t("readwrite",e=>(e.clear(),ti(e.transaction)))}function bS(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},ti(t.transaction)}function vS(t=vs()){return t("readonly",e=>{if(e.getAllKeys)return ti(e.getAllKeys());const r=[];return bS(e,i=>r.push(i.key)).then(()=>r)})}const ES="idb-keyval";var xS=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=s=>e+s;let i;return t.dbName&&t.storeName&&(i=ug(t.dbName,t.storeName)),{name:ES,options:t,async hasItem(s){return!(typeof await uh(r(s),i)>"u")},async getItem(s){return await uh(r(s),i)??null},setItem(s,n){return yS(r(s),n,i)},removeItem(s){return wS(r(s),i)},getKeys(){return vS(i)},clear(){return mS(i)}}};const _S="WALLET_CONNECT_V2_INDEXED_DB",IS="keyvaluestorage";let SS=class{constructor(){this.indexedDb=gS({driver:xS({dbName:_S,storeName:IS})})}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,Yr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var Lo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Zs={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 Lo<"u"&&Lo.localStorage?Zs.exports=Lo.localStorage:typeof window<"u"&&window.localStorage?Zs.exports=window.localStorage:Zs.exports=new e})();function OS(t){var e;return[t[0],Gr((e=t[1])!=null?e:"")]}let DS=class{constructor(){this.localStorage=Zs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(OS)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return Gr(r)}async setItem(e,r){this.localStorage.setItem(e,Yr(r))}async removeItem(e){this.localStorage.removeItem(e)}};const $S="wc_storage_version",hh=1,AS=async(t,e,r)=>{const i=$S,s=await e.getItem(i);if(s&&s>=hh){r(e);return}const n=await t.getKeys();if(!n.length){r(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(i,hh),r(e),PS(t,o)},PS=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let BS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new DS;this.storage=e;try{const r=new SS;AS(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 CS=Object.defineProperty,TS=(t,e,r)=>e in t?CS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fh=(t,e,r)=>TS(t,typeof e!="symbol"?e+"":e,r);let RS=class extends Qr{constructor(e){super(),this.opts=e,fh(this,"protocol","wc"),fh(this,"version",2)}};var US=Object.defineProperty,NS=(t,e,r)=>e in t?US(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kS=(t,e,r)=>NS(t,e+"",r);let jS=class extends Qr{constructor(e,r){super(),this.core=e,this.logger=r,kS(this,"records",new Map)}},FS=class{constructor(e,r){this.logger=e,this.core=r}},LS=class extends Qr{constructor(e,r){super(),this.relayer=e,this.logger=r}},MS=class extends Qr{constructor(e){super()}},qS=class{constructor(e,r,i,s){this.core=e,this.logger=r,this.name=i}},zS=class extends Qr{constructor(e,r){super(),this.relayer=e,this.logger=r}},VS=class extends Qr{constructor(e,r){super(),this.core=e,this.logger=r}},HS=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},KS=class{constructor(e,r){this.projectId=e,this.logger=r}},WS=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var GS=Object.defineProperty,YS=(t,e,r)=>e in t?GS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,dh=(t,e,r)=>YS(t,typeof e!="symbol"?e+"":e,r);let ZS=class{constructor(e){this.opts=e,dh(this,"protocol","wc"),dh(this,"version",2)}},JS=class{constructor(e){this.client=e}};const XS="PARSE_ERROR",QS="INVALID_REQUEST",e8="METHOD_NOT_FOUND",t8="INVALID_PARAMS",hg="INTERNAL_ERROR",Rc="SERVER_ERROR",r8=[-32700,-32600,-32601,-32602,-32603],Ji={[XS]:{code:-32700,message:"Parse error"},[QS]:{code:-32600,message:"Invalid Request"},[e8]:{code:-32601,message:"Method not found"},[t8]:{code:-32602,message:"Invalid params"},[hg]:{code:-32603,message:"Internal error"},[Rc]:{code:-32e3,message:"Server error"}},fg=Rc;function i8(t){return r8.includes(t)}function ph(t){return Object.keys(Ji).includes(t)?Ji[t]:Ji[fg]}function s8(t){const e=Object.values(Ji).find(r=>r.code===t);return e||Ji[fg]}function dg(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Mo={};var Ua=function(t,e){return Ua=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},Ua(t,e)};function n8(t,e){Ua(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Na=function(){return Na=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Na.apply(this,arguments)};function o8(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function a8(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function c8(t,e){return function(r,i){e(r,i,t)}}function l8(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function u8(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?n(u.value):s(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function h8(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=l[0]&2?s.return:l[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,l[1])).done)return n;switch(s=0,n&&(l=[l[0]&2,n.value]),l[0]){case 0:case 1:n=l;break;case 4:return r.label++,{value:l[1],done:!1};case 5:r.label++,s=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!n||l[1]>n[0]&&l[1]<n[3])){r.label=l[1];break}if(l[0]===6&&r.label<n[1]){r.label=n[1],n=l;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(l);break}n[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],s=0}finally{i=n=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function f8(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function d8(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ka(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function p8(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(pg(arguments[e]));return t}function g8(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function cs(t){return this instanceof cs?(this.v=t,this):new cs(t)}function y8(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(p){return new Promise(function(d,y){n.push([f,p,d,y])>1||a(f,p)})})}function a(f,p){try{c(i[f](p))}catch(d){h(n[0][3],d)}}function c(f){f.value instanceof cs?Promise.resolve(f.value.v).then(l,u):h(n[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function w8(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:cs(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function m8(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof ka=="function"?ka(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(l){n({value:l,done:a})},o)}}function b8(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function v8(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 E8(t){return t&&t.__esModule?t:{default:t}}function x8(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function _8(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 I8=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Na},__asyncDelegator:w8,__asyncGenerator:y8,__asyncValues:m8,__await:cs,__awaiter:u8,__classPrivateFieldGet:x8,__classPrivateFieldSet:_8,__createBinding:f8,__decorate:a8,__exportStar:d8,__extends:n8,__generator:h8,__importDefault:E8,__importStar:v8,__makeTemplateObject:b8,__metadata:l8,__param:c8,__read:pg,__rest:o8,__spread:p8,__spreadArrays:g8,__values:ka},Symbol.toStringTag,{value:"Module"})),S8=Of(I8);var Wt={},gh;function O8(){if(gh)return Wt;gh=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.isBrowserCryptoAvailable=Wt.getSubtleCrypto=Wt.getBrowerCrypto=void 0;function t(){return(Ut===null||Ut===void 0?void 0:Ut.crypto)||(Ut===null||Ut===void 0?void 0:Ut.msCrypto)||{}}Wt.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Wt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Wt.isBrowserCryptoAvailable=r,Wt}var Gt={},yh;function D8(){if(yh)return Gt;yh=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.isBrowser=Gt.isNode=Gt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Gt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Gt.isNode=e;function r(){return!t()&&!e()}return Gt.isBrowser=r,Gt}var wh;function $8(){return wh||(wh=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=S8;e.__exportStar(O8(),t),e.__exportStar(D8(),t)})(Mo)),Mo}var A8=$8();function Tt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ir(t=6){return BigInt(Tt(t))}function _t(t,e,r){return{id:r||Tt(),jsonrpc:"2.0",method:t,params:e}}function ls(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Mn(t,e,r){return{id:t,jsonrpc:"2.0",error:P8(e)}}function P8(t,e){return typeof t>"u"?ph(hg):(typeof t=="string"&&(t=Object.assign(Object.assign({},ph(Rc)),{message:t})),i8(t.code)&&(t=s8(t.code)),t)}class B8{}class C8 extends B8{constructor(){super()}}class T8 extends C8{constructor(e){super()}}const R8="^https?:",U8="^wss?:";function N8(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function gg(t,e){const r=N8(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function mh(t){return gg(t,R8)}function bh(t){return gg(t,U8)}function k8(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function yg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Uc(t){return yg(t)&&"method"in t}function qn(t){return yg(t)&&(Rt(t)||dt(t))}function Rt(t){return"result"in t}function dt(t){return"error"in t}let Nc=class extends T8{constructor(e){super(e),this.events=new wt.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(_t(e.method,e.params||[],e.id||Ir().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{dt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),qn(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const j8=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),F8=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",vh=t=>t.split("?")[0],Eh=10,L8=j8();let M8=class{constructor(e){if(this.url=e,this.events=new wt.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(Yr(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,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=A8.isReactNative()?void 0:{rejectUnauthorized:!k8(e)},n=new L8(e,[],s);F8()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?Gr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Mn(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dg(e,vh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Eh&&this.events.setMaxListeners(Eh)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${vh(this.url)}`));return this.events.emit("register_error",r),r}};var q8={};const wg="wc",mg=2,ja="core",Mt=`${wg}@2:${ja}:`,z8={logger:"error"},V8={database:":memory:"},H8="crypto",xh="client_ed25519_seed",K8=q.ONE_DAY,W8="keychain",G8="0.3",Y8="messages",Z8="0.3",J8=q.SIX_HOURS,X8="publisher",bg="irn",Q8="error",vg="wss://relay.walletconnect.org",eO="relayer",pe={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"},tO="_subscription",ct={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},rO=.1,Fa="2.23.1",ae={link_mode:"link_mode",relay:"relay"},Js={inbound:"inbound",outbound:"outbound"},iO="0.3",sO="WALLETCONNECT_CLIENT_ID",_h="WALLETCONNECT_LINK_MODE_APPS",rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},nO="subscription",oO="0.3",aO="pairing",cO="0.3",Fi={wc_pairingDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:q.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:q.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:q.ONE_DAY,prompt:!1,tag:0},res:{ttl:q.ONE_DAY,prompt:!1,tag:0}}},Fr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},bt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},lO="history",uO="0.3",hO="expirer",ut={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},fO="0.3",dO="verify-api",pO="https://verify.walletconnect.com",Eg="https://verify.walletconnect.org",Xi=Eg,gO=`${Xi}/v3`,yO=[pO,Eg],wO="echo",mO="https://echo.walletconnect.com",Ct={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Zt={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},vt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",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"},Tr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Rr={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},Li={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},bO=.1,vO="event-client",EO=86400,xO="https://pulse.walletconnect.org/batch";function _O(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,m=0,v=0,I=d.length;v!==I&&d[v]===0;)v++,y++;for(var b=(I-v)*u+1>>>0,E=new Uint8Array(b);v!==I;){for(var $=d[v],B=0,T=b-1;($!==0||B<m)&&T!==-1;T--,B++)$+=256*E[T]>>>0,E[T]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");m=B,v++}for(var R=b-m;R!==b&&E[R]===0;)R++;for(var A=c.repeat(y);R<b;++R)A+=t.charAt(E[R]);return A}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var m=0,v=0;d[y]===c;)m++,y++;for(var I=(d.length-y)*l+1>>>0,b=new Uint8Array(I);d[y];){var E=r[d.charCodeAt(y)];if(E===255)return;for(var $=0,B=I-1;(E!==0||$<v)&&B!==-1;B--,$++)E+=a*b[B]>>>0,b[B]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");v=$,y++}if(d[y]!==" "){for(var T=I-v;T!==I&&b[T]===0;)T++;for(var R=new Uint8Array(m+(I-T)),A=m;T!==I;)R[A++]=b[T++];return R}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var IO=_O,SO=IO;const xg=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")},OO=t=>new TextEncoder().encode(t),DO=t=>new TextDecoder().decode(t);class $O{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 AO{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 _g(this,e)}}class PO{constructor(e){this.decoders=e}or(e){return _g(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 _g=(t,e)=>new PO({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class BO{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new $O(e,r,i),this.decoder=new AO(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const zn=({name:t,prefix:e,encode:r,decode:i})=>new BO(t,e,r,i),Es=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=SO(r,e);return zn({prefix:t,name:e,encode:i,decode:n=>xg(s(n))})},CO=(t,e,r,i)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},TO=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Ce=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>zn({prefix:e,name:t,encode(s){return TO(s,i,r)},decode(s){return CO(s,i,r,t)}}),RO=zn({prefix:"\0",name:"identity",encode:t=>DO(t),decode:t=>OO(t)});var UO=Object.freeze({__proto__:null,identity:RO});const NO=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var kO=Object.freeze({__proto__:null,base2:NO});const jO=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var FO=Object.freeze({__proto__:null,base8:jO});const LO=Es({prefix:"9",name:"base10",alphabet:"0123456789"});var MO=Object.freeze({__proto__:null,base10:LO});const qO=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zO=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var VO=Object.freeze({__proto__:null,base16:qO,base16upper:zO});const HO=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),KO=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),WO=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),GO=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YO=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ZO=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),JO=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),XO=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),QO=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var eD=Object.freeze({__proto__:null,base32:HO,base32upper:KO,base32pad:WO,base32padupper:GO,base32hex:YO,base32hexupper:ZO,base32hexpad:JO,base32hexpadupper:XO,base32z:QO});const tD=Es({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rD=Es({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var iD=Object.freeze({__proto__:null,base36:tD,base36upper:rD});const sD=Es({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nD=Es({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var oD=Object.freeze({__proto__:null,base58btc:sD,base58flickr:nD});const aD=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cD=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lD=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uD=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hD=Object.freeze({__proto__:null,base64:aD,base64pad:cD,base64url:lD,base64urlpad:uD});const Ig=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),fD=Ig.reduce((t,e,r)=>(t[r]=e,t),[]),dD=Ig.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function pD(t){return t.reduce((e,r)=>(e+=fD[r],e),"")}function gD(t){const e=[];for(const r of t){const i=dD[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const yD=zn({prefix:"🚀",name:"base256emoji",encode:pD,decode:gD});var wD=Object.freeze({__proto__:null,base256emoji:yD}),mD=Sg,Ih=128,bD=-128,vD=Math.pow(2,31);function Sg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=vD;)e[r++]=t&255|Ih,t/=128;for(;t&bD;)e[r++]=t&255|Ih,t>>>=7;return e[r]=t|0,Sg.bytes=r-i+1,e}var ED=La,xD=128,Sh=127;function La(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw La.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Sh)<<s:(o&Sh)*Math.pow(2,s),s+=7}while(o>=xD);return La.bytes=n-i,r}var _D=Math.pow(2,7),ID=Math.pow(2,14),SD=Math.pow(2,21),OD=Math.pow(2,28),DD=Math.pow(2,35),$D=Math.pow(2,42),AD=Math.pow(2,49),PD=Math.pow(2,56),BD=Math.pow(2,63),CD=function(t){return t<_D?1:t<ID?2:t<SD?3:t<OD?4:t<DD?5:t<$D?6:t<AD?7:t<PD?8:t<BD?9:10},TD={encode:mD,decode:ED,encodingLength:CD},Og=TD;const Oh=(t,e,r=0)=>(Og.encode(t,e,r),e),Dh=t=>Og.encodingLength(t),Ma=(t,e)=>{const r=e.byteLength,i=Dh(t),s=i+Dh(r),n=new Uint8Array(s+r);return Oh(t,n,0),Oh(r,n,i),n.set(e,s),new RD(t,r,e,n)};class RD{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const Dg=({name:t,code:e,encode:r})=>new UD(t,e,r);class UD{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?Ma(this.code,r):r.then(i=>Ma(this.code,i))}else throw Error("Unknown type, must be binary type")}}const $g=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ND=Dg({name:"sha2-256",code:18,encode:$g("SHA-256")}),kD=Dg({name:"sha2-512",code:19,encode:$g("SHA-512")});var jD=Object.freeze({__proto__:null,sha256:ND,sha512:kD});const Ag=0,FD="identity",Pg=xg,LD=t=>Ma(Ag,Pg(t)),MD={code:Ag,name:FD,encode:Pg,digest:LD};var qD=Object.freeze({__proto__:null,identity:MD});new TextEncoder,new TextDecoder;const $h={...UO,...kO,...FO,...MO,...VO,...eD,...iD,...oD,...hD,...wD};({...jD,...qD});function Bg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function zD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Bg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Cg(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Ah=Cg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),qo=Cg("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=zD(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),VD={utf8:Ah,"utf-8":Ah,hex:$h.base16,latin1:qo,ascii:qo,binary:qo,...$h};function HD(t,e="utf8"){const r=VD[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Bg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}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,Pt=(t,e,r)=>WD(t,typeof e!="symbol"?e+"":e,r);class GD{constructor(e,r){this.core=e,this.logger=r,Pt(this,"keychain",new Map),Pt(this,"name",W8),Pt(this,"version",G8),Pt(this,"initialized",!1),Pt(this,"storagePrefix",Mt),Pt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Pt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Pt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),Pt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),Pt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=ot(r,this.name)}get context(){return Xe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,va(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ea(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var YD=Object.defineProperty,ZD=(t,e,r)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ve=(t,e,r)=>ZD(t,typeof e!="symbol"?e+"":e,r);class JD{constructor(e,r,i){this.core=e,this.logger=r,ve(this,"name",H8),ve(this,"keychain"),ve(this,"randomSessionIdentifier",Ca()),ve(this,"initialized",!1),ve(this,"clientId"),ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ve(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=Zl(s),o=Kd(n.publicKey);return this.clientId=o,o}),ve(this,"generateKeyPair",()=>{this.isInitialized();const s=C3();return this.setPrivateKey(s.publicKey,s.privateKey)}),ve(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=Zl(n),a=this.randomSessionIdentifier;return await Uv(a,s,K8,o)}),ve(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=T3(a,n);return this.setSymKey(c,o)}),ve(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||Gs(s);return await this.keychain.set(o,s),o}),ve(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),ve(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),ve(this,"encode",async(s,n,o)=>{this.isInitialized();const a=ng(o),c=Yr(n);if(Wu(a))return N3(c,o?.encoding);if(Ku(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const l=this.getSymKey(s),{type:u,senderPublicKey:h}=a;return R3({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})}),ve(this,"decode",async(s,n,o)=>{this.isInitialized();const a=j3(n,o);if(Wu(a)){const c=k3(n,o?.encoding);return Gr(c)}if(Ku(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=U3({symKey:c,encoded:n,encoding:o?.encoding});return Gr(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ve(this,"getPayloadType",(s,n=Ge)=>{const o=as({encoded:s,encoding:n});return Jr(o.type)}),ve(this,"getPayloadSenderPublicKey",(s,n=Ge)=>{const o=as({encoded:s,encoding:n});return o.senderPublicKey?Je(o.senderPublicKey,Me):void 0}),this.core=e,this.logger=ot(r,this.name),this.keychain=i||new GD(this.core,this.logger)}get context(){return Xe(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(xh)}catch{e=Ca(),await this.keychain.set(xh,e)}return HD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XD=Object.defineProperty,QD=Object.defineProperties,e$=Object.getOwnPropertyDescriptors,Ph=Object.getOwnPropertySymbols,t$=Object.prototype.hasOwnProperty,r$=Object.prototype.propertyIsEnumerable,qa=(t,e,r)=>e in t?XD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,i$=(t,e)=>{for(var r in e||(e={}))t$.call(e,r)&&qa(t,r,e[r]);if(Ph)for(var r of Ph(e))r$.call(e,r)&&qa(t,r,e[r]);return t},s$=(t,e)=>QD(t,e$(e)),Qe=(t,e,r)=>qa(t,typeof e!="symbol"?e+"":e,r);class n$ extends FS{constructor(e,r){super(e,r),this.logger=e,this.core=r,Qe(this,"messages",new Map),Qe(this,"messagesWithoutClientAck",new Map),Qe(this,"name",Y8),Qe(this,"version",Z8),Qe(this,"initialized",!1),Qe(this,"storagePrefix",Mt),Qe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Qe(this,"set",async(i,s,n)=>{this.isInitialized();const o=ft(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===Js.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,s$(i$({},c),{[o]:s}))}return await this.persist(),o}),Qe(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),Qe(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Qe(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=ft(s);return typeof n[o]<"u"}),Qe(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=ft(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),Qe(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=ot(e,this.name),this.core=r}get context(){return Xe(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,va(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,va(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ea(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ea(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var o$=Object.defineProperty,a$=Object.defineProperties,c$=Object.getOwnPropertyDescriptors,Bh=Object.getOwnPropertySymbols,l$=Object.prototype.hasOwnProperty,u$=Object.prototype.propertyIsEnumerable,za=(t,e,r)=>e in t?o$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ci=(t,e)=>{for(var r in e||(e={}))l$.call(e,r)&&za(t,r,e[r]);if(Bh)for(var r of Bh(e))u$.call(e,r)&&za(t,r,e[r]);return t},Ch=(t,e)=>a$(t,c$(e)),lt=(t,e,r)=>za(t,typeof e!="symbol"?e+"":e,r);class h$ extends LS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,lt(this,"events",new wt.EventEmitter),lt(this,"name",X8),lt(this,"queue",new Map),lt(this,"publishTimeout",q.toMiliseconds(q.ONE_MINUTE)),lt(this,"initialPublishTimeout",q.toMiliseconds(q.ONE_SECOND*15)),lt(this,"needsTransportRestart",!1),lt(this,"publish",async(i,s,n)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const h=n?.ttl||J8,f=n?.prompt||!1,p=n?.tag||0,d=n?.id||Ir().toString(),y=di(wn().protocol),m={id:d,method:n?.publishMethod||y.publish,params:ci({topic:i,message:s,ttl:h,prompt:f,tag:p,attestation:n?.attestation},n?.tvf)},v=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{Ie((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Ie((c=m.params)==null?void 0:c.tag)&&((l=m.params)==null||delete l.tag);const I=new Promise(async b=>{const E=({id:B})=>{var T;((T=m.id)==null?void 0:T.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(pe.publish,E),b())};this.relayer.events.on(pe.publish,E);const $=jt(new Promise((B,T)=>{this.rpcPublish(m,n).then(B).catch(R=>{this.logger.warn(R,R?.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await $,this.events.removeListener(pe.publish,E)}catch(B){this.queue.set(d,{request:m,opts:n,attempt:1}),this.logger.warn(B,B?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:s,opts:n}}),await jt(I,this.publishTimeout,v)}catch(I){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(I),(u=n?.internal)!=null&&u.throwOnFailedPublish)throw I}finally{this.queue.delete(d)}}),lt(this,"publishCustom",async i=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:p,prompt:d,tag:y,ttl:m=q.FIVE_MINUTES}=u,v=u.id||Ir().toString(),I=di(wn().protocol),b=p||I.publish,E={id:v,method:b,params:ci(Ch(ci({},l),{ttl:m,prompt:d,tag:y,attestation:h}),f)},$=`Failed to publish custom payload, please try again. id:${v} tag:${y}`;try{Ie((s=E.params)==null?void 0:s.prompt)&&((n=E.params)==null||delete n.prompt),Ie((o=E.params)==null?void 0:o.tag)&&((a=E.params)==null||delete a.tag);const B=new Promise(async T=>{const R=({id:j})=>{var N;((N=E.id)==null?void 0:N.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(pe.publish,R),T())};this.relayer.events.on(pe.publish,R);const A=jt(new Promise((j,N)=>{this.rpcPublish(E,u).then(j).catch(C=>{this.logger.warn(C,C?.message),N(C)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${v} tag:${y}`);try{await A,this.events.removeListener(pe.publish,R)}catch(j){this.queue.set(v,{request:E,opts:u,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:v,payload:l,opts:u}}),await jt(B,this.publishTimeout,$)}catch(B){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(B),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw B}finally{this.queue.delete(v)}}),lt(this,"on",(i,s)=>{this.events.on(i,s)}),lt(this,"once",(i,s)=>{this.events.once(i,s)}),lt(this,"off",(i,s)=>{this.events.off(i,s)}),lt(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=ot(r,this.name),this.registerEventListeners()}get context(){return Xe(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(pe.publish,ci(ci({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const s=e.attempt+1;this.queue.set(r,Ch(ci({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(ei.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pe.connection_stalled);return}this.checkQueue()}),this.relayer.on(pe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var f$=Object.defineProperty,d$=(t,e,r)=>e in t?f$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,li=(t,e,r)=>d$(t,typeof e!="symbol"?e+"":e,r);class p${constructor(){li(this,"map",new Map),li(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),li(this,"get",e=>this.map.get(e)||[]),li(this,"exists",(e,r)=>this.get(e).includes(r)),li(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),li(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var g$=Object.defineProperty,y$=Object.defineProperties,w$=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,m$=Object.prototype.hasOwnProperty,b$=Object.prototype.propertyIsEnumerable,Va=(t,e,r)=>e in t?g$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mi=(t,e)=>{for(var r in e||(e={}))m$.call(e,r)&&Va(t,r,e[r]);if(Th)for(var r of Th(e))b$.call(e,r)&&Va(t,r,e[r]);return t},zo=(t,e)=>y$(t,w$(e)),ne=(t,e,r)=>Va(t,typeof e!="symbol"?e+"":e,r);class v$ extends zS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ne(this,"subscriptions",new Map),ne(this,"topicMap",new p$),ne(this,"events",new wt.EventEmitter),ne(this,"name",nO),ne(this,"version",oO),ne(this,"pending",new Map),ne(this,"cached",[]),ne(this,"initialized",!1),ne(this,"storagePrefix",Mt),ne(this,"subscribeTimeout",q.toMiliseconds(q.ONE_MINUTE)),ne(this,"initialSubscribeTimeout",q.toMiliseconds(q.ONE_SECOND*15)),ne(this,"clientId"),ne(this,"batchSubscribeTopicsLimit",500),ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ne(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=wn(s),a={topic:i,relay:o,transportType:s?.transportType};(n=s?.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ne(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ne(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ne(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ne(this,"on",(i,s)=>{this.events.on(i,s)}),ne(this,"once",(i,s)=>{this.events.once(i,s)}),ne(this,"off",(i,s)=>{this.events.off(i,s)}),ne(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ne(this,"start",async()=>{await this.onConnect()}),ne(this,"stop",async()=>{await this.onDisconnect()}),ne(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ne(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),ne(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(ei.pulse,async()=>{await this.checkPending()}),this.events.on(rt.created,async i=>{const s=rt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(rt.deleted,async i=>{const s=rt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=ot(r,this.name),this.clientId=""}get context(){return Xe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const s=wn(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=ce("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s,n;const o=await this.getSubscriptionId(e);if((s=i?.internal)!=null&&s.skipSubscribe)return o;(!i||i?.transportType===ae.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:di(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{if(i?.transportType===ae.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},q.toMiliseconds(q.ONE_SECOND)),o;const l=new Promise(async h=>{const f=p=>{p.topic===e&&(this.events.removeListener(rt.created,f),h(p.id))};this.events.on(rt.created,f);try{const p=await jt(new Promise((d,y)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m?.message),y(m)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rt.created,f),h(p)}catch{}}),u=await jt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pe.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:di(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await jt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:di(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await jt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:di(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,zo(Mi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,Mi({},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,Mi({},r)),this.topicMap.set(r.topic,e),this.events.emit(rt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(rt.deleted,zo(Mi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>zo(Mi({},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 XE(q.toMiliseconds(q.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return ft(e+await this.getClientId())}}var E$=Object.defineProperty,Rh=Object.getOwnPropertySymbols,x$=Object.prototype.hasOwnProperty,_$=Object.prototype.propertyIsEnumerable,Ha=(t,e,r)=>e in t?E$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Uh=(t,e)=>{for(var r in e||(e={}))x$.call(e,r)&&Ha(t,r,e[r]);if(Rh)for(var r of Rh(e))_$.call(e,r)&&Ha(t,r,e[r]);return t},te=(t,e,r)=>Ha(t,typeof e!="symbol"?e+"":e,r);class I$ extends MS{constructor(e){var r;super(e),te(this,"protocol","wc"),te(this,"version",2),te(this,"core"),te(this,"logger"),te(this,"events",new wt.EventEmitter),te(this,"provider"),te(this,"messages"),te(this,"subscriber"),te(this,"publisher"),te(this,"name",eO),te(this,"transportExplicitlyClosed",!1),te(this,"initialized",!1),te(this,"connectionAttemptInProgress",!1),te(this,"relayUrl"),te(this,"projectId"),te(this,"packageName"),te(this,"bundleId"),te(this,"hasExperiencedNetworkDisruption",!1),te(this,"pingTimeout"),te(this,"heartBeatTimeout",q.toMiliseconds(q.THIRTY_SECONDS+q.FIVE_SECONDS)),te(this,"reconnectTimeout"),te(this,"connectPromise"),te(this,"reconnectInProgress",!1),te(this,"requestsInFlight",[]),te(this,"connectTimeout",q.toMiliseconds(q.ONE_SECOND*15)),te(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||Ir().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),te(this,"resetPingTimeout",()=>{hn()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),te(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),te(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(pe.connect)}),te(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),te(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(pe.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),te(this,"registerProviderListeners",()=>{this.provider.on(ct.payload,this.onPayloadHandler),this.provider.on(ct.connect,this.onConnectHandler),this.provider.on(ct.disconnect,this.onDisconnectHandler),this.provider.on(ct.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Tc({logger:(r=e.logger)!=null?r:Q8,name:this.name}),this.messages=new n$(this.logger,e.core),this.subscriber=new v$(this,this.logger),this.publisher=new h$(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||vg,NE()?this.packageName=pu():kE()&&(this.bundleId=pu()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return Xe(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:ae.relay},Js.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=r?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(rt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(rt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,Uh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await jt(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 oh())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=de(q.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(pe.message,e),await this.recordMessageEvent(e,Js.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(ct.disconnect,n),await jt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(ct.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(ct.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(ct.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,q.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(hn())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Nc(new M8(qE({sdkVersion:Fa,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:s}=e;await this.messages.set(i,s,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Uc(e)){if(!e.method.endsWith(tO))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:ae.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Uh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else qn(e)&&this.events.emit(pe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Js.inbound),this.events.emit(pe.message,e))}async acknowledgePayload(e){const r=ls(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(ct.payload,this.onPayloadHandler),this.provider.off(ct.connect,this.onConnectHandler),this.provider.off(ct.disconnect,this.onDisconnectHandler),this.provider.off(ct.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await oh();jI(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(ei.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&MI())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(pe.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?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},q.toMiliseconds(rO)))))}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function S$(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Nh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function kh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const O$="[object RegExp]",D$="[object String]",$$="[object Number]",A$="[object Boolean]",jh="[object Arguments]",P$="[object Symbol]",B$="[object Date]",C$="[object Map]",T$="[object Set]",R$="[object Array]",U$="[object Function]",N$="[object ArrayBuffer]",Vo="[object Object]",k$="[object Error]",j$="[object DataView]",F$="[object Uint8Array]",L$="[object Uint8ClampedArray]",M$="[object Uint16Array]",q$="[object Uint32Array]",z$="[object BigUint64Array]",V$="[object Int8Array]",H$="[object Int16Array]",K$="[object Int32Array]",W$="[object BigInt64Array]",G$="[object Float32Array]",Y$="[object Float64Array]";function Z$(){}function Fh(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 J$(t,e,r){return Wi(t,e,void 0,void 0,void 0,void 0,r)}function Wi(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Qi(t,e,n,o)}return Qi(t,e,n,o)}function Qi(t,e,r,i){if(Object.is(t,e))return!0;let s=kh(t),n=kh(e);if(s===jh&&(s=Vo),n===jh&&(n=Vo),s!==n)return!1;switch(s){case D$:return t.toString()===e.toString();case $$:{const c=t.valueOf(),l=e.valueOf();return S$(c,l)}case A$:case B$:case P$:return Object.is(t.valueOf(),e.valueOf());case O$:return t.source===e.source&&t.flags===e.flags;case U$:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(s){case C$:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Wi(l,e.get(c),c,t,e,r,i))return!1;return!0}case T$:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(p=>Wi(h,p,void 0,t,e,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case R$:case F$:case L$:case M$:case q$:case z$:case V$:case H$:case K$:case W$:case G$:case Y$:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Wi(t[c],e[c],c,t,e,r,i))return!1;return!0}case N$:return t.byteLength!==e.byteLength?!1:Qi(new Uint8Array(t),new Uint8Array(e),r,i);case j$:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Qi(new Uint8Array(t),new Uint8Array(e),r,i);case k$:return t.name===e.name&&t.message===e.message;case Vo:{if(!(Qi(t.constructor,e.constructor,r,i)||Fh(t)&&Fh(e)))return!1;const c=[...Object.keys(t),...Nh(t)],l=[...Object.keys(e),...Nh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Wi(f,p,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function X$(t,e){return J$(t,e,Z$)}var Q$=Object.defineProperty,Lh=Object.getOwnPropertySymbols,eA=Object.prototype.hasOwnProperty,tA=Object.prototype.propertyIsEnumerable,Ka=(t,e,r)=>e in t?Q$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mh=(t,e)=>{for(var r in e||(e={}))eA.call(e,r)&&Ka(t,r,e[r]);if(Lh)for(var r of Lh(e))tA.call(e,r)&&Ka(t,r,e[r]);return t},ze=(t,e,r)=>Ka(t,typeof e!="symbol"?e+"":e,r);class ri extends qS{constructor(e,r,i,s=Mt,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,ze(this,"map",new Map),ze(this,"version",iO),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"getKey"),ze(this,"storagePrefix",Mt),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&&!Ie(o)?this.map.set(this.getKey(o),o):gI(o)?this.map.set(o.id,o):yI(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=>X$(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=Mh(Mh({},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=ot(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return Xe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rA=Object.defineProperty,iA=(t,e,r)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,X=(t,e,r)=>iA(t,typeof e!="symbol"?e+"":e,r);class sA{constructor(e,r){this.core=e,this.logger=r,X(this,"name",aO),X(this,"version",cO),X(this,"events",new ec),X(this,"pairings"),X(this,"initialized",!1),X(this,"storagePrefix",Mt),X(this,"ignoredPayloadTypes",[sr]),X(this,"registeredMethods",[]),X(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),X(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),X(this,"create",async i=>{this.isInitialized();const s=Ca(),n=await this.core.crypto.setSymKey(s),o=de(q.FIVE_MINUTES),a={protocol:bg},c={topic:n,expiry:o,relay:a,active:!1,methods:i?.methods},l=Ju({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Fr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i?.transportType,internal:i?.internal}),{topic:n,uri:l}}),X(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[Ct.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Zu(i.uri);s.props.properties.topic=n,s.addTrace(Ct.pairing_uri_validation_success),s.addTrace(Ct.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),s.addTrace(Ct.existing_pairing),u.active)throw s.setError(Zt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(Ct.pairing_not_expired)}const h=c||de(q.FIVE_MINUTES),f={topic:n,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(n,h),await this.pairings.set(n,f),s.addTrace(Ct.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Fr.create,f),s.addTrace(Ct.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(Ct.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Zt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw s.setError(Zt.subscribe_pairing_topic_failure),p}return s.addTrace(Ct.subscribe_pairing_topic_success),f}),X(this,"activate",async({topic:i})=>{this.isInitialized();const s=de(q.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),X(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Nr();this.events.once(ie("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),X(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),X(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),X(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),X(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",ce("USER_DISCONNECTED")),await this.deletePairing(s))}),X(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return Ju({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),X(this,"sendRequest",async(i,s,n)=>{const o=_t(s,n),a=await this.core.crypto.encode(i,o),c=Fi[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),X(this,"sendResult",async(i,s,n)=>{const o=ls(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Fi[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),X(this,"sendError",async(i,s,n)=>{const o=Mn(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,l=Fi[c]?Fi[c].res:Fi.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)}),X(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,ce("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),X(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Nt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),X(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),X(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;return o==="wc_pairingPing"?this.onPairingPingResponse(s,n):this.onUnknownRpcMethodResponse(o)}),X(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Fr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),X(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{Rt(s)?this.events.emit(ie("pairing_ping",n),{}):dt(s)&&this.events.emit(ie("pairing_ping",n),{error:s.error})},500)}),X(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Fr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),X(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=ce("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),X(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(ce("WC_METHOD_UNSUPPORTED",i))}),X(this,"isValidPair",(i,s)=>{var n;if(!He(i)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(Zt.malformed_pairing_uri),new Error(a)}if(!pI(i.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(Zt.malformed_pairing_uri),new Error(a)}const o=Zu(i?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Zt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Zt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&q.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(Zt.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),X(this,"isValidPing",async i=>{if(!He(i)){const{message:n}=z("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),X(this,"isValidDisconnect",async i=>{if(!He(i)){const{message:n}=z("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),X(this,"isValidPairingTopic",async i=>{if(!ge(i,!1)){const{message:s}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Nt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=z("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=ot(r,this.name),this.pairings=new ri(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Xe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pe.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==ae.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);Uc(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):qn(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ut.expired,async e=>{const{topic:r}=ap(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Fr.expire,{topic:r}))})}}var nA=Object.defineProperty,oA=(t,e,r)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,De=(t,e,r)=>oA(t,typeof e!="symbol"?e+"":e,r);class aA extends jS{constructor(e,r){super(e,r),this.core=e,this.logger=r,De(this,"records",new Map),De(this,"events",new wt.EventEmitter),De(this,"name",lO),De(this,"version",uO),De(this,"cached",[]),De(this,"initialized",!1),De(this,"storagePrefix",Mt),De(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)}),De(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:de(q.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(bt.created,o)}),De(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=dt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(bt.updated,s))}),De(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),De(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(bt.deleted,n)}}),this.persist()}),De(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),De(this,"on",(i,s)=>{this.events.on(i,s)}),De(this,"once",(i,s)=>{this.events.once(i,s)}),De(this,"off",(i,s)=>{this.events.off(i,s)}),De(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ot(r,this.name)}get context(){return Xe(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:_t(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(bt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(bt.created,e=>{const r=bt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(bt.updated,e=>{const r=bt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(bt.deleted,e=>{const r=bt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(ei.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{q.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(bt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var cA=Object.defineProperty,lA=(t,e,r)=>e in t?cA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>lA(t,typeof e!="symbol"?e+"":e,r);class uA extends VS{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ne(this,"expirations",new Map),Ne(this,"events",new wt.EventEmitter),Ne(this,"name",hO),Ne(this,"version",fO),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Mt),Ne(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)}),Ne(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Ne(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ut.created,{target:n,expiration:o})}),Ne(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Ne(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(ut.deleted,{target:s,expiration:n})}}),Ne(this,"on",(i,s)=>{this.events.on(i,s)}),Ne(this,"once",(i,s)=>{this.events.once(i,s)}),Ne(this,"off",(i,s)=>{this.events.off(i,s)}),Ne(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=ot(r,this.name)}get context(){return Xe(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 zE(e);if(typeof e=="number")return VE(e);const{message:r}=z("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ut.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;q.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ut.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(ei.pulse,()=>this.checkExpirations()),this.events.on(ut.created,e=>{const r=ut.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.expired,e=>{const r=ut.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ut.deleted,e=>{const r=ut.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var hA=Object.defineProperty,fA=(t,e,r)=>e in t?hA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fe=(t,e,r)=>fA(t,typeof e!="symbol"?e+"":e,r);class dA extends HS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,fe(this,"name",dO),fe(this,"abortController"),fe(this,"isDevEnv"),fe(this,"verifyUrlV3",gO),fe(this,"storagePrefix",Mt),fe(this,"version",mg),fe(this,"publicKey"),fe(this,"fetchPromise"),fe(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&q.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),fe(this,"register",async s=>{if(!Di()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=nr.getDocument(),u=this.startAbortTimer(q.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",m),l.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const y=l.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",d,{signal:this.abortController.signal});const m=v=>{if(v.data&&typeof v.data=="string")try{const I=JSON.parse(v.data);if(I.type==="verify_attestation"){if(ya(I.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(y),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",m),f(I.attestation===null?"":I.attestation)}}catch(I){this.logger.warn(I)}};l.body.appendChild(y),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),fe(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(ya(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)}),fe(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(q.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),fe(this,"getVerifyUrl",s=>{let n=s||Xi;return yO.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Xi}`),n=Xi),n}),fe(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(q.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),fe(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),fe(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),fe(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),fe(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),fe(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),fe(this,"validateAttestation",(s,n)=>{const o=L3(s,n.publicKey),a={hasExpired:q.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=ot(r,this.name),this.abortController=new AbortController,this.isDevEnv=xc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Xe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),q.toMiliseconds(e))}}var pA=Object.defineProperty,gA=(t,e,r)=>e in t?pA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qh=(t,e,r)=>gA(t,typeof e!="symbol"?e+"":e,r);class yA extends KS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,qh(this,"context",wO),qh(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${mO}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=ot(r,this.context)}}var wA=Object.defineProperty,zh=Object.getOwnPropertySymbols,mA=Object.prototype.hasOwnProperty,bA=Object.prototype.propertyIsEnumerable,Wa=(t,e,r)=>e in t?wA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qi=(t,e)=>{for(var r in e||(e={}))mA.call(e,r)&&Wa(t,r,e[r]);if(zh)for(var r of zh(e))bA.call(e,r)&&Wa(t,r,e[r]);return t},Ee=(t,e,r)=>Wa(t,typeof e!="symbol"?e+"":e,r);class vA extends WS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,Ee(this,"context",vO),Ee(this,"storagePrefix",Mt),Ee(this,"storageVersion",bO),Ee(this,"events",new Map),Ee(this,"shouldPersist",!1),Ee(this,"init",async()=>{if(!xc())try{const s={eventId:yu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:np(this.core.relayer.protocol,this.core.relayer.version,Fa)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),Ee(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=yu(),u=this.core.projectId||"",h=Date.now(),f=qi({eventId:l,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),Ee(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return qi(qi({},a),this.setMethods(a.eventId))}),Ee(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),Ee(this,"setEventListeners",()=>{this.core.heartbeat.on(ei.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{q.fromMiliseconds(Date.now())-q.fromMiliseconds(s.timestamp)>EO&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),Ee(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),Ee(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ee(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,qi(qi({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),Ee(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Ee(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${xO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Fa}${n}`,{method:"POST",body:JSON.stringify(s)})}),Ee(this,"getAppDomain",()=>sp().url),this.logger=ot(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 EA=Object.defineProperty,Vh=Object.getOwnPropertySymbols,xA=Object.prototype.hasOwnProperty,_A=Object.prototype.propertyIsEnumerable,Ga=(t,e,r)=>e in t?EA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hh=(t,e)=>{for(var r in e||(e={}))xA.call(e,r)&&Ga(t,r,e[r]);if(Vh)for(var r of Vh(e))_A.call(e,r)&&Ga(t,r,e[r]);return t},oe=(t,e,r)=>Ga(t,typeof e!="symbol"?e+"":e,r);let IA=class Tg extends RS{constructor(e){var r;super(e),oe(this,"protocol",wg),oe(this,"version",mg),oe(this,"name",ja),oe(this,"relayUrl"),oe(this,"projectId"),oe(this,"customStoragePrefix"),oe(this,"events",new wt.EventEmitter),oe(this,"logger"),oe(this,"heartbeat"),oe(this,"relayer"),oe(this,"crypto"),oe(this,"storage"),oe(this,"history"),oe(this,"expirer"),oe(this,"pairing"),oe(this,"verify"),oe(this,"echoClient"),oe(this,"linkModeSupportedApps"),oe(this,"eventClient"),oe(this,"initialized",!1),oe(this,"logChunkController"),oe(this,"on",(a,c)=>this.events.on(a,c)),oe(this,"once",(a,c)=>this.events.once(a,c)),oe(this,"off",(a,c)=>this.events.off(a,c)),oe(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),oe(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:ae.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const i=this.getGlobalCore(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?.projectId,this.relayUrl=e?.relayUrl||vg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=EE({level:typeof e?.logger=="string"&&e.logger?e.logger:z8.logger,name:ja}),{logger:n,chunkLoggerController:o}=rp({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride: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=ot(n,this.name),this.heartbeat=new JI,this.crypto=new JD(this,this.logger,e?.keychain),this.history=new aA(this,this.logger),this.expirer=new uA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new BS(Hh(Hh({},V8),e?.storageOptions)),this.relayer=new I$({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new sA(this,this.logger),this.verify=new dA(this,this.logger,this.storage),this.echoClient=new yA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new vA(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Tg(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(sO,i),r}get context(){return Xe(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(_h,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(_h)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&q8.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const SA=IA,Rg="wc",Ug=2,Ng="client",kc=`${Rg}@${Ug}:${Ng}:`,Ho={name:Ng,logger:"error"},Kh="WALLETCONNECT_DEEPLINK_CHOICE",OA="proposal",Wh="Proposal expired",DA="session",ui=q.SEVEN_DAYS,$A="engine",$e={wc_sessionPropose:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1104},res:{ttl:q.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1106},res:{ttl:q.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:q.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1112},res:{ttl:q.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:q.ONE_DAY,prompt:!1,tag:1114},res:{ttl:q.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:q.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:q.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:q.FIVE_MINUTES,prompt:!1,tag:1119}}},Ko={min:q.FIVE_MINUTES,max:q.SEVEN_DAYS},Bt={idle:"IDLE",active:"ACTIVE"},AA={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:""}},PA="request",BA=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],CA="wc",TA="auth",RA="authKeys",UA="pairingTopics",NA="requests",Vn=`${CA}@${1.5}:${TA}:`,Xs=`${Vn}:PUB_KEY`;var kA=Object.defineProperty,jA=Object.defineProperties,FA=Object.getOwnPropertyDescriptors,Gh=Object.getOwnPropertySymbols,LA=Object.prototype.hasOwnProperty,MA=Object.prototype.propertyIsEnumerable,Ya=(t,e,r)=>e in t?kA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,re=(t,e)=>{for(var r in e||(e={}))LA.call(e,r)&&Ya(t,r,e[r]);if(Gh)for(var r of Gh(e))MA.call(e,r)&&Ya(t,r,e[r]);return t},Ae=(t,e)=>jA(t,FA(e)),F=(t,e,r)=>Ya(t,typeof e!="symbol"?e+"":e,r);class qA extends JS{constructor(e){super(e),F(this,"name",$A),F(this,"events",new ec),F(this,"initialized",!1),F(this,"requestQueue",{state:Bt.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Bt.idle,queue:[]}),F(this,"emittedSessionRequests",new QE({limit:500})),F(this,"requestQueueDelay",q.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys($e)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Ae(re({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=lI(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=s,p=((i=h?.[0])==null?void 0:i.ttl)||$e.wc_sessionPropose.req.ttl||q.FIVE_MINUTES;this.validateRequestExpiry(p);let d=n,y,m=!1;try{if(d){const A=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),A}if(!d||!m){const{topic:A,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=A,y=j}if(!d){const{message:A}=z("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(A)}const v=await this.client.core.crypto.generateKeyPair(),I=de(p),b=re(Ae(re(re({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:bg}],proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:I,pairingTopic:d},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:Tt()}),(h||f)&&{requests:{authentication:h?.map(A=>{const{domain:j,chains:N,nonce:C,uri:O,exp:P,nbf:g,type:w,statement:x,requestId:D,resources:_,signatureTypes:S}=A;return{domain:j,chains:N,nonce:C,type:w??"caip122",aud:O,version:"1",iat:new Date().toISOString(),exp:P,nbf:g,statement:x,requestId:D,resources:_,signatureTypes:S}}),walletPay:f}}),E=ie("session_connect",b.id),{reject:$,resolve:B,done:T}=Nr(p,Wh),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(E,{error:{message:Wh,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(E,({error:A,session:j})=>{this.client.events.off("proposal_expire",R),A?$(A):j&&B(j)}),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:y,approval:T}}),F(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),F(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[vt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Tr.no_internet_connection),j}try{await this.isValidProposalId(r?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Tr.proposal_not_found),j}try{await this.isValidApprove(r)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Tr.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=r,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:m,requiredNamespaces:v,optionalNamespaces:I}=d;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:y});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:vt.session_approve_started,properties:{topic:y,trace:[vt.session_approve_started,vt.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),$=m.publicKey,B=await this.client.core.crypto.generateSharedKey(E,$),T=Ae(re(re(re({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:E,metadata:this.client.metadata},expiry:de(ui)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:p}),R=ae.relay;b.addTrace(vt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:R,internal:{skipSubscribe:!0}})}catch(j){throw b.setError(Tr.subscribe_session_topic_failure),j}b.addTrace(vt.subscribe_session_topic_success);const A=Ae(re({},T),{topic:B,requiredNamespaces:v,optionalNamespaces:I,pairingTopic:y,acknowledged:!1,self:T.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:E,transportType:ae.relay,authentication:p?.authentication,walletPayResult:p?.walletPay});await this.client.session.set(B,A),b.addTrace(vt.store_session);try{await this.sendApproveSession({sessionTopic:B,proposal:d,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:E},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:re({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(vt.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(B,ce("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),j}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(B,de(ui)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}}),F(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&await this.sendError({id:i,topic:n,error:s,rpcOpts:$e.wc_sessionPropose.reject}),await this.deleteProposal(i)}),F(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:s}=r,{done:n,resolve:o,reject:a}=Nr(q.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Tt(),l=Ir().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ie("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:n}}),F(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,s=Tt(),{done:n,resolve:o,reject:a}=Nr(q.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ie("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,de(ui)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),F(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:i,request:s,topic:n,expiry:o=$e.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);a?.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const c=Tt(),l=Ir().toString(),{done:u,resolve:h,reject:f}=Nr(o,"Request expired. Please try again.");this.events.once(ie("session_request",c),({error:m,result:v})=>{m?f(m):h(v)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:{request:Ae(re({},s),{expiryTimestamp:de(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(m=>f(m)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await u();const y={request:Ae(re({},s),{expiryTimestamp:de(o)}),chainId:i};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:y,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,y)}).catch(v=>f(v)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),m()}),new Promise(async m=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const I=await GE(this.client.core.storage,Kh);await HE({id:c,topic:n,wcDeepLink:I})}m()}),u()]).then(m=>m[2])}),F(this,"respond",async r=>{var i,s;this.isInitialized();const n=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||((s=(i=r?.response)==null?void 0:i.id)==null?void 0:s.toString()),trace:[vt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw n.addTrace(h?.message),n.setError(Tr.session_request_response_validation_failure),h}n.addTrace(vt.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,l=this.client.session.get(o);l.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{n.addTrace(vt.session_request_response_publish_started),Rt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):dt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(r)}catch(h){throw n.addTrace(h?.message),n.setError(Tr.session_request_response_publish_failure),h}}),F(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=Tt(),n=Ir().toString(),{done:o,resolve:a,reject:c}=Nr(q.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ie("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),F(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=Ir().toString(),a=Tt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:ce("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),F(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>fI(i,r)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ae.link_mode:ae.relay;o===ae.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:p,nbf:d,methods:y=[],expiry:m}=r,v=[...r.resources||[]],{topic:I,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:I,uri:b}});const E=await this.client.core.crypto.generateKeyPair(),$=Gs(E);if(await Promise.all([this.client.auth.authKeys.set(Xs,{responseTopic:$,publicKey:E}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:I})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${I}`),y.length>0){const{namespace:_}=ir(a[0]);let S=f_(_,"request",y);Ws(v)&&(S=p_(S,v.pop())),v.push(S)}const B=m&&m>$e.wc_sessionAuthenticate.req.ttl?m:$e.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:v},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:de(B)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:I,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:de($e.wc_sessionPropose.req.ttl),id:Tt()},{done:j,resolve:N,reject:C}=Nr(B,"Request expired"),O=Tt(),P=ie("session_connect",A.id),g=ie("session_request",O),w=async({error:_,session:S})=>{this.events.off(g,x),_?C(_):S&&N({session:S})},x=async _=>{var S,U,k;if(await this.deletePendingAuthRequest(O,{message:"fulfilled",code:0}),_.error){const W=ce("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===W.code?void 0:(this.events.off(P,w),C(_.error.message))}await this.deleteProposal(A.id),this.events.off(P,w);const{cacaos:V,responder:L}=_.result,M=[],K=[];for(const W of V){await Du({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),C(ce("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:J}=W,ue=Ws(J.resources),ye=[xa(J.iss)],be=dn(J.iss);if(ue){const je=$u(ue),Ot=Au(ue);M.push(...je),ye.push(...Ot)}for(const je of ye)K.push(`${je}:${be}`)}const G=await this.client.core.crypto.generateSharedKey(E,L.publicKey);let Z;M.length>0&&(Z={topic:G,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:de(ui),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:I,namespaces:th([...new Set(M)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,Z),I&&await this.client.core.pairing.updateMetadata({topic:I,metadata:L.metadata}),Z=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(U=L.metadata.redirect)!=null&&U.linkMode&&(k=L.metadata.redirect)!=null&&k.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(G,{transportType:ae.link_mode})),N({auths:V,session:Z})};this.events.once(P,w),this.events.once(g,x);let D;try{if(n){const _=_t("wc_sessionAuthenticate",T,O);this.client.core.history.set(I,_);const S=await this.client.core.crypto.encode("",_,{type:bs,encoding:xr});D=ks(i,I,S)}else await Promise.all([this.sendRequest({topic:I,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:O}),this.sendRequest({topic:I,method:"wc_sessionPropose",params:A,expiry:$e.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(_){throw this.events.off(P,w),this.events.off(g,x),_}return await this.setProposal(A.id,A),await this.setAuthRequest(O,{request:Ae(re({},T),{verifyContext:{}}),pairingTopic:I,transportType:o}),{uri:D??b,response:j}}),F(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Rr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw n.setError(Li.no_internet_connection),m}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(Li.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ae.relay;a===ae.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Gs(c),h={type:sr,receiverPublicKey:c,senderPublicKey:l},f=[],p=[];for(const m of s){if(!await Du({cacao:m,projectId:this.client.core.projectId})){n.setError(Li.invalid_cacao);const $=ce("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:$,encodeOpts:h}),new Error($.message)}n.addTrace(Rr.cacaos_verified);const{p:v}=m,I=Ws(v.resources),b=[xa(v.iss)],E=dn(v.iss);if(I){const $=$u(I),B=Au(I);f.push(...$),b.push(...B)}for(const $ of b)p.push(`${$}:${E}`)}const d=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Rr.create_authenticated_session_topic);let y;if(f?.length>0){y={topic:d,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:de(ui),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:th([...new Set(f)],[...new Set(p)]),transportType:a},n.addTrace(Rr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(m){throw n.setError(Li.subscribe_authenticated_session_topic_failure),m}n.addTrace(Rr.subscribe_authenticated_session_topic_success),await this.client.session.set(d,y),n.addTrace(Rr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Rr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw n.setError(Li.authenticated_session_approve_publish_failure),m}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),F(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Gs(o),l={type:sr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:l,rpcOpts:$e.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),F(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return Ip(i,s)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),F(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),F(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,ce("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(Kh).catch(l=>this.client.logger.warn(l)),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Bt.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===s).map(l=>this.deletePendingSessionRequest(l.id,ce("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),F(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(Tr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,ce("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),F(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=Bt.idle,this.client.events.emit("session_request_expire",{id:r}))}),F(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),F(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),F(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,de($e.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),F(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=ae.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||de($e.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),F(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,p=_t(s,n,c);let d;const y=!!u;try{const I=y?xr:Ge;d=await this.client.core.crypto.encode(i,p,{encoding:I})}catch(I){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),I}let m;if(BA.includes(s)){const I=ft(JSON.stringify(p)),b=ft(d);m=await this.client.core.verify.register({id:b,decryptedId:I})}const v=re(re({},$e[s].req),f);if(v.attestation=m,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(i,p),y){const I=ks(u,i,d);await global.Linking.openURL(I,this.client.name)}else v.tvf=Ae(re({},h),{correlationId:p.id}),l?(v.internal=Ae(re({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,d,v)):this.client.core.relayer.publish(i,d,v).catch(I=>this.client.logger.error(I));return p.id}),F(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:s}=r,n=_t("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,n);const o=await this.client.core.crypto.encode(i.pairingTopic,n,{encoding:Ge}),a=ft(JSON.stringify(n)),c=ft(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Ae(re({},s),{publishMethod:"wc_proposeSession",attestation:l})})}),F(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:s,proposal:n,sessionSettleRequest:o,publishOpts:a}=r,c=ls(n.id,s),l=await this.client.core.crypto.encode(n.pairingTopic,c,{encoding:Ge}),u=_t("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(i,u,{encoding:Ge});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:n.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Ae(re({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=ls(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?xr:Ge;u=await this.client.core.crypto.encode(s,l,Ae(re({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),d}let f,p;try{f=await this.client.core.history.get(s,i);const d=f.request;try{p=this.getTVFParams(i,d.params,n)}catch(y){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${y?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),d}if(h){const d=ks(c,s,u);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,y=$e[d].res;y.tvf=Ae(re({},p),{correlationId:i}),o?(y.internal=Ae(re({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,y)):this.client.core.relayer.publish(s,u,y).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(l)}),F(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=Mn(i,n);let u;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?xr:Ge;u=await this.client.core.crypto.encode(s,l,Ae(re({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),p}if(h){const p=ks(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||$e[p].res;this.client.core.relayer.publish(s,u,d)}await this.client.core.history.resolve(l)}),F(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Nt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Nt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),F(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),F(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Bt.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=Bt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Bt.idle}),F(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=z("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),F(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Zt.proposal_listener_not_found)),this.isValidConnect(re({},s.params));const u=a.expiryTimestamp||de($e.wc_sessionPropose.req.ttl),h=re({id:c,pairingTopic:i,expiryTimestamp:u,attestation:n,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:n,hash:ft(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(Ct.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:i,error:l,rpcOpts:$e.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),F(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(Rt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:r,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(dt(i)){await this.deleteProposal(n);const o=ie("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),F(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=i.params,d=[...this.pendingSessions.values()].find(v=>v.sessionTopic===r);if(!d)return this.client.logger.error(`Pending session not found for topic ${r}`);const y=this.client.proposal.get(d.proposalId),m=Ae(re(re(re({topic:r,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:ae.relay,authentication:p?.authentication,walletPayResult:p?.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(ie("session_connect",d.proposalId),{session:m})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;Rt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ie("session_approve",s),{})):dt(i)&&(await this.client.session.delete(r,ce("USER_DISCONNECTED")),this.events.emit(ie("session_approve",s),{error:i.error}))}),F(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:ce("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(re({topic:r},s));try{ji.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0})}catch(c){throw ji.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=ie("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Rt(i)?this.events.emit(ie("session_update",s),{}):dt(i)&&this.events.emit(ie("session_update",s),{error:i.error})}),F(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,de(ui)),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=ie("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Rt(i)?this.events.emit(ie("session_extend",s),{}):dt(i)&&this.events.emit(ie("session_extend",s),{error:i.error})}),F(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),F(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=ie("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);Rt(i)?this.events.emit(ie("session_ping",s),{}):dt(i)&&this.events.emit(ie("session_ping",s),{error:i.error})},500)}),F(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:ce("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:s})}catch(n){this.client.logger.error(n)}}),F(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{id:h,params:f}=a;try{await this.isValidRequest(re({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:ft(JSON.stringify(_t("wc_sessionRequest",f,h))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),y={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(y),u===ae.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),F(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=ie("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Rt(i)?this.events.emit(ie("session_request",s),{result:i.result}):dt(i)&&this.events.emit(ie("session_request",s),{error:i.error})}),F(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(re({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),ji.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Rt(i)?this.events.emit(ie("session_request",s),{result:i.result}):dt(i)&&this.events.emit(ie("session_request",s),{error:i.error})}),F(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:l,authPayload:u,expiryTimestamp:h}=n.params,f=await this.getVerifyContext({attestationId:o,hash:ft(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:s,id:n.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:p,pairingTopic:s,transportType:c}),c===ae.link_mode&&(i=l.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:sr,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:l,encodeOpts:p,rpcOpts:$e.wc_sessionAuthenticate.autoReject,appLink:f})}}),F(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),F(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Bt.idle,this.processSessionRequestQueue()},q.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{this.events.emit(ie("session_request",n.request.id),{error:i})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Bt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),F(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Bt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),F(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:_t("wc_sessionPropose",Ae(re({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),F(this,"isValidConnect",async r=>{if(!He(r)){const{message:l}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Ie(i)||await this.isValidPairingTopic(i),!II(c)){const{message:l}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!Ie(s)&&Lt(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(n&&!Ie(n)&&Lt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),F(this,"validateNamespaces",(r,i)=>{const s=_I(r,"connect()",i);if(s)throw new Error(s.message)}),F(this,"isValidApprove",async r=>{if(!He(r))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=ko(s,"approve()");if(l)throw new Error(l.message);const u=sh(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!ge(n,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),F(this,"isValidReject",async r=>{if(!He(r)){const{message:n}=z("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!OI(s)){const{message:n}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),F(this,"isValidSessionSettleRequest",r=>{if(!He(r)){const{message:l}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!cg(i)){const{message:l}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=wI(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ko(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Nt(o)){const{message:l}=z("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),F(this,"isValidUpdate",async r=>{if(!He(r)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=ko(s,"update()");if(o)throw new Error(o.message);const a=sh(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async r=>{if(!He(r)){const{message:s}=z("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),F(this,"isValidRequest",async r=>{if(!He(r)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!ih(a,n)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!DI(s)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!PI(a,n,s.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),F(this,"isValidRespond",async r=>{var i;if(!He(r)){const{message:a}=z("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!$I(n)){const{message:a}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(a)}const o=this.client.pendingRequest.get(n.id);if(o.topic!==s){const{message:a}=z("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),F(this,"isValidPing",async r=>{if(!He(r)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidEmit",async r=>{if(!He(r)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!ih(o,n)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!AI(s)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!BI(o,n,s.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async r=>{if(!He(r)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),F(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ge(s,!1))throw new Error("uri is required parameter");if(!ge(n,!1))throw new Error("domain is required parameter");if(!ge(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>ir(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ir(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Xi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ae.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=z("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),F(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=z("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),F(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,l,u,h,f;return!r||i!==ae.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=r?.redirect)==null?void 0:u.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((f=r?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r?.redirect)==null?void 0:s.universal:void 0}),F(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=gu(r,"topic")||"",s=decodeURIComponent(gu(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ae.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),F(this,"registerLinkModeListeners",async()=>{var r;if(xc()||$r()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),F(this,"getTVFApproveParams",r=>{try{const i=og(r.namespaces),s=sI(r.namespaces),n=nI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:s,approvedEvents:n,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),F(this,"getTVFParams",(r,i,s)=>{var n,o,a;if(!((n=i.request)!=null&&n.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,s);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),F(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=r?.data||((i=r?.[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(r,i)=>{var s;try{if(!i)return[];const n=r.method,o=AA[n];if(n==="sui_signTransaction")return[Wx(i.transactionBytes)];if(n==="near_signTransaction")return[_u(i)];if(n==="near_signTransactions")return i.map(c=>_u(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=i.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[YI({transaction:r.params.transactionPayload,signature:i.signature})];if(n==="algo_signTxn")return gt(i)?i.map(c=>Iu(c)):[Iu(i)];if(n==="cosmos_signDirect")return[Yx(i)];if(n==="wallet_sendCalls")return Zx(i);if(typeof i=="string")return[i];const a=i[o.key];if(gt(a))return n==="solana_signAllTransactions"?a.map(c=>Kx(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn(n,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Xs)?this.client.auth.authKeys.get(Xs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===ae.link_mode?xr:Ge});Uc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:ft(i)})):qn(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ut.expired,async e=>{const{topic:r,id:i}=ap(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,z("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,z("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Fr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Fr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ge(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Nt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ge(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Nt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=z("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=z("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ge(e,!1)){const{message:r}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!SI(e)){const{message:r}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Nt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=z("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!RI(e,Ko)){const{message:r}=z("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${Ko.min} and ${Ko.max}`);throw new Error(r)}}}class zA extends ri{constructor(e,r){super(e,r,OA,kc),this.core=e,this.logger=r}}let VA=class extends ri{constructor(e,r){super(e,r,DA,kc),this.core=e,this.logger=r}};class HA extends ri{constructor(e,r){super(e,r,PA,kc,i=>i.id),this.core=e,this.logger=r}}class KA extends ri{constructor(e,r){super(e,r,RA,Vn,()=>Xs),this.core=e,this.logger=r}}class WA extends ri{constructor(e,r){super(e,r,UA,Vn),this.core=e,this.logger=r}}class GA extends ri{constructor(e,r){super(e,r,NA,Vn,i=>i.id),this.core=e,this.logger=r}}var YA=Object.defineProperty,ZA=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wo=(t,e,r)=>ZA(t,typeof e!="symbol"?e+"":e,r);class JA{constructor(e,r){this.core=e,this.logger=r,Wo(this,"authKeys"),Wo(this,"pairingTopics"),Wo(this,"requests"),this.authKeys=new KA(this.core,this.logger),this.pairingTopics=new WA(this.core,this.logger),this.requests=new GA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var XA=Object.defineProperty,QA=(t,e,r)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q=(t,e,r)=>QA(t,typeof e!="symbol"?e+"":e,r);class jc extends ZS{constructor(e){super(e),Q(this,"protocol",Rg),Q(this,"version",Ug),Q(this,"name",Ho.name),Q(this,"metadata"),Q(this,"core"),Q(this,"logger"),Q(this,"events",new wt.EventEmitter),Q(this,"engine"),Q(this,"session"),Q(this,"proposal"),Q(this,"pendingRequest"),Q(this,"auth"),Q(this,"signConfig"),Q(this,"on",(i,s)=>this.events.on(i,s)),Q(this,"once",(i,s)=>this.events.once(i,s)),Q(this,"off",(i,s)=>this.events.off(i,s)),Q(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),Q(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),Q(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),Q(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),Q(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=e?.name||Ho.name,this.metadata=FE(e?.metadata),this.signConfig=e?.signConfig;const r=Tc({logger:e?.logger||Ho.logger,name:this.name});this.logger=r,this.core=e?.core||new SA(e),this.session=new VA(this.core,this.logger),this.proposal=new zA(this.core,this.logger),this.pendingRequest=new HA(this.core,this.logger),this.engine=new qA(this),this.auth=new JA(this.core,this.logger)}static async init(e){const r=new jc(e);return await r.initialize(),r}get context(){return Xe(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 e6=jc;var Ls={exports:{}},Yh;function t6(){return Yh||(Yh=1,(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ut<"u"&&Ut,i=(function(){function n(){this.fetch=!1,this.DOMException=r.DOMException}return n.prototype=r,new n})();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof Ut<"u"&&Ut||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],h=ArrayBuffer.isView||function(g){return g&&u.indexOf(Object.prototype.toString.call(g))>-1};function f(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function p(g){return typeof g!="string"&&(g=String(g)),g}function d(g){var w={next:function(){var x=g.shift();return{done:x===void 0,value:x}}};return c.iterable&&(w[Symbol.iterator]=function(){return w}),w}function y(g){this.map={},g instanceof y?g.forEach(function(w,x){this.append(x,w)},this):Array.isArray(g)?g.forEach(function(w){if(w.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+w.length);this.append(w[0],w[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(w){this.append(w,g[w])},this)}y.prototype.append=function(g,w){g=f(g),w=p(w);var x=this.map[g];this.map[g]=x?x+", "+w:w},y.prototype.delete=function(g){delete this.map[f(g)]},y.prototype.get=function(g){return g=f(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(f(g))},y.prototype.set=function(g,w){this.map[f(g)]=p(w)},y.prototype.forEach=function(g,w){for(var x in this.map)this.map.hasOwnProperty(x)&&g.call(w,this.map[x],x,this)},y.prototype.keys=function(){var g=[];return this.forEach(function(w,x){g.push(x)}),d(g)},y.prototype.values=function(){var g=[];return this.forEach(function(w){g.push(w)}),d(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(w,x){g.push([x,w])}),d(g)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function m(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function v(g){return new Promise(function(w,x){g.onload=function(){w(g.result)},g.onerror=function(){x(g.error)}})}function I(g){var w=new FileReader,x=v(w);return w.readAsArrayBuffer(g),x}function b(g){var w=new FileReader,x=v(w),D=/charset=([A-Za-z0-9_-]+)/.exec(g.type),_=D?D[1]:"utf-8";return w.readAsText(g,_),x}function E(g){for(var w=new Uint8Array(g),x=new Array(w.length),D=0;D<w.length;D++)x[D]=String.fromCharCode(w[D]);return x.join("")}function $(g){if(g.slice)return g.slice(0);var w=new Uint8Array(g.byteLength);return w.set(new Uint8Array(g)),w.buffer}function B(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&l(g)?(this._bodyArrayBuffer=$(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=$(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=m(this);if(g)return g;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var g=m(this);return g||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(I);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=m(this);if(g)return g;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(E(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(j)}),this.json=function(){return this.text().then(JSON.parse)},this}var T=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function R(g){var w=g.toUpperCase();return T.indexOf(w)>-1?w:g}function A(g,w){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');w=w||{};var x=w.body;if(g instanceof A){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,w.headers||(this.headers=new y(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!x&&g._bodyInit!=null&&(x=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=w.credentials||this.credentials||"same-origin",(w.headers||!this.headers)&&(this.headers=new y(w.headers)),this.method=R(w.method||this.method||"GET"),this.mode=w.mode||this.mode||null,this.signal=w.signal||this.signal||(function(){if("AbortController"in a){var S=new AbortController;return S.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&x)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(x),(this.method==="GET"||this.method==="HEAD")&&(w.cache==="no-store"||w.cache==="no-cache")){var D=/([?&])_=[^&]*/;if(D.test(this.url))this.url=this.url.replace(D,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}A.prototype.clone=function(){return new A(this,{body:this._bodyInit})};function j(g){var w=new FormData;return g.trim().split("&").forEach(function(x){if(x){var D=x.split("="),_=D.shift().replace(/\+/g," "),S=D.join("=").replace(/\+/g," ");w.append(decodeURIComponent(_),decodeURIComponent(S))}}),w}function N(g){var w=new y,x=g.replace(/\r?\n[\t ]+/g," ");return x.split("\r").map(function(D){return D.indexOf(`
|
|
15
|
-
`)===0?D.substr(1,D.length):D}).forEach(function(D){var _=D.split(":"),S=_.shift().trim();if(S){var U=_.join(":").trim();try{w.append(S,U)}catch(k){console.warn("Response "+k.message)}}}),w}B.call(A.prototype);function C(g,w){if(!(this instanceof C))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(w||(w={}),this.type="default",this.status=w.status===void 0?200:w.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=w.statusText===void 0?"":""+w.statusText,this.headers=new y(w.headers),this.url=w.url||"",this._initBody(g)}B.call(C.prototype),C.prototype.clone=function(){return new C(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},C.error=function(){var g=new C(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var O=[301,302,303,307,308];C.redirect=function(g,w){if(O.indexOf(w)===-1)throw new RangeError("Invalid status code");return new C(null,{status:w,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(w,x){this.message=w,this.name=x;var D=Error(w);this.stack=D.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(g,w){return new Promise(function(x,D){var _=new A(g,w);if(_.signal&&_.signal.aborted)return D(new o.DOMException("Aborted","AbortError"));var S=new XMLHttpRequest;function U(){S.abort()}S.onload=function(){var L={statusText:S.statusText,headers:N(S.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(S.status<200||S.status>599)?L.status=200:L.status=S.status,L.url="responseURL"in S?S.responseURL:L.headers.get("X-Request-URL");var M="response"in S?S.response:S.responseText;setTimeout(function(){x(new C(M,L))},0)},S.onerror=function(){setTimeout(function(){D(new TypeError("Network request failed"))},0)},S.ontimeout=function(){setTimeout(function(){D(new TypeError("Network request timed out"))},0)},S.onabort=function(){setTimeout(function(){D(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(S.open(_.method,k(_.url),!0),_.credentials==="include"?S.withCredentials=!0:_.credentials==="omit"&&(S.withCredentials=!1),"responseType"in S&&(c.blob?S.responseType="blob":c.arrayBuffer&&(S.responseType="arraybuffer")),w&&typeof w.headers=="object"&&!(w.headers instanceof y||a.Headers&&w.headers instanceof a.Headers)){var V=[];Object.getOwnPropertyNames(w.headers).forEach(function(L){V.push(f(L)),S.setRequestHeader(L,p(w.headers[L]))}),_.headers.forEach(function(L,M){V.indexOf(M)===-1&&S.setRequestHeader(M,L)})}else _.headers.forEach(function(L,M){S.setRequestHeader(M,L)});_.signal&&(_.signal.addEventListener("abort",U),S.onreadystatechange=function(){S.readyState===4&&_.signal.removeEventListener("abort",U)}),S.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return P.polyfill=!0,a.fetch||(a.fetch=P,a.Headers=y,a.Request=A,a.Response=C),o.Headers=y,o.Request=A,o.Response=C,o.fetch=P,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(Ls,Ls.exports)),Ls.exports}var r6=t6();const Zh=ay(r6);var i6=Object.defineProperty,s6=Object.defineProperties,n6=Object.getOwnPropertyDescriptors,Jh=Object.getOwnPropertySymbols,o6=Object.prototype.hasOwnProperty,a6=Object.prototype.propertyIsEnumerable,Xh=(t,e,r)=>e in t?i6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qh=(t,e)=>{for(var r in e||(e={}))o6.call(e,r)&&Xh(t,r,e[r]);if(Jh)for(var r of Jh(e))a6.call(e,r)&&Xh(t,r,e[r]);return t},ef=(t,e)=>s6(t,n6(e));const c6={Accept:"application/json","Content-Type":"application/json"},l6="POST",tf={headers:c6,method:l6},rf=10;let kg=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new wt.EventEmitter,this.isAvailable=!1,this.registering=!1,!mh(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=Yr(e),i=await(await Zh(this.url,ef(Qh({},tf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!mh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Yr({id:1,jsonrpc:"2.0",method:"test",params:[]});await Zh(e,ef(Qh({},tf),{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"?Gr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Mn(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>rf&&this.events.setMaxListeners(rf)}};function Fc(t){return t==null||typeof t!="object"&&typeof t!="function"}function jg(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Fg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const u6="[object RegExp]",Lg="[object String]",Mg="[object Number]",qg="[object Boolean]",zg="[object Arguments]",h6="[object Symbol]",f6="[object Date]",d6="[object Map]",p6="[object Set]",g6="[object Array]",y6="[object ArrayBuffer]",w6="[object Object]",m6="[object DataView]",b6="[object Uint8Array]",v6="[object Uint8ClampedArray]",E6="[object Uint16Array]",x6="[object Uint32Array]",_6="[object Int8Array]",I6="[object Int16Array]",S6="[object Int32Array]",O6="[object Float32Array]",D6="[object Float64Array]";function Lc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function $6(t,e){return gi(t,void 0,t,new Map,e)}function gi(t,e,r,i=new Map,s=void 0){const n=s?.(t,e,r,i);if(n!=null)return n;if(Fc(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]=gi(t[a],a,r,i,s);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,gi(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(gi(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Lc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=gi(t[a],a,r,i,s);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Lr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Lr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Lr(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Lr(o,t,r,i,s),o}if(typeof t=="object"&&A6(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Lr(o,t,r,i,s),o}return t}function Lr(t,e,r=t,i,s){const n=[...Object.keys(e),...jg(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=gi(e[a],a,r,i,s))}}function A6(t){switch(Fg(t)){case zg:case g6:case y6:case m6:case qg:case f6:case O6:case D6:case _6:case I6:case S6:case d6:case Mg:case w6:case u6:case p6:case Lg:case h6:case b6:case v6:case E6:case x6:return!0;default:return!1}}function P6(t,e){return $6(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Mg:case Lg:case qg:{const o=new t.constructor(t?.valueOf());return Lr(o,t),o}case zg:{const o={};return Lr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function sf(t){return P6(t)}function nf(t){return t!==null&&typeof t=="object"&&Fg(t)==="[object Arguments]"}function of(t){return typeof t=="object"&&t!==null}function B6(){}function C6(t){return Lc(t)}function T6(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function R6(t){if(Fc(t))return t;if(Array.isArray(t)||Lc(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 U6(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Za(s,o,i,new Map)}return s}function Za(t,e,r,i){if(Fc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return R6(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...jg(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(nf(a)&&(a={...a}),nf(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=sf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const p=h[f];u[p]=c[p]}c=u}else c=[];const l=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||of(c)&&of(a)?t[o]=Za(c,a,r,i):c==null&&T6(a)?t[o]=Za({},a,r,i):c==null&&C6(a)?t[o]=sf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function N6(t,...e){return U6(t,...e,B6)}const af="error",k6="wss://relay.walletconnect.org",j6="wc",Vg="universal_provider",Ms=`${j6}@2:${Vg}:`,Hg="https://rpc.walletconnect.org/v1/",Kg="generic",F6=`${Hg}bundler`,vi="call_status",L6=86400,Mc={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var M6=Object.defineProperty,q6=Object.defineProperties,z6=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,V6=Object.prototype.hasOwnProperty,H6=Object.prototype.propertyIsEnumerable,lf=(t,e,r)=>e in t?M6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qs=(t,e)=>{for(var r in e||(e={}))V6.call(e,r)&&lf(t,r,e[r]);if(cf)for(var r of cf(e))H6.call(e,r)&&lf(t,r,e[r]);return t},K6=(t,e)=>q6(t,z6(e));function Wg(t,e,r){var i;const s=ir(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${Hg}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function W6(t){return t.includes(":")?t.split(":")[1]:t}function Gg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function G6(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function uf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,s;return((i=r?.chains)==null?void 0:i.length)&&((s=r?.chains)==null?void 0:s.length)>0}))}function zs(t={},e={}){const r=uf(hf(t)),i=uf(hf(e));return N6(r,i)}function hf(t){var e,r,i,s,n;const o={};if(!Lt(t))return o;for(const[a,c]of Object.entries(t)){const l=Ln(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},p=pi(a);o[p]=K6(qs(qs({},o[p]),c),{chains:Ft(l,(e=o[p])==null?void 0:e.chains),methods:Ft(u,(r=o[p])==null?void 0:r.methods),events:Ft(h,(i=o[p])==null?void 0:i.events)}),(Lt(f)||Lt(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=qs(qs({},f),(n=o[p])==null?void 0:n.rpcMap))}return o}function ff(t){return t.includes(":")?t.split(":")[2]:t}function df(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ln(r)?[r]:i.chains?i.chains:Gg(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Go(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 Y6(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Yg={},Ei=t=>Yg[t],Yo=(t,e)=>{Yg[t]=e};var Z6=Object.defineProperty,pf=Object.getOwnPropertySymbols,J6=Object.prototype.hasOwnProperty,X6=Object.prototype.propertyIsEnumerable,gf=(t,e,r)=>e in t?Z6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))J6.call(e,r)&&gf(t,r,e[r]);if(pf)for(var r of pf(e))X6.call(e,r)&&gf(t,r,e[r]);return t};const wf="eip155",Q6=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],eP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,Zo=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,mf=t=>Object.keys(t).filter(e=>Q6.includes(e)).reduce((e,r)=>(e[r]=tP(t[r]),e),{}),tP=t=>typeof t=="string"&&Y6(t)?JSON.parse(t):t,rP=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:s={}}=t,n={};if(!Lt(s)&&!Lt(i))return;const o=mf(i);for(const a of r){const c=eP(a);if(!c)continue;n[Zo(c)]=o;const l=s?.[`${wf}:${c}`];if(l){const u=l?.[`${wf}:${c}:${e}`];n[Zo(c)]=yf(yf({},n[Zo(c)]),mf(u||l))}}for(const[a,c]of Object.entries(n))Object.keys(c).length===0&&delete n[a];return Object.keys(n).length>0?n:void 0};var iP=Object.defineProperty,sP=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nP=(t,e,r)=>sP(t,e+"",r);let Jo,oP=class Zg{constructor(e){nP(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 Jo||(Jo=new Zg(e)),Jo}};var aP=Object.defineProperty,cP=Object.defineProperties,lP=Object.getOwnPropertyDescriptors,bf=Object.getOwnPropertySymbols,uP=Object.prototype.hasOwnProperty,hP=Object.prototype.propertyIsEnumerable,vf=(t,e,r)=>e in t?aP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fP=(t,e)=>{for(var r in e||(e={}))uP.call(e,r)&&vf(t,r,e[r]);if(bf)for(var r of bf(e))hP.call(e,r)&&vf(t,r,e[r]);return t},dP=(t,e)=>cP(t,lP(e));async function pP(t,e){const r=ir(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(i.map(h=>gP(r.reference,h,e))),n=s.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);s.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!n.length||n.some(h=>!h),a=n.every(h=>h?.status==="0x1"),c=n.every(h=>h?.status==="0x0"),l=n.some(h=>h?.status==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:n,status:u}}async function gP(t,e,r){return await r(parseInt(t)).request(_t("eth_getTransactionReceipt",[e]))}async function yP({sendCalls:t,storage:e}){const r=await e.getItem(vi);await e.setItem(vi,dP(fP({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:de(L6)}}))}async function wP({resultId:t,storage:e}){const r=await e.getItem(vi);if(r){delete r[t],await e.setItem(vi,r);for(const i in r)Nt(r[i].expiry)&&delete r[i];await e.setItem(vi,r)}}async function mP({resultId:t,storage:e}){const r=await e.getItem(vi),i=r?.[t];if(i&&!Nt(i.expiry))return i;await wP({resultId:t,storage:e})}var bP=Object.defineProperty,vP=Object.defineProperties,EP=Object.getOwnPropertyDescriptors,Ef=Object.getOwnPropertySymbols,xP=Object.prototype.hasOwnProperty,_P=Object.prototype.propertyIsEnumerable,Ja=(t,e,r)=>e in t?bP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xo=(t,e)=>{for(var r in e||(e={}))xP.call(e,r)&&Ja(t,r,e[r]);if(Ef)for(var r of Ef(e))_P.call(e,r)&&Ja(t,r,e[r]);return t},Qo=(t,e)=>vP(t,EP(e)),Ur=(t,e,r)=>Ja(t,typeof e!="symbol"?e+"":e,r);class IP{constructor(e){Ur(this,"name","eip155"),Ur(this,"client"),Ur(this,"chainId"),Ur(this,"namespace"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"storage"),this.namespace=e.namespace,this.events=Ei("events"),this.client=Ei("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=oP.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(Mc.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||Wg(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new kg(i,Ei("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(W6(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=Qo(Xo({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u?.[h];if(f)return f;let p;try{p=rP(l,a,c)}catch(y){console.warn("Failed to extract capabilities from session",y)}if(p)return p;const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Qo(Xo({},l.sessionProperties||{}),{capabilities:Qo(Xo({},u||{}),{[h]:d})})})}catch(y){console.warn("Failed to update session with capabilities",y)}return d}async getCallStatus(e){var r,i,s;const n=this.client.session.get(e.topic),o=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await mP({resultId:(s=e.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await pP(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_t("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${F6}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,s;const n=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=n?.id,c=n?.capabilities||{},l=(i=c?.caip345)==null?void 0:i.caip2,u=(s=c?.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await yP({sendCalls:{request:o,result:n},storage:this.storage}),n}}var SP=Object.defineProperty,OP=(t,e,r)=>e in t?SP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hi=(t,e,r)=>OP(t,typeof e!="symbol"?e+"":e,r);class DP{constructor(e){hi(this,"name",Kg),hi(this,"client"),hi(this,"httpProviders"),hi(this,"events"),hi(this,"namespace"),hi(this,"chainId"),this.namespace=e.namespace,this.events=Ei("events"),this.client=Ei("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(Mc.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 ir(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{var n,o;const a=ir(s),c=(o=(n=this.namespace)==null?void 0:n.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(s,c)}),i}getHttpProvider(e){const r=ir(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||Wg(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new kg(i,Ei("disableProviderPing")))}}var $P=Object.defineProperty,AP=Object.defineProperties,PP=Object.getOwnPropertyDescriptors,xf=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,Xa=(t,e,r)=>e in t?$P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zi=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&Xa(t,r,e[r]);if(xf)for(var r of xf(e))CP.call(e,r)&&Xa(t,r,e[r]);return t},Vs=(t,e)=>AP(t,PP(e)),et=(t,e,r)=>Xa(t,typeof e!="symbol"?e+"":e,r);class qc{constructor(e){et(this,"client"),et(this,"namespaces"),et(this,"optionalNamespaces"),et(this,"sessionProperties"),et(this,"scopedProperties"),et(this,"events",new ec),et(this,"rpcProviders",{}),et(this,"session"),et(this,"providerOpts"),et(this,"logger"),et(this,"uri"),et(this,"disableProviderPing",!1),et(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Tc({logger:(r=e.logger)!=null?r:af,name:(i=this.providerOpts.name)!=null?i:Vg}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new qc(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:zi({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,ls(n,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ce("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=df(this.session.namespaces);this.namespaces=zs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});s&&(this.uri=s,this.events.emit("display_uri",s));const o=await n();this.session=o;const a=df(o.namespaces);return this.namespaces=zs(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e);this.getProvider(i).setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!gt(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 e6.init({core:this.providerOpts.core,logger:this.providerOpts.logger||af,relayUrl:this.providerOpts.relayUrl||k6,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=>pi(r)))];Yo("client",this.client),Yo("events",this.events),Yo("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=G6(r,this.session);if(i?.length===0)return;const s=Gg(i),n=zs(this.namespaces,this.optionalNamespaces),o=Vs(zi({},n[r]),{accounts:i,chains:s});r==="eip155"?this.rpcProviders[r]=new IP({namespace:o}):this.rpcProviders[r]=new DP({namespace:o})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&>(o)&&this.events.emit("accountsChanged",o.map(ff))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=pi(o),l=Go(o)!==Go(a)?`${c}:${Go(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Vs(zi({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Vs(zi({},ce("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Mc.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Vs(zi({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Kg]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=zs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>pi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=pi(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[s,n]=this.validateChain(e);n&&(this.updateNamespaceChain(s,n),i?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(s).setDefaultChain(n),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var s,n;try{if(i===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(ff);if(!gt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Ms}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${Ms}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Ms}/${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(Ms)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const TP=qc,RP="wc",UP="ethereum_provider",NP=`${RP}@2:${UP}:`,kP="https://rpc.walletconnect.org/v1/",bn=["eth_sendTransaction","personal_sign"],Jg=["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"],vn=["chainChanged","accountsChanged"],Xg=["chainChanged","accountsChanged","message","disconnect","connect"],jP=async()=>{const{createAppKit:t}=await cy(()=>import("./core-Ds-5UYKM.js").then(e=>e.bt),__vite__mapDeps([0,1,2]));return t};var FP=Object.defineProperty,LP=Object.defineProperties,MP=Object.getOwnPropertyDescriptors,_f=Object.getOwnPropertySymbols,qP=Object.prototype.hasOwnProperty,zP=Object.prototype.propertyIsEnumerable,Qa=(t,e,r)=>e in t?FP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kr=(t,e)=>{for(var r in e||(e={}))qP.call(e,r)&&Qa(t,r,e[r]);if(_f)for(var r of _f(e))zP.call(e,r)&&Qa(t,r,e[r]);return t},Vi=(t,e)=>LP(t,MP(e)),tt=(t,e,r)=>Qa(t,typeof e!="symbol"?e+"":e,r);function En(t){return Number(t[0].split(":")[1])}function Hs(t){return`0x${t.toString(16)}`}function VP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!gt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||bn,events:n||vn,rpcMap:kr({},e.length?{[En(e)]:a[En(e)]}:{})},l=n?.filter(p=>!vn.includes(p)),u=i?.filter(p=>!bn.includes(p));if(!r&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=l?.length&&u?.length||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Jg))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Xg))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class Hn{constructor(){tt(this,"events",new wt.EventEmitter),tt(this,"namespace","eip155"),tt(this,"accounts",[]),tt(this,"signer"),tt(this,"chainId",1),tt(this,"modal"),tt(this,"rpc"),tt(this,"STORAGE_KEY",NP),tt(this,"on",(e,r)=>(this.events.on(e,r),this)),tt(this,"once",(e,r)=>(this.events.once(e,r),this)),tt(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),tt(this,"off",(e,r)=>(this.events.off(e,r),this)),tt(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Hn;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=VP(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Vi(kr({namespaces:kr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!n)return;const o=uu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Hs(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Vi(kr({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=uu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Hs(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Hs(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",Vi(kr({},ce("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",Hs(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e?.chains)!=null?r:[],n=(i=e?.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?e?.methods||bn:[],c=s.length?e?.events||vn:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),f=e?.qrModalOptions||void 0;return{chains:s?.map(p=>this.formatChainId(p)),optionalChains:n.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?En(this.rpc.chains):En(this.rpc.optionalChains),this.signer=await TP.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let i;try{const s=await jP(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return t4}),o=n(Vi(kr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=s(Vi(kr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&>(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)})),i&>(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${kP}?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?.accounts),this.setAccounts(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 HP=Hn;var KP=Object.defineProperty,WP=Object.defineProperties,GP=Object.getOwnPropertyDescriptors,If=Object.getOwnPropertySymbols,YP=Object.prototype.hasOwnProperty,ZP=Object.prototype.propertyIsEnumerable,Sf=(t,e,r)=>e in t?KP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qg=(t,e)=>{for(var r in e||(e={}))YP.call(e,r)&&Sf(t,r,e[r]);if(If)for(var r of If(e))ZP.call(e,r)&&Sf(t,r,e[r]);return t},JP=(t,e)=>WP(t,GP(e));function XP(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 QP=t=>{const[e,r]=t.split(":");return ey({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function e4(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(QP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:XP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:JP(Qg({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(t.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],p=h.filter(d=>!f.includes(d.id));p.length&&(u.customWallets=p)}return u}function ey(t){return Qg({formatters:void 0,fees:void 0,serializers:void 0},t)}var t4=Object.freeze({__proto__:null,convertWCMToAppKitOptions:e4,defineChain:ey});const K4=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:HP,OPTIONAL_EVENTS:Xg,OPTIONAL_METHODS:Jg,REQUIRED_EVENTS:vn,REQUIRED_METHODS:bn,default:Hn},Symbol.toStringTag,{value:"Module"}));export{ei as A,Nc as B,C2 as C,M8 as D,Uc as E,qn as F,ls as G,Uv as H,Qr as I,Ir as J,Mn as K,Rt as L,dt as M,Tt as N,kg as O,Zl as P,Kd as Q,K4 as R,Yr as a,mS as b,ug as c,js as d,wS as e,yS as f,uh as g,Qy as h,pt as i,q as j,vS as k,nr as l,wy as m,Yi as n,ya as o,fs as p,zm as q,Rm as r,Gr as s,Je as t,im as u,N2 as v,Hw as w,sm as x,JI as y,_t as z};
|
|
15
|
+
`)===0?D.substr(1,D.length):D}).forEach(function(D){var _=D.split(":"),S=_.shift().trim();if(S){var U=_.join(":").trim();try{w.append(S,U)}catch(k){console.warn("Response "+k.message)}}}),w}B.call(A.prototype);function C(g,w){if(!(this instanceof C))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(w||(w={}),this.type="default",this.status=w.status===void 0?200:w.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=w.statusText===void 0?"":""+w.statusText,this.headers=new y(w.headers),this.url=w.url||"",this._initBody(g)}B.call(C.prototype),C.prototype.clone=function(){return new C(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},C.error=function(){var g=new C(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var O=[301,302,303,307,308];C.redirect=function(g,w){if(O.indexOf(w)===-1)throw new RangeError("Invalid status code");return new C(null,{status:w,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(w,x){this.message=w,this.name=x;var D=Error(w);this.stack=D.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function P(g,w){return new Promise(function(x,D){var _=new A(g,w);if(_.signal&&_.signal.aborted)return D(new o.DOMException("Aborted","AbortError"));var S=new XMLHttpRequest;function U(){S.abort()}S.onload=function(){var L={statusText:S.statusText,headers:N(S.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(S.status<200||S.status>599)?L.status=200:L.status=S.status,L.url="responseURL"in S?S.responseURL:L.headers.get("X-Request-URL");var M="response"in S?S.response:S.responseText;setTimeout(function(){x(new C(M,L))},0)},S.onerror=function(){setTimeout(function(){D(new TypeError("Network request failed"))},0)},S.ontimeout=function(){setTimeout(function(){D(new TypeError("Network request timed out"))},0)},S.onabort=function(){setTimeout(function(){D(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(S.open(_.method,k(_.url),!0),_.credentials==="include"?S.withCredentials=!0:_.credentials==="omit"&&(S.withCredentials=!1),"responseType"in S&&(c.blob?S.responseType="blob":c.arrayBuffer&&(S.responseType="arraybuffer")),w&&typeof w.headers=="object"&&!(w.headers instanceof y||a.Headers&&w.headers instanceof a.Headers)){var V=[];Object.getOwnPropertyNames(w.headers).forEach(function(L){V.push(f(L)),S.setRequestHeader(L,p(w.headers[L]))}),_.headers.forEach(function(L,M){V.indexOf(M)===-1&&S.setRequestHeader(M,L)})}else _.headers.forEach(function(L,M){S.setRequestHeader(M,L)});_.signal&&(_.signal.addEventListener("abort",U),S.onreadystatechange=function(){S.readyState===4&&_.signal.removeEventListener("abort",U)}),S.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return P.polyfill=!0,a.fetch||(a.fetch=P,a.Headers=y,a.Request=A,a.Response=C),o.Headers=y,o.Request=A,o.Response=C,o.fetch=P,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(Ls,Ls.exports)),Ls.exports}var r6=t6();const Zh=ay(r6);var i6=Object.defineProperty,s6=Object.defineProperties,n6=Object.getOwnPropertyDescriptors,Jh=Object.getOwnPropertySymbols,o6=Object.prototype.hasOwnProperty,a6=Object.prototype.propertyIsEnumerable,Xh=(t,e,r)=>e in t?i6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qh=(t,e)=>{for(var r in e||(e={}))o6.call(e,r)&&Xh(t,r,e[r]);if(Jh)for(var r of Jh(e))a6.call(e,r)&&Xh(t,r,e[r]);return t},ef=(t,e)=>s6(t,n6(e));const c6={Accept:"application/json","Content-Type":"application/json"},l6="POST",tf={headers:c6,method:l6},rf=10;let kg=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new wt.EventEmitter,this.isAvailable=!1,this.registering=!1,!mh(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=Yr(e),i=await(await Zh(this.url,ef(Qh({},tf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!mh(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=Yr({id:1,jsonrpc:"2.0",method:"test",params:[]});await Zh(e,ef(Qh({},tf),{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"?Gr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Mn(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return dg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>rf&&this.events.setMaxListeners(rf)}};function Fc(t){return t==null||typeof t!="object"&&typeof t!="function"}function jg(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Fg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const u6="[object RegExp]",Lg="[object String]",Mg="[object Number]",qg="[object Boolean]",zg="[object Arguments]",h6="[object Symbol]",f6="[object Date]",d6="[object Map]",p6="[object Set]",g6="[object Array]",y6="[object ArrayBuffer]",w6="[object Object]",m6="[object DataView]",b6="[object Uint8Array]",v6="[object Uint8ClampedArray]",E6="[object Uint16Array]",x6="[object Uint32Array]",_6="[object Int8Array]",I6="[object Int16Array]",S6="[object Int32Array]",O6="[object Float32Array]",D6="[object Float64Array]";function Lc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function $6(t,e){return gi(t,void 0,t,new Map,e)}function gi(t,e,r,i=new Map,s=void 0){const n=s?.(t,e,r,i);if(n!=null)return n;if(Fc(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]=gi(t[a],a,r,i,s);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;i.set(t,o);for(const[a,c]of t)o.set(a,gi(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(gi(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Lc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=gi(t[a],a,r,i,s);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return i.set(t,o),Lr(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Lr(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Lr(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Lr(o,t,r,i,s),o}if(typeof t=="object"&&A6(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Lr(o,t,r,i,s),o}return t}function Lr(t,e,r=t,i,s){const n=[...Object.keys(e),...jg(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=gi(e[a],a,r,i,s))}}function A6(t){switch(Fg(t)){case zg:case g6:case y6:case m6:case qg:case f6:case O6:case D6:case _6:case I6:case S6:case d6:case Mg:case w6:case u6:case p6:case Lg:case h6:case b6:case v6:case E6:case x6:return!0;default:return!1}}function P6(t,e){return $6(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Mg:case Lg:case qg:{const o=new t.constructor(t?.valueOf());return Lr(o,t),o}case zg:{const o={};return Lr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function sf(t){return P6(t)}function nf(t){return t!==null&&typeof t=="object"&&Fg(t)==="[object Arguments]"}function of(t){return typeof t=="object"&&t!==null}function B6(){}function C6(t){return Lc(t)}function T6(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function R6(t){if(Fc(t))return t;if(Array.isArray(t)||Lc(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 U6(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Za(s,o,i,new Map)}return s}function Za(t,e,r,i){if(Fc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return R6(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...jg(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(nf(a)&&(a={...a}),nf(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=sf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const p=h[f];u[p]=c[p]}c=u}else c=[];const l=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||of(c)&&of(a)?t[o]=Za(c,a,r,i):c==null&&T6(a)?t[o]=Za({},a,r,i):c==null&&C6(a)?t[o]=sf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function N6(t,...e){return U6(t,...e,B6)}const af="error",k6="wss://relay.walletconnect.org",j6="wc",Vg="universal_provider",Ms=`${j6}@2:${Vg}:`,Hg="https://rpc.walletconnect.org/v1/",Kg="generic",F6=`${Hg}bundler`,vi="call_status",L6=86400,Mc={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var M6=Object.defineProperty,q6=Object.defineProperties,z6=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,V6=Object.prototype.hasOwnProperty,H6=Object.prototype.propertyIsEnumerable,lf=(t,e,r)=>e in t?M6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qs=(t,e)=>{for(var r in e||(e={}))V6.call(e,r)&&lf(t,r,e[r]);if(cf)for(var r of cf(e))H6.call(e,r)&&lf(t,r,e[r]);return t},K6=(t,e)=>q6(t,z6(e));function Wg(t,e,r){var i;const s=ir(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${Hg}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function W6(t){return t.includes(":")?t.split(":")[1]:t}function Gg(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function G6(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function uf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,s;return((i=r?.chains)==null?void 0:i.length)&&((s=r?.chains)==null?void 0:s.length)>0}))}function zs(t={},e={}){const r=uf(hf(t)),i=uf(hf(e));return N6(r,i)}function hf(t){var e,r,i,s,n;const o={};if(!Lt(t))return o;for(const[a,c]of Object.entries(t)){const l=Ln(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},p=pi(a);o[p]=K6(qs(qs({},o[p]),c),{chains:Ft(l,(e=o[p])==null?void 0:e.chains),methods:Ft(u,(r=o[p])==null?void 0:r.methods),events:Ft(h,(i=o[p])==null?void 0:i.events)}),(Lt(f)||Lt(((s=o[p])==null?void 0:s.rpcMap)||{}))&&(o[p].rpcMap=qs(qs({},f),(n=o[p])==null?void 0:n.rpcMap))}return o}function ff(t){return t.includes(":")?t.split(":")[2]:t}function df(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Ln(r)?[r]:i.chains?i.chains:Gg(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Go(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 Y6(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Yg={},Ei=t=>Yg[t],Yo=(t,e)=>{Yg[t]=e};var Z6=Object.defineProperty,pf=Object.getOwnPropertySymbols,J6=Object.prototype.hasOwnProperty,X6=Object.prototype.propertyIsEnumerable,gf=(t,e,r)=>e in t?Z6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))J6.call(e,r)&&gf(t,r,e[r]);if(pf)for(var r of pf(e))X6.call(e,r)&&gf(t,r,e[r]);return t};const wf="eip155",Q6=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],eP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,Zo=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,mf=t=>Object.keys(t).filter(e=>Q6.includes(e)).reduce((e,r)=>(e[r]=tP(t[r]),e),{}),tP=t=>typeof t=="string"&&Y6(t)?JSON.parse(t):t,rP=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:s={}}=t,n={};if(!Lt(s)&&!Lt(i))return;const o=mf(i);for(const a of r){const c=eP(a);if(!c)continue;n[Zo(c)]=o;const l=s?.[`${wf}:${c}`];if(l){const u=l?.[`${wf}:${c}:${e}`];n[Zo(c)]=yf(yf({},n[Zo(c)]),mf(u||l))}}for(const[a,c]of Object.entries(n))Object.keys(c).length===0&&delete n[a];return Object.keys(n).length>0?n:void 0};var iP=Object.defineProperty,sP=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nP=(t,e,r)=>sP(t,e+"",r);let Jo,oP=class Zg{constructor(e){nP(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 Jo||(Jo=new Zg(e)),Jo}};var aP=Object.defineProperty,cP=Object.defineProperties,lP=Object.getOwnPropertyDescriptors,bf=Object.getOwnPropertySymbols,uP=Object.prototype.hasOwnProperty,hP=Object.prototype.propertyIsEnumerable,vf=(t,e,r)=>e in t?aP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fP=(t,e)=>{for(var r in e||(e={}))uP.call(e,r)&&vf(t,r,e[r]);if(bf)for(var r of bf(e))hP.call(e,r)&&vf(t,r,e[r]);return t},dP=(t,e)=>cP(t,lP(e));async function pP(t,e){const r=ir(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,s=await Promise.allSettled(i.map(h=>gP(r.reference,h,e))),n=s.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);s.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!n.length||n.some(h=>!h),a=n.every(h=>h?.status==="0x1"),c=n.every(h=>h?.status==="0x0"),l=n.some(h=>h?.status==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:n,status:u}}async function gP(t,e,r){return await r(parseInt(t)).request(_t("eth_getTransactionReceipt",[e]))}async function yP({sendCalls:t,storage:e}){const r=await e.getItem(vi);await e.setItem(vi,dP(fP({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:de(L6)}}))}async function wP({resultId:t,storage:e}){const r=await e.getItem(vi);if(r){delete r[t],await e.setItem(vi,r);for(const i in r)Nt(r[i].expiry)&&delete r[i];await e.setItem(vi,r)}}async function mP({resultId:t,storage:e}){const r=await e.getItem(vi),i=r?.[t];if(i&&!Nt(i.expiry))return i;await wP({resultId:t,storage:e})}var bP=Object.defineProperty,vP=Object.defineProperties,EP=Object.getOwnPropertyDescriptors,Ef=Object.getOwnPropertySymbols,xP=Object.prototype.hasOwnProperty,_P=Object.prototype.propertyIsEnumerable,Ja=(t,e,r)=>e in t?bP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xo=(t,e)=>{for(var r in e||(e={}))xP.call(e,r)&&Ja(t,r,e[r]);if(Ef)for(var r of Ef(e))_P.call(e,r)&&Ja(t,r,e[r]);return t},Qo=(t,e)=>vP(t,EP(e)),Ur=(t,e,r)=>Ja(t,typeof e!="symbol"?e+"":e,r);class IP{constructor(e){Ur(this,"name","eip155"),Ur(this,"client"),Ur(this,"chainId"),Ur(this,"namespace"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"storage"),this.namespace=e.namespace,this.events=Ei("events"),this.client=Ei("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=oP.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(Mc.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||Wg(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new kg(i,Ei("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(W6(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=Qo(Xo({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u?.[h];if(f)return f;let p;try{p=rP(l,a,c)}catch(y){console.warn("Failed to extract capabilities from session",y)}if(p)return p;const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Qo(Xo({},l.sessionProperties||{}),{capabilities:Qo(Xo({},u||{}),{[h]:d})})})}catch(y){console.warn("Failed to update session with capabilities",y)}return d}async getCallStatus(e){var r,i,s;const n=this.client.session.get(e.topic),o=(r=n.sessionProperties)==null?void 0:r.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(i=n.sessionProperties)==null?void 0:i.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await mP({resultId:(s=e.request.params)==null?void 0:s[0],storage:this.storage});if(c)try{return await pP(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_t("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${F6}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,s;const n=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=n?.id,c=n?.capabilities||{},l=(i=c?.caip345)==null?void 0:i.caip2,u=(s=c?.caip345)==null?void 0:s.transactionHashes;return!a||!l||!(u!=null&&u.length)||await yP({sendCalls:{request:o,result:n},storage:this.storage}),n}}var SP=Object.defineProperty,OP=(t,e,r)=>e in t?SP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hi=(t,e,r)=>OP(t,typeof e!="symbol"?e+"":e,r);class DP{constructor(e){hi(this,"name",Kg),hi(this,"client"),hi(this,"httpProviders"),hi(this,"events"),hi(this,"namespace"),hi(this,"chainId"),this.namespace=e.namespace,this.events=Ei("events"),this.client=Ei("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(Mc.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 ir(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{var n,o;const a=ir(s),c=(o=(n=this.namespace)==null?void 0:n.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(s,c)}),i}getHttpProvider(e){const r=ir(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||Wg(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Nc(new kg(i,Ei("disableProviderPing")))}}var $P=Object.defineProperty,AP=Object.defineProperties,PP=Object.getOwnPropertyDescriptors,xf=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,CP=Object.prototype.propertyIsEnumerable,Xa=(t,e,r)=>e in t?$P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zi=(t,e)=>{for(var r in e||(e={}))BP.call(e,r)&&Xa(t,r,e[r]);if(xf)for(var r of xf(e))CP.call(e,r)&&Xa(t,r,e[r]);return t},Vs=(t,e)=>AP(t,PP(e)),et=(t,e,r)=>Xa(t,typeof e!="symbol"?e+"":e,r);class qc{constructor(e){et(this,"client"),et(this,"namespaces"),et(this,"optionalNamespaces"),et(this,"sessionProperties"),et(this,"scopedProperties"),et(this,"events",new ec),et(this,"rpcProviders",{}),et(this,"session"),et(this,"providerOpts"),et(this,"logger"),et(this,"uri"),et(this,"disableProviderPing",!1),et(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Tc({logger:(r=e.logger)!=null?r:af,name:(i=this.providerOpts.name)!=null?i:Vg}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const r=new qc(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:zi({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,ls(n,o))).catch(o=>r(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ce("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=df(this.session.namespaces);this.namespaces=zs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});s&&(this.uri=s,this.events.emit("display_uri",s));const o=await n();this.session=o;const a=df(o.namespaces);return this.namespaces=zs(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e);this.getProvider(i).setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!gt(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 e6.init({core:this.providerOpts.core,logger:this.providerOpts.logger||af,relayUrl:this.providerOpts.relayUrl||k6,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=>pi(r)))];Yo("client",this.client),Yo("events",this.events),Yo("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=G6(r,this.session);if(i?.length===0)return;const s=Gg(i),n=zs(this.namespaces,this.optionalNamespaces),o=Vs(zi({},n[r]),{accounts:i,chains:s});r==="eip155"?this.rpcProviders[r]=new IP({namespace:o}):this.rpcProviders[r]=new DP({namespace:o})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&>(o)&&this.events.emit("accountsChanged",o.map(ff))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=pi(o),l=Go(o)!==Go(a)?`${c}:${Go(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Vs(zi({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Vs(zi({},ce("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Mc.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Vs(zi({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Kg]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=zs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>pi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=pi(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:r,internal:i=!1}){if(!this.namespaces)return;const[s,n]=this.validateChain(e);n&&(this.updateNamespaceChain(s,n),i?(this.events.emit("chainChanged",n),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(s).setDefaultChain(n),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var s,n;try{if(i===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(ff);if(!gt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Ms}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${Ms}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${Ms}/${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(Ms)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const TP=qc,RP="wc",UP="ethereum_provider",NP=`${RP}@2:${UP}:`,kP="https://rpc.walletconnect.org/v1/",bn=["eth_sendTransaction","personal_sign"],Jg=["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"],vn=["chainChanged","accountsChanged"],Xg=["chainChanged","accountsChanged","message","disconnect","connect"],jP=async()=>{const{createAppKit:t}=await cy(()=>import("./core-rAd4NtOZ.js").then(e=>e.bt),__vite__mapDeps([0,1,2]));return t};var FP=Object.defineProperty,LP=Object.defineProperties,MP=Object.getOwnPropertyDescriptors,_f=Object.getOwnPropertySymbols,qP=Object.prototype.hasOwnProperty,zP=Object.prototype.propertyIsEnumerable,Qa=(t,e,r)=>e in t?FP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kr=(t,e)=>{for(var r in e||(e={}))qP.call(e,r)&&Qa(t,r,e[r]);if(_f)for(var r of _f(e))zP.call(e,r)&&Qa(t,r,e[r]);return t},Vi=(t,e)=>LP(t,MP(e)),tt=(t,e,r)=>Qa(t,typeof e!="symbol"?e+"":e,r);function En(t){return Number(t[0].split(":")[1])}function Hs(t){return`0x${t.toString(16)}`}function VP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!gt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||bn,events:n||vn,rpcMap:kr({},e.length?{[En(e)]:a[En(e)]}:{})},l=n?.filter(p=>!vn.includes(p)),u=i?.filter(p=>!bn.includes(p));if(!r&&!o&&!s&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=l?.length&&u?.length||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Jg))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Xg))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?f:void 0}}class Hn{constructor(){tt(this,"events",new wt.EventEmitter),tt(this,"namespace","eip155"),tt(this,"accounts",[]),tt(this,"signer"),tt(this,"chainId",1),tt(this,"modal"),tt(this,"rpc"),tt(this,"STORAGE_KEY",NP),tt(this,"on",(e,r)=>(this.events.on(e,r),this)),tt(this,"once",(e,r)=>(this.events.once(e,r),this)),tt(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),tt(this,"off",(e,r)=>(this.events.off(e,r),this)),tt(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Hn;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=VP(this.rpc);try{const n=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Vi(kr({namespaces:kr({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e?.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var p;(p=this.modal)==null||p.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!n)return;const o=uu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Hs(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const s=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Vi(kr({},e),{chains:this.rpc.chains}),r).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=uu(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:Hs(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",Hs(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",Vi(kr({},ce("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",Hs(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e?.chains)!=null?r:[],n=(i=e?.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?e?.methods||bn:[],c=s.length?e?.events||vn:[],l=e?.optionalMethods||[],u=e?.optionalEvents||[],h=e?.rpcMap||this.buildRpcMap(o,e.projectId),f=e?.qrModalOptions||void 0;return{chains:s?.map(p=>this.formatChainId(p)),optionalChains:n.map(p=>this.formatChainId(p)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?En(this.rpc.chains):En(this.rpc.optionalChains),this.signer=await TP.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let i;try{const s=await jP(),{convertWCMToAppKitOptions:n}=await Promise.resolve().then(function(){return t4}),o=n(Vi(kr({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");i=s(Vi(kr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(s){throw console.warn(s),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(s){throw this.signer.logger.error(s),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&>(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)})),i&>(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${kP}?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?.accounts),this.setAccounts(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 HP=Hn;var KP=Object.defineProperty,WP=Object.defineProperties,GP=Object.getOwnPropertyDescriptors,If=Object.getOwnPropertySymbols,YP=Object.prototype.hasOwnProperty,ZP=Object.prototype.propertyIsEnumerable,Sf=(t,e,r)=>e in t?KP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qg=(t,e)=>{for(var r in e||(e={}))YP.call(e,r)&&Sf(t,r,e[r]);if(If)for(var r of If(e))ZP.call(e,r)&&Sf(t,r,e[r]);return t},JP=(t,e)=>WP(t,GP(e));function XP(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 QP=t=>{const[e,r]=t.split(":");return ey({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function e4(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(QP).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:XP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:JP(Qg({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(d=>({id:d.id,name:d.name,links:d.links})),...(t.desktopWallets||[]).map(d=>({id:d.id,name:d.name,links:{native:d.links.native,universal:d.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],p=h.filter(d=>!f.includes(d.id));p.length&&(u.customWallets=p)}return u}function ey(t){return Qg({formatters:void 0,fees:void 0,serializers:void 0},t)}var t4=Object.freeze({__proto__:null,convertWCMToAppKitOptions:e4,defineChain:ey});const K4=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:HP,OPTIONAL_EVENTS:Xg,OPTIONAL_METHODS:Jg,REQUIRED_EVENTS:vn,REQUIRED_METHODS:bn,default:Hn},Symbol.toStringTag,{value:"Module"}));export{ei as A,Nc as B,C2 as C,M8 as D,Uc as E,qn as F,ls as G,Uv as H,Qr as I,Ir as J,Mn as K,Rt as L,dt as M,Tt as N,kg as O,Zl as P,Kd as Q,K4 as R,Yr as a,mS as b,ug as c,js as d,wS as e,yS as f,uh as g,Qy as h,pt as i,q as j,vS as k,nr as l,wy as m,Yi as n,ya as o,fs as p,zm as q,Rm as r,Gr as s,Je as t,im as u,N2 as v,Hw as w,sm as x,JI as y,_t as z};
|