const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-PreWv3wh.js","assets/index-JBrYCIWF.js","assets/index-BLNHGcsd.css"])))=>i.map(i=>d[i]);
import{h as wo,j as Ju,_ as Zu,V as Dd,k as pr}from"./index-JBrYCIWF.js";import{r as Pd}from"./events-DQ172AOg.js";var Ye=Pd();const bo=wo(Ye);var Qo=function(r,e,t){if(t||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 r.concat(n||Array.prototype.slice.call(e))},Od=function(){function r(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"}return r}(),Ad=function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r}(),xd=function(){function r(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"}return r}(),Cd=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}(),Td=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}(),Rd=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Nd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Xo=3,jd=[["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",Rd]],ea=[["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 Bd(r){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Td:typeof navigator<"u"?Fd(navigator.userAgent):Ld()}function Ud(r){return r!==""&&jd.reduce(function(e,t){var i=t[0],s=t[1];if(e)return e;var n=s.exec(r);return!!n&&[i,n]},!1)}function Fd(r){var e=Ud(r);if(!e)return null;var t=e[0],i=e[1];if(t==="searchbot")return new Cd;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<Xo&&(s=Qo(Qo([],s,!0),kd(Xo-s.length),!0)):s=[];var n=s.join("."),o=qd(r),a=Nd.exec(r);return a&&a[1]?new xd(t,n,o,a[1]):new Od(t,n,o)}function qd(r){for(var e=0,t=ea.length;e<t;e++){var i=ea[e],s=i[0],n=i[1],o=n.exec(r);if(o)return s}return null}function Ld(){var r=typeof process<"u"&&process.version;return r?new Ad(process.version.slice(1)):null}function kd(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}var Bs={};/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var Pn=function(r,e){return Pn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])},Pn(r,e)};function Md(r,e){Pn(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var On=function(){return On=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},On.apply(this,arguments)};function zd(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s])&&(t[i[s]]=r[i[s]]);return t}function Hd(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(n=(s<3?o(n):s>3?o(e,t,n):o(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function Vd(r,e){return function(t,i){e(t,i,r)}}function Kd(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function Wd(r,e,t,i){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{u(i.next(h))}catch(l){o(l)}}function c(h){try{u(i.throw(h))}catch(l){o(l)}}function u(h){h.done?n(h.value):s(h.value).then(a,c)}u((i=i.apply(r,e||[])).next())})}function Gd(r,e){var t={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(u){return function(h){return c([u,h])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){t.label=u[1];break}if(u[0]===6&&t.label<n[1]){t.label=n[1],n=u;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(u);break}n[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(h){u=[6,h],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Yd(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function Jd(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function An(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qu(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),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&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return n}function Zd(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Qu(arguments[e]));return r}function Qd(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function wi(r){return this instanceof wi?(this.v=r,this):new wi(r)}function Xd(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(f){return new Promise(function(p,y){n.push([d,f,p,y])>1||a(d,f)})})}function a(d,f){try{c(i[d](f))}catch(p){l(n[0][3],p)}}function c(d){d.value instanceof wi?Promise.resolve(d.value.v).then(u,h):l(n[0][2],d)}function u(d){a("next",d)}function h(d){a("throw",d)}function l(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function ep(r){var e,t;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]=r[s]?function(o){return(t=!t)?{value:wi(r[s](o)),done:s==="return"}:n?n(o):o}:n}}function tp(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof An=="function"?An(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=r[n]&&function(o){return new Promise(function(a,c){o=r[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function rp(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function ip(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function sp(r){return r&&r.__esModule?r:{default:r}}function np(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function op(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const ap=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return On},__asyncDelegator:ep,__asyncGenerator:Xd,__asyncValues:tp,__await:wi,__awaiter:Wd,__classPrivateFieldGet:np,__classPrivateFieldSet:op,__createBinding:Yd,__decorate:Hd,__exportStar:Jd,__extends:Md,__generator:Gd,__importDefault:sp,__importStar:ip,__makeTemplateObject:rp,__metadata:Kd,__param:Vd,__read:Qu,__rest:zd,__spread:Zd,__spreadArrays:Qd,__values:An},Symbol.toStringTag,{value:"Module"})),bs=Ju(ap);var Us={},Zr={},ta;function cp(){if(ta)return Zr;ta=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.delay=void 0;function r(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return Zr.delay=r,Zr}var Ht={},Fs={},Vt={},ra;function up(){return ra||(ra=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.ONE_THOUSAND=Vt.ONE_HUNDRED=void 0,Vt.ONE_HUNDRED=100,Vt.ONE_THOUSAND=1e3),Vt}var qs={},ia;function hp(){return ia||(ia=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.ONE_YEAR=r.FOUR_WEEKS=r.THREE_WEEKS=r.TWO_WEEKS=r.ONE_WEEK=r.THIRTY_DAYS=r.SEVEN_DAYS=r.FIVE_DAYS=r.THREE_DAYS=r.ONE_DAY=r.TWENTY_FOUR_HOURS=r.TWELVE_HOURS=r.SIX_HOURS=r.THREE_HOURS=r.ONE_HOUR=r.SIXTY_MINUTES=r.THIRTY_MINUTES=r.TEN_MINUTES=r.FIVE_MINUTES=r.ONE_MINUTE=r.SIXTY_SECONDS=r.THIRTY_SECONDS=r.TEN_SECONDS=r.FIVE_SECONDS=r.ONE_SECOND=void 0,r.ONE_SECOND=1,r.FIVE_SECONDS=5,r.TEN_SECONDS=10,r.THIRTY_SECONDS=30,r.SIXTY_SECONDS=60,r.ONE_MINUTE=r.SIXTY_SECONDS,r.FIVE_MINUTES=r.ONE_MINUTE*5,r.TEN_MINUTES=r.ONE_MINUTE*10,r.THIRTY_MINUTES=r.ONE_MINUTE*30,r.SIXTY_MINUTES=r.ONE_MINUTE*60,r.ONE_HOUR=r.SIXTY_MINUTES,r.THREE_HOURS=r.ONE_HOUR*3,r.SIX_HOURS=r.ONE_HOUR*6,r.TWELVE_HOURS=r.ONE_HOUR*12,r.TWENTY_FOUR_HOURS=r.ONE_HOUR*24,r.ONE_DAY=r.TWENTY_FOUR_HOURS,r.THREE_DAYS=r.ONE_DAY*3,r.FIVE_DAYS=r.ONE_DAY*5,r.SEVEN_DAYS=r.ONE_DAY*7,r.THIRTY_DAYS=r.ONE_DAY*30,r.ONE_WEEK=r.SEVEN_DAYS,r.TWO_WEEKS=r.ONE_WEEK*2,r.THREE_WEEKS=r.ONE_WEEK*3,r.FOUR_WEEKS=r.ONE_WEEK*4,r.ONE_YEAR=r.ONE_DAY*365}(qs)),qs}var sa;function Xu(){return sa||(sa=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=bs;e.__exportStar(up(),r),e.__exportStar(hp(),r)}(Fs)),Fs}var na;function lp(){if(na)return Ht;na=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.fromMiliseconds=Ht.toMiliseconds=void 0;const r=Xu();function e(i){return i*r.ONE_THOUSAND}Ht.toMiliseconds=e;function t(i){return Math.floor(i/r.ONE_THOUSAND)}return Ht.fromMiliseconds=t,Ht}var oa;function dp(){return oa||(oa=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=bs;e.__exportStar(cp(),r),e.__exportStar(lp(),r)}(Us)),Us}var fr={},aa;function pp(){if(aa)return fr;aa=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.Watch=void 0;class r{constructor(){this.timestamps=new Map}start(t){if(this.timestamps.has(t))throw new Error(`Watch already started for label: ${t}`);this.timestamps.set(t,{started:Date.now()})}stop(t){const i=this.get(t);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const s=Date.now()-i.started;this.timestamps.set(t,{started:i.started,elapsed:s})}get(t){const i=this.timestamps.get(t);if(typeof i>"u")throw new Error(`No timestamp found for label: ${t}`);return i}elapsed(t){const i=this.get(t);return i.elapsed||Date.now()-i.started}}return fr.Watch=r,fr.default=r,fr}var Ls={},Qr={},ca;function fp(){if(ca)return Qr;ca=1,Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.IWatch=void 0;class r{}return Qr.IWatch=r,Qr}var ua;function gp(){return ua||(ua=1,function(r){Object.defineProperty(r,"__esModule",{value:!0}),bs.__exportStar(fp(),r)}(Ls)),Ls}var ha;function yp(){return ha||(ha=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=bs;e.__exportStar(dp(),r),e.__exportStar(pp(),r),e.__exportStar(gp(),r),e.__exportStar(Xu(),r)}(Bs)),Bs}var U=yp(),re={},la;function eh(){if(la)return re;la=1,Object.defineProperty(re,"__esModule",{value:!0}),re.getLocalStorage=re.getLocalStorageOrThrow=re.getCrypto=re.getCryptoOrThrow=re.getLocation=re.getLocationOrThrow=re.getNavigator=re.getNavigatorOrThrow=re.getDocument=re.getDocumentOrThrow=re.getFromWindowOrThrow=re.getFromWindow=void 0;function r(d){let f;return typeof window<"u"&&typeof window[d]<"u"&&(f=window[d]),f}re.getFromWindow=r;function e(d){const f=r(d);if(!f)throw new Error(`${d} is not defined in Window`);return f}re.getFromWindowOrThrow=e;function t(){return e("document")}re.getDocumentOrThrow=t;function i(){return r("document")}re.getDocument=i;function s(){return e("navigator")}re.getNavigatorOrThrow=s;function n(){return r("navigator")}re.getNavigator=n;function o(){return e("location")}re.getLocationOrThrow=o;function a(){return r("location")}re.getLocation=a;function c(){return e("crypto")}re.getCryptoOrThrow=c;function u(){return r("crypto")}re.getCrypto=u;function h(){return e("localStorage")}re.getLocalStorageOrThrow=h;function l(){return r("localStorage")}return re.getLocalStorage=l,re}var rr=eh(),Xr={},da;function mp(){if(da)return Xr;da=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.getWindowMetadata=void 0;const r=eh();function e(){let t,i;try{t=r.getDocumentOrThrow(),i=r.getLocationOrThrow()}catch{return null}function s(){const f=t.getElementsByTagName("link"),p=[];for(let y=0;y<f.length;y++){const m=f[y],_=m.getAttribute("rel");if(_&&_.toLowerCase().indexOf("icon")>-1){const b=m.getAttribute("href");if(b)if(b.toLowerCase().indexOf("https:")===-1&&b.toLowerCase().indexOf("http:")===-1&&b.indexOf("//")!==0){let I=i.protocol+"//"+i.host;if(b.indexOf("/")===0)I+=b;else{const A=i.pathname.split("/");A.pop();const C=A.join("/");I+=C+"/"+b}p.push(I)}else if(b.indexOf("//")===0){const I=i.protocol+b;p.push(I)}else p.push(b)}}return p}function n(...f){const p=t.getElementsByTagName("meta");for(let y=0;y<p.length;y++){const m=p[y],_=["itemprop","property","name"].map(b=>m.getAttribute(b)).filter(b=>b?f.includes(b):!1);if(_.length&&_){const b=m.getAttribute("content");if(b)return b}}return""}function o(){let f=n("name","og:site_name","og:title","twitter:title");return f||(f=t.title),f}function a(){return n("description","og:description","twitter:description","keywords")}const c=o(),u=a(),h=i.origin,l=s();return{description:u,url:h,icons:l,name:c}}return Xr.getWindowMetadata=e,Xr}var wp=mp();function bi(r,{strict:e=!0}={}){return!r||typeof r!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(r):r.startsWith("0x")}function pa(r){return bi(r,{strict:!1})?Math.ceil((r.length-2)/2):r.length}const th="2.23.2";let ei={getDocsUrl:({docsBaseUrl:r,docsPath:e="",docsSlug:t})=>e?`${r??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${th}`};class ir extends Error{constructor(e,t={}){var a;const i=(()=>{var c;return t.cause instanceof ir?t.cause.details:(c=t.cause)!=null&&c.message?t.cause.message:t.details})(),s=t.cause instanceof ir&&t.cause.docsPath||t.docsPath,n=(a=ei.getDocsUrl)==null?void 0:a.call(ei,{...t,docsPath:s}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...ei.version?[`Version: ${ei.version}`]:[]].join(`
`);super(o,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=i,this.docsPath=s,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=th}walk(e){return rh(this,e)}}function rh(r,e){return e!=null&&e(r)?r:r&&typeof r=="object"&&"cause"in r&&r.cause!==void 0?rh(r.cause,e):e?null:r}class ih extends ir{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Hr(r,{dir:e,size:t=32}={}){return typeof r=="string"?bp(r,{dir:e,size:t}):vp(r,{dir:e,size:t})}function bp(r,{dir:e,size:t=32}={}){if(t===null)return r;const i=r.replace("0x","");if(i.length>t*2)throw new ih({size:Math.ceil(i.length/2),targetSize:t,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function vp(r,{dir:e,size:t=32}={}){if(t===null)return r;if(r.length>t)throw new ih({size:r.length,targetSize:t,type:"bytes"});const i=new Uint8Array(t);for(let s=0;s<t;s++){const n=e==="right";i[n?s:t-s-1]=r[n?s:r.length-s-1]}return i}class Ep extends ir{constructor({max:e,min:t,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class _p extends ir{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Vr(r,{size:e}){if(pa(r)>e)throw new _p({givenSize:pa(r),maxSize:e})}function xn(r,e={}){const{signed:t}=e;e.size&&Vr(r,{size:e.size});const i=BigInt(r);if(!t)return i;const s=(r.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function Ip(r,e={}){return Number(xn(r,e))}const $p=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Cn(r,e={}){return typeof r=="number"||typeof r=="bigint"?nh(r,e):typeof r=="string"?Pp(r,e):typeof r=="boolean"?Sp(r,e):sh(r,e)}function Sp(r,e={}){const t=`0x${Number(r)}`;return typeof e.size=="number"?(Vr(t,{size:e.size}),Hr(t,{size:e.size})):t}function sh(r,e={}){let t="";for(let s=0;s<r.length;s++)t+=$p[r[s]];const i=`0x${t}`;return typeof e.size=="number"?(Vr(i,{size:e.size}),Hr(i,{dir:"right",size:e.size})):i}function nh(r,e={}){const{signed:t,size:i}=e,s=BigInt(r);let n;i?t?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof r=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&t?-n-1n:0;if(n&&s>n||s<o){const c=typeof r=="bigint"?"n":"";throw new Ep({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:i,value:`${r}${c}`})}const a=`0x${(t&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?Hr(a,{size:i}):a}const Dp=new TextEncoder;function Pp(r,e={}){const t=Dp.encode(r);return sh(t,e)}const Op=new TextEncoder;function Ap(r,e={}){return typeof r=="number"||typeof r=="bigint"?Cp(r,e):typeof r=="boolean"?xp(r,e):bi(r)?oh(r,e):ah(r,e)}function xp(r,e={}){const t=new Uint8Array(1);return t[0]=Number(r),typeof e.size=="number"?(Vr(t,{size:e.size}),Hr(t,{size:e.size})):t}const _t={zero:48,nine:57,A:65,F:70,a:97,f:102};function fa(r){if(r>=_t.zero&&r<=_t.nine)return r-_t.zero;if(r>=_t.A&&r<=_t.F)return r-(_t.A-10);if(r>=_t.a&&r<=_t.f)return r-(_t.a-10)}function oh(r,e={}){let t=r;e.size&&(Vr(t,{size:e.size}),t=Hr(t,{dir:"right",size:e.size}));let i=t.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=fa(i.charCodeAt(a++)),u=fa(i.charCodeAt(a++));if(c===void 0||u===void 0)throw new ir(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+u}return n}function Cp(r,e){const t=nh(r,e);return oh(t)}function ah(r,e={}){const t=Op.encode(r);return typeof e.size=="number"?(Vr(t,{size:e.size}),Hr(t,{dir:"right",size:e.size})):t}function ga(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Tp(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function vo(r,...e){if(!Tp(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ya(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Rp(r,e){vo(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Li=BigInt(2**32-1),ma=BigInt(32);function Np(r,e=!1){return e?{h:Number(r&Li),l:Number(r>>ma&Li)}:{h:Number(r>>ma&Li)|0,l:Number(r&Li)|0}}function jp(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=Np(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Bp=(r,e,t)=>r<<t|e>>>32-t,Up=(r,e,t)=>e<<t|r>>>32-t,Fp=(r,e,t)=>e<<t-32|r>>>64-t,qp=(r,e,t)=>r<<t-32|e>>>64-t;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lp(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}const wa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kp(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function ba(r){for(let e=0;e<r.length;e++)r[e]=kp(r[e])}function Mp(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function ch(r){return typeof r=="string"&&(r=Mp(r)),vo(r),r}class zp{clone(){return this._cloneInto()}}function Hp(r){const e=i=>r().update(ch(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}const uh=[],hh=[],lh=[],Vp=BigInt(0),ti=BigInt(1),Kp=BigInt(2),Wp=BigInt(7),Gp=BigInt(256),Yp=BigInt(113);for(let r=0,e=ti,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],uh.push(2*(5*i+t)),hh.push((r+1)*(r+2)/2%64);let s=Vp;for(let n=0;n<7;n++)e=(e<<ti^(e>>Wp)*Yp)%Gp,e&Kp&&(s^=ti<<(ti<<BigInt(n))-ti);lh.push(s)}const[Jp,Zp]=jp(lh,!0),va=(r,e,t)=>t>32?Fp(r,e,t):Bp(r,e,t),Ea=(r,e,t)=>t>32?qp(r,e,t):Up(r,e,t);function Qp(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],h=t[c+1],l=va(u,h,1)^t[a],d=Ea(u,h,1)^t[a+1];for(let f=0;f<50;f+=10)r[o+f]^=l,r[o+f+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=hh[o],c=va(s,n,a),u=Ea(s,n,a),h=uh[o];s=r[h],n=r[h+1],r[h]=c,r[h+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=Jp[i],r[1]^=Zp[i]}t.fill(0)}class Eo extends zp{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ga(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Lp(this.state)}keccak(){wa||ba(this.state32),Qp(this.state32,this.rounds),wa||ba(this.state32),this.posOut=0,this.pos=0}update(e){ya(this);const{blockLen:t,state:i}=this;e=ch(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,t&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ya(this,!1),vo(e),this.finish();const t=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(t.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 ga(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rp(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Eo(t,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 Xp=(r,e,t)=>Hp(()=>new Eo(e,r,t)),ef=Xp(1,136,256/8);function dh(r,e){const t=e||"hex",i=ef(bi(r,{strict:!1})?Ap(r):r);return t==="bytes"?i:Cn(i)}class tf extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&t!==void 0&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const ks=new tf(8192);function rf(r,e){if(ks.has(`${r}.${e}`))return ks.get(`${r}.${e}`);const t=r.substring(2).toLowerCase(),i=dh(ah(t),"bytes"),s=t.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return ks.set(`${r}.${e}`,n),n}function sf(r){const e=dh(`0x${r.substring(4)}`).substring(26);return rf(`0x${e}`)}async function nf({hash:r,signature:e}){const t=bi(r)?r:Cn(r),{secp256k1:i}=await Zu(async()=>{const{secp256k1:o}=await import("./secp256k1-IRfSGIr4.js");return{secp256k1:o}},[]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:h,v:l,yParity:d}=e,f=Number(d??l),p=_a(f);return new i.Signature(xn(u),xn(h)).addRecoveryBit(p)}const o=bi(e)?e:Cn(e),a=Ip(`0x${o.slice(130)}`),c=_a(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function _a(r){if(r===0||r===1)return r;if(r===27)return 0;if(r===28)return 1;throw new Error("Invalid yParityOrV value")}async function of({hash:r,signature:e}){return sf(await nf({hash:r,signature:e}))}const af=r=>JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),cf=r=>{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,t=r.replace(e,'$1"$2n"$3');return JSON.parse(t,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function sr(r){if(typeof r!="string")throw new Error(`Cannot safe json parse value of type ${typeof r}`);try{return cf(r)}catch{return r}}function Rt(r){return typeof r=="string"?r:af(r)||""}function uf(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ph(r,...e){if(!uf(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Ia(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function hf(r,e){ph(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const gr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ms=r=>new DataView(r.buffer,r.byteOffset,r.byteLength);function lf(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function fh(r){return typeof r=="string"&&(r=lf(r)),ph(r),r}let df=class{clone(){return this._cloneInto()}};function pf(r){const e=i=>r().update(fh(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function gh(r=32){if(gr&&typeof gr.getRandomValues=="function")return gr.getRandomValues(new Uint8Array(r));if(gr&&typeof gr.randomBytes=="function")return gr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function ff(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=i?4:0,u=i?0:4;r.setUint32(e+c,o,i),r.setUint32(e+u,a,i)}let gf=class extends df{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ms(this.buffer)}update(e){Ia(this);const{view:t,buffer:i,blockLen:s}=this;e=fh(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=Ms(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(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ia(this),hf(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let l=o;l<s;l++)t[l]=0;ff(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Ms(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,h[l],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(i),e}};const ki=BigInt(2**32-1),Tn=BigInt(32);function yh(r,e=!1){return e?{h:Number(r&ki),l:Number(r>>Tn&ki)}:{h:Number(r>>Tn&ki)|0,l:Number(r&ki)|0}}function yf(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=yh(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const mf=(r,e)=>BigInt(r>>>0)<<Tn|BigInt(e>>>0),wf=(r,e,t)=>r>>>t,bf=(r,e,t)=>r<<32-t|e>>>t,vf=(r,e,t)=>r>>>t|e<<32-t,Ef=(r,e,t)=>r<<32-t|e>>>t,_f=(r,e,t)=>r<<64-t|e>>>t-32,If=(r,e,t)=>r>>>t-32|e<<64-t,$f=(r,e)=>e,Sf=(r,e)=>r,Df=(r,e,t)=>r<<t|e>>>32-t,Pf=(r,e,t)=>e<<t|r>>>32-t,Of=(r,e,t)=>e<<t-32|r>>>64-t,Af=(r,e,t)=>r<<t-32|e>>>64-t;function xf(r,e,t,i){const s=(e>>>0)+(i>>>0);return{h:r+t+(s/2**32|0)|0,l:s|0}}const Cf=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Tf=(r,e,t,i)=>e+t+i+(r/2**32|0)|0,Rf=(r,e,t,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Nf=(r,e,t,i,s)=>e+t+i+s+(r/2**32|0)|0,jf=(r,e,t,i,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),Bf=(r,e,t,i,s,n)=>e+t+i+s+n+(r/2**32|0)|0,K={fromBig:yh,split:yf,toBig:mf,shrSH:wf,shrSL:bf,rotrSH:vf,rotrSL:Ef,rotrBH:_f,rotrBL:If,rotr32H:$f,rotr32L:Sf,rotlSH:Df,rotlSL:Pf,rotlBH:Of,rotlBL:Af,add:xf,add3L:Cf,add3H:Tf,add4L:Rf,add4H:Nf,add5H:Bf,add5L:jf},[Uf,Ff]=K.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(r=>BigInt(r))),Nt=new Uint32Array(80),jt=new Uint32Array(80);let qf=class extends gf{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:h,Fh:l,Fl:d,Gh:f,Gl:p,Hh:y,Hl:m}=this;return[e,t,i,s,n,o,a,c,u,h,l,d,f,p,y,m]}set(e,t,i,s,n,o,a,c,u,h,l,d,f,p,y,m){this.Ah=e|0,this.Al=t|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=u|0,this.El=h|0,this.Fh=l|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=y|0,this.Hl=m|0}process(e,t){for(let I=0;I<16;I++,t+=4)Nt[I]=e.getUint32(t),jt[I]=e.getUint32(t+=4);for(let I=16;I<80;I++){const A=Nt[I-15]|0,C=jt[I-15]|0,E=K.rotrSH(A,C,1)^K.rotrSH(A,C,8)^K.shrSH(A,C,7),$=K.rotrSL(A,C,1)^K.rotrSL(A,C,8)^K.shrSL(A,C,7),S=Nt[I-2]|0,P=jt[I-2]|0,j=K.rotrSH(S,P,19)^K.rotrBH(S,P,61)^K.shrSH(S,P,6),T=K.rotrSL(S,P,19)^K.rotrBL(S,P,61)^K.shrSL(S,P,6),B=K.add4L($,T,jt[I-7],jt[I-16]),k=K.add4H(B,E,j,Nt[I-7],Nt[I-16]);Nt[I]=k|0,jt[I]=B|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:h,Eh:l,El:d,Fh:f,Fl:p,Gh:y,Gl:m,Hh:_,Hl:b}=this;for(let I=0;I<80;I++){const A=K.rotrSH(l,d,14)^K.rotrSH(l,d,18)^K.rotrBH(l,d,41),C=K.rotrSL(l,d,14)^K.rotrSL(l,d,18)^K.rotrBL(l,d,41),E=l&f^~l&y,$=d&p^~d&m,S=K.add5L(b,C,$,Ff[I],jt[I]),P=K.add5H(S,_,A,E,Uf[I],Nt[I]),j=S|0,T=K.rotrSH(i,s,28)^K.rotrBH(i,s,34)^K.rotrBH(i,s,39),B=K.rotrSL(i,s,28)^K.rotrBL(i,s,34)^K.rotrBL(i,s,39),k=i&n^i&a^n&a,g=s&o^s&c^o&c;_=y|0,b=m|0,y=f|0,m=p|0,f=l|0,p=d|0,{h:l,l:d}=K.add(u|0,h|0,P|0,j|0),u=a|0,h=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const w=K.add3L(j,B,g);i=K.add3H(w,P,T,k),s=w|0}({h:i,l:s}=K.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=K.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=K.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:h}=K.add(this.Dh|0,this.Dl|0,u|0,h|0),{h:l,l:d}=K.add(this.Eh|0,this.El|0,l|0,d|0),{h:f,l:p}=K.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:y,l:m}=K.add(this.Gh|0,this.Gl|0,y|0,m|0),{h:_,l:b}=K.add(this.Hh|0,this.Hl|0,_|0,b|0),this.set(i,s,n,o,a,c,u,h,l,d,f,p,y,m,_,b)}roundClean(){Nt.fill(0),jt.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 Lf=pf(()=>new qf);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _o=BigInt(0),mh=BigInt(1),kf=BigInt(2);function Io(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $o(r){if(!Io(r))throw new Error("Uint8Array expected")}function zs(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}const Mf=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function So(r){$o(r);let e="";for(let t=0;t<r.length;t++)e+=Mf[r[t]];return e}function wh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?_o:BigInt("0x"+r)}const It={_0:48,_9:57,A:65,F:70,a:97,f:102};function $a(r){if(r>=It._0&&r<=It._9)return r-It._0;if(r>=It.A&&r<=It.F)return r-(It.A-10);if(r>=It.a&&r<=It.f)return r-(It.a-10)}function bh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);const e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=$a(r.charCodeAt(n)),a=$a(r.charCodeAt(n+1));if(o===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function zf(r){return wh(So(r))}function ts(r){return $o(r),wh(So(Uint8Array.from(r).reverse()))}function vh(r,e){return bh(r.toString(16).padStart(e*2,"0"))}function Rn(r,e){return vh(r,e).reverse()}function $t(r,e,t){let i;if(typeof e=="string")try{i=bh(e)}catch(n){throw new Error(r+" must be hex string or Uint8Array, cause: "+n)}else if(Io(e))i=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const s=i.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return i}function Sa(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];$o(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}const Hs=r=>typeof r=="bigint"&&_o<=r;function Hf(r,e,t){return Hs(r)&&Hs(e)&&Hs(t)&&e<=r&&r<t}function ri(r,e,t,i){if(!Hf(e,t,i))throw new Error("expected valid "+r+": "+t+" <= n < "+i+", got "+e)}function Vf(r){let e;for(e=0;r>_o;r>>=mh,e+=1);return e}const Kf=r=>(kf<<BigInt(r-1))-mh,Wf={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Io(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Do(r,e,t={}){const i=(s,n,o)=>{const a=Wf[n];if(typeof a!="function")throw new Error("invalid validator function");const c=r[s];if(!(o&&c===void 0)&&!a(c,r))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(t))i(s,n,!0);return r}function Da(r){const e=new WeakMap;return(t,...i)=>{const s=e.get(t);if(s!==void 0)return s;const n=r(t,...i);return e.set(t,n),n}}const be=BigInt(0),ce=BigInt(1),Yt=BigInt(2),Gf=BigInt(3),Nn=BigInt(4),Pa=BigInt(5),Oa=BigInt(8);function pe(r,e){const t=r%e;return t>=be?t:e+t}function Yf(r,e,t){if(e<be)throw new Error("invalid exponent, negatives unsupported");if(t<=be)throw new Error("invalid modulus");if(t===ce)return be;let i=ce;for(;e>be;)e&ce&&(i=i*r%t),r=r*r%t,e>>=ce;return i}function pt(r,e,t){let i=r;for(;e-- >be;)i*=i,i%=t;return i}function Aa(r,e){if(r===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let t=pe(r,e),i=e,s=be,n=ce;for(;t!==be;){const o=i/t,a=i%t,c=s-n*o;i=t,t=a,s=n,n=c}if(i!==ce)throw new Error("invert: does not exist");return pe(s,e)}function Jf(r){const e=(r-ce)/Yt;let t,i,s;for(t=r-ce,i=0;t%Yt===be;t/=Yt,i++);for(s=Yt;s<r&&Yf(s,e,r)!==r-ce;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(r+ce)/Nn;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(t+ce)/Yt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),t),h=o.pow(a,n),l=o.pow(a,t);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(l);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(u,ce<<BigInt(c-d-1));u=o.sqr(f),h=o.mul(h,f),l=o.mul(l,u),c=d}return h}}function Zf(r){if(r%Nn===Gf){const e=(r+ce)/Nn;return function(t,i){const s=t.pow(i,e);if(!t.eql(t.sqr(s),i))throw new Error("Cannot find square root");return s}}if(r%Oa===Pa){const e=(r-Pa)/Oa;return function(t,i){const s=t.mul(i,Yt),n=t.pow(s,e),o=t.mul(i,n),a=t.mul(t.mul(o,Yt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),i))throw new Error("Cannot find square root");return c}}return Jf(r)}const Qf=(r,e)=>(pe(r,e)&ce)===ce,Xf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function eg(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Xf.reduce((i,s)=>(i[s]="function",i),e);return Do(r,t)}function tg(r,e,t){if(t<be)throw new Error("invalid exponent, negatives unsupported");if(t===be)return r.ONE;if(t===ce)return e;let i=r.ONE,s=e;for(;t>be;)t&ce&&(i=r.mul(i,s)),s=r.sqr(s),t>>=ce;return i}function rg(r,e){const t=new Array(e.length),i=e.reduce((n,o,a)=>r.is0(o)?n:(t[a]=n,r.mul(n,o)),r.ONE),s=r.inv(i);return e.reduceRight((n,o,a)=>r.is0(o)?n:(t[a]=r.mul(n,t[a]),r.mul(n,o)),s),t}function Eh(r,e){const t=e!==void 0?e:r.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function _h(r,e,t=!1,i={}){if(r<=be)throw new Error("invalid field: expected ORDER > 0, got "+r);const{nBitLength:s,nByteLength:n}=Eh(r,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:n,MASK:Kf(s),ZERO:be,ONE:ce,create:c=>pe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return be<=c&&c<r},is0:c=>c===be,isOdd:c=>(c&ce)===ce,neg:c=>pe(-c,r),eql:(c,u)=>c===u,sqr:c=>pe(c*c,r),add:(c,u)=>pe(c+u,r),sub:(c,u)=>pe(c-u,r),mul:(c,u)=>pe(c*u,r),pow:(c,u)=>tg(a,c,u),div:(c,u)=>pe(c*Aa(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Aa(c,r),sqrt:i.sqrt||(c=>(o||(o=Zf(r)),o(a,c))),invertBatch:c=>rg(a,c),cmov:(c,u,h)=>h?u:c,toBytes:c=>t?Rn(c,n):vh(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?ts(c):zf(c)}});return Object.freeze(a)}const xa=BigInt(0),Mi=BigInt(1);function Vs(r,e){const t=e.negate();return r?t:e}function Ih(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ks(r,e){Ih(r,e);const t=Math.ceil(e/r)+1,i=2**(r-1);return{windows:t,windowSize:i}}function ig(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function sg(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const Ws=new WeakMap,$h=new WeakMap;function Gs(r){return $h.get(r)||1}function ng(r,e){return{constTimeNegate:Vs,hasPrecomputes(t){return Gs(t)!==1},unsafeLadder(t,i,s=r.ZERO){let n=t;for(;i>xa;)i&Mi&&(s=s.add(n)),n=n.double(),i>>=Mi;return s},precomputeWindow(t,i){const{windows:s,windowSize:n}=Ks(i,e),o=[];let a=t,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let h=1;h<n;h++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,s){const{windows:n,windowSize:o}=Ks(t,e);let a=r.ZERO,c=r.BASE;const u=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&u);s>>=l,p>o&&(p-=h,s+=Mi);const y=f,m=f+Math.abs(p)-1,_=d%2!==0,b=p<0;p===0?c=c.add(Vs(_,i[y])):a=a.add(Vs(b,i[m]))}return{p:a,f:c}},wNAFUnsafe(t,i,s,n=r.ZERO){const{windows:o,windowSize:a}=Ks(t,e),c=BigInt(2**t-1),u=2**t,h=BigInt(t);for(let l=0;l<o;l++){const d=l*a;if(s===xa)break;let f=Number(s&c);if(s>>=h,f>a&&(f-=u,s+=Mi),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(t,i,s){let n=Ws.get(i);return n||(n=this.precomputeWindow(i,t),t!==1&&Ws.set(i,s(n))),n},wNAFCached(t,i,s){const n=Gs(t);return this.wNAF(n,this.getPrecomputes(n,t,s),i)},wNAFCachedUnsafe(t,i,s,n){const o=Gs(t);return o===1?this.unsafeLadder(t,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),i,n)},setWindowSize(t,i){Ih(i,e),$h.set(t,i),Ws.delete(t)}}}function og(r,e,t,i){if(ig(t,r),sg(i,e),t.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=r.ZERO,n=Vf(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let h=s;for(let l=u;l>=0;l-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(l)&BigInt(a));c[y]=c[y].add(t[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(h=h.add(d),l!==0)for(let f=0;f<o;f++)h=h.double()}return h}function ag(r){return eg(r.Fp),Do(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Eh(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}const nt=BigInt(0),je=BigInt(1),zi=BigInt(2),cg=BigInt(8),ug={zip215:!0};function hg(r){const e=ag(r);return Do(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function lg(r){const e=hg(r),{Fp:t,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=zi<<BigInt(a*8)-je,h=t.create,l=_h(e.n,e.nBitLength),d=e.uvRatio||((w,v)=>{try{return{isValid:!0,value:t.sqrt(w*t.inv(v))}}catch{return{isValid:!1,value:nt}}}),f=e.adjustScalarBytes||(w=>w),p=e.domain||((w,v,O)=>{if(zs("phflag",O),v.length||O)throw new Error("Contexts/pre-hash are not supported");return w});function y(w,v){ri("coordinate "+w,v,nt,u)}function m(w){if(!(w instanceof I))throw new Error("ExtendedPoint expected")}const _=Da((w,v)=>{const{ex:O,ey:x,ez:D}=w,R=w.is0();v==null&&(v=R?cg:t.inv(D));const q=h(O*v),L=h(x*v),M=h(D*v);if(R)return{x:nt,y:je};if(M!==je)throw new Error("invZ was invalid");return{x:q,y:L}}),b=Da(w=>{const{a:v,d:O}=e;if(w.is0())throw new Error("bad point: ZERO");const{ex:x,ey:D,ez:R,et:q}=w,L=h(x*x),M=h(D*D),z=h(R*R),V=h(z*z),H=h(L*v),ne=h(z*h(H+M)),ee=h(V+h(O*h(L*M)));if(ne!==ee)throw new Error("bad point: equation left != right (1)");const Y=h(x*D),Ae=h(R*q);if(Y!==Ae)throw new Error("bad point: equation left != right (2)");return!0});class I{constructor(v,O,x,D){this.ex=v,this.ey=O,this.ez=x,this.et=D,y("x",v),y("y",O),y("z",x),y("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof I)throw new Error("extended point not allowed");const{x:O,y:x}=v||{};return y("x",O),y("y",x),new I(O,x,je,h(O*x))}static normalizeZ(v){const O=t.invertBatch(v.map(x=>x.ez));return v.map((x,D)=>x.toAffine(O[D])).map(I.fromAffine)}static msm(v,O){return og(I,l,v,O)}_setWindowSize(v){E.setWindowSize(this,v)}assertValidity(){b(this)}equals(v){m(v);const{ex:O,ey:x,ez:D}=this,{ex:R,ey:q,ez:L}=v,M=h(O*L),z=h(R*D),V=h(x*L),H=h(q*D);return M===z&&V===H}is0(){return this.equals(I.ZERO)}negate(){return new I(h(-this.ex),this.ey,this.ez,h(-this.et))}double(){const{a:v}=e,{ex:O,ey:x,ez:D}=this,R=h(O*O),q=h(x*x),L=h(zi*h(D*D)),M=h(v*R),z=O+x,V=h(h(z*z)-R-q),H=M+q,ne=H-L,ee=M-q,Y=h(V*ne),Ae=h(H*ee),Ee=h(V*ee),Ce=h(ne*H);return new I(Y,Ae,Ce,Ee)}add(v){m(v);const{a:O,d:x}=e,{ex:D,ey:R,ez:q,et:L}=this,{ex:M,ey:z,ez:V,et:H}=v;if(O===BigInt(-1)){const Vo=h((R-D)*(z+M)),Ko=h((R+D)*(z-M)),js=h(Ko-Vo);if(js===nt)return this.double();const Wo=h(q*zi*H),Go=h(L*zi*V),Yo=Go+Wo,Jo=Ko+Vo,Zo=Go-Wo,_d=h(Yo*js),Id=h(Jo*Zo),$d=h(Yo*Zo),Sd=h(js*Jo);return new I(_d,Id,Sd,$d)}const ne=h(D*M),ee=h(R*z),Y=h(L*x*H),Ae=h(q*V),Ee=h((D+R)*(M+z)-ne-ee),Ce=Ae-Y,Je=Ae+Y,Ze=h(ee-O*ne),dr=h(Ee*Ce),bd=h(Je*Ze),vd=h(Ee*Ze),Ed=h(Ce*Je);return new I(dr,bd,Ed,vd)}subtract(v){return this.add(v.negate())}wNAF(v){return E.wNAFCached(this,v,I.normalizeZ)}multiply(v){const O=v;ri("scalar",O,je,i);const{p:x,f:D}=this.wNAF(O);return I.normalizeZ([x,D])[0]}multiplyUnsafe(v,O=I.ZERO){const x=v;return ri("scalar",x,nt,i),x===nt?C:this.is0()||x===je?this:E.wNAFCachedUnsafe(this,x,I.normalizeZ,O)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return E.unsafeLadder(this,i).is0()}toAffine(v){return _(this,v)}clearCofactor(){const{h:v}=e;return v===je?this:this.multiplyUnsafe(v)}static fromHex(v,O=!1){const{d:x,a:D}=e,R=t.BYTES;v=$t("pointHex",v,R),zs("zip215",O);const q=v.slice(),L=v[R-1];q[R-1]=L&-129;const M=ts(q),z=O?u:t.ORDER;ri("pointHex.y",M,nt,z);const V=h(M*M),H=h(V-je),ne=h(x*V-D);let{isValid:ee,value:Y}=d(H,ne);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const Ae=(Y&je)===je,Ee=(L&128)!==0;if(!O&&Y===nt&&Ee)throw new Error("Point.fromHex: x=0 and x_0=1");return Ee!==Ae&&(Y=h(-Y)),I.fromAffine({x:Y,y:M})}static fromPrivateKey(v){return P(v).point}toRawBytes(){const{x:v,y:O}=this.toAffine(),x=Rn(O,t.BYTES);return x[x.length-1]|=v&je?128:0,x}toHex(){return So(this.toRawBytes())}}I.BASE=new I(e.Gx,e.Gy,je,h(e.Gx*e.Gy)),I.ZERO=new I(nt,je,je,nt);const{BASE:A,ZERO:C}=I,E=ng(I,a*8);function $(w){return pe(w,i)}function S(w){return $(ts(w))}function P(w){const v=t.BYTES;w=$t("private key",w,v);const O=$t("hashed private key",n(w),2*v),x=f(O.slice(0,v)),D=O.slice(v,2*v),R=S(x),q=A.multiply(R),L=q.toRawBytes();return{head:x,prefix:D,scalar:R,point:q,pointBytes:L}}function j(w){return P(w).pointBytes}function T(w=new Uint8Array,...v){const O=Sa(...v);return S(n(p(O,$t("context",w),!!s)))}function B(w,v,O={}){w=$t("message",w),s&&(w=s(w));const{prefix:x,scalar:D,pointBytes:R}=P(v),q=T(O.context,x,w),L=A.multiply(q).toRawBytes(),M=T(O.context,L,R,w),z=$(q+M*D);ri("signature.s",z,nt,i);const V=Sa(L,Rn(z,t.BYTES));return $t("result",V,t.BYTES*2)}const k=ug;function g(w,v,O,x=k){const{context:D,zip215:R}=x,q=t.BYTES;w=$t("signature",w,2*q),v=$t("message",v),O=$t("publicKey",O,q),R!==void 0&&zs("zip215",R),s&&(v=s(v));const L=ts(w.slice(q,2*q));let M,z,V;try{M=I.fromHex(O,R),z=I.fromHex(w.slice(0,q),R),V=A.multiplyUnsafe(L)}catch{return!1}if(!R&&M.isSmallOrder())return!1;const H=T(D,z.toRawBytes(),M.toRawBytes(),v);return z.add(M.multiplyUnsafe(H)).subtract(V).clearCofactor().equals(I.ZERO)}return A._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:B,verify:g,ExtendedPoint:I,utils:{getExtendedPublicKey:P,randomPrivateKey:()=>o(t.BYTES),precompute(w=8,v=I.BASE){return v._setWindowSize(w),v.multiply(BigInt(3)),v}}}}BigInt(0),BigInt(1);const Po=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ca=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const dg=BigInt(1),Ta=BigInt(2);BigInt(3);const pg=BigInt(5),fg=BigInt(8);function gg(r){const e=BigInt(10),t=BigInt(20),i=BigInt(40),s=BigInt(80),n=Po,o=r*r%n*r%n,a=pt(o,Ta,n)*o%n,c=pt(a,dg,n)*r%n,u=pt(c,pg,n)*c%n,h=pt(u,e,n)*u%n,l=pt(h,t,n)*h%n,d=pt(l,i,n)*l%n,f=pt(d,s,n)*d%n,p=pt(f,s,n)*d%n,y=pt(p,e,n)*u%n;return{pow_p_5_8:pt(y,Ta,n)*r%n,b2:o}}function yg(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function mg(r,e){const t=Po,i=pe(e*e*e,t),s=pe(i*i*e,t),n=gg(r*s).pow_p_5_8;let o=pe(r*i*n,t);const a=pe(e*o*o,t),c=o,u=pe(o*Ca,t),h=a===r,l=a===pe(-r,t),d=a===pe(-r*Ca,t);return h&&(o=c),(l||d)&&(o=u),Qf(o,t)&&(o=pe(-o,t)),{isValid:h||l,value:o}}const wg=_h(Po,void 0,!0),bg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:wg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:fg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Lf,randomBytes:gh,adjustScalarBytes:yg,uvRatio:mg},Sh=lg(bg),vg="EdDSA",Eg="JWT",us=".",vs="base64url",Dh="utf8",Ph="utf8",_g=":",Ig="did",$g="key",Ra="base58btc",Sg="z",Dg="K36",Pg=32;function Oo(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}function Oh(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Oo(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}function Ah(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=Oh(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return Oo(t)}function Og(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,m=0,_=0,b=p.length;_!==b&&p[_]===0;)_++,y++;for(var I=(b-_)*h+1>>>0,A=new Uint8Array(I);_!==b;){for(var C=p[_],E=0,$=I-1;(C!==0||E<m)&&$!==-1;$--,E++)C+=256*A[$]>>>0,A[$]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");m=E,_++}for(var S=I-m;S!==I&&A[S]===0;)S++;for(var P=c.repeat(y);S<I;++S)P+=r.charAt(A[S]);return P}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,_=0;p[y]===c;)m++,y++;for(var b=(p.length-y)*u+1>>>0,I=new Uint8Array(b);p[y];){var A=t[p.charCodeAt(y)];if(A===255)return;for(var C=0,E=b-1;(A!==0||C<_)&&E!==-1;E--,C++)A+=a*I[E]>>>0,I[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");_=C,y++}if(p[y]!==" "){for(var $=b-_;$!==b&&I[$]===0;)$++;for(var S=new Uint8Array(m+(b-$)),P=m;$!==b;)S[P++]=I[$++];return S}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var Ag=Og,xg=Ag;const xh=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},Cg=r=>new TextEncoder().encode(r),Tg=r=>new TextDecoder().decode(r);let Rg=class{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ng=class{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Ch(this,e)}},jg=class{constructor(e){this.decoders=e}or(e){return Ch(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Ch=(r,e)=>new jg({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});let Bg=class{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Rg(e,t,i),this.decoder=new Ng(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Es=({name:r,prefix:e,encode:t,decode:i})=>new Bg(r,e,t,i),Pi=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=xg(t,e);return Es({prefix:r,name:e,encode:i,decode:n=>xh(s(n))})},Ug=(r,e,t,i)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[r[h]];if(l===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Fg=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},De=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Es({prefix:e,name:r,encode(s){return Fg(s,i,t)},decode(s){return Ug(s,i,t,r)}}),qg=Es({prefix:"\0",name:"identity",encode:r=>Tg(r),decode:r=>Cg(r)});var Lg=Object.freeze({__proto__:null,identity:qg});const kg=De({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Mg=Object.freeze({__proto__:null,base2:kg});const zg=De({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Hg=Object.freeze({__proto__:null,base8:zg});const Vg=Pi({prefix:"9",name:"base10",alphabet:"0123456789"});var Kg=Object.freeze({__proto__:null,base10:Vg});const Wg=De({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Gg=De({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Yg=Object.freeze({__proto__:null,base16:Wg,base16upper:Gg});const Jg=De({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Zg=De({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qg=De({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xg=De({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ey=De({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ty=De({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ry=De({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iy=De({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),sy=De({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ny=Object.freeze({__proto__:null,base32:Jg,base32upper:Zg,base32pad:Qg,base32padupper:Xg,base32hex:ey,base32hexupper:ty,base32hexpad:ry,base32hexpadupper:iy,base32z:sy});const oy=Pi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ay=Pi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var cy=Object.freeze({__proto__:null,base36:oy,base36upper:ay});const uy=Pi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hy=Pi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ly=Object.freeze({__proto__:null,base58btc:uy,base58flickr:hy});const dy=De({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),py=De({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fy=De({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gy=De({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var yy=Object.freeze({__proto__:null,base64:dy,base64pad:py,base64url:fy,base64urlpad:gy});const Th=Array.from("🚀🊐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀ðŸ’ŧðŸ–ĨðŸ’ūðŸ’ŋ😂âĪ😍ðŸĪĢ😊🙏💕😭😘👍😅👏😁ðŸ”ĨðŸĨ°ðŸ’”💖💙ðŸ˜ĒðŸĪ”😆🙄💊😉☚👌ðŸĪ—💜😔😎😇ðŸŒđðŸĪĶ🎉💞✌âœĻðŸĪ·ðŸ˜ąðŸ˜ŒðŸŒļ🙌😋💗💚😏💛🙂💓ðŸĪĐ😄😀ðŸ–Ī😃ðŸ’Ŋ🙈👇ðŸŽķ😒ðŸĪ­âĢ😜💋👀😊😑ðŸ’Ĩ🙋😞ðŸ˜ĐðŸ˜ĄðŸĪŠðŸ‘ŠðŸĨģðŸ˜ĨðŸĪĪ👉💃ðŸ˜ģ✋😚😝ðŸ˜ī🌟😎🙃🍀🌷ðŸ˜ŧ😓⭐✅ðŸĨšðŸŒˆðŸ˜ˆðŸĪ˜ðŸ’Ķ✔ðŸ˜Ģ🏃💐â˜đ🎊💘😠☝😕🌚🎂ðŸŒŧ😐🖕💝🙊ðŸ˜đðŸ—ĢðŸ’Ŧ💀👑ðŸŽĩðŸĪžðŸ˜›ðŸ”īðŸ˜Ī🌞ðŸ˜Ŧâš―ðŸĪ™â˜•🏆ðŸĪŦ👈ðŸ˜Ū🙆ðŸŧ🍃ðŸķ💁ðŸ˜ēðŸŒŋðŸ§ĄðŸŽâšĄðŸŒžðŸŽˆâŒâœŠðŸ‘‹ðŸ˜°ðŸĪĻðŸ˜ķðŸĪðŸšķ💰🍓ðŸ’ĒðŸĪŸðŸ™ðŸšĻðŸ’ĻðŸĪŽâœˆðŸŽ€ðŸšðŸĪ“ðŸ˜™ðŸ’ŸðŸŒąðŸ˜–ðŸ‘ķðŸĨīâ–ķâžĄâ“ðŸ’ŽðŸ’ļ⮇ðŸ˜Ļ🌚ðŸĶ‹ðŸ˜·ðŸ•šâš ðŸ™…😟ðŸ˜ĩ👎ðŸĪēðŸĪ ðŸĪ§ðŸ“ŒðŸ”ĩ💅🧐ðŸū🍒😗ðŸĪ‘🌊ðŸĪŊ🐷☎💧ðŸ˜Ŋ💆👆ðŸŽĪ🙇🍑❄ðŸŒīðŸ’ĢðŸļ💌📍ðŸĨ€ðŸĪĒðŸ‘…ðŸ’ĄðŸ’Đ👐ðŸ“ļðŸ‘ŧðŸĪðŸĪŪ🎞ðŸĨĩðŸšĐ🍎🍊👞💍ðŸ“ĢðŸĨ‚"),my=Th.reduce((r,e,t)=>(r[t]=e,r),[]),wy=Th.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function by(r){return r.reduce((e,t)=>(e+=my[t],e),"")}function vy(r){const e=[];for(const t of r){const i=wy[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Ey=Es({prefix:"🚀",name:"base256emoji",encode:by,decode:vy});var _y=Object.freeze({__proto__:null,base256emoji:Ey}),Iy=Rh,Na=128,$y=-128,Sy=Math.pow(2,31);function Rh(r,e,t){e=e||[],t=t||0;for(var i=t;r>=Sy;)e[t++]=r&255|Na,r/=128;for(;r&$y;)e[t++]=r&255|Na,r>>>=7;return e[t]=r|0,Rh.bytes=t-i+1,e}var Dy=jn,Py=128,ja=127;function jn(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw jn.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&ja)<<s:(o&ja)*Math.pow(2,s),s+=7}while(o>=Py);return jn.bytes=n-i,t}var Oy=Math.pow(2,7),Ay=Math.pow(2,14),xy=Math.pow(2,21),Cy=Math.pow(2,28),Ty=Math.pow(2,35),Ry=Math.pow(2,42),Ny=Math.pow(2,49),jy=Math.pow(2,56),By=Math.pow(2,63),Uy=function(r){return r<Oy?1:r<Ay?2:r<xy?3:r<Cy?4:r<Ty?5:r<Ry?6:r<Ny?7:r<jy?8:r<By?9:10},Fy={encode:Iy,decode:Dy,encodingLength:Uy},Nh=Fy;const Ba=(r,e,t=0)=>(Nh.encode(r,e,t),e),Ua=r=>Nh.encodingLength(r),Bn=(r,e)=>{const t=e.byteLength,i=Ua(r),s=i+Ua(t),n=new Uint8Array(s+t);return Ba(r,n,0),Ba(t,n,i),n.set(e,s),new qy(r,t,e,n)};let qy=class{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}};const jh=({name:r,code:e,encode:t})=>new Ly(r,e,t);let Ly=class{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Bn(this.code,t):t.then(i=>Bn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Bh=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),ky=jh({name:"sha2-256",code:18,encode:Bh("SHA-256")}),My=jh({name:"sha2-512",code:19,encode:Bh("SHA-512")});var zy=Object.freeze({__proto__:null,sha256:ky,sha512:My});const Uh=0,Hy="identity",Fh=xh,Vy=r=>Bn(Uh,Fh(r)),Ky={code:Uh,name:Hy,encode:Fh,digest:Vy};var Wy=Object.freeze({__proto__:null,identity:Ky});new TextEncoder,new TextDecoder;const Fa={...Lg,...Mg,...Hg,...Kg,...Yg,...ny,...cy,...ly,...yy,..._y};({...zy,...Wy});function qh(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const qa=qh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ys=qh("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=Oh(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Lh={utf8:qa,"utf-8":qa,hex:Fa.base16,latin1:Ys,ascii:Ys,binary:Ys,...Fa};function _s(r,e="utf8"){const t=Lh[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}function Kr(r,e="utf8"){const t=Lh[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Oo(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}function La(r){return sr(_s(Kr(r,vs),Dh))}function hs(r){return _s(Kr(Rt(r),Dh),vs)}function kh(r){const e=Kr(Dg,Ra),t=Sg+_s(Ah([e,r]),Ra);return[Ig,$g,t].join(_g)}function Gy(r){return _s(r,vs)}function Yy(r){return Kr(r,vs)}function Jy(r){return Kr([hs(r.header),hs(r.payload)].join(us),Ph)}function Zy(r){return[hs(r.header),hs(r.payload),Gy(r.signature)].join(us)}function Un(r){const e=r.split(us),t=La(e[0]),i=La(e[1]),s=Yy(e[2]),n=Kr(e.slice(0,2).join(us),Ph);return{header:t,payload:i,signature:s,data:n}}function ka(r=gh(Pg)){const e=Sh.getPublicKey(r);return{secretKey:Ah([r,e]),publicKey:e}}async function Qy(r,e,t,i,s=U.fromMiliseconds(Date.now())){const n={alg:vg,typ:Eg},o=kh(i.publicKey),a=s+t,c={iss:o,sub:r,aud:e,iat:s,exp:a},u=Jy({header:n,payload:c}),h=Sh.sign(u,i.secretKey.slice(0,32));return Zy({header:n,payload:c,signature:h})}function Mh(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function pi(r,e){e||(e=r.reduce((s,n)=>s+n.length,0));const t=Mh(e);let i=0;for(const s of r)t.set(s,i),i+=s.length;return t}function Xy(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,m=0,_=0,b=p.length;_!==b&&p[_]===0;)_++,y++;for(var I=(b-_)*h+1>>>0,A=new Uint8Array(I);_!==b;){for(var C=p[_],E=0,$=I-1;(C!==0||E<m)&&$!==-1;$--,E++)C+=256*A[$]>>>0,A[$]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");m=E,_++}for(var S=I-m;S!==I&&A[S]===0;)S++;for(var P=c.repeat(y);S<I;++S)P+=r.charAt(A[S]);return P}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,_=0;p[y]===c;)m++,y++;for(var b=(p.length-y)*u+1>>>0,I=new Uint8Array(b);p[y];){var A=t[p.charCodeAt(y)];if(A===255)return;for(var C=0,E=b-1;(A!==0||C<_)&&E!==-1;E--,C++)A+=a*I[E]>>>0,I[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");_=C,y++}if(p[y]!==" "){for(var $=b-_;$!==b&&I[$]===0;)$++;for(var S=new Uint8Array(m+(b-$)),P=m;$!==b;)S[P++]=I[$++];return S}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var em=Xy,tm=em;const rm=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},im=r=>new TextEncoder().encode(r),sm=r=>new TextDecoder().decode(r);class nm{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class om{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 zh(this,e)}}class am{constructor(e){this.decoders=e}or(e){return zh(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const zh=(r,e)=>new am({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class cm{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new nm(e,t,i),this.decoder=new om(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Is=({name:r,prefix:e,encode:t,decode:i})=>new cm(r,e,t,i),Oi=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=tm(t,e);return Is({prefix:r,name:e,encode:i,decode:n=>rm(s(n))})},um=(r,e,t,i)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[r[h]];if(l===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},hm=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Pe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Is({prefix:e,name:r,encode(s){return hm(s,i,t)},decode(s){return um(s,i,t,r)}}),lm=Is({prefix:"\0",name:"identity",encode:r=>sm(r),decode:r=>im(r)}),dm=Object.freeze(Object.defineProperty({__proto__:null,identity:lm},Symbol.toStringTag,{value:"Module"})),pm=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),fm=Object.freeze(Object.defineProperty({__proto__:null,base2:pm},Symbol.toStringTag,{value:"Module"})),gm=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ym=Object.freeze(Object.defineProperty({__proto__:null,base8:gm},Symbol.toStringTag,{value:"Module"})),mm=Oi({prefix:"9",name:"base10",alphabet:"0123456789"}),wm=Object.freeze(Object.defineProperty({__proto__:null,base10:mm},Symbol.toStringTag,{value:"Module"})),bm=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vm=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Em=Object.freeze(Object.defineProperty({__proto__:null,base16:bm,base16upper:vm},Symbol.toStringTag,{value:"Module"})),_m=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Im=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$m=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sm=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dm=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pm=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Om=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Am=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),xm=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Cm=Object.freeze(Object.defineProperty({__proto__:null,base32:_m,base32hex:Dm,base32hexpad:Om,base32hexpadupper:Am,base32hexupper:Pm,base32pad:$m,base32padupper:Sm,base32upper:Im,base32z:xm},Symbol.toStringTag,{value:"Module"})),Tm=Oi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rm=Oi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base36:Tm,base36upper:Rm},Symbol.toStringTag,{value:"Module"})),jm=Oi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bm=Oi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Um=Object.freeze(Object.defineProperty({__proto__:null,base58btc:jm,base58flickr:Bm},Symbol.toStringTag,{value:"Module"})),Fm=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qm=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Lm=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),km=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Mm=Object.freeze(Object.defineProperty({__proto__:null,base64:Fm,base64pad:qm,base64url:Lm,base64urlpad:km},Symbol.toStringTag,{value:"Module"})),Hh=Array.from("🚀🊐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀ðŸ’ŧðŸ–ĨðŸ’ūðŸ’ŋ😂âĪ😍ðŸĪĢ😊🙏💕😭😘👍😅👏😁ðŸ”ĨðŸĨ°ðŸ’”💖💙ðŸ˜ĒðŸĪ”😆🙄💊😉☚👌ðŸĪ—💜😔😎😇ðŸŒđðŸĪĶ🎉💞✌âœĻðŸĪ·ðŸ˜ąðŸ˜ŒðŸŒļ🙌😋💗💚😏💛🙂💓ðŸĪĐ😄😀ðŸ–Ī😃ðŸ’Ŋ🙈👇ðŸŽķ😒ðŸĪ­âĢ😜💋👀😊😑ðŸ’Ĩ🙋😞ðŸ˜ĐðŸ˜ĄðŸĪŠðŸ‘ŠðŸĨģðŸ˜ĨðŸĪĪ👉💃ðŸ˜ģ✋😚😝ðŸ˜ī🌟😎🙃🍀🌷ðŸ˜ŧ😓⭐✅ðŸĨšðŸŒˆðŸ˜ˆðŸĪ˜ðŸ’Ķ✔ðŸ˜Ģ🏃💐â˜đ🎊💘😠☝😕🌚🎂ðŸŒŧ😐🖕💝🙊ðŸ˜đðŸ—ĢðŸ’Ŧ💀👑ðŸŽĩðŸĪžðŸ˜›ðŸ”īðŸ˜Ī🌞ðŸ˜Ŧâš―ðŸĪ™â˜•🏆ðŸĪŦ👈ðŸ˜Ū🙆ðŸŧ🍃ðŸķ💁ðŸ˜ēðŸŒŋðŸ§ĄðŸŽâšĄðŸŒžðŸŽˆâŒâœŠðŸ‘‹ðŸ˜°ðŸĪĻðŸ˜ķðŸĪðŸšķ💰🍓ðŸ’ĒðŸĪŸðŸ™ðŸšĻðŸ’ĻðŸĪŽâœˆðŸŽ€ðŸšðŸĪ“ðŸ˜™ðŸ’ŸðŸŒąðŸ˜–ðŸ‘ķðŸĨīâ–ķâžĄâ“ðŸ’ŽðŸ’ļ⮇ðŸ˜Ļ🌚ðŸĶ‹ðŸ˜·ðŸ•šâš ðŸ™…😟ðŸ˜ĩ👎ðŸĪēðŸĪ ðŸĪ§ðŸ“ŒðŸ”ĩ💅🧐ðŸū🍒😗ðŸĪ‘🌊ðŸĪŊ🐷☎💧ðŸ˜Ŋ💆👆ðŸŽĪ🙇🍑❄ðŸŒīðŸ’ĢðŸļ💌📍ðŸĨ€ðŸĪĒðŸ‘…ðŸ’ĄðŸ’Đ👐ðŸ“ļðŸ‘ŧðŸĪðŸĪŪ🎞ðŸĨĩðŸšĐ🍎🍊👞💍ðŸ“ĢðŸĨ‚"),zm=Hh.reduce((r,e,t)=>(r[t]=e,r),[]),Hm=Hh.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function Vm(r){return r.reduce((e,t)=>(e+=zm[t],e),"")}function Km(r){const e=[];for(const t of r){const i=Hm[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const Wm=Is({prefix:"🚀",name:"base256emoji",encode:Vm,decode:Km}),Gm=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Wm},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Ma={...dm,...fm,...ym,...wm,...Em,...Cm,...Nm,...Um,...Mm,...Gm};function Vh(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const za=Vh("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Js=Vh("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=Mh(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Kh={utf8:za,"utf-8":za,hex:Ma.base16,latin1:Js,ascii:Js,binary:Js,...Ma};function rt(r,e="utf8"){const t=Kh[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}function Le(r,e="utf8"){const t=Kh[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}const Ym={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 Jm={};const Zm=":";function Br(r){const[e,t]=r.split(Zm);return{namespace:e,reference:t}}function Ha(r,e=[]){const t=[];return Object.keys(r).forEach(i=>{if(e.length&&!e.includes(i))return;const s=r[i];t.push(...s.accounts)}),t}function Wh(r,e){return r.includes(":")?[r]:e.chains||[]}var Qm=Object.defineProperty,Xm=Object.defineProperties,ew=Object.getOwnPropertyDescriptors,Va=Object.getOwnPropertySymbols,tw=Object.prototype.hasOwnProperty,rw=Object.prototype.propertyIsEnumerable,Ka=(r,e,t)=>e in r?Qm(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Wa=(r,e)=>{for(var t in e||(e={}))tw.call(e,t)&&Ka(r,t,e[t]);if(Va)for(var t of Va(e))rw.call(e,t)&&Ka(r,t,e[t]);return r},iw=(r,e)=>Xm(r,ew(e));const sw="ReactNative",We={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},nw="js";function ls(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function zt(){return!rr.getDocument()&&!!rr.getNavigator()&&navigator.product===sw}function ow(){return zt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function aw(){return zt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Ai(){return!ls()&&!!rr.getNavigator()&&!!rr.getDocument()}function xi(){return zt()?We.reactNative:ls()?We.node:Ai()?We.browser:We.unknown}function Ga(){var r;try{return zt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(r=global.Application)==null?void 0:r.applicationId:void 0}catch{return}}function cw(r,e){const t=new URLSearchParams(r);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&t.set(i,s)}return t.toString()}function uw(r){var e,t;const i=Gh();try{return r!=null&&r.url&&i.url&&r.url!==i.url&&(console.warn(`The configured WalletConnect 'metadata.url':${r.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),r.url=i.url),(e=r==null?void 0:r.icons)!=null&&e.length&&r.icons.length>0&&(r.icons=r.icons.filter(s=>s!=="")),iw(Wa(Wa({},i),r),{url:(r==null?void 0:r.url)||i.url,name:(r==null?void 0:r.name)||i.name,description:(r==null?void 0:r.description)||i.description,icons:(t=r==null?void 0:r.icons)!=null&&t.length&&r.icons.length>0?r.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),r||i}}function Gh(){return wp.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function hw(){if(xi()===We.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:t,Version:i}=global.Platform;return[t,i].join("-")}const r=Bd();if(r===null)return"unknown";const e=r.os?r.os.replace(" ","").toLowerCase():"unknown";return r.type==="browser"?[e,r.name,r.version].join("-"):[e,r.version].join("-")}function lw(){var r;const e=xi();return e===We.browser?[e,((r=rr.getLocation())==null?void 0:r.host)||"unknown"].join(":"):e}function Yh(r,e,t){const i=hw(),s=lw();return[[r,e].join("-"),[nw,t].join("-"),i,s].join("/")}function dw({protocol:r,version:e,relayUrl:t,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=t.split("?"),h=Yh(r,e,i),l={auth:s,ua:h,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=cw(u[1]||"",l);return u[0]+"?"+d}function Xt(r,e){return r.filter(t=>e.includes(t)).length===r.length}function Fn(r){return Object.fromEntries(r.entries())}function qn(r){return new Map(Object.entries(r))}function Gt(r=U.FIVE_MINUTES,e){const t=U.toMiliseconds(r||U.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 u=new Error(e);o=Promise.reject(u),c(u)},t),i=a,s=c})}}function Lt(r,e,t){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(t)),e);try{const o=await r;i(o)}catch(o){s(o)}clearTimeout(n)})}function Jh(r,e){if(typeof e=="string"&&e.startsWith(`${r}:`))return e;if(r.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(r.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: ${r}`)}function pw(r){return Jh("topic",r)}function fw(r){return Jh("id",r)}function Zh(r){const[e,t]=r.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")i.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))i.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return i}function de(r,e){return U.fromMiliseconds(Date.now()+U.toMiliseconds(r))}function Ft(r){return Date.now()>=U.toMiliseconds(r)}function X(r,e){return`${r}${e?`:${e}`:""}`}function rs(r=[],e=[]){return[...new Set([...r,...e])]}async function gw({id:r,topic:e,wcDeepLink:t}){var i;try{if(!t)return;const s=typeof t=="string"?JSON.parse(t):t,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=yw(n,r,e),a=xi();if(a===We.browser){if(!((i=rr.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}mw(o)}else a===We.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function yw(r,e,t){const i=`requestId=${e}&sessionTopic=${t}`;r.endsWith("/")&&(r=r.slice(0,-1));let s=`${r}`;if(r.startsWith("https://t.me")){const n=r.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Ew(i,!0)}`}else s=`${s}/wc?${i}`;return s}function mw(r){let e="_self";vw()?e="_top":(bw()||r.startsWith("https://")||r.startsWith("http://"))&&(e="_blank"),window.open(r,e,"noreferrer noopener")}async function ww(r,e){let t="";try{if(Ai()&&(t=localStorage.getItem(e),t))return t;t=await r.getItem(e)}catch(i){console.error(i)}return t}function Ya(r,e){if(!r.includes(e))return null;const t=r.split(/([&,?,=])/),i=t.indexOf(e);return t[i+2]}function Ja(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}function Ao(){return typeof process<"u"&&Jm.IS_VITEST==="true"}function bw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function vw(){try{return window.self!==window.top}catch{return!1}}function Ew(r,e=!1){const t=Buffer.from(r).toString("base64");return e?t.replace(/[=]/g,""):t}function Qh(r){return Buffer.from(r,"base64").toString("utf-8")}function _w(r){return new Promise(e=>setTimeout(e,r))}function vi(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Iw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ci(r,...e){if(!Iw(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function xo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");vi(r.outputLen),vi(r.blockLen)}function Ur(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Xh(r,e){Ci(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Hi=BigInt(2**32-1),Za=BigInt(32);function $w(r,e=!1){return e?{h:Number(r&Hi),l:Number(r>>Za&Hi)}:{h:Number(r>>Za&Hi)|0,l:Number(r&Hi)|0}}function Sw(r,e=!1){let t=new Uint32Array(r.length),i=new Uint32Array(r.length);for(let s=0;s<r.length;s++){const{h:n,l:o}=$w(r[s],e);[t[s],i[s]]=[n,o]}return[t,i]}const Dw=(r,e,t)=>r<<t|e>>>32-t,Pw=(r,e,t)=>e<<t|r>>>32-t,Ow=(r,e,t)=>e<<t-32|r>>>64-t,Aw=(r,e,t)=>r<<t-32|e>>>64-t,yr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xw(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Zs(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ft(r,e){return r<<32-e|r>>>e}const Qa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Cw(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Xa(r){for(let e=0;e<r.length;e++)r[e]=Cw(r[e])}function Tw(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Fr(r){return typeof r=="string"&&(r=Tw(r)),Ci(r),r}function Rw(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ci(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}let Co=class{clone(){return this._cloneInto()}};function el(r){const e=i=>r().update(Fr(i)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Wr(r=32){if(yr&&typeof yr.getRandomValues=="function")return yr.getRandomValues(new Uint8Array(r));if(yr&&typeof yr.randomBytes=="function")return yr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}const tl=[],rl=[],il=[],Nw=BigInt(0),ii=BigInt(1),jw=BigInt(2),Bw=BigInt(7),Uw=BigInt(256),Fw=BigInt(113);for(let r=0,e=ii,t=1,i=0;r<24;r++){[t,i]=[i,(2*t+3*i)%5],tl.push(2*(5*i+t)),rl.push((r+1)*(r+2)/2%64);let s=Nw;for(let n=0;n<7;n++)e=(e<<ii^(e>>Bw)*Fw)%Uw,e&jw&&(s^=ii<<(ii<<BigInt(n))-ii);il.push(s)}const[qw,Lw]=Sw(il,!0),ec=(r,e,t)=>t>32?Ow(r,e,t):Dw(r,e,t),tc=(r,e,t)=>t>32?Aw(r,e,t):Pw(r,e,t);function kw(r,e=24){const t=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)t[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=t[c],h=t[c+1],l=ec(u,h,1)^t[a],d=tc(u,h,1)^t[a+1];for(let f=0;f<50;f+=10)r[o+f]^=l,r[o+f+1]^=d}let s=r[2],n=r[3];for(let o=0;o<24;o++){const a=rl[o],c=ec(s,n,a),u=tc(s,n,a),h=tl[o];s=r[h],n=r[h+1],r[h]=c,r[h+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}r[0]^=qw[i],r[1]^=Lw[i]}t.fill(0)}let Mw=class sl extends Co{constructor(e,t,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,vi(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=xw(this.state)}keccak(){Qa||Xa(this.state32),kw(this.state32,this.rounds),Qa||Xa(this.state32),this.posOut=0,this.pos=0}update(e){Ur(this);const{blockLen:t,state:i}=this;e=Fr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(t-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,t&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Ur(this,!1),Ci(e),this.finish();const t=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(t.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 vi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Xh(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,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new sl(t,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 zw=(r,e,t)=>el(()=>new Mw(e,r,t)),Hw=zw(1,136,256/8),Vw="https://rpc.walletconnect.org/v1";function nl(r){const e=`Ethereum Signed Message:
${r.length}`,t=new TextEncoder().encode(e+r);return"0x"+Buffer.from(Hw(t)).toString("hex")}async function Kw(r,e,t,i,s,n){switch(t.t){case"eip191":return await Ww(r,e,t.s);case"eip1271":return await Gw(r,e,t.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function Ww(r,e,t){return(await of({hash:nl(e),signature:t})).toLowerCase()===r.toLowerCase()}async function Gw(r,e,t,i,s,n){const o=Br(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u="0000000000000000000000000000000000000000000000000000000000000041",h=t.substring(2),l=nl(e).substring(2),d=a+l+c+u+h,f=await fetch(`${n||Vw}/?chainId=${i}&projectId=${s}`,{method:"POST",body:JSON.stringify({id:Yw(),jsonrpc:"2.0",method:"eth_call",params:[{to:r,data:d},"latest"]})}),{result:p}=await f.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Yw(){return Date.now()+Math.floor(Math.random()*1e3)}function Jw(r){const e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const i=t[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(t.length<s)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const n=Buffer.from(r,"base64").slice(1,65);return Dd.encode(n)}var Zw=Object.defineProperty,Qw=Object.defineProperties,Xw=Object.getOwnPropertyDescriptors,rc=Object.getOwnPropertySymbols,eb=Object.prototype.hasOwnProperty,tb=Object.prototype.propertyIsEnumerable,ic=(r,e,t)=>e in r?Zw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,rb=(r,e)=>{for(var t in e||(e={}))eb.call(e,t)&&ic(r,t,e[t]);if(rc)for(var t of rc(e))tb.call(e,t)&&ic(r,t,e[t]);return r},ib=(r,e)=>Qw(r,Xw(e));const sb="did:pkh:",To=r=>r==null?void 0:r.split(":"),nb=r=>{const e=r&&To(r);if(e)return r.includes(sb)?e[3]:e[1]},Ln=r=>{const e=r&&To(r);if(e)return e[2]+":"+e[3]},ds=r=>{const e=r&&To(r);if(e)return e.pop()};async function sc(r){const{cacao:e,projectId:t}=r,{s:i,p:s}=e,n=ol(s,s.iss),o=ds(s.iss);return await Kw(o,n,i,Ln(s.iss),t)}const ol=(r,e)=>{const t=`${r.domain} wants you to sign in with your Ethereum account:`,i=ds(e);if(!r.aud&&!r.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=r.statement||void 0;const n=`URI: ${r.aud||r.uri}`,o=`Version: ${r.version}`,a=`Chain ID: ${nb(e)}`,c=`Nonce: ${r.nonce}`,u=`Issued At: ${r.iat}`,h=r.exp?`Expiration Time: ${r.exp}`:void 0,l=r.nbf?`Not Before: ${r.nbf}`:void 0,d=r.requestId?`Request ID: ${r.requestId}`:void 0,f=r.resources?`Resources:${r.resources.map(y=>`
- ${y}`).join("")}`:void 0,p=is(r.resources);if(p){const y=Ei(p);s=fb(s,y)}return[t,i,"",s,"",n,o,a,c,u,h,l,d,f].filter(y=>y!=null).join(`
`)};function ob(r){return Buffer.from(JSON.stringify(r)).toString("base64")}function ab(r){return JSON.parse(Buffer.from(r,"base64").toString("utf-8"))}function nr(r){if(!r)throw new Error("No recap provided, value is undefined");if(!r.att)throw new Error("No `att` property found");const e=Object.keys(r.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const i=r.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function cb(r,e,t,i={}){return t==null||t.sort((s,n)=>s.localeCompare(n)),{att:{[r]:ub(e,t,i)}}}function ub(r,e,t={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${r}/${s}`]:[t]}));return Object.assign({},...i)}function al(r){return nr(r),`urn:recap:${ob(r).replace(/=/g,"")}`}function Ei(r){const e=ab(r.replace("urn:recap:",""));return nr(e),e}function hb(r,e,t){const i=cb(r,e,t);return al(i)}function lb(r){return r&&r.includes("urn:recap:")}function db(r,e){const t=Ei(r),i=Ei(e),s=pb(t,i);return al(s)}function pb(r,e){nr(r),nr(e);const t=Object.keys(r.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return t.forEach(s=>{var n,o;Object.keys(((n=r.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;i.att[s]=ib(rb({},i.att[s]),{[a]:((c=r.att[s])==null?void 0:c[a])||((u=e.att[s])==null?void 0:u[a])})})}),i}function fb(r="",e){nr(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(r.includes(t))return r;const i=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(l=>({ability:l.split("/")[0],action:l.split("/")[1]}));c.sort((l,d)=>l.action.localeCompare(d.action));const u={};c.forEach(l=>{u[l.ability]||(u[l.ability]=[]),u[l.ability].push(l.action)});const h=Object.keys(u).map(l=>(s++,`(${s}) '${l}': '${u[l].join("', '")}' for '${a}'.`));i.push(h.join(", ").replace(".,","."))});const n=i.join(" "),o=`${t}${n}`;return`${r?r+" ":""}${o}`}function nc(r){var e;const t=Ei(r);nr(t);const i=(e=t.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function oc(r){const e=Ei(r);nr(e);const t=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&t.push(s[0].chains)})}),[...new Set(t.flat())]}function is(r){if(!r)return;const e=r==null?void 0:r[r.length-1];return lb(e)?e:void 0}function Qs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function cl(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ke(r,...e){if(!cl(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function ac(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function gb(r,e){Ke(r);const t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function cc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}const Mt=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),yb=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),mb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!mb)throw new Error("Non little-endian hardware is not supported");function wb(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function kn(r){if(typeof r=="string")r=wb(r);else if(cl(r))r=Mn(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function bb(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function vb(r,e){if(r.length!==e.length)return!1;let t=0;for(let i=0;i<r.length;i++)t|=r[i]^e[i];return t===0}const Eb=(r,e)=>{function t(i,...s){if(Ke(i),r.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Ke(u):Ke(u,r.nonceLength)}const n=r.tagLength;n&&s[1]!==void 0&&Ke(s[1]);const o=e(i,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");Ke(h)}};let c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ke(u),a(o.encrypt.length,h),o.encrypt(u,h)},decrypt(u,h){if(Ke(u),n&&u.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(u,h)}}}return Object.assign(t,r),t};function uc(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!_b(e))throw new Error("invalid output, must be aligned");return e}function hc(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n);r.setUint32(e+4,o,i),r.setUint32(e+0,a,i)}function _b(r){return r.byteOffset%4===0}function Mn(r){return Uint8Array.from(r)}function qr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}const ul=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),Ib=ul("expand 16-byte k"),$b=ul("expand 32-byte k"),Sb=Mt(Ib),Db=Mt($b);function J(r,e){return r<<e|r>>>32-e}function zn(r){return r.byteOffset%4===0}const Vi=64,Pb=16,hl=2**32-1,lc=new Uint32Array;function Ob(r,e,t,i,s,n,o,a){const c=s.length,u=new Uint8Array(Vi),h=Mt(u),l=zn(s)&&zn(n),d=l?Mt(s):lc,f=l?Mt(n):lc;for(let p=0;p<c;o++){if(r(e,t,i,h,o,a),o>=hl)throw new Error("arx: counter overflow");const y=Math.min(Vi,c-p);if(l&&y===Vi){const m=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let _=0,b;_<Pb;_++)b=m+_,f[b]=d[b]^h[_];p+=Vi;continue}for(let m=0,_;m<y;m++)_=p+m,n[_]=s[_]^u[m];p+=y}}function Ab(r,e){const{allowShortKeys:t,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=bb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return Qs(s),Qs(o),cc(n),cc(t),(a,c,u,h,l=0)=>{Ke(a),Ke(c),Ke(u);const d=u.length;if(h===void 0&&(h=new Uint8Array(d)),Ke(h),Qs(l),l<0||l>=hl)throw new Error("arx: counter overflow");if(h.length<d)throw new Error(`arx: output (${h.length}) is shorter than data (${d})`);const f=[];let p=a.length,y,m;if(p===32)f.push(y=Mn(a)),m=Db;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),m=Sb,f.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);zn(c)||f.push(c=Mn(c));const _=Mt(y);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(m,_,Mt(c.subarray(0,16)),_),c=c.subarray(16)}const b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const A=new Uint8Array(12);A.set(c,n?0:12-c.length),c=A,f.push(c)}const I=Mt(c);return Ob(r,m,_,I,u,h,l,o),qr(...f),h}}const _e=(r,e)=>r[e++]&255|(r[e++]&255)<<8;class xb{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=kn(e),Ke(e,32);const t=_e(e,0),i=_e(e,2),s=_e(e,4),n=_e(e,6),o=_e(e,8),a=_e(e,10),c=_e(e,12),u=_e(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let h=0;h<8;h++)this.pad[h]=_e(e,16+2*h)}process(e,t,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],u=o[2],h=o[3],l=o[4],d=o[5],f=o[6],p=o[7],y=o[8],m=o[9],_=_e(e,t+0),b=_e(e,t+2),I=_e(e,t+4),A=_e(e,t+6),C=_e(e,t+8),E=_e(e,t+10),$=_e(e,t+12),S=_e(e,t+14);let P=n[0]+(_&8191),j=n[1]+((_>>>13|b<<3)&8191),T=n[2]+((b>>>10|I<<6)&8191),B=n[3]+((I>>>7|A<<9)&8191),k=n[4]+((A>>>4|C<<12)&8191),g=n[5]+(C>>>1&8191),w=n[6]+((C>>>14|E<<2)&8191),v=n[7]+((E>>>11|$<<5)&8191),O=n[8]+(($>>>8|S<<8)&8191),x=n[9]+(S>>>5|s),D=0,R=D+P*a+j*(5*m)+T*(5*y)+B*(5*p)+k*(5*f);D=R>>>13,R&=8191,R+=g*(5*d)+w*(5*l)+v*(5*h)+O*(5*u)+x*(5*c),D+=R>>>13,R&=8191;let q=D+P*c+j*a+T*(5*m)+B*(5*y)+k*(5*p);D=q>>>13,q&=8191,q+=g*(5*f)+w*(5*d)+v*(5*l)+O*(5*h)+x*(5*u),D+=q>>>13,q&=8191;let L=D+P*u+j*c+T*a+B*(5*m)+k*(5*y);D=L>>>13,L&=8191,L+=g*(5*p)+w*(5*f)+v*(5*d)+O*(5*l)+x*(5*h),D+=L>>>13,L&=8191;let M=D+P*h+j*u+T*c+B*a+k*(5*m);D=M>>>13,M&=8191,M+=g*(5*y)+w*(5*p)+v*(5*f)+O*(5*d)+x*(5*l),D+=M>>>13,M&=8191;let z=D+P*l+j*h+T*u+B*c+k*a;D=z>>>13,z&=8191,z+=g*(5*m)+w*(5*y)+v*(5*p)+O*(5*f)+x*(5*d),D+=z>>>13,z&=8191;let V=D+P*d+j*l+T*h+B*u+k*c;D=V>>>13,V&=8191,V+=g*a+w*(5*m)+v*(5*y)+O*(5*p)+x*(5*f),D+=V>>>13,V&=8191;let H=D+P*f+j*d+T*l+B*h+k*u;D=H>>>13,H&=8191,H+=g*c+w*a+v*(5*m)+O*(5*y)+x*(5*p),D+=H>>>13,H&=8191;let ne=D+P*p+j*f+T*d+B*l+k*h;D=ne>>>13,ne&=8191,ne+=g*u+w*c+v*a+O*(5*m)+x*(5*y),D+=ne>>>13,ne&=8191;let ee=D+P*y+j*p+T*f+B*d+k*l;D=ee>>>13,ee&=8191,ee+=g*h+w*u+v*c+O*a+x*(5*m),D+=ee>>>13,ee&=8191;let Y=D+P*m+j*y+T*p+B*f+k*d;D=Y>>>13,Y&=8191,Y+=g*l+w*h+v*u+O*c+x*a,D+=Y>>>13,Y&=8191,D=(D<<2)+D|0,D=D+R|0,R=D&8191,D=D>>>13,q+=D,n[0]=R,n[1]=q,n[2]=L,n[3]=M,n[4]=z,n[5]=V,n[6]=H,n[7]=ne,n[8]=ee,n[9]=Y}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;qr(i)}update(e){ac(this);const{buffer:t,blockLen:i}=this;e=kn(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){qr(this.h,this.r,this.buffer,this.pad)}digestInto(e){ac(this),gb(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}}function Cb(r){const e=(i,s)=>r(s).update(kn(i)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=i=>r(i),e}const Tb=Cb(r=>new xb(r));function Rb(r,e,t,i,s,n=20){let o=r[0],a=r[1],c=r[2],u=r[3],h=e[0],l=e[1],d=e[2],f=e[3],p=e[4],y=e[5],m=e[6],_=e[7],b=s,I=t[0],A=t[1],C=t[2],E=o,$=a,S=c,P=u,j=h,T=l,B=d,k=f,g=p,w=y,v=m,O=_,x=b,D=I,R=A,q=C;for(let M=0;M<n;M+=2)E=E+j|0,x=J(x^E,16),g=g+x|0,j=J(j^g,12),E=E+j|0,x=J(x^E,8),g=g+x|0,j=J(j^g,7),$=$+T|0,D=J(D^$,16),w=w+D|0,T=J(T^w,12),$=$+T|0,D=J(D^$,8),w=w+D|0,T=J(T^w,7),S=S+B|0,R=J(R^S,16),v=v+R|0,B=J(B^v,12),S=S+B|0,R=J(R^S,8),v=v+R|0,B=J(B^v,7),P=P+k|0,q=J(q^P,16),O=O+q|0,k=J(k^O,12),P=P+k|0,q=J(q^P,8),O=O+q|0,k=J(k^O,7),E=E+T|0,q=J(q^E,16),v=v+q|0,T=J(T^v,12),E=E+T|0,q=J(q^E,8),v=v+q|0,T=J(T^v,7),$=$+B|0,x=J(x^$,16),O=O+x|0,B=J(B^O,12),$=$+B|0,x=J(x^$,8),O=O+x|0,B=J(B^O,7),S=S+k|0,D=J(D^S,16),g=g+D|0,k=J(k^g,12),S=S+k|0,D=J(D^S,8),g=g+D|0,k=J(k^g,7),P=P+j|0,R=J(R^P,16),w=w+R|0,j=J(j^w,12),P=P+j|0,R=J(R^P,8),w=w+R|0,j=J(j^w,7);let L=0;i[L++]=o+E|0,i[L++]=a+$|0,i[L++]=c+S|0,i[L++]=u+P|0,i[L++]=h+j|0,i[L++]=l+T|0,i[L++]=d+B|0,i[L++]=f+k|0,i[L++]=p+g|0,i[L++]=y+w|0,i[L++]=m+v|0,i[L++]=_+O|0,i[L++]=b+x|0,i[L++]=I+D|0,i[L++]=A+R|0,i[L++]=C+q|0}const Nb=Ab(Rb,{counterRight:!1,counterLength:4,allowShortKeys:!1}),jb=new Uint8Array(16),dc=(r,e)=>{r.update(e);const t=e.length%16;t&&r.update(jb.subarray(t))},Bb=new Uint8Array(32);function pc(r,e,t,i,s){const n=r(e,t,Bb),o=Tb.create(n);s&&dc(o,s),dc(o,i);const a=new Uint8Array(16),c=yb(a);hc(c,0,BigInt(s?s.length:0),!0),hc(c,8,BigInt(i.length),!0),o.update(a);const u=o.digest();return qr(n,a),u}const Ub=r=>(e,t,i)=>({encrypt(s,n){const o=s.length;n=uc(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);r(e,t,a,a,1);const c=pc(r,e,t,a,i);return n.set(c,o),qr(c),n},decrypt(s,n){n=uc(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=pc(r,e,t,o,i);if(!vb(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),r(e,t,n,n,1),qr(c),n}}),ll=Eb({blockSize:64,nonceLength:12,tagLength:16},Ub(Nb));let dl=class extends Co{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,xo(e);const i=Fr(t);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),n.fill(0)}update(e){return Ur(this),this.iHash.update(e),this}digestInto(e){Ur(this),Ci(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const $s=(r,e,t)=>new dl(r,e).update(t).digest();$s.create=(r,e)=>new dl(r,e);function Fb(r,e,t){return xo(r),t===void 0&&(t=new Uint8Array(r.outputLen)),$s(r,Fr(t),Fr(e))}const Xs=new Uint8Array([0]),fc=new Uint8Array;function qb(r,e,t,i=32){if(xo(r),vi(i),i>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/r.outputLen);t===void 0&&(t=fc);const n=new Uint8Array(s*r.outputLen),o=$s.create(r,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<s;u++)Xs[0]=u+1,a.update(u===0?fc:c).update(t).update(Xs).digestInto(c),n.set(c,r.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),Xs.fill(0),n.slice(0,i)}const Lb=(r,e,t,i,s)=>qb(r,Fb(r,e,t),i,s);function kb(r,e,t,i){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=i?4:0,u=i?0:4;r.setUint32(e+c,o,i),r.setUint32(e+u,a,i)}function Mb(r,e,t){return r&e^~r&t}function zb(r,e,t){return r&e^r&t^e&t}let Hb=class extends Co{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Zs(this.buffer)}update(e){Ur(this);const{view:t,buffer:i,blockLen:s}=this;e=Fr(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=Zs(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(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ur(this),Xh(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let l=o;l<s;l++)t[l]=0;kb(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=Zs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,h[l],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(i),e}};const Vb=new Uint32Array([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]),Bt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ut=new Uint32Array(64);class Kb extends Hb{constructor(){super(64,32,8,!1),this.A=Bt[0]|0,this.B=Bt[1]|0,this.C=Bt[2]|0,this.D=Bt[3]|0,this.E=Bt[4]|0,this.F=Bt[5]|0,this.G=Bt[6]|0,this.H=Bt[7]|0}get(){const{A:e,B:t,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,t,i,s,n,o,a,c]}set(e,t,i,s,n,o,a,c){this.A=e|0,this.B=t|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,t){for(let l=0;l<16;l++,t+=4)Ut[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){const d=Ut[l-15],f=Ut[l-2],p=ft(d,7)^ft(d,18)^d>>>3,y=ft(f,17)^ft(f,19)^f>>>10;Ut[l]=y+Ut[l-7]+p+Ut[l-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:u,H:h}=this;for(let l=0;l<64;l++){const d=ft(a,6)^ft(a,11)^ft(a,25),f=h+d+Mb(a,c,u)+Vb[l]+Ut[l]|0,p=(ft(i,2)^ft(i,13)^ft(i,22))+zb(i,s,n)|0;h=u,u=c,c=a,a=o+f|0,o=n,n=s,s=i,i=f+p|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,u=u+this.G|0,h=h+this.H|0,this.set(i,s,n,o,a,c,u,h)}roundClean(){Ut.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ti=el(()=>new Kb);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ss=BigInt(0),Ds=BigInt(1),Wb=BigInt(2);function or(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ri(r){if(!or(r))throw new Error("Uint8Array expected")}function Lr(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}const Gb=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function kr(r){Ri(r);let e="";for(let t=0;t<r.length;t++)e+=Gb[r[t]];return e}function Nr(r){const e=r.toString(16);return e.length&1?"0"+e:e}function Ro(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ss:BigInt("0x"+r)}const St={_0:48,_9:57,A:65,F:70,a:97,f:102};function gc(r){if(r>=St._0&&r<=St._9)return r-St._0;if(r>=St.A&&r<=St.F)return r-(St.A-10);if(r>=St.a&&r<=St.f)return r-(St.a-10)}function Mr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);const e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=gc(r.charCodeAt(n)),a=gc(r.charCodeAt(n+1));if(o===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function tr(r){return Ro(kr(r))}function _i(r){return Ri(r),Ro(kr(Uint8Array.from(r).reverse()))}function zr(r,e){return Mr(r.toString(16).padStart(e*2,"0"))}function Ps(r,e){return zr(r,e).reverse()}function Yb(r){return Mr(Nr(r))}function Ve(r,e,t){let i;if(typeof e=="string")try{i=Mr(e)}catch(n){throw new Error(r+" must be hex string or Uint8Array, cause: "+n)}else if(or(e))i=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");const s=i.length;if(typeof t=="number"&&s!==t)throw new Error(r+" of length "+t+" expected, got "+s);return i}function Ii(...r){let e=0;for(let i=0;i<r.length;i++){const s=r[i];Ri(s),e+=s.length}const t=new Uint8Array(e);for(let i=0,s=0;i<r.length;i++){const n=r[i];t.set(n,s),s+=n.length}return t}function Jb(r,e){if(r.length!==e.length)return!1;let t=0;for(let i=0;i<r.length;i++)t|=r[i]^e[i];return t===0}function Zb(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}const en=r=>typeof r=="bigint"&&Ss<=r;function Os(r,e,t){return en(r)&&en(e)&&en(t)&&e<=r&&r<t}function Ct(r,e,t,i){if(!Os(e,t,i))throw new Error("expected valid "+r+": "+t+" <= n < "+i+", got "+e)}function pl(r){let e;for(e=0;r>Ss;r>>=Ds,e+=1);return e}function Qb(r,e){return r>>BigInt(e)&Ds}function Xb(r,e,t){return r|(t?Ds:Ss)<<BigInt(e)}const No=r=>(Wb<<BigInt(r-1))-Ds,tn=r=>new Uint8Array(r),yc=r=>Uint8Array.from(r);function fl(r,e,t){if(typeof r!="number"||r<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 t!="function")throw new Error("hmacFn must be a function");let i=tn(r),s=tn(r),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...h)=>t(s,i,...h),c=(h=tn())=>{s=a(yc([0]),h),i=a(),h.length!==0&&(s=a(yc([1]),h),i=a())},u=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const l=[];for(;h<e;){i=a();const d=i.slice();l.push(d),h+=i.length}return Ii(...l)};return(h,l)=>{o(),c(h);let d;for(;!(d=l(u()));)c();return o(),d}}const ev={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||or(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Gr(r,e,t={}){const i=(s,n,o)=>{const a=ev[n];if(typeof a!="function")throw new Error("invalid validator function");const c=r[s];if(!(o&&c===void 0)&&!a(c,r))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(t))i(s,n,!0);return r}const tv=()=>{throw new Error("not implemented")};function Hn(r){const e=new WeakMap;return(t,...i)=>{const s=e.get(t);if(s!==void 0)return s;const n=r(t,...i);return e.set(t,n),n}}var rv=Object.freeze({__proto__:null,isBytes:or,abytes:Ri,abool:Lr,bytesToHex:kr,numberToHexUnpadded:Nr,hexToNumber:Ro,hexToBytes:Mr,bytesToNumberBE:tr,bytesToNumberLE:_i,numberToBytesBE:zr,numberToBytesLE:Ps,numberToVarBytesBE:Yb,ensureBytes:Ve,concatBytes:Ii,equalBytes:Jb,utf8ToBytes:Zb,inRange:Os,aInRange:Ct,bitLen:pl,bitGet:Qb,bitSet:Xb,bitMask:No,createHmacDrbg:fl,validateObject:Gr,notImplemented:tv,memoized:Hn});const ve=BigInt(0),ue=BigInt(1),Jt=BigInt(2),iv=BigInt(3),Vn=BigInt(4),mc=BigInt(5),wc=BigInt(8);function qe(r,e){const t=r%e;return t>=ve?t:e+t}function gl(r,e,t){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(t<=ve)throw new Error("invalid modulus");if(t===ue)return ve;let i=ue;for(;e>ve;)e&ue&&(i=i*r%t),r=r*r%t,e>>=ue;return i}function ut(r,e,t){let i=r;for(;e-- >ve;)i*=i,i%=t;return i}function Kn(r,e){if(r===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let t=qe(r,e),i=e,s=ve,n=ue;for(;t!==ve;){const o=i/t,a=i%t,c=s-n*o;i=t,t=a,s=n,n=c}if(i!==ue)throw new Error("invert: does not exist");return qe(s,e)}function sv(r){const e=(r-ue)/Jt;let t,i,s;for(t=r-ue,i=0;t%Jt===ve;t/=Jt,i++);for(s=Jt;s<r&&gl(s,e,r)!==r-ue;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(r+ue)/Vn;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(t+ue)/Jt;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),t),h=o.pow(a,n),l=o.pow(a,t);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(l);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(u,ue<<BigInt(c-d-1));u=o.sqr(f),h=o.mul(h,f),l=o.mul(l,u),c=d}return h}}function nv(r){if(r%Vn===iv){const e=(r+ue)/Vn;return function(t,i){const s=t.pow(i,e);if(!t.eql(t.sqr(s),i))throw new Error("Cannot find square root");return s}}if(r%wc===mc){const e=(r-mc)/wc;return function(t,i){const s=t.mul(i,Jt),n=t.pow(s,e),o=t.mul(i,n),a=t.mul(t.mul(o,Jt),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),i))throw new Error("Cannot find square root");return c}}return sv(r)}const ov=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function av(r){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=ov.reduce((i,s)=>(i[s]="function",i),e);return Gr(r,t)}function cv(r,e,t){if(t<ve)throw new Error("invalid exponent, negatives unsupported");if(t===ve)return r.ONE;if(t===ue)return e;let i=r.ONE,s=e;for(;t>ve;)t&ue&&(i=r.mul(i,s)),s=r.sqr(s),t>>=ue;return i}function uv(r,e){const t=new Array(e.length),i=e.reduce((n,o,a)=>r.is0(o)?n:(t[a]=n,r.mul(n,o)),r.ONE),s=r.inv(i);return e.reduceRight((n,o,a)=>r.is0(o)?n:(t[a]=r.mul(n,t[a]),r.mul(n,o)),s),t}function yl(r,e){const t=e!==void 0?e:r.toString(2).length,i=Math.ceil(t/8);return{nBitLength:t,nByteLength:i}}function ml(r,e,t=!1,i={}){if(r<=ve)throw new Error("invalid field: expected ORDER > 0, got "+r);const{nBitLength:s,nByteLength:n}=yl(r,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:r,isLE:t,BITS:s,BYTES:n,MASK:No(s),ZERO:ve,ONE:ue,create:c=>qe(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<r},is0:c=>c===ve,isOdd:c=>(c&ue)===ue,neg:c=>qe(-c,r),eql:(c,u)=>c===u,sqr:c=>qe(c*c,r),add:(c,u)=>qe(c+u,r),sub:(c,u)=>qe(c-u,r),mul:(c,u)=>qe(c*u,r),pow:(c,u)=>cv(a,c,u),div:(c,u)=>qe(c*Kn(u,r),r),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Kn(c,r),sqrt:i.sqrt||(c=>(o||(o=nv(r)),o(a,c))),invertBatch:c=>uv(a,c),cmov:(c,u,h)=>h?u:c,toBytes:c=>t?Ps(c,n):zr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?_i(c):tr(c)}});return Object.freeze(a)}function wl(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function bl(r){const e=wl(r);return e+Math.ceil(e/2)}function hv(r,e,t=!1){const i=r.length,s=wl(e),n=bl(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=t?_i(r):tr(r),a=qe(o,e-ue)+ue;return t?Ps(a,s):zr(a,s)}const bc=BigInt(0),Ki=BigInt(1);function rn(r,e){const t=e.negate();return r?t:e}function vl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function sn(r,e){vl(r,e);const t=Math.ceil(e/r)+1,i=2**(r-1);return{windows:t,windowSize:i}}function lv(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function dv(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,i)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+i)})}const nn=new WeakMap,El=new WeakMap;function on(r){return El.get(r)||1}function pv(r,e){return{constTimeNegate:rn,hasPrecomputes(t){return on(t)!==1},unsafeLadder(t,i,s=r.ZERO){let n=t;for(;i>bc;)i&Ki&&(s=s.add(n)),n=n.double(),i>>=Ki;return s},precomputeWindow(t,i){const{windows:s,windowSize:n}=sn(i,e),o=[];let a=t,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let h=1;h<n;h++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,i,s){const{windows:n,windowSize:o}=sn(t,e);let a=r.ZERO,c=r.BASE;const u=BigInt(2**t-1),h=2**t,l=BigInt(t);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&u);s>>=l,p>o&&(p-=h,s+=Ki);const y=f,m=f+Math.abs(p)-1,_=d%2!==0,b=p<0;p===0?c=c.add(rn(_,i[y])):a=a.add(rn(b,i[m]))}return{p:a,f:c}},wNAFUnsafe(t,i,s,n=r.ZERO){const{windows:o,windowSize:a}=sn(t,e),c=BigInt(2**t-1),u=2**t,h=BigInt(t);for(let l=0;l<o;l++){const d=l*a;if(s===bc)break;let f=Number(s&c);if(s>>=h,f>a&&(f-=u,s+=Ki),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(t,i,s){let n=nn.get(i);return n||(n=this.precomputeWindow(i,t),t!==1&&nn.set(i,s(n))),n},wNAFCached(t,i,s){const n=on(t);return this.wNAF(n,this.getPrecomputes(n,t,s),i)},wNAFCachedUnsafe(t,i,s,n){const o=on(t);return o===1?this.unsafeLadder(t,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),i,n)},setWindowSize(t,i){vl(i,e),El.set(t,i),nn.delete(t)}}}function fv(r,e,t,i){if(lv(t,r),dv(i,e),t.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=r.ZERO,n=pl(BigInt(t.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let h=s;for(let l=u;l>=0;l-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(l)&BigInt(a));c[y]=c[y].add(t[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(h=h.add(d),l!==0)for(let f=0;f<o;f++)h=h.double()}return h}function _l(r){return av(r.Fp),Gr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yl(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const mr=BigInt(0),an=BigInt(1);function gv(r){return Gr(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function yv(r){const e=gv(r),{P:t}=e,i=b=>qe(b,t),s=e.montgomeryBits,n=Math.ceil(s/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>gl(b,t-BigInt(2),t));function u(b,I,A){const C=i(b*(I-A));return I=i(I-C),A=i(A+C),[I,A]}const h=(e.a-BigInt(2))/BigInt(4);function l(b,I){Ct("u",b,mr,t),Ct("scalar",I,mr,t);const A=I,C=b;let E=an,$=mr,S=b,P=an,j=mr,T;for(let k=BigInt(s-1);k>=mr;k--){const g=A>>k&an;j^=g,T=u(j,E,S),E=T[0],S=T[1],T=u(j,$,P),$=T[0],P=T[1],j=g;const w=E+$,v=i(w*w),O=E-$,x=i(O*O),D=v-x,R=S+P,q=S-P,L=i(q*w),M=i(R*O),z=L+M,V=L-M;S=i(z*z),P=i(C*i(V*V)),E=i(v*x),$=i(D*(v+i(h*D)))}T=u(j,E,S),E=T[0],S=T[1],T=u(j,$,P),$=T[0],P=T[1];const B=c($);return i(E*B)}function d(b){return Ps(i(b),n)}function f(b){const I=Ve("u coordinate",b,n);return o===32&&(I[31]&=127),_i(I)}function p(b){const I=Ve("scalar",b),A=I.length;if(A!==n&&A!==o){let C=""+n+" or "+o;throw new Error("invalid scalar, expected "+C+" bytes, got "+A)}return _i(a(I))}function y(b,I){const A=f(I),C=p(b),E=l(A,C);if(E===mr)throw new Error("invalid private or public key received");return d(E)}const m=d(e.Gu);function _(b){return y(b,m)}return{scalarMult:y,scalarMultBase:_,getSharedSecret:(b,I)=>y(b,I),getPublicKey:b=>_(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:m}}const Wn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const mv=BigInt(1),vc=BigInt(2),wv=BigInt(3),bv=BigInt(5);BigInt(8);function vv(r){const e=BigInt(10),t=BigInt(20),i=BigInt(40),s=BigInt(80),n=Wn,o=r*r%n*r%n,a=ut(o,vc,n)*o%n,c=ut(a,mv,n)*r%n,u=ut(c,bv,n)*c%n,h=ut(u,e,n)*u%n,l=ut(h,t,n)*h%n,d=ut(l,i,n)*l%n,f=ut(d,s,n)*d%n,p=ut(f,s,n)*d%n,y=ut(p,e,n)*u%n;return{pow_p_5_8:ut(y,vc,n)*r%n,b2:o}}function Ev(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}const Gn=yv({P:Wn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{const e=Wn,{pow_p_5_8:t,b2:i}=vv(r);return qe(ut(t,wv,e)*i,e)},adjustScalarBytes:Ev,randomBytes:Wr});function Ec(r){r.lowS!==void 0&&Lr("lowS",r.lowS),r.prehash!==void 0&&Lr("prehash",r.prehash)}function _v(r){const e=_l(r);Gr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:i,a:s}=e;if(t){if(!i.eql(s,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Iv,hexToBytes:$v}=rv;class Sv extends Error{constructor(e=""){super(e)}}const At={Err:Sv,_tlv:{encode:(r,e)=>{const{Err:t}=At;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const i=e.length/2,s=Nr(i);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const n=i>127?Nr(s.length/2|128):"";return Nr(r)+n+s+e},decode(r,e){const{Err:t}=At;let i=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[i++]!==r)throw new t("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 t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const h of u)o=o<<8|h;if(i+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(r){const{Err:e}=At;if(r<xt)throw new e("integer: negative integers are not allowed");let t=Nr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){const{Err:e}=At;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Iv(r)}},toSig(r){const{Err:e,_int:t,_tlv:i}=At,s=typeof r=="string"?$v(r):r;Ri(s);const{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:u,l:h}=i.decode(2,c);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(u)}},hexFromSig(r){const{_tlv:e,_int:t}=At,i=e.encode(2,t.encode(r.r)),s=e.encode(2,t.encode(r.s)),n=i+s;return e.encode(48,n)}},xt=BigInt(0),me=BigInt(1);BigInt(2);const _c=BigInt(3);BigInt(4);function Dv(r){const e=_v(r),{Fp:t}=e,i=ml(e.n,e.nBitLength),s=e.toBytes||((y,m,_)=>{const b=m.toAffine();return Ii(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),n=e.fromBytes||(y=>{const m=y.subarray(1),_=t.fromBytes(m.subarray(0,t.BYTES)),b=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:_,y:b}});function o(y){const{a:m,b:_}=e,b=t.sqr(y),I=t.mul(b,y);return t.add(t.add(I,t.mul(y,m)),_)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Os(y,me,e.n)}function c(y){const{allowedPrivateKeyLengths:m,nByteLength:_,wrapPrivateKey:b,n:I}=e;if(m&&typeof y!="bigint"){if(or(y)&&(y=kr(y)),typeof y!="string"||!m.includes(y.length))throw new Error("invalid private key");y=y.padStart(_*2,"0")}let A;try{A=typeof y=="bigint"?y:tr(Ve("private key",y,_))}catch{throw new Error("invalid private key, expected hex or "+_+" bytes, got "+typeof y)}return b&&(A=qe(A,I)),Ct("private key",A,me,I),A}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const h=Hn((y,m)=>{const{px:_,py:b,pz:I}=y;if(t.eql(I,t.ONE))return{x:_,y:b};const A=y.is0();m==null&&(m=A?t.ONE:t.inv(I));const C=t.mul(_,m),E=t.mul(b,m),$=t.mul(I,m);if(A)return{x:t.ZERO,y:t.ZERO};if(!t.eql($,t.ONE))throw new Error("invZ was invalid");return{x:C,y:E}}),l=Hn(y=>{if(y.is0()){if(e.allowInfinityPoint&&!t.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:m,y:_}=y.toAffine();if(!t.isValid(m)||!t.isValid(_))throw new Error("bad point: x or y not FE");const b=t.sqr(_),I=o(m);if(!t.eql(b,I))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(m,_,b){if(this.px=m,this.py=_,this.pz=b,m==null||!t.isValid(m))throw new Error("x required");if(_==null||!t.isValid(_))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(m){const{x:_,y:b}=m||{};if(!m||!t.isValid(_)||!t.isValid(b))throw new Error("invalid affine point");if(m instanceof d)throw new Error("projective point not allowed");const I=A=>t.eql(A,t.ZERO);return I(_)&&I(b)?d.ZERO:new d(_,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const _=t.invertBatch(m.map(b=>b.pz));return m.map((b,I)=>b.toAffine(_[I])).map(d.fromAffine)}static fromHex(m){const _=d.fromAffine(n(Ve("pointHex",m)));return _.assertValidity(),_}static fromPrivateKey(m){return d.BASE.multiply(c(m))}static msm(m,_){return fv(d,i,m,_)}_setWindowSize(m){p.setWindowSize(this,m)}assertValidity(){l(this)}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){u(m);const{px:_,py:b,pz:I}=this,{px:A,py:C,pz:E}=m,$=t.eql(t.mul(_,E),t.mul(A,I)),S=t.eql(t.mul(b,E),t.mul(C,I));return $&&S}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:_}=e,b=t.mul(_,_c),{px:I,py:A,pz:C}=this;let E=t.ZERO,$=t.ZERO,S=t.ZERO,P=t.mul(I,I),j=t.mul(A,A),T=t.mul(C,C),B=t.mul(I,A);return B=t.add(B,B),S=t.mul(I,C),S=t.add(S,S),E=t.mul(m,S),$=t.mul(b,T),$=t.add(E,$),E=t.sub(j,$),$=t.add(j,$),$=t.mul(E,$),E=t.mul(B,E),S=t.mul(b,S),T=t.mul(m,T),B=t.sub(P,T),B=t.mul(m,B),B=t.add(B,S),S=t.add(P,P),P=t.add(S,P),P=t.add(P,T),P=t.mul(P,B),$=t.add($,P),T=t.mul(A,C),T=t.add(T,T),P=t.mul(T,B),E=t.sub(E,P),S=t.mul(T,j),S=t.add(S,S),S=t.add(S,S),new d(E,$,S)}add(m){u(m);const{px:_,py:b,pz:I}=this,{px:A,py:C,pz:E}=m;let $=t.ZERO,S=t.ZERO,P=t.ZERO;const j=e.a,T=t.mul(e.b,_c);let B=t.mul(_,A),k=t.mul(b,C),g=t.mul(I,E),w=t.add(_,b),v=t.add(A,C);w=t.mul(w,v),v=t.add(B,k),w=t.sub(w,v),v=t.add(_,I);let O=t.add(A,E);return v=t.mul(v,O),O=t.add(B,g),v=t.sub(v,O),O=t.add(b,I),$=t.add(C,E),O=t.mul(O,$),$=t.add(k,g),O=t.sub(O,$),P=t.mul(j,v),$=t.mul(T,g),P=t.add($,P),$=t.sub(k,P),P=t.add(k,P),S=t.mul($,P),k=t.add(B,B),k=t.add(k,B),g=t.mul(j,g),v=t.mul(T,v),k=t.add(k,g),g=t.sub(B,g),g=t.mul(j,g),v=t.add(v,g),B=t.mul(k,v),S=t.add(S,B),B=t.mul(O,v),$=t.mul(w,$),$=t.sub($,B),B=t.mul(w,k),P=t.mul(O,P),P=t.add(P,B),new d($,S,P)}subtract(m){return this.add(m.negate())}is0(){return this.equals(d.ZERO)}wNAF(m){return p.wNAFCached(this,m,d.normalizeZ)}multiplyUnsafe(m){const{endo:_,n:b}=e;Ct("scalar",m,xt,b);const I=d.ZERO;if(m===xt)return I;if(this.is0()||m===me)return this;if(!_||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,m,d.normalizeZ);let{k1neg:A,k1:C,k2neg:E,k2:$}=_.splitScalar(m),S=I,P=I,j=this;for(;C>xt||$>xt;)C&me&&(S=S.add(j)),$&me&&(P=P.add(j)),j=j.double(),C>>=me,$>>=me;return A&&(S=S.negate()),E&&(P=P.negate()),P=new d(t.mul(P.px,_.beta),P.py,P.pz),S.add(P)}multiply(m){const{endo:_,n:b}=e;Ct("scalar",m,me,b);let I,A;if(_){const{k1neg:C,k1:E,k2neg:$,k2:S}=_.splitScalar(m);let{p:P,f:j}=this.wNAF(E),{p:T,f:B}=this.wNAF(S);P=p.constTimeNegate(C,P),T=p.constTimeNegate($,T),T=new d(t.mul(T.px,_.beta),T.py,T.pz),I=P.add(T),A=j.add(B)}else{const{p:C,f:E}=this.wNAF(m);I=C,A=E}return d.normalizeZ([I,A])[0]}multiplyAndAddUnsafe(m,_,b){const I=d.BASE,A=(E,$)=>$===xt||$===me||!E.equals(I)?E.multiplyUnsafe($):E.multiply($),C=A(this,_).add(A(m,b));return C.is0()?void 0:C}toAffine(m){return h(this,m)}isTorsionFree(){const{h:m,isTorsionFree:_}=e;if(m===me)return!0;if(_)return _(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:_}=e;return m===me?this:_?_(d,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return Lr("isCompressed",m),this.assertValidity(),s(d,this,m)}toHex(m=!0){return Lr("isCompressed",m),kr(this.toRawBytes(m))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);const f=e.nBitLength,p=pv(d,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Pv(r){const e=_l(r);return Gr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Ov(r){const e=Pv(r),{Fp:t,n:i}=e,s=t.BYTES+1,n=2*t.BYTES+1;function o(g){return qe(g,i)}function a(g){return Kn(g,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:h,isWithinCurveOrder:l}=Dv({...e,toBytes(g,w,v){const O=w.toAffine(),x=t.toBytes(O.x),D=Ii;return Lr("isCompressed",v),v?D(Uint8Array.from([w.hasEvenY()?2:3]),x):D(Uint8Array.from([4]),x,t.toBytes(O.y))},fromBytes(g){const w=g.length,v=g[0],O=g.subarray(1);if(w===s&&(v===2||v===3)){const x=tr(O);if(!Os(x,me,t.ORDER))throw new Error("Point is not on curve");const D=h(x);let R;try{R=t.sqrt(D)}catch(L){const M=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+M)}const q=(R&me)===me;return(v&1)===1!==q&&(R=t.neg(R)),{x,y:R}}else if(w===n&&v===4){const x=t.fromBytes(O.subarray(0,t.BYTES)),D=t.fromBytes(O.subarray(t.BYTES,2*t.BYTES));return{x,y:D}}else{const x=s,D=n;throw new Error("invalid Point, expected length of "+x+", or uncompressed "+D+", got "+w)}}}),d=g=>kr(zr(g,e.nByteLength));function f(g){const w=i>>me;return g>w}function p(g){return f(g)?o(-g):g}const y=(g,w,v)=>tr(g.slice(w,v));class m{constructor(w,v,O){this.r=w,this.s=v,this.recovery=O,this.assertValidity()}static fromCompact(w){const v=e.nByteLength;return w=Ve("compactSignature",w,v*2),new m(y(w,0,v),y(w,v,2*v))}static fromDER(w){const{r:v,s:O}=At.toSig(Ve("DER",w));return new m(v,O)}assertValidity(){Ct("r",this.r,me,i),Ct("s",this.s,me,i)}addRecoveryBit(w){return new m(this.r,this.s,w)}recoverPublicKey(w){const{r:v,s:O,recovery:x}=this,D=E(Ve("msgHash",w));if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");const R=x===2||x===3?v+e.n:v;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const q=x&1?"03":"02",L=c.fromHex(q+d(R)),M=a(R),z=o(-D*M),V=o(O*M),H=c.BASE.multiplyAndAddUnsafe(L,z,V);if(!H)throw new Error("point at infinify");return H.assertValidity(),H}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Mr(this.toDERHex())}toDERHex(){return At.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Mr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const _={isValidPrivateKey(g){try{return u(g),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const g=bl(e.n);return hv(e.randomBytes(g),e.n)},precompute(g=8,w=c.BASE){return w._setWindowSize(g),w.multiply(BigInt(3)),w}};function b(g,w=!0){return c.fromPrivateKey(g).toRawBytes(w)}function I(g){const w=or(g),v=typeof g=="string",O=(w||v)&&g.length;return w?O===s||O===n:v?O===2*s||O===2*n:g instanceof c}function A(g,w,v=!0){if(I(g))throw new Error("first arg must be private key");if(!I(w))throw new Error("second arg must be public key");return c.fromHex(w).multiply(u(g)).toRawBytes(v)}const C=e.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const w=tr(g),v=g.length*8-e.nBitLength;return v>0?w>>BigInt(v):w},E=e.bits2int_modN||function(g){return o(C(g))},$=No(e.nBitLength);function S(g){return Ct("num < 2^"+e.nBitLength,g,xt,$),zr(g,e.nByteLength)}function P(g,w,v=j){if(["recovered","canonical"].some(ee=>ee in v))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:x}=e;let{lowS:D,prehash:R,extraEntropy:q}=v;D==null&&(D=!0),g=Ve("msgHash",g),Ec(v),R&&(g=Ve("prehashed msgHash",O(g)));const L=E(g),M=u(w),z=[S(M),S(L)];if(q!=null&&q!==!1){const ee=q===!0?x(t.BYTES):q;z.push(Ve("extraEntropy",ee))}const V=Ii(...z),H=L;function ne(ee){const Y=C(ee);if(!l(Y))return;const Ae=a(Y),Ee=c.BASE.multiply(Y).toAffine(),Ce=o(Ee.x);if(Ce===xt)return;const Je=o(Ae*o(H+Ce*M));if(Je===xt)return;let Ze=(Ee.x===Ce?0:2)|Number(Ee.y&me),dr=Je;return D&&f(Je)&&(dr=p(Je),Ze^=1),new m(Ce,dr,Ze)}return{seed:V,k2sig:ne}}const j={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function B(g,w,v=j){const{seed:O,k2sig:x}=P(g,w,v),D=e;return fl(D.hash.outputLen,D.nByteLength,D.hmac)(O,x)}c.BASE._setWindowSize(8);function k(g,w,v,O=T){var Je;const x=g;w=Ve("msgHash",w),v=Ve("publicKey",v);const{lowS:D,prehash:R,format:q}=O;if(Ec(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(q!==void 0&&q!=="compact"&&q!=="der")throw new Error("format must be compact or der");const L=typeof x=="string"||or(x),M=!L&&!q&&typeof x=="object"&&x!==null&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let z,V;try{if(M&&(z=new m(x.r,x.s)),L){try{q!=="compact"&&(z=m.fromDER(x))}catch(Ze){if(!(Ze instanceof At.Err))throw Ze}!z&&q!=="der"&&(z=m.fromCompact(x))}V=c.fromHex(v)}catch{return!1}if(!z||D&&z.hasHighS())return!1;R&&(w=e.hash(w));const{r:H,s:ne}=z,ee=E(w),Y=a(ne),Ae=o(ee*Y),Ee=o(H*Y),Ce=(Je=c.BASE.multiplyAndAddUnsafe(V,Ae,Ee))==null?void 0:Je.toAffine();return Ce?o(Ce.x)===H:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:A,sign:B,verify:k,ProjectivePoint:c,Signature:m,utils:_}}function Av(r){return{hash:r,hmac:(e,...t)=>$s(r,e,Rw(...t)),randomBytes:Wr}}function xv(r,e){const t=i=>Ov({...r,...Av(i)});return{...t(e),create:t}}const Il=ml(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Cv=Il.create(BigInt("-3")),Tv=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Rv=xv({a:Cv,b:Tv,Fp:Il,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Ti),$l="base10",Re="base16",ht="base64pad",qt="base64url",Ni="utf8",Sl=0,Tt=1,ji=2,Nv=0,Ic=1,fi=12,jo=32;function jv(){const r=Gn.utils.randomPrivateKey(),e=Gn.getPublicKey(r);return{privateKey:Le(r,Re),publicKey:Le(e,Re)}}function Yn(){const r=Wr(jo);return Le(r,Re)}function Bv(r,e){const t=Gn.getSharedSecret(rt(r,Re),rt(e,Re)),i=Lb(Ti,t,void 0,void 0,jo);return Le(i,Re)}function ss(r){const e=Ti(rt(r,Re));return Le(e,Re)}function vt(r){const e=Ti(rt(r,Ni));return Le(e,Re)}function Dl(r){return rt(`${r}`,$l)}function ar(r){return Number(Le(r,$l))}function Pl(r){return r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ol(r){const e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function Uv(r){const e=Dl(typeof r.type<"u"?r.type:Sl);if(ar(e)===Tt&&typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof r.senderPublicKey<"u"?rt(r.senderPublicKey,Re):void 0,i=typeof r.iv<"u"?rt(r.iv,Re):Wr(fi),s=rt(r.symKey,Re),n=ll(s,i).encrypt(rt(r.message,Ni)),o=Al({type:e,sealed:n,iv:i,senderPublicKey:t});return r.encoding===qt?Pl(o):o}function Fv(r){const e=rt(r.symKey,Re),{sealed:t,iv:i}=$i({encoded:r.encoded,encoding:r.encoding}),s=ll(e,i).decrypt(t);if(s===null)throw new Error("Failed to decrypt");return Le(s,Ni)}function qv(r,e){const t=Dl(ji),i=Wr(fi),s=rt(r,Ni),n=Al({type:t,sealed:s,iv:i});return e===qt?Pl(n):n}function Lv(r,e){const{sealed:t}=$i({encoded:r,encoding:e});return Le(t,Ni)}function Al(r){if(ar(r.type)===ji)return Le(pi([r.type,r.sealed]),ht);if(ar(r.type)===Tt){if(typeof r.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Le(pi([r.type,r.senderPublicKey,r.iv,r.sealed]),ht)}return Le(pi([r.type,r.iv,r.sealed]),ht)}function $i(r){const e=(r.encoding||ht)===qt?Ol(r.encoded):r.encoded,t=rt(e,ht),i=t.slice(Nv,Ic),s=Ic;if(ar(i)===Tt){const c=s+jo,u=c+fi,h=t.slice(s,c),l=t.slice(c,u),d=t.slice(u);return{type:i,sealed:d,iv:l,senderPublicKey:h}}if(ar(i)===ji){const c=t.slice(s),u=Wr(fi);return{type:i,sealed:c,iv:u}}const n=s+fi,o=t.slice(s,n),a=t.slice(n);return{type:i,sealed:a,iv:o}}function kv(r,e){const t=$i({encoded:r,encoding:e==null?void 0:e.encoding});return xl({type:ar(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Le(t.senderPublicKey,Re):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function xl(r){const e=(r==null?void 0:r.type)||Sl;if(e===Tt){if(typeof(r==null?void 0:r.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(r==null?void 0:r.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:r==null?void 0:r.senderPublicKey,receiverPublicKey:r==null?void 0:r.receiverPublicKey}}function $c(r){return r.type===Tt&&typeof r.senderPublicKey=="string"&&typeof r.receiverPublicKey=="string"}function Sc(r){return r.type===ji}function Mv(r){const e=Buffer.from(r.x,"base64"),t=Buffer.from(r.y,"base64");return pi([new Uint8Array([4]),e,t])}function zv(r,e){const[t,i,s]=r.split("."),n=Buffer.from(Ol(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${i}`,u=Ti(c),h=Mv(e);if(!Rv.verify(pi([o,a]),u,h))throw new Error("Invalid signature");return Un(r).payload}const Hv="irn";function ps(r){return(r==null?void 0:r.relay)||{protocol:Hv}}function ui(r){const e=Ym[r];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${r}`);return e}function Vv(r,e="-"){const t={},i="relay"+e;return Object.keys(r).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=r[s];t[n]=o}}),t}function Dc(r){if(!r.includes("wc:")){const u=Qh(r);u!=null&&u.includes("wc:")&&(r=u)}r=r.includes("wc://")?r.replace("wc://",""):r,r=r.includes("wc:")?r.replace("wc:",""):r;const e=r.indexOf(":"),t=r.indexOf("?")!==-1?r.indexOf("?"):void 0,i=r.substring(0,e),s=r.substring(e+1,t).split("@"),n=typeof t<"u"?r.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((u,h)=>{a[h]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:Kv(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:Vv(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function Kv(r){return r.startsWith("//")?r.substring(2):r}function Wv(r,e="-"){const t="relay",i={};return Object.keys(r).forEach(s=>{const n=s,o=t+e+n;r[n]&&(i[o]=r[n])}),i}function Pc(r){const e=new URLSearchParams,t=Wv(r.relay);Object.keys(t).sort().forEach(s=>{e.set(s,t[s])}),e.set("symKey",r.symKey),r.expiryTimestamp&&e.set("expiryTimestamp",r.expiryTimestamp.toString()),r.methods&&e.set("methods",r.methods.join(","));const i=e.toString();return`${r.protocol}:${r.topic}@${r.version}?${i}`}function Wi(r,e,t){return`${r}?wc_ev=${t}&topic=${e}`}function Yr(r){const e=[];return r.forEach(t=>{const[i,s]=t.split(":");e.push(`${i}:${s}`)}),e}function Gv(r){const e=[];return Object.values(r).forEach(t=>{e.push(...Yr(t.accounts))}),e}function Yv(r,e){const t=[];return Object.values(r).forEach(i=>{Yr(i.accounts).includes(e)&&t.push(...i.methods)}),t}function Jv(r,e){const t=[];return Object.values(r).forEach(i=>{Yr(i.accounts).includes(e)&&t.push(...i.events)}),t}function Bo(r){return r.includes(":")}function hi(r){return Bo(r)?r.split(":")[0]:r}function Zv(r){const e={};return r==null||r.forEach(t=>{var i;const[s,n]=t.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(t),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function Oc(r,e){e=e.map(i=>i.replace("did:pkh:",""));const t=Zv(e);for(const[i,s]of Object.entries(t))s.methods?s.methods=rs(s.methods,r):s.methods=r,s.events=["chainChanged","accountsChanged"];return t}const Qv={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},Xv={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function F(r,e){const{message:t,code:i}=Xv[r];return{message:e?`${t} ${e}`:t,code:i}}function te(r,e){const{message:t,code:i}=Qv[r];return{message:e?`${t} ${e}`:t,code:i}}function lt(r,e){return!!Array.isArray(r)}function Si(r){return Object.getPrototypeOf(r)===Object.prototype&&Object.keys(r).length}function Se(r){return typeof r>"u"}function le(r,e){return e&&Se(r)?!0:typeof r=="string"&&!!r.trim().length}function Uo(r,e){return e&&Se(r)?!0:typeof r=="number"&&!isNaN(r)}function e1(r,e){const{requiredNamespaces:t}=e,i=Object.keys(r.namespaces),s=Object.keys(t);let n=!0;return Xt(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:u}=r.namespaces[o],h=Yr(a),l=t[o];(!Xt(Wh(o,l),h)||!Xt(l.methods,c)||!Xt(l.events,u))&&(n=!1)}),n):!1}function fs(r){return le(r,!1)&&r.includes(":")?r.split(":").length===2:!1}function t1(r){if(le(r,!1)&&r.includes(":")){const e=r.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&fs(t)}}return!1}function r1(r){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(le(r,!1)){if(e(r))return!0;const t=Qh(r);return e(t)}}catch{}return!1}function i1(r){var e;return(e=r==null?void 0:r.proposer)==null?void 0:e.publicKey}function s1(r){return r==null?void 0:r.topic}function n1(r,e){let t=null;return le(r==null?void 0:r.publicKey,!1)||(t=F("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function Ac(r){let e=!0;return lt(r)?r.length&&(e=r.every(t=>le(t,!1))):e=!1,e}function o1(r,e,t){let i=null;return lt(e)&&e.length?e.forEach(s=>{i||fs(s)||(i=te("UNSUPPORTED_CHAINS",`${t}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):fs(r)||(i=te("UNSUPPORTED_CHAINS",`${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function a1(r,e,t){let i=null;return Object.entries(r).forEach(([s,n])=>{if(i)return;const o=o1(s,Wh(s,n),`${e} ${t}`);o&&(i=o)}),i}function c1(r,e){let t=null;return lt(r)?r.forEach(i=>{t||t1(i)||(t=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):t=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function u1(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const s=c1(i==null?void 0:i.accounts,`${e} namespace`);s&&(t=s)}),t}function h1(r,e){let t=null;return Ac(r==null?void 0:r.methods)?Ac(r==null?void 0:r.events)||(t=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function Cl(r,e){let t=null;return Object.values(r).forEach(i=>{if(t)return;const s=h1(i,`${e}, namespace`);s&&(t=s)}),t}function l1(r,e,t){let i=null;if(r&&Si(r)){const s=Cl(r,e);s&&(i=s);const n=a1(r,e,t);n&&(i=n)}else i=F("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return i}function cn(r,e){let t=null;if(r&&Si(r)){const i=Cl(r,e);i&&(t=i);const s=u1(r,e);s&&(t=s)}else t=F("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Tl(r){return le(r.protocol,!0)}function d1(r,e){let t=!1;return r?r&&lt(r)&&r.length&&r.forEach(i=>{t=Tl(i)}):t=!0,t}function p1(r){return typeof r=="number"}function Fe(r){return typeof r<"u"&&typeof r!==null}function f1(r){return!(!r||typeof r!="object"||!r.code||!Uo(r.code,!1)||!r.message||!le(r.message,!1))}function g1(r){return!(Se(r)||!le(r.method,!1))}function y1(r){return!(Se(r)||Se(r.result)&&Se(r.error)||!Uo(r.id,!1)||!le(r.jsonrpc,!1))}function m1(r){return!(Se(r)||!le(r.name,!1))}function xc(r,e){return!(!fs(e)||!Gv(r).includes(e))}function w1(r,e,t){return le(t,!1)?Yv(r,e).includes(t):!1}function b1(r,e,t){return le(t,!1)?Jv(r,e).includes(t):!1}function Cc(r,e,t){let i=null;const s=v1(r),n=E1(e),o=Object.keys(s),a=Object.keys(n),c=Tc(Object.keys(r)),u=Tc(Object.keys(e)),h=c.filter(l=>!u.includes(l));return h.length&&(i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces.
      Required: ${h.toString()}
      Received: ${Object.keys(e).toString()}`)),Xt(o,a)||(i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces.
      Required: ${o.toString()}
      Approved: ${a.toString()}`)),Object.keys(e).forEach(l=>{if(!l.includes(":")||i)return;const d=Yr(e[l].accounts);d.includes(l)||(i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${l}
        Required: ${l}
        Approved: ${d.toString()}`))}),o.forEach(l=>{i||(Xt(s[l].methods,n[l].methods)?Xt(s[l].events,n[l].events)||(i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${l}`)):i=F("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${l}`))}),i}function v1(r){const e={};return Object.keys(r).forEach(t=>{var i;t.includes(":")?e[t]=r[t]:(i=r[t].chains)==null||i.forEach(s=>{e[s]={methods:r[t].methods,events:r[t].events}})}),e}function Tc(r){return[...new Set(r.map(e=>e.includes(":")?e.split(":")[0]:e))]}function E1(r){const e={};return Object.keys(r).forEach(t=>{if(t.includes(":"))e[t]=r[t];else{const i=Yr(r[t].accounts);i==null||i.forEach(s=>{e[s]={accounts:r[t].accounts.filter(n=>n.includes(`${s}:`)),methods:r[t].methods,events:r[t].events}})}}),e}function _1(r,e){return Uo(r,!1)&&r<=e.max&&r>=e.min}function Rc(){const r=xi();return new Promise(e=>{switch(r){case We.browser:e(I1());break;case We.reactNative:e($1());break;case We.node:e(S1());break;default:e(!0)}})}function I1(){return Ai()&&(navigator==null?void 0:navigator.onLine)}async function $1(){if(zt()&&typeof global<"u"&&global!=null&&global.NetInfo){const r=await(global==null?void 0:global.NetInfo.fetch());return r==null?void 0:r.isConnected}return!0}function S1(){return!0}function D1(r){switch(xi()){case We.browser:P1(r);break;case We.reactNative:O1(r);break}}function P1(r){!zt()&&Ai()&&(window.addEventListener("online",()=>r(!0)),window.addEventListener("offline",()=>r(!1)))}function O1(r){zt()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>r(e==null?void 0:e.isConnected)))}const un={};class si{static get(e){return un[e]}static set(e,t){un[e]=t}static delete(e){delete un[e]}}class cr{}let A1=class extends cr{constructor(e){super()}};const Nc=U.FIVE_SECONDS,Jr={pulse:"heartbeat_pulse"};let x1=class Rl extends A1{constructor(e){super(e),this.events=new Ye.EventEmitter,this.interval=Nc,this.interval=(e==null?void 0:e.interval)||Nc}static async init(e){const t=new Rl(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),U.toMiliseconds(this.interval))}pulse(){this.events.emit(Jr.pulse)}};const C1=/"(?:_|\\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*:/,T1=/"(?: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*:/,R1=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function N1(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){j1(r);return}return e}function j1(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`)}function Gi(r,e={}){if(typeof r!="string")return r;const t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){const i=t.toLowerCase();if(i==="true")return!0;if(i==="false")return!1;if(i==="undefined")return;if(i==="null")return null;if(i==="nan")return Number.NaN;if(i==="infinity")return Number.POSITIVE_INFINITY;if(i==="-infinity")return Number.NEGATIVE_INFINITY}if(!R1.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(C1.test(r)||T1.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,N1)}return JSON.parse(r)}catch(i){if(e.strict)throw i;return r}}function B1(r){return!r||typeof r.then!="function"?Promise.resolve(r):r}function ye(r,...e){try{return B1(r(...e))}catch(t){return Promise.reject(t)}}function U1(r){const e=typeof r;return r===null||e!=="object"&&e!=="function"}function F1(r){const e=Object.getPrototypeOf(r);return!e||e.isPrototypeOf(Object)}function ns(r){if(U1(r))return String(r);if(F1(r)||Array.isArray(r))return JSON.stringify(r);if(typeof r.toJSON=="function")return ns(r.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Nl(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const Jn="base64:";function q1(r){if(typeof r=="string")return r;Nl();const e=Buffer.from(r).toString("base64");return Jn+e}function L1(r){return typeof r!="string"||!r.startsWith(Jn)?r:(Nl(),Buffer.from(r.slice(Jn.length),"base64"))}function Ue(r){return r?r.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function k1(...r){return Ue(r.join(":"))}function Yi(r){return r=Ue(r),r?r+":":""}const M1="memory",z1=()=>{const r=new Map;return{name:M1,getInstance:()=>r,hasItem(e){return r.has(e)},getItem(e){return r.get(e)??null},getItemRaw(e){return r.get(e)??null},setItem(e,t){r.set(e,t)},setItemRaw(e,t){r.set(e,t)},removeItem(e){r.delete(e)},getKeys(){return[...r.keys()]},clear(){r.clear()},dispose(){r.clear()}}};function H1(r={}){const e={mounts:{"":r.driver||z1()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},t=u=>{for(const h of e.mountpoints)if(u.startsWith(h))return{base:h,relativeKey:u.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:u,driver:e.mounts[""]}},i=(u,h)=>e.mountpoints.filter(l=>l.startsWith(u)||h&&u.startsWith(l)).map(l=>({relativeBase:u.length>l.length?u.slice(l.length):void 0,mountpoint:l,driver:e.mounts[l]})),s=(u,h)=>{if(e.watching){h=Ue(h);for(const l of e.watchListeners)l(u,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await jc(e.mounts[u],s,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,h,l)=>{const d=new Map,f=p=>{let y=d.get(p.base);return y||(y={driver:p.driver,base:p.base,items:[]},d.set(p.base,y)),y};for(const p of u){const y=typeof p=="string",m=Ue(y?p:p.key),_=y?void 0:p.value,b=y||!p.options?h:{...h,...p.options},I=t(m);f(I).items.push({key:m,value:_,relativeKey:I.relativeKey,options:b})}return Promise.all([...d.values()].map(p=>l(p))).then(p=>p.flat())},c={hasItem(u,h={}){u=Ue(u);const{relativeKey:l,driver:d}=t(u);return ye(d.hasItem,l,h)},getItem(u,h={}){u=Ue(u);const{relativeKey:l,driver:d}=t(u);return ye(d.getItem,l,h).then(f=>Gi(f))},getItems(u,h){return a(u,h,l=>l.driver.getItems?ye(l.driver.getItems,l.items.map(d=>({key:d.relativeKey,options:d.options})),h).then(d=>d.map(f=>({key:k1(l.base,f.key),value:Gi(f.value)}))):Promise.all(l.items.map(d=>ye(l.driver.getItem,d.relativeKey,d.options).then(f=>({key:d.key,value:Gi(f)})))))},getItemRaw(u,h={}){u=Ue(u);const{relativeKey:l,driver:d}=t(u);return d.getItemRaw?ye(d.getItemRaw,l,h):ye(d.getItem,l,h).then(f=>L1(f))},async setItem(u,h,l={}){if(h===void 0)return c.removeItem(u);u=Ue(u);const{relativeKey:d,driver:f}=t(u);f.setItem&&(await ye(f.setItem,d,ns(h),l),f.watch||s("update",u))},async setItems(u,h){await a(u,h,async l=>{if(l.driver.setItems)return ye(l.driver.setItems,l.items.map(d=>({key:d.relativeKey,value:ns(d.value),options:d.options})),h);l.driver.setItem&&await Promise.all(l.items.map(d=>ye(l.driver.setItem,d.relativeKey,ns(d.value),d.options)))})},async setItemRaw(u,h,l={}){if(h===void 0)return c.removeItem(u,l);u=Ue(u);const{relativeKey:d,driver:f}=t(u);if(f.setItemRaw)await ye(f.setItemRaw,d,h,l);else if(f.setItem)await ye(f.setItem,d,q1(h),l);else return;f.watch||s("update",u)},async removeItem(u,h={}){typeof h=="boolean"&&(h={removeMeta:h}),u=Ue(u);const{relativeKey:l,driver:d}=t(u);d.removeItem&&(await ye(d.removeItem,l,h),(h.removeMeta||h.removeMata)&&await ye(d.removeItem,l+"$",h),d.watch||s("remove",u))},async getMeta(u,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),u=Ue(u);const{relativeKey:l,driver:d}=t(u),f=Object.create(null);if(d.getMeta&&Object.assign(f,await ye(d.getMeta,l,h)),!h.nativeOnly){const p=await ye(d.getItem,l+"$",h).then(y=>Gi(y));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(f,p))}return f},setMeta(u,h,l={}){return this.setItem(u+"$",h,l)},removeMeta(u,h={}){return this.removeItem(u+"$",h)},async getKeys(u,h={}){u=Yi(u);const l=i(u,!0);let d=[];const f=[];for(const p of l){const y=await ye(p.driver.getKeys,p.relativeBase,h);for(const m of y){const _=p.mountpoint+Ue(m);d.some(b=>_.startsWith(b))||f.push(_)}d=[p.mountpoint,...d.filter(m=>!m.startsWith(p.mountpoint))]}return u?f.filter(p=>p.startsWith(u)&&p[p.length-1]!=="$"):f.filter(p=>p[p.length-1]!=="$")},async clear(u,h={}){u=Yi(u),await Promise.all(i(u,!1).map(async l=>{if(l.driver.clear)return ye(l.driver.clear,l.relativeBase,h);if(l.driver.removeItem){const d=await l.driver.getKeys(l.relativeBase||"",h);return Promise.all(d.map(f=>l.driver.removeItem(f,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Bc(u)))},async watch(u){return await n(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,h){if(u=Yi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((l,d)=>d.length-l.length)),e.mounts[u]=h,e.watching&&Promise.resolve(jc(h,s,u)).then(l=>{e.unwatch[u]=l}).catch(console.error),c},async unmount(u,h=!0){u=Yi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),h&&await Bc(e.mounts[u]),e.mountpoints=e.mountpoints.filter(l=>l!==u),delete e.mounts[u])},getMount(u=""){u=Ue(u)+":";const h=t(u);return{driver:h.driver,base:h.base}},getMounts(u="",h={}){return u=Ue(u),i(u,h.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(u,h={})=>c.getKeys(u,h),get:(u,h={})=>c.getItem(u,h),set:(u,h,l={})=>c.setItem(u,h,l),has:(u,h={})=>c.hasItem(u,h),del:(u,h={})=>c.removeItem(u,h),remove:(u,h={})=>c.removeItem(u,h)};return c}function jc(r,e,t){return r.watch?r.watch((i,s)=>e(i,t+s)):()=>{}}async function Bc(r){typeof r.dispose=="function"&&await ye(r.dispose)}function ur(r){return new Promise((e,t)=>{r.oncomplete=r.onsuccess=()=>e(r.result),r.onabort=r.onerror=()=>t(r.error)})}function jl(r,e){const t=indexedDB.open(r);t.onupgradeneeded=()=>t.result.createObjectStore(e);const i=ur(t);return(s,n)=>i.then(o=>n(o.transaction(e,s).objectStore(e)))}let hn;function Bi(){return hn||(hn=jl("keyval-store","keyval")),hn}function Uc(r,e=Bi()){return e("readonly",t=>ur(t.get(r)))}function V1(r,e,t=Bi()){return t("readwrite",i=>(i.put(e,r),ur(i.transaction)))}function K1(r,e=Bi()){return e("readwrite",t=>(t.delete(r),ur(t.transaction)))}function W1(r=Bi()){return r("readwrite",e=>(e.clear(),ur(e.transaction)))}function G1(r,e){return r.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},ur(r.transaction)}function Y1(r=Bi()){return r("readonly",e=>{if(e.getAllKeys)return ur(e.getAllKeys());const t=[];return G1(e,i=>t.push(i.key)).then(()=>t)})}const J1="idb-keyval";var Z1=(r={})=>{const e=r.base&&r.base.length>0?`${r.base}:`:"",t=s=>e+s;let i;return r.dbName&&r.storeName&&(i=jl(r.dbName,r.storeName)),{name:J1,options:r,async hasItem(s){return!(typeof await Uc(t(s),i)>"u")},async getItem(s){return await Uc(t(s),i)??null},setItem(s,n){return V1(t(s),n,i)},removeItem(s){return K1(t(s),i)},getKeys(){return Y1(i)},clear(){return W1(i)}}};const Q1="WALLET_CONNECT_V2_INDEXED_DB",X1="keyvaluestorage";let e0=class{constructor(){this.indexedDb=H1({driver:Z1({dbName:Q1,storeName:X1})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const t=await this.indexedDb.getItem(e);if(t!==null)return t}async setItem(e,t){await this.indexedDb.setItem(e,Rt(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ln=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},os={exports:{}};(function(){let r;function e(){}r=e,r.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},r.prototype.setItem=function(t,i){this[t]=String(i)},r.prototype.removeItem=function(t){delete this[t]},r.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(i){t[i]=void 0,delete t[i]})},r.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},r.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ln<"u"&&ln.localStorage?os.exports=ln.localStorage:typeof window<"u"&&window.localStorage?os.exports=window.localStorage:os.exports=new e})();function t0(r){var e;return[r[0],sr((e=r[1])!=null?e:"")]}let r0=class{constructor(){this.localStorage=os.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(t0)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return sr(t)}async setItem(e,t){this.localStorage.setItem(e,Rt(t))}async removeItem(e){this.localStorage.removeItem(e)}};const i0="wc_storage_version",Fc=1,s0=async(r,e,t)=>{const i=i0,s=await e.getItem(i);if(s&&s>=Fc){t(e);return}const n=await r.getKeys();if(!n.length){t(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 u=await r.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(i,Fc),t(e),n0(r,o)},n0=async(r,e)=>{e.length&&e.forEach(async t=>{await r.removeItem(t)})};let o0=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new r0;this.storage=e;try{const t=new e0;s0(e,t,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const t=setInterval(()=>{this.initialized&&(clearInterval(t),e())},20)})}};var dn,qc;function a0(){if(qc)return dn;qc=1;function r(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}dn=e;function e(t,i,s){var n=s&&s.stringify||r,o=1;if(typeof t=="object"&&t!==null){var a=i.length+o;if(a===1)return t;var c=new Array(a);c[0]=n(t);for(var u=1;u<a;u++)c[u]=n(i[u]);return c.join(" ")}if(typeof t!="string")return t;var h=i.length;if(h===0)return t;for(var l="",d=1-o,f=-1,p=t&&t.length||0,y=0;y<p;){if(t.charCodeAt(y)===37&&y+1<p){switch(f=f>-1?f:0,t.charCodeAt(y+1)){case 100:case 102:if(d>=h||i[d]==null)break;f<y&&(l+=t.slice(f,y)),l+=Number(i[d]),f=y+2,y++;break;case 105:if(d>=h||i[d]==null)break;f<y&&(l+=t.slice(f,y)),l+=Math.floor(Number(i[d])),f=y+2,y++;break;case 79:case 111:case 106:if(d>=h||i[d]===void 0)break;f<y&&(l+=t.slice(f,y));var m=typeof i[d];if(m==="string"){l+="'"+i[d]+"'",f=y+2,y++;break}if(m==="function"){l+=i[d].name||"<anonymous>",f=y+2,y++;break}l+=n(i[d]),f=y+2,y++;break;case 115:if(d>=h)break;f<y&&(l+=t.slice(f,y)),l+=String(i[d]),f=y+2,y++;break;case 37:f<y&&(l+=t.slice(f,y)),l+="%",f=y+2,y++,d--;break}++d}++y}return f===-1?t:(f<p&&(l+=t.slice(f)),l)}return dn}var pn,Lc;function c0(){if(Lc)return pn;Lc=1;const r=a0();pn=s;const e=C().console||{},t={mapHttpRequest:p,mapHttpResponse:p,wrapRequestSerializer:y,wrapResponseSerializer:y,wrapErrorSerializer:y,req:p,res:p,err:d};function i(E,$){return Array.isArray(E)?E.filter(function(P){return P!=="!stdSerializers.err"}):E===!0?Object.keys($):!1}function s(E){E=E||{},E.browser=E.browser||{};const $=E.browser.transmit;if($&&typeof $.send!="function")throw Error("pino: transmit option must have a send function");const S=E.browser.write||e;E.browser.write&&(E.browser.asObject=!0);const P=E.serializers||{},j=i(E.browser.serialize,P);let T=E.browser.serialize;Array.isArray(E.browser.serialize)&&E.browser.serialize.indexOf("!stdSerializers.err")>-1&&(T=!1);const B=["error","fatal","warn","info","debug","trace"];typeof S=="function"&&(S.error=S.fatal=S.warn=S.info=S.debug=S.trace=S),E.enabled===!1&&(E.level="silent");const k=E.level||"info",g=Object.create(S);g.log||(g.log=m),Object.defineProperty(g,"levelVal",{get:v}),Object.defineProperty(g,"level",{get:O,set:x});const w={transmit:$,serialize:j,asObject:E.browser.asObject,levels:B,timestamp:f(E)};g.levels=s.levels,g.level=k,g.setMaxListeners=g.getMaxListeners=g.emit=g.addListener=g.on=g.prependListener=g.once=g.prependOnceListener=g.removeListener=g.removeAllListeners=g.listeners=g.listenerCount=g.eventNames=g.write=g.flush=m,g.serializers=P,g._serialize=j,g._stdErrSerialize=T,g.child=D,$&&(g._logEvent=l());function v(){return this.level==="silent"?1/0:this.levels.values[this.level]}function O(){return this._level}function x(R){if(R!=="silent"&&!this.levels.values[R])throw Error("unknown level "+R);this._level=R,n(w,g,"error","log"),n(w,g,"fatal","error"),n(w,g,"warn","error"),n(w,g,"info","log"),n(w,g,"debug","log"),n(w,g,"trace","log")}function D(R,q){if(!R)throw new Error("missing bindings for child Pino");q=q||{},j&&R.serializers&&(q.serializers=R.serializers);const L=q.serializers;if(j&&L){var M=Object.assign({},P,L),z=E.browser.serialize===!0?Object.keys(M):j;delete R.serializers,c([R],z,M,this._stdErrSerialize)}function V(H){this._childLevel=(H._childLevel|0)+1,this.error=u(H,R,"error"),this.fatal=u(H,R,"fatal"),this.warn=u(H,R,"warn"),this.info=u(H,R,"info"),this.debug=u(H,R,"debug"),this.trace=u(H,R,"trace"),M&&(this.serializers=M,this._serialize=z),$&&(this._logEvent=l([].concat(H._logEvent.bindings,R)))}return V.prototype=this,new V(this)}return g}s.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"}},s.stdSerializers=t,s.stdTimeFunctions=Object.assign({},{nullTime:_,epochTime:b,unixTime:I,isoTime:A});function n(E,$,S,P){const j=Object.getPrototypeOf($);$[S]=$.levelVal>$.levels.values[S]?m:j[S]?j[S]:e[S]||e[P]||m,o(E,$,S)}function o(E,$,S){!E.transmit&&$[S]===m||($[S]=function(P){return function(){const T=E.timestamp(),B=new Array(arguments.length),k=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var g=0;g<B.length;g++)B[g]=arguments[g];if(E.serialize&&!E.asObject&&c(B,this._serialize,this.serializers,this._stdErrSerialize),E.asObject?P.call(k,a(this,S,B,T)):P.apply(k,B),E.transmit){const w=E.transmit.level||$.level,v=s.levels.values[w],O=s.levels.values[S];if(O<v)return;h(this,{ts:T,methodLevel:S,methodValue:O,transmitLevel:w,transmitValue:s.levels.values[E.transmit.level||$.level],send:E.transmit.send,val:$.levelVal},B)}}}($[S]))}function a(E,$,S,P){E._serialize&&c(S,E._serialize,E.serializers,E._stdErrSerialize);const j=S.slice();let T=j[0];const B={};P&&(B.time=P),B.level=s.levels.values[$];let k=(E._childLevel|0)+1;if(k<1&&(k=1),T!==null&&typeof T=="object"){for(;k--&&typeof j[0]=="object";)Object.assign(B,j.shift());T=j.length?r(j.shift(),j):void 0}else typeof T=="string"&&(T=r(j.shift(),j));return T!==void 0&&(B.msg=T),B}function c(E,$,S,P){for(const j in E)if(P&&E[j]instanceof Error)E[j]=s.stdSerializers.err(E[j]);else if(typeof E[j]=="object"&&!Array.isArray(E[j]))for(const T in E[j])$&&$.indexOf(T)>-1&&T in S&&(E[j][T]=S[T](E[j][T]))}function u(E,$,S){return function(){const P=new Array(1+arguments.length);P[0]=$;for(var j=1;j<P.length;j++)P[j]=arguments[j-1];return E[S].apply(this,P)}}function h(E,$,S){const P=$.send,j=$.ts,T=$.methodLevel,B=$.methodValue,k=$.val,g=E._logEvent.bindings;c(S,E._serialize||Object.keys(E.serializers),E.serializers,E._stdErrSerialize===void 0?!0:E._stdErrSerialize),E._logEvent.ts=j,E._logEvent.messages=S.filter(function(w){return g.indexOf(w)===-1}),E._logEvent.level.label=T,E._logEvent.level.value=B,P(T,E._logEvent,k),E._logEvent=l(g)}function l(E){return{ts:0,messages:[],bindings:E||[],level:{label:"",value:0}}}function d(E){const $={type:E.constructor.name,msg:E.message,stack:E.stack};for(const S in E)$[S]===void 0&&($[S]=E[S]);return $}function f(E){return typeof E.timestamp=="function"?E.timestamp:E.timestamp===!1?_:b}function p(){return{}}function y(E){return E}function m(){}function _(){return!1}function b(){return Date.now()}function I(){return Math.round(Date.now()/1e3)}function A(){return new Date(Date.now()).toISOString()}function C(){function E($){return typeof $<"u"&&$}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return E(self)||E(window)||E(this)||{}}}return pn}var Cr=c0();const Ui=wo(Cr),u0={level:"info"},Fi="custom_context",Fo=1e3*1024;let h0=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},kc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new h0(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let t=this.head;for(;t!==null;)e.push(t.value),t=t.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const t=e.value;return e=e.next,{done:!1,value:t}}}}},Bl=class{constructor(e,t=Fo){this.level=e??"error",this.levelValue=Cr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new kc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Cr.levels.values.error?console.error(e):t===Cr.levels.values.warn?console.warn(e):t===Cr.levels.values.debug?console.debug(e):t===Cr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Rt({timestamp:new Date().toISOString(),log:e}));const t=typeof e=="string"?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new kc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(Rt({extraMetadata:e})),new Blob(t,{type:"application/json"})}},l0=class{constructor(e,t=Fo){this.baseChunkLogger=new Bl(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}},d0=class{constructor(e,t=Fo){this.baseChunkLogger=new Bl(e,t)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var p0=Object.defineProperty,f0=Object.defineProperties,g0=Object.getOwnPropertyDescriptors,Mc=Object.getOwnPropertySymbols,y0=Object.prototype.hasOwnProperty,m0=Object.prototype.propertyIsEnumerable,zc=(r,e,t)=>e in r?p0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gs=(r,e)=>{for(var t in e||(e={}))y0.call(e,t)&&zc(r,t,e[t]);if(Mc)for(var t of Mc(e))m0.call(e,t)&&zc(r,t,e[t]);return r},ys=(r,e)=>f0(r,g0(e));function As(r){return ys(gs({},r),{level:(r==null?void 0:r.level)||u0.level})}function w0(r,e=Fi){return r[e]||""}function b0(r,e,t=Fi){return r[t]=e,r}function ke(r,e=Fi){let t="";return typeof r.bindings>"u"?t=w0(r,e):t=r.bindings().context||"",t}function v0(r,e,t=Fi){const i=ke(r,t);return i.trim()?`${i}/${e}`:e}function Ne(r,e,t=Fi){const i=v0(r,e,t),s=r.child({context:i});return b0(s,i,t)}function E0(r){var e,t;const i=new l0((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Ui(ys(gs({},r.opts),{level:"trace",browser:ys(gs({},(t=r.opts)==null?void 0:t.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function _0(r){var e;const t=new d0((e=r.opts)==null?void 0:e.level,r.maxSizeInBytes);return{logger:Ui(ys(gs({},r.opts),{level:"trace"}),t),chunkLoggerController:t}}function I0(r){return typeof r.loggerOverride<"u"&&typeof r.loggerOverride!="string"?{logger:r.loggerOverride,chunkLoggerController:null}:typeof window<"u"?E0(r):_0(r)}var $0=Object.defineProperty,S0=(r,e,t)=>e in r?$0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Hc=(r,e,t)=>S0(r,typeof e!="symbol"?e+"":e,t);let D0=class extends cr{constructor(e){super(),this.opts=e,Hc(this,"protocol","wc"),Hc(this,"version",2)}};var P0=Object.defineProperty,O0=(r,e,t)=>e in r?P0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,A0=(r,e,t)=>O0(r,e+"",t);let x0=class extends cr{constructor(e,t){super(),this.core=e,this.logger=t,A0(this,"records",new Map)}},C0=class{constructor(e,t){this.logger=e,this.core=t}},T0=class extends cr{constructor(e,t){super(),this.relayer=e,this.logger=t}},R0=class extends cr{constructor(e){super()}},N0=class{constructor(e,t,i,s){this.core=e,this.logger=t,this.name=i}},j0=class extends cr{constructor(e,t){super(),this.relayer=e,this.logger=t}},B0=class extends cr{constructor(e,t){super(),this.core=e,this.logger=t}},U0=class{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}},F0=class{constructor(e,t){this.projectId=e,this.logger=t}},q0=class{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}};var L0=Object.defineProperty,k0=(r,e,t)=>e in r?L0(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Vc=(r,e,t)=>k0(r,typeof e!="symbol"?e+"":e,t);let M0=class{constructor(e){this.opts=e,Vc(this,"protocol","wc"),Vc(this,"version",2)}},z0=class{constructor(e){this.client=e}};const H0="PARSE_ERROR",V0="INVALID_REQUEST",K0="METHOD_NOT_FOUND",W0="INVALID_PARAMS",Ul="INTERNAL_ERROR",qo="SERVER_ERROR",G0=[-32700,-32600,-32601,-32602,-32603],gi={[H0]:{code:-32700,message:"Parse error"},[V0]:{code:-32600,message:"Invalid Request"},[K0]:{code:-32601,message:"Method not found"},[W0]:{code:-32602,message:"Invalid params"},[Ul]:{code:-32603,message:"Internal error"},[qo]:{code:-32e3,message:"Server error"}},Fl=qo;function Y0(r){return G0.includes(r)}function Kc(r){return Object.keys(gi).includes(r)?gi[r]:gi[Fl]}function J0(r){const e=Object.values(gi).find(t=>t.code===r);return e||gi[Fl]}function ql(r,e,t){return r.message.includes("getaddrinfo ENOTFOUND")||r.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):r}var fn={};/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var Zn=function(r,e){return Zn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])},Zn(r,e)};function Z0(r,e){Zn(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Qn=function(){return Qn=Object.assign||function(e){for(var t,i=1,s=arguments.length;i<s;i++){t=arguments[i];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},Qn.apply(this,arguments)};function Q0(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(r);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(r,i[s])&&(t[i[s]]=r[i[s]]);return t}function X0(r,e,t,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(r,e,t,i);else for(var a=r.length-1;a>=0;a--)(o=r[a])&&(n=(s<3?o(n):s>3?o(e,t,n):o(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}function eE(r,e){return function(t,i){e(t,i,r)}}function tE(r,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,e)}function rE(r,e,t,i){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(h){try{u(i.next(h))}catch(l){o(l)}}function c(h){try{u(i.throw(h))}catch(l){o(l)}}function u(h){h.done?n(h.value):s(h.value).then(a,c)}u((i=i.apply(r,e||[])).next())})}function iE(r,e){var t={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(u){return function(h){return c([u,h])}}function c(u){if(i)throw new TypeError("Generator is already executing.");for(;t;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return t.label++,{value:u[1],done:!1};case 5:t.label++,s=u[1],u=[0];continue;case 7:u=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){t.label=u[1];break}if(u[0]===6&&t.label<n[1]){t.label=n[1],n=u;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(u);break}n[2]&&t.ops.pop(),t.trys.pop();continue}u=e.call(r,t)}catch(h){u=[6,h],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function sE(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]}function nE(r,e){for(var t in r)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=r[t])}function Xn(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],i=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ll(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i=t.call(r),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&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return n}function oE(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Ll(arguments[e]));return r}function aE(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var i=Array(r),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Di(r){return this instanceof Di?(this.v=r,this):new Di(r)}function cE(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(r,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(f){return new Promise(function(p,y){n.push([d,f,p,y])>1||a(d,f)})})}function a(d,f){try{c(i[d](f))}catch(p){l(n[0][3],p)}}function c(d){d.value instanceof Di?Promise.resolve(d.value.v).then(u,h):l(n[0][2],d)}function u(d){a("next",d)}function h(d){a("throw",d)}function l(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function uE(r){var e,t;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]=r[s]?function(o){return(t=!t)?{value:Di(r[s](o)),done:s==="return"}:n?n(o):o}:n}}function hE(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof Xn=="function"?Xn(r):r[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=r[n]&&function(o){return new Promise(function(a,c){o=r[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function lE(r,e){return Object.defineProperty?Object.defineProperty(r,"raw",{value:e}):r.raw=e,r}function dE(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)Object.hasOwnProperty.call(r,t)&&(e[t]=r[t]);return e.default=r,e}function pE(r){return r&&r.__esModule?r:{default:r}}function fE(r,e){if(!e.has(r))throw new TypeError("attempted to get private field on non-instance");return e.get(r)}function gE(r,e,t){if(!e.has(r))throw new TypeError("attempted to set private field on non-instance");return e.set(r,t),t}const yE=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Qn},__asyncDelegator:uE,__asyncGenerator:cE,__asyncValues:hE,__await:Di,__awaiter:rE,__classPrivateFieldGet:fE,__classPrivateFieldSet:gE,__createBinding:sE,__decorate:X0,__exportStar:nE,__extends:Z0,__generator:iE,__importDefault:pE,__importStar:dE,__makeTemplateObject:lE,__metadata:tE,__param:eE,__read:Ll,__rest:Q0,__spread:oE,__spreadArrays:aE,__values:Xn},Symbol.toStringTag,{value:"Module"})),mE=Ju(yE);var Dt={},Wc;function wE(){if(Wc)return Dt;Wc=1,Object.defineProperty(Dt,"__esModule",{value:!0}),Dt.isBrowserCryptoAvailable=Dt.getSubtleCrypto=Dt.getBrowerCrypto=void 0;function r(){return(pr===null||pr===void 0?void 0:pr.crypto)||(pr===null||pr===void 0?void 0:pr.msCrypto)||{}}Dt.getBrowerCrypto=r;function e(){const i=r();return i.subtle||i.webkitSubtle}Dt.getSubtleCrypto=e;function t(){return!!r()&&!!e()}return Dt.isBrowserCryptoAvailable=t,Dt}var Pt={},Gc;function bE(){if(Gc)return Pt;Gc=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.isBrowser=Pt.isNode=Pt.isReactNative=void 0;function r(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Pt.isReactNative=r;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Pt.isNode=e;function t(){return!r()&&!e()}return Pt.isBrowser=t,Pt}var Yc;function vE(){return Yc||(Yc=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});const e=mE;e.__exportStar(wE(),r),e.__exportStar(bE(),r)}(fn)),fn}var EE=vE();function wt(r=3){const e=Date.now()*Math.pow(10,r),t=Math.floor(Math.random()*Math.pow(10,r));return e+t}function er(r=6){return BigInt(wt(r))}function kt(r,e,t){return{id:t||wt(),jsonrpc:"2.0",method:r,params:e}}function xs(r,e){return{id:r,jsonrpc:"2.0",result:e}}function Cs(r,e,t){return{id:r,jsonrpc:"2.0",error:_E(e)}}function _E(r,e){return typeof r>"u"?Kc(Ul):(typeof r=="string"&&(r=Object.assign(Object.assign({},Kc(qo)),{message:r})),Y0(r.code)&&(r=J0(r.code)),r)}class IE{}class $E extends IE{constructor(){super()}}class SE extends $E{constructor(e){super()}}const DE="^https?:",PE="^wss?:";function OE(r){const e=r.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function kl(r,e){const t=OE(r);return typeof t>"u"?!1:new RegExp(e).test(t)}function Jc(r){return kl(r,DE)}function Zc(r){return kl(r,PE)}function AE(r){return new RegExp("wss?://localhost(:d{2,5})?").test(r)}function Ml(r){return typeof r=="object"&&"id"in r&&"jsonrpc"in r&&r.jsonrpc==="2.0"}function Lo(r){return Ml(r)&&"method"in r}function Ts(r){return Ml(r)&&(bt(r)||tt(r))}function bt(r){return"result"in r}function tt(r){return"error"in r}let it=class extends SE{constructor(e){super(e),this.events=new Ye.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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(kt(e.method,e.params||[],e.id||er().toString()),t)}async requestStrict(e,t){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{tt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,t)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ts(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 xE=()=>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"),CE=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Qc=r=>r.split("?")[0],Xc=10,TE=xE();let RE=class{constructor(e){if(this.url=e,this.events=new Ye.EventEmitter,this.registering=!1,!Zc(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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,t)=>{if(typeof this.socket>"u"){t(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(Rt(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Zc(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+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((t,i)=>{const s=EE.isReactNative()?void 0:{rejectUnauthorized:!AE(e)},n=new TE(e,[],s);CE()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),t(n)}})}onOpen(e){e.onmessage=t=>this.onPayload(t),e.onclose=t=>this.onClose(t),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Cs(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return ql(e,Qc(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Xc&&this.events.setMaxListeners(Xc)}emitError(e){const t=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Qc(this.url)}`));return this.events.emit("register_error",t),t}};var NE={};const zl="wc",Hl=2,ms="core",Et=`${zl}@2:${ms}:`,jE={name:ms,logger:"error"},BE={database:":memory:"},UE="crypto",eu="client_ed25519_seed",FE=U.ONE_DAY,qE="keychain",LE="0.3",kE="messages",ME="0.3",tu=U.SIX_HOURS,zE="publisher",Vl="irn",HE="error",Kl="wss://relay.walletconnect.org",VE="relayer",we={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"},KE="_subscription",Qe={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},WE=.1,eo="2.19.2",ae={link_mode:"link_mode",relay:"relay"},as={inbound:"inbound",outbound:"outbound"},GE="0.3",YE="WALLETCONNECT_CLIENT_ID",ru="WALLETCONNECT_LINK_MODE_APPS",He={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},JE="subscription",ZE="0.3",QE="pairing",XE="0.3",ni={wc_pairingDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:U.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:U.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:U.ONE_DAY,prompt:!1,tag:0},res:{ttl:U.ONE_DAY,prompt:!1,tag:0}}},Zt={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},e_="history",t_="0.3",r_="expirer",et={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},i_="0.3",s_="verify-api",n_="https://verify.walletconnect.com",Wl="https://verify.walletconnect.org",yi=Wl,o_=`${yi}/v3`,a_=[n_,Wl],c_="echo",u_="https://echo.walletconnect.com",mt={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"},Ot={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"},at={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"},Kt={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"},Wt={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},oi={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},h_=.1,l_="event-client",d_=86400,p_="https://pulse.walletconnect.org/batch";function f_(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i<t.length;i++)t[i]=255;for(var s=0;s<r.length;s++){var n=r.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,m=0,_=0,b=p.length;_!==b&&p[_]===0;)_++,y++;for(var I=(b-_)*h+1>>>0,A=new Uint8Array(I);_!==b;){for(var C=p[_],E=0,$=I-1;(C!==0||E<m)&&$!==-1;$--,E++)C+=256*A[$]>>>0,A[$]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");m=E,_++}for(var S=I-m;S!==I&&A[S]===0;)S++;for(var P=c.repeat(y);S<I;++S)P+=r.charAt(A[S]);return P}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var m=0,_=0;p[y]===c;)m++,y++;for(var b=(p.length-y)*u+1>>>0,I=new Uint8Array(b);p[y];){var A=t[p.charCodeAt(y)];if(A===255)return;for(var C=0,E=b-1;(A!==0||C<_)&&E!==-1;E--,C++)A+=a*I[E]>>>0,I[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");_=C,y++}if(p[y]!==" "){for(var $=b-_;$!==b&&I[$]===0;)$++;for(var S=new Uint8Array(m+(b-$)),P=m;$!==b;)S[P++]=I[$++];return S}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var g_=f_,y_=g_;const Gl=r=>{if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")},m_=r=>new TextEncoder().encode(r),w_=r=>new TextDecoder().decode(r);class b_{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class v_{constructor(e,t,i){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.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 Yl(this,e)}}class E_{constructor(e){this.decoders=e}or(e){return Yl(this,e)}decode(e){const t=e[0],i=this.decoders[t];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yl=(r,e)=>new E_({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}});class __{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new b_(e,t,i),this.decoder=new v_(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Rs=({name:r,prefix:e,encode:t,decode:i})=>new __(r,e,t,i),qi=({prefix:r,name:e,alphabet:t})=>{const{encode:i,decode:s}=y_(t,e);return Rs({prefix:r,name:e,encode:i,decode:n=>Gl(s(n))})},I_=(r,e,t,i)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=r.length;for(;r[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[r[h]];if(l===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},$_=(r,e,t)=>{const i=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),i)for(;n.length*t&7;)n+="=";return n},Oe=({name:r,prefix:e,bitsPerChar:t,alphabet:i})=>Rs({prefix:e,name:r,encode(s){return $_(s,i,t)},decode(s){return I_(s,i,t,r)}}),S_=Rs({prefix:"\0",name:"identity",encode:r=>w_(r),decode:r=>m_(r)});var D_=Object.freeze({__proto__:null,identity:S_});const P_=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var O_=Object.freeze({__proto__:null,base2:P_});const A_=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var x_=Object.freeze({__proto__:null,base8:A_});const C_=qi({prefix:"9",name:"base10",alphabet:"0123456789"});var T_=Object.freeze({__proto__:null,base10:C_});const R_=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),N_=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var j_=Object.freeze({__proto__:null,base16:R_,base16upper:N_});const B_=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),U_=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F_=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),q_=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),L_=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),k_=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),M_=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),z_=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),H_=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var V_=Object.freeze({__proto__:null,base32:B_,base32upper:U_,base32pad:F_,base32padupper:q_,base32hex:L_,base32hexupper:k_,base32hexpad:M_,base32hexpadupper:z_,base32z:H_});const K_=qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),W_=qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var G_=Object.freeze({__proto__:null,base36:K_,base36upper:W_});const Y_=qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),J_=qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Z_=Object.freeze({__proto__:null,base58btc:Y_,base58flickr:J_});const Q_=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),X_=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),eI=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tI=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var rI=Object.freeze({__proto__:null,base64:Q_,base64pad:X_,base64url:eI,base64urlpad:tI});const Jl=Array.from("🚀🊐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀ðŸ’ŧðŸ–ĨðŸ’ūðŸ’ŋ😂âĪ😍ðŸĪĢ😊🙏💕😭😘👍😅👏😁ðŸ”ĨðŸĨ°ðŸ’”💖💙ðŸ˜ĒðŸĪ”😆🙄💊😉☚👌ðŸĪ—💜😔😎😇ðŸŒđðŸĪĶ🎉💞✌âœĻðŸĪ·ðŸ˜ąðŸ˜ŒðŸŒļ🙌😋💗💚😏💛🙂💓ðŸĪĐ😄😀ðŸ–Ī😃ðŸ’Ŋ🙈👇ðŸŽķ😒ðŸĪ­âĢ😜💋👀😊😑ðŸ’Ĩ🙋😞ðŸ˜ĐðŸ˜ĄðŸĪŠðŸ‘ŠðŸĨģðŸ˜ĨðŸĪĪ👉💃ðŸ˜ģ✋😚😝ðŸ˜ī🌟😎🙃🍀🌷ðŸ˜ŧ😓⭐✅ðŸĨšðŸŒˆðŸ˜ˆðŸĪ˜ðŸ’Ķ✔ðŸ˜Ģ🏃💐â˜đ🎊💘😠☝😕🌚🎂ðŸŒŧ😐🖕💝🙊ðŸ˜đðŸ—ĢðŸ’Ŧ💀👑ðŸŽĩðŸĪžðŸ˜›ðŸ”īðŸ˜Ī🌞ðŸ˜Ŧâš―ðŸĪ™â˜•🏆ðŸĪŦ👈ðŸ˜Ū🙆ðŸŧ🍃ðŸķ💁ðŸ˜ēðŸŒŋðŸ§ĄðŸŽâšĄðŸŒžðŸŽˆâŒâœŠðŸ‘‹ðŸ˜°ðŸĪĻðŸ˜ķðŸĪðŸšķ💰🍓ðŸ’ĒðŸĪŸðŸ™ðŸšĻðŸ’ĻðŸĪŽâœˆðŸŽ€ðŸšðŸĪ“ðŸ˜™ðŸ’ŸðŸŒąðŸ˜–ðŸ‘ķðŸĨīâ–ķâžĄâ“ðŸ’ŽðŸ’ļ⮇ðŸ˜Ļ🌚ðŸĶ‹ðŸ˜·ðŸ•šâš ðŸ™…😟ðŸ˜ĩ👎ðŸĪēðŸĪ ðŸĪ§ðŸ“ŒðŸ”ĩ💅🧐ðŸū🍒😗ðŸĪ‘🌊ðŸĪŊ🐷☎💧ðŸ˜Ŋ💆👆ðŸŽĪ🙇🍑❄ðŸŒīðŸ’ĢðŸļ💌📍ðŸĨ€ðŸĪĒðŸ‘…ðŸ’ĄðŸ’Đ👐ðŸ“ļðŸ‘ŧðŸĪðŸĪŪ🎞ðŸĨĩðŸšĐ🍎🍊👞💍ðŸ“ĢðŸĨ‚"),iI=Jl.reduce((r,e,t)=>(r[t]=e,r),[]),sI=Jl.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function nI(r){return r.reduce((e,t)=>(e+=iI[t],e),"")}function oI(r){const e=[];for(const t of r){const i=sI[t.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}const aI=Rs({prefix:"🚀",name:"base256emoji",encode:nI,decode:oI});var cI=Object.freeze({__proto__:null,base256emoji:aI}),uI=Zl,iu=128,hI=-128,lI=Math.pow(2,31);function Zl(r,e,t){e=e||[],t=t||0;for(var i=t;r>=lI;)e[t++]=r&255|iu,r/=128;for(;r&hI;)e[t++]=r&255|iu,r>>>=7;return e[t]=r|0,Zl.bytes=t-i+1,e}var dI=to,pI=128,su=127;function to(r,i){var t=0,i=i||0,s=0,n=i,o,a=r.length;do{if(n>=a)throw to.bytes=0,new RangeError("Could not decode varint");o=r[n++],t+=s<28?(o&su)<<s:(o&su)*Math.pow(2,s),s+=7}while(o>=pI);return to.bytes=n-i,t}var fI=Math.pow(2,7),gI=Math.pow(2,14),yI=Math.pow(2,21),mI=Math.pow(2,28),wI=Math.pow(2,35),bI=Math.pow(2,42),vI=Math.pow(2,49),EI=Math.pow(2,56),_I=Math.pow(2,63),II=function(r){return r<fI?1:r<gI?2:r<yI?3:r<mI?4:r<wI?5:r<bI?6:r<vI?7:r<EI?8:r<_I?9:10},$I={encode:uI,decode:dI,encodingLength:II},Ql=$I;const nu=(r,e,t=0)=>(Ql.encode(r,e,t),e),ou=r=>Ql.encodingLength(r),ro=(r,e)=>{const t=e.byteLength,i=ou(r),s=i+ou(t),n=new Uint8Array(s+t);return nu(r,n,0),nu(t,n,i),n.set(e,s),new SI(r,t,e,n)};class SI{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Xl=({name:r,code:e,encode:t})=>new DI(r,e,t);class DI{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ro(this.code,t):t.then(i=>ro(this.code,i))}else throw Error("Unknown type, must be binary type")}}const ed=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),PI=Xl({name:"sha2-256",code:18,encode:ed("SHA-256")}),OI=Xl({name:"sha2-512",code:19,encode:ed("SHA-512")});var AI=Object.freeze({__proto__:null,sha256:PI,sha512:OI});const td=0,xI="identity",rd=Gl,CI=r=>ro(td,rd(r)),TI={code:td,name:xI,encode:rd,digest:CI};var RI=Object.freeze({__proto__:null,identity:TI});new TextEncoder,new TextDecoder;const au={...D_,...O_,...x_,...T_,...j_,...V_,...G_,...Z_,...rI,...cI};({...AI,...RI});function NI(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(r):new Uint8Array(r)}function id(r,e,t,i){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:i}}}const cu=id("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),gn=id("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);const e=NI(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),jI={utf8:cu,"utf-8":cu,hex:au.base16,latin1:gn,ascii:gn,binary:gn,...au};function BI(r,e="utf8"){const t=jI[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r,"utf8"):t.decoder.decode(`${t.prefix}${r}`)}var UI=Object.defineProperty,FI=(r,e,t)=>e in r?UI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>FI(r,typeof e!="symbol"?e+"":e,t);class qI{constructor(e,t){this.core=e,this.logger=t,gt(this,"keychain",new Map),gt(this,"name",qE),gt(this,"version",LE),gt(this,"initialized",!1),gt(this,"storagePrefix",Et),gt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),gt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),gt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),gt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=F("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),gt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(t,this.name)}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Fn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?qn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var LI=Object.defineProperty,kI=(r,e,t)=>e in r?LI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ie=(r,e,t)=>kI(r,typeof e!="symbol"?e+"":e,t);class MI{constructor(e,t,i){this.core=e,this.logger=t,Ie(this,"name",UE),Ie(this,"keychain"),Ie(this,"randomSessionIdentifier",Yn()),Ie(this,"initialized",!1),Ie(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ie(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ie(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=ka(s);return kh(n.publicKey)}),Ie(this,"generateKeyPair",()=>{this.isInitialized();const s=jv();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ie(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=ka(n),a=this.randomSessionIdentifier;return await Qy(a,s,FE,o)}),Ie(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=Bv(a,n);return this.setSymKey(c,o)}),Ie(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||ss(s);return await this.keychain.set(o,s),o}),Ie(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"encode",async(s,n,o)=>{this.isInitialized();const a=xl(o),c=Rt(n);if(Sc(a))return qv(c,o==null?void 0:o.encoding);if($c(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;s=await this.generateSharedKey(d,f)}const u=this.getSymKey(s),{type:h,senderPublicKey:l}=a;return Uv({type:h,symKey:u,message:c,senderPublicKey:l,encoding:o==null?void 0:o.encoding})}),Ie(this,"decode",async(s,n,o)=>{this.isInitialized();const a=kv(n,o);if(Sc(a)){const c=Lv(n,o==null?void 0:o.encoding);return sr(c)}if($c(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;s=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(s),u=Fv({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return sr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ie(this,"getPayloadType",(s,n=ht)=>{const o=$i({encoded:s,encoding:n});return ar(o.type)}),Ie(this,"getPayloadSenderPublicKey",(s,n=ht)=>{const o=$i({encoded:s,encoding:n});return o.senderPublicKey?Le(o.senderPublicKey,Re):void 0}),this.core=e,this.logger=Ne(t,this.name),this.keychain=i||new qI(this.core,this.logger)}get context(){return ke(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(eu)}catch{e=Yn(),await this.keychain.set(eu,e)}return BI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zI=Object.defineProperty,HI=Object.defineProperties,VI=Object.getOwnPropertyDescriptors,uu=Object.getOwnPropertySymbols,KI=Object.prototype.hasOwnProperty,WI=Object.prototype.propertyIsEnumerable,io=(r,e,t)=>e in r?zI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,GI=(r,e)=>{for(var t in e)KI.call(e,t)&&io(r,t,e[t]);if(uu)for(var t of uu(e))WI.call(e,t)&&io(r,t,e[t]);return r},YI=(r,e)=>HI(r,VI(e)),Me=(r,e,t)=>io(r,typeof e!="symbol"?e+"":e,t);class JI extends C0{constructor(e,t){super(e,t),this.logger=e,this.core=t,Me(this,"messages",new Map),Me(this,"messagesWithoutClientAck",new Map),Me(this,"name",kE),Me(this,"version",ME),Me(this,"initialized",!1),Me(this,"storagePrefix",Et),Me(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}}}),Me(this,"set",async(i,s,n)=>{this.isInitialized();const o=vt(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===as.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,YI(GI({},c),{[o]:s}))}return await this.persist(),o}),Me(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),Me(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}),Me(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=vt(s);return typeof n[o]<"u"}),Me(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=vt(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),Me(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=t}get context(){return ke(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,Fn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Fn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?qn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?qn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZI=Object.defineProperty,QI=Object.defineProperties,XI=Object.getOwnPropertyDescriptors,hu=Object.getOwnPropertySymbols,e2=Object.prototype.hasOwnProperty,t2=Object.prototype.propertyIsEnumerable,so=(r,e,t)=>e in r?ZI(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ji=(r,e)=>{for(var t in e||(e={}))e2.call(e,t)&&so(r,t,e[t]);if(hu)for(var t of hu(e))t2.call(e,t)&&so(r,t,e[t]);return r},yn=(r,e)=>QI(r,XI(e)),ct=(r,e,t)=>so(r,typeof e!="symbol"?e+"":e,t);class r2 extends T0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ct(this,"events",new Ye.EventEmitter),ct(this,"name",zE),ct(this,"queue",new Map),ct(this,"publishTimeout",U.toMiliseconds(U.ONE_MINUTE)),ct(this,"initialPublishTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ct(this,"needsTransportRestart",!1),ct(this,"publish",async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||tu,c=ps(n),u=(n==null?void 0:n.prompt)||!1,h=(n==null?void 0:n.tag)||0,l=(n==null?void 0:n.id)||er().toString(),d={topic:i,message:s,opts:{ttl:a,relay:c,prompt:u,tag:h,id:l,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${l} tag:${h}`;try{const p=new Promise(async y=>{const m=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(we.publish,m),y(d))};this.relayer.events.on(we.publish,m);const _=Lt(new Promise((b,I)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:u,tag:h,id:l,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(A=>{this.logger.warn(A,A==null?void 0:A.message),I(A)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${l} tag:${h}`);try{await _,this.events.removeListener(we.publish,m)}catch(b){this.queue.set(l,yn(Ji({},d),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,topic:i,message:s,opts:n}}),await Lt(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(l)}}),ct(this,"on",(i,s)=>{this.events.on(i,s)}),ct(this,"once",(i,s)=>{this.events.once(i,s)}),ct(this,"off",(i,s)=>{this.events.off(i,s)}),ct(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=Ne(t,this.name),this.registerEventListeners()}get context(){return ke(this.logger)}async rpcPublish(e){var t,i,s,n;const{topic:o,message:a,ttl:c=tu,prompt:u,tag:h,id:l,attestation:d,tvf:f}=e,p={method:ui(ps().protocol).publish,params:Ji({topic:o,message:a,ttl:c,prompt:u,tag:h,attestation:d},f),id:l};Se((t=p.params)==null?void 0:t.prompt)&&((i=p.params)==null||delete i.prompt),Se((s=p.params)==null?void 0:s.tag)&&((n=p.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const y=await this.relayer.request(p);return this.relayer.events.emit(we.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const i=e.attempt+1;this.queue.set(t,yn(Ji({},e),{attempt:i}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(yn(Ji({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Jr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(we.connection_stalled);return}this.checkQueue()}),this.relayer.on(we.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var i2=Object.defineProperty,s2=(r,e,t)=>e in r?i2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wr=(r,e,t)=>s2(r,typeof e!="symbol"?e+"":e,t);class n2{constructor(){wr(this,"map",new Map),wr(this,"set",(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])}),wr(this,"get",e=>this.map.get(e)||[]),wr(this,"exists",(e,t)=>this.get(e).includes(t)),wr(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter(n=>n!==t);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),wr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var o2=Object.defineProperty,a2=Object.defineProperties,c2=Object.getOwnPropertyDescriptors,lu=Object.getOwnPropertySymbols,u2=Object.prototype.hasOwnProperty,h2=Object.prototype.propertyIsEnumerable,no=(r,e,t)=>e in r?o2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ai=(r,e)=>{for(var t in e||(e={}))u2.call(e,t)&&no(r,t,e[t]);if(lu)for(var t of lu(e))h2.call(e,t)&&no(r,t,e[t]);return r},mn=(r,e)=>a2(r,c2(e)),ie=(r,e,t)=>no(r,typeof e!="symbol"?e+"":e,t);class l2 extends j0{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ie(this,"subscriptions",new Map),ie(this,"topicMap",new n2),ie(this,"events",new Ye.EventEmitter),ie(this,"name",JE),ie(this,"version",ZE),ie(this,"pending",new Map),ie(this,"cached",[]),ie(this,"initialized",!1),ie(this,"storagePrefix",Et),ie(this,"subscribeTimeout",U.toMiliseconds(U.ONE_MINUTE)),ie(this,"initialSubscribeTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ie(this,"clientId"),ie(this,"batchSubscribeTopicsLimit",500),ie(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ie(this,"subscribe",async(i,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=ps(s),o={topic:i,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),ie(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ie(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ie(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ie(this,"on",(i,s)=>{this.events.on(i,s)}),ie(this,"once",(i,s)=>{this.events.once(i,s)}),ie(this,"off",(i,s)=>{this.events.off(i,s)}),ie(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ie(this,"start",async()=>{await this.onConnect()}),ie(this,"stop",async()=>{await this.onDisconnect()}),ie(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ie(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)}),ie(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Jr.pulse,async()=>{await this.checkPending()}),this.events.on(He.created,async i=>{const s=He.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(He.deleted,async i=>{const s=He.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(t,this.name),this.clientId=""}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,t){let i=!1;try{i=this.getSubscription(e).topic===t}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.cached=this.values,this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=ps(i);await this.restartToComplete({topic:e,id:t,relay:s}),await this.rpcUnsubscribe(e,t,s);const n=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t,i){var s;(!i||(i==null?void 0:i.transportType)===ae.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:ui(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===ae.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(h=>this.logger.warn(h))},U.toMiliseconds(U.ONE_SECOND)),a;const c=new Promise(async h=>{const l=d=>{d.topic===e&&(this.events.removeListener(He.created,l),h(d.id))};this.events.on(He.created,l);try{const d=await Lt(new Promise((f,p)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),p(y)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(He.created,l),h(d)}catch{}}),u=await Lt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(we.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,i={method:ui(t.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 Lt(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(we.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,i={method:ui(t.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 Lt(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(we.connection_stalled)}return s}rpcUnsubscribe(e,t,i){const s={method:ui(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,mn(ai({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ai({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,ai({},t)),this.topicMap.set(t.topic,e),this.events.emit(He.created,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(He.deleted,mn(ai({},i),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(He.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(He.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(t)}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 t=>mn(ai({},t),{id:await this.getSubscriptionId(t.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);t&&t.messages&&(await _w(U.toMiliseconds(U.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=F("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 vt(e+await this.getClientId())}}var d2=Object.defineProperty,du=Object.getOwnPropertySymbols,p2=Object.prototype.hasOwnProperty,f2=Object.prototype.propertyIsEnumerable,oo=(r,e,t)=>e in r?d2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pu=(r,e)=>{for(var t in e||(e={}))p2.call(e,t)&&oo(r,t,e[t]);if(du)for(var t of du(e))f2.call(e,t)&&oo(r,t,e[t]);return r},Z=(r,e,t)=>oo(r,typeof e!="symbol"?e+"":e,t);class g2 extends R0{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Ye.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",VE),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",U.toMiliseconds(U.ONE_SECOND*15)),Z(this,"request",async t=>{var i,s;this.logger.debug("Publishing Request Payload");const n=t.id||er().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(i=t.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=t.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(t);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Z(this,"resetPingTimeout",()=>{ls()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(t=this.provider)==null?void 0:t.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(we.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(we.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(Qe.payload,this.onPayloadHandler),this.provider.on(Qe.connect,this.onConnectHandler),this.provider.on(Qe.disconnect,this.onDisconnectHandler),this.provider.on(Qe.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Ui(As({level:e.logger||HE})),this.messages=new JI(this.logger,e.core),this.subscriber=new l2(this,this.logger),this.publisher=new r2(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Kl,this.projectId=e.projectId,ow()?this.packageName=Ga():aw()&&(this.bundleId=Ga()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return ke(this.logger)}get connected(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,t,i;return((i=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:ae.relay},as.outbound)}async subscribe(e,t){var i,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||(t==null?void 0:t.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=t==null?void 0:t.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=t==null?void 0:t.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const u=h=>{h.topic===e&&(this.subscriber.off(He.created,u),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(He.created,u)}),new Promise(async(h,l)=>{a=await this.subscriber.subscribe(e,pu({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&l(d)})||a,h()})]),a}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Lt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(t,i)=>{await this.connect(e).then(t).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 Rc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const i of t)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const s=de(U.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(we.message,e),await this.recordMessageEvent(e,as.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let t=1;for(;t<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,n),await Lt(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(Qe.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Qe.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: ${t}`);break}await new Promise(i=>setTimeout(i,U.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,i,s,n;if(ls())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new it(new RE(dw({sdkVersion:eo,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,t){const{topic:i,message:s}=e;await this.messages.set(i,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Lo(e)){if(!e.method.endsWith(KE))return;const t=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=t.data,a={topic:i,message:s,publishedAt:n,transportType:ae.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(pu({type:"event",event:t.id},a)),this.events.emit(t.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ts(e)&&this.events.emit(we.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,as.inbound),this.events.emit(we.message,e))}async acknowledgePayload(e){const t=xs(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Qe.payload,this.onPayloadHandler),this.provider.off(Qe.connect,this.onConnectHandler),this.provider.off(Qe.disconnect,this.onDisconnectHandler),this.provider.off(Qe.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Rc();D1(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(we.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(WE)))))}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){await this.confirmOnlineStateOrThrow(),!this.connected&&await this.connect()}}function y2(){}function fu(r){if(!r||typeof r!="object")return!1;const e=Object.getPrototypeOf(r);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(r)==="[object Object]":!1}function gu(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function yu(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const m2="[object RegExp]",w2="[object String]",b2="[object Number]",v2="[object Boolean]",mu="[object Arguments]",E2="[object Symbol]",_2="[object Date]",I2="[object Map]",$2="[object Set]",S2="[object Array]",D2="[object Function]",P2="[object ArrayBuffer]",wn="[object Object]",O2="[object Error]",A2="[object DataView]",x2="[object Uint8Array]",C2="[object Uint8ClampedArray]",T2="[object Uint16Array]",R2="[object Uint32Array]",N2="[object BigUint64Array]",j2="[object Int8Array]",B2="[object Int16Array]",U2="[object Int32Array]",F2="[object BigInt64Array]",q2="[object Float32Array]",L2="[object Float64Array]";function k2(r,e){return r===e||Number.isNaN(r)&&Number.isNaN(e)}function M2(r,e,t){return li(r,e,void 0,void 0,void 0,void 0,t)}function li(r,e,t,i,s,n,o){const a=o(r,e,t,i,s,n);if(a!==void 0)return a;if(typeof r==typeof e)switch(typeof r){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return r===e;case"number":return r===e||Object.is(r,e);case"function":return r===e;case"object":return mi(r,e,n,o)}return mi(r,e,n,o)}function mi(r,e,t,i){if(Object.is(r,e))return!0;let s=yu(r),n=yu(e);if(s===mu&&(s=wn),n===mu&&(n=wn),s!==n)return!1;switch(s){case w2:return r.toString()===e.toString();case b2:{const c=r.valueOf(),u=e.valueOf();return k2(c,u)}case v2:case _2:case E2:return Object.is(r.valueOf(),e.valueOf());case m2:return r.source===e.source&&r.flags===e.flags;case D2:return r===e}t=t??new Map;const o=t.get(r),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(r,e),t.set(e,r);try{switch(s){case I2:{if(r.size!==e.size)return!1;for(const[c,u]of r.entries())if(!e.has(c)||!li(u,e.get(c),c,r,e,t,i))return!1;return!0}case $2:{if(r.size!==e.size)return!1;const c=Array.from(r.values()),u=Array.from(e.values());for(let h=0;h<c.length;h++){const l=c[h],d=u.findIndex(f=>li(l,f,void 0,r,e,t,i));if(d===-1)return!1;u.splice(d,1)}return!0}case S2:case x2:case C2:case T2:case R2:case N2:case j2:case B2:case U2:case F2:case q2:case L2:{if(typeof Buffer<"u"&&Buffer.isBuffer(r)!==Buffer.isBuffer(e)||r.length!==e.length)return!1;for(let c=0;c<r.length;c++)if(!li(r[c],e[c],c,r,e,t,i))return!1;return!0}case P2:return r.byteLength!==e.byteLength?!1:mi(new Uint8Array(r),new Uint8Array(e),t,i);case A2:return r.byteLength!==e.byteLength||r.byteOffset!==e.byteOffset?!1:mi(new Uint8Array(r),new Uint8Array(e),t,i);case O2:return r.name===e.name&&r.message===e.message;case wn:{if(!(mi(r.constructor,e.constructor,t,i)||fu(r)&&fu(e)))return!1;const c=[...Object.keys(r),...gu(r)],u=[...Object.keys(e),...gu(e)];if(c.length!==u.length)return!1;for(let h=0;h<c.length;h++){const l=c[h],d=r[l];if(!Object.hasOwn(e,l))return!1;const f=e[l];if(!li(d,f,l,r,e,t,i))return!1}return!0}default:return!1}}finally{t.delete(r),t.delete(e)}}function z2(r,e){return M2(r,e,y2)}var H2=Object.defineProperty,wu=Object.getOwnPropertySymbols,V2=Object.prototype.hasOwnProperty,K2=Object.prototype.propertyIsEnumerable,ao=(r,e,t)=>e in r?H2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,bu=(r,e)=>{for(var t in e||(e={}))V2.call(e,t)&&ao(r,t,e[t]);if(wu)for(var t of wu(e))K2.call(e,t)&&ao(r,t,e[t]);return r},Be=(r,e,t)=>ao(r,typeof e!="symbol"?e+"":e,t);class hr extends N0{constructor(e,t,i,s=Et,n=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,Be(this,"map",new Map),Be(this,"version",GE),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"getKey"),Be(this,"storagePrefix",Et),Be(this,"recentlyDeleted",[]),Be(this,"recentlyDeletedLimit",200),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Se(o)?this.map.set(this.getKey(o),o):i1(o)?this.map.set(o.id,o):s1(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Be(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())}),Be(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Be(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>z2(a[c],o[c]))):this.values)),Be(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=bu(bu({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Be(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=Ne(t,this.name),this.storagePrefix=s,this.getKey=n}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return t}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}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}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var W2=Object.defineProperty,G2=(r,e,t)=>e in r?W2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,W=(r,e,t)=>G2(r,typeof e!="symbol"?e+"":e,t);class Y2{constructor(e,t){this.core=e,this.logger=t,W(this,"name",QE),W(this,"version",XE),W(this,"events",new bo),W(this,"pairings"),W(this,"initialized",!1),W(this,"storagePrefix",Et),W(this,"ignoredPayloadTypes",[Tt]),W(this,"registeredMethods",[]),W(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),W(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),W(this,"create",async i=>{this.isInitialized();const s=Yn(),n=await this.core.crypto.setSymKey(s),o=de(U.FIVE_MINUTES),a={protocol:Vl},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},u=Pc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Zt.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:u}}),W(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[mt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Dc(i.uri);s.props.properties.topic=n,s.addTrace(mt.pairing_uri_validation_success),s.addTrace(mt.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),s.addTrace(mt.existing_pairing),h.active)throw s.setError(Ot.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(mt.pairing_not_expired)}const l=c||de(U.FIVE_MINUTES),d={topic:n,relay:a,expiry:l,active:!1,methods:u};this.core.expirer.set(n,l),await this.pairings.set(n,d),s.addTrace(mt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Zt.create,d),s.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Ot.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw s.setError(Ot.subscribe_pairing_topic_failure),f}return s.addTrace(mt.subscribe_pairing_topic_success),d}),W(this,"activate",async({topic:i})=>{this.isInitialized();const s=de(U.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),W(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}=Gt();this.events.once(X("pairing_ping",n),({error:u})=>{u?c(u):a()}),await o()}}),W(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),W(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),W(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),W(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",te("USER_DISCONNECTED")),await this.deletePairing(s))}),W(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return Pc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),W(this,"sendRequest",async(i,s,n)=>{const o=kt(s,n),a=await this.core.crypto.encode(i,o),c=ni[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),W(this,"sendResult",async(i,s,n)=>{const o=xs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=ni[c].res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),W(this,"sendError",async(i,s,n)=>{const o=Cs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=ni[c]?ni[c].res:ni.unregistered_method.res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),W(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),W(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Ft(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),W(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)}}),W(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),W(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Zt.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{bt(s)?this.events.emit(X("pairing_ping",n),{}):tt(s)&&this.events.emit(X("pairing_ping",n),{error:s.error})},500)}),W(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Zt.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),W(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("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)}}),W(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),W(this,"isValidPair",(i,s)=>{var n;if(!Fe(i)){const{message:a}=F("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(Ot.malformed_pairing_uri),new Error(a)}if(!r1(i.uri)){const{message:a}=F("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(Ot.malformed_pairing_uri),new Error(a)}const o=Dc(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Ot.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=F("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Ot.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&U.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(Ot.pairing_expired);const{message:a}=F("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),W(this,"isValidPing",async i=>{if(!Fe(i)){const{message:n}=F("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidDisconnect",async i=>{if(!Fe(i)){const{message:n}=F("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),W(this,"isValidPairingTopic",async i=>{if(!le(i,!1)){const{message:s}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Ft(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=F("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=Ne(t,this.name),this.pairings=new hr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ke(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(we.message,async e=>{const{topic:t,message:i,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==ae.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(t,i);Lo(n)?(this.core.history.set(t,n),await this.onRelayEventRequest({topic:t,payload:n})):Ts(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:t,payload:n}),this.core.history.delete(t,n.id)),await this.core.relayer.messages.ack(t,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(et.expired,async e=>{const{topic:t}=Zh(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(Zt.expire,{topic:t}))})}}var J2=Object.defineProperty,Z2=(r,e,t)=>e in r?J2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$e=(r,e,t)=>Z2(r,typeof e!="symbol"?e+"":e,t);class Q2 extends x0{constructor(e,t){super(e,t),this.core=e,this.logger=t,$e(this,"records",new Map),$e(this,"events",new Ye.EventEmitter),$e(this,"name",e_),$e(this,"version",t_),$e(this,"cached",[]),$e(this,"initialized",!1),$e(this,"storagePrefix",Et),$e(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)}),$e(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(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ot.created,o)}),$e(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=tt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(ot.updated,s))}),$e(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))),$e(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(ot.deleted,n)}}),this.persist()}),$e(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),$e(this,"on",(i,s)=>{this.events.on(i,s)}),$e(this,"once",(i,s)=>{this.events.once(i,s)}),$e(this,"off",(i,s)=>{this.events.off(i,s)}),$e(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return ke(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:kt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(ot.created,e=>{const t=ot.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.updated,e=>{const t=ot.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ot.deleted,e=>{const t=ot.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(Jr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(t=>{U.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(ot.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var X2=Object.defineProperty,e$=(r,e,t)=>e in r?X2(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xe=(r,e,t)=>e$(r,typeof e!="symbol"?e+"":e,t);class t$ extends B0{constructor(e,t){super(e,t),this.core=e,this.logger=t,xe(this,"expirations",new Map),xe(this,"events",new Ye.EventEmitter),xe(this,"name",r_),xe(this,"version",i_),xe(this,"cached",[]),xe(this,"initialized",!1),xe(this,"storagePrefix",Et),xe(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)}),xe(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),xe(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(et.created,{target:n,expiration:o})}),xe(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),xe(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(et.deleted,{target:s,expiration:n})}}),xe(this,"on",(i,s)=>{this.events.on(i,s)}),xe(this,"once",(i,s)=>{this.events.once(i,s)}),xe(this,"off",(i,s)=>{this.events.off(i,s)}),xe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(t,this.name)}get context(){return ke(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 pw(e);if(typeof e=="number")return fw(e);const{message:t}=F("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(t)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(et.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:t}=F("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(t),new Error(t)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const t=this.expirations.get(e);if(!t){const{message:i}=F("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return t}checkExpiry(e,t){const{expiry:i}=t;U.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(et.expired,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,t)=>this.checkExpiry(t,e))}registerEventListeners(){this.core.heartbeat.on(Jr.pulse,()=>this.checkExpirations()),this.events.on(et.created,e=>{const t=et.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.expired,e=>{const t=et.expired;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}),this.events.on(et.deleted,e=>{const t=et.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}}var r$=Object.defineProperty,i$=(r,e,t)=>e in r?r$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>i$(r,typeof e!="symbol"?e+"":e,t);class s$ extends U0{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,he(this,"name",s_),he(this,"abortController"),he(this,"isDevEnv"),he(this,"verifyUrlV3",o_),he(this,"storagePrefix",Et),he(this,"version",Hl),he(this,"publicKey"),he(this,"fetchPromise"),he(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&U.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),he(this,"register",async s=>{if(!Ai()||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 u=rr.getDocument(),h=this.startAbortTimer(U.ONE_SECOND*5),l=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",m),u.body.removeChild(y),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",p,{signal:this.abortController.signal});const m=_=>{if(_.data&&typeof _.data=="string")try{const b=JSON.parse(_.data);if(b.type==="verify_attestation"){if(Un(b.attestation).payload.id!==o)return;clearInterval(h),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",m),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};u.body.appendChild(y),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",l),l}catch(u){this.logger.warn(u)}return""}),he(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(Un(n).payload.id!==a)return;const u=await this.isValidJwtAttestation(n);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),he(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(U.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}),he(this,"getVerifyUrl",s=>{let n=s||yi;return a_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${yi}`),n=yi),n}),he(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(U.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)}}),he(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),he(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),he(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")}}),he(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),he(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}),he(this,"validateAttestation",(s,n)=>{const o=zv(s,n.publicKey),a={hasExpired:U.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=Ne(t,this.name),this.abortController=new AbortController,this.isDevEnv=Ao(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ke(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}var n$=Object.defineProperty,o$=(r,e,t)=>e in r?n$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vu=(r,e,t)=>o$(r,typeof e!="symbol"?e+"":e,t);class a$ extends F0{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,vu(this,"context",c_),vu(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${u_}/${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=Ne(t,this.context)}}var c$=Object.defineProperty,Eu=Object.getOwnPropertySymbols,u$=Object.prototype.hasOwnProperty,h$=Object.prototype.propertyIsEnumerable,co=(r,e,t)=>e in r?c$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ci=(r,e)=>{for(var t in e||(e={}))u$.call(e,t)&&co(r,t,e[t]);if(Eu)for(var t of Eu(e))h$.call(e,t)&&co(r,t,e[t]);return r},fe=(r,e,t)=>co(r,typeof e!="symbol"?e+"":e,t);class l$ extends q0{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,fe(this,"context",l_),fe(this,"storagePrefix",Et),fe(this,"storageVersion",h_),fe(this,"events",new Map),fe(this,"shouldPersist",!1),fe(this,"init",async()=>{if(!Ao())try{const s={eventId:Ja(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Yh(this.core.relayer.protocol,this.core.relayer.version,eo)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),fe(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,u=Ja(),h=this.core.projectId||"",l=Date.now(),d=ci({eventId:u,timestamp:l,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:h,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,d),this.shouldPersist=!0),d}),fe(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 ci(ci({},a),this.setMethods(a.eventId))}),fe(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),fe(this,"setEventListeners",()=>{this.core.heartbeat.on(Jr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(s.timestamp)>d_&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),fe(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),fe(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)}),fe(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)}),fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),fe(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,ci(ci({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),fe(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)}}),fe(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${p_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${eo}${n}`,{method:"POST",body:JSON.stringify(s)})}),fe(this,"getAppDomain",()=>Gh().url),this.logger=Ne(t,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var d$=Object.defineProperty,_u=Object.getOwnPropertySymbols,p$=Object.prototype.hasOwnProperty,f$=Object.prototype.propertyIsEnumerable,uo=(r,e,t)=>e in r?d$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Iu=(r,e)=>{for(var t in e||(e={}))p$.call(e,t)&&uo(r,t,e[t]);if(_u)for(var t of _u(e))f$.call(e,t)&&uo(r,t,e[t]);return r},oe=(r,e,t)=>uo(r,typeof e!="symbol"?e+"":e,t);let g$=class sd extends D0{constructor(e){var t;super(e),oe(this,"protocol",zl),oe(this,"version",Hl),oe(this,"name",ms),oe(this,"relayUrl"),oe(this,"projectId"),oe(this,"customStoragePrefix"),oe(this,"events",new Ye.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:u})=>{if(!a||!c)return;const h={topic:a,message:c,publishedAt:Date.now(),transportType:ae.link_mode};this.relayer.onLinkMessageEvent(h,{sessionExists:u})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Kl,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=As({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:jE.logger,name:ms}),{logger:n,chunkLoggerController:o}=I0({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(t=this.logChunkController)!=null&&t.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=Ne(n,this.name),this.heartbeat=new x1,this.crypto=new MI(this,this.logger,e==null?void 0:e.keychain),this.history=new Q2(this,this.logger),this.expirer=new t$(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new o0(Iu(Iu({},BE),e==null?void 0:e.storageOptions)),this.relayer=new g2({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new Y2(this,this.logger),this.verify=new s$(this,this.logger,this.storage),this.echoClient=new a$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new l$(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new sd(e);await t.initialize();const i=await t.crypto.getClientId();return await t.storage.setItem(YE,i),t}get context(){return ke(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(ru,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(ru)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&NE.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const y$=g$,nd="wc",od=2,ad="client",ko=`${nd}@${od}:${ad}:`,bn={name:ad,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},$u="WALLETCONNECT_DEEPLINK_CHOICE",m$="proposal",Su="Proposal expired",w$="session",br=U.SEVEN_DAYS,b$="engine",ge={wc_sessionPropose:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1104},res:{ttl:U.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1106},res:{ttl:U.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:U.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1112},res:{ttl:U.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:U.ONE_DAY,prompt:!1,tag:1114},res:{ttl:U.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:U.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:U.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:U.FIVE_MINUTES,prompt:!1,tag:1119}}},vn={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},yt={idle:"IDLE",active:"ACTIVE"},Du={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},v$="request",E$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_$="wc",I$="auth",$$="authKeys",S$="pairingTopics",D$="requests",Ns=`${_$}@${1.5}:${I$}:`,cs=`${Ns}:PUB_KEY`;var P$=Object.defineProperty,O$=Object.defineProperties,A$=Object.getOwnPropertyDescriptors,Pu=Object.getOwnPropertySymbols,x$=Object.prototype.hasOwnProperty,C$=Object.prototype.propertyIsEnumerable,ho=(r,e,t)=>e in r?P$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,se=(r,e)=>{for(var t in e||(e={}))x$.call(e,t)&&ho(r,t,e[t]);if(Pu)for(var t of Pu(e))C$.call(e,t)&&ho(r,t,e[t]);return r},Te=(r,e)=>O$(r,A$(e)),N=(r,e,t)=>ho(r,typeof e!="symbol"?e+"":e,t);class T$ extends z0{constructor(e){super(e),N(this,"name",b$),N(this,"events",new bo),N(this,"initialized",!1),N(this,"requestQueue",{state:yt.idle,queue:[]}),N(this,"sessionRequestQueue",{state:yt.idle,queue:[]}),N(this,"requestQueueDelay",U.ONE_SECOND),N(this,"expectedPairingMethodMap",new Map),N(this,"recentlyDeletedMap",new Map),N(this,"recentlyDeletedLimit",200),N(this,"relayMessageCache",[]),N(this,"pendingSessions",new Map),N(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(ge)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay)))}),N(this,"connect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Te(se({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(i);const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=i;let h=s,l,d=!1;try{if(h){const E=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=E.active}}catch(E){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),E}if(!h||!d){const{topic:E,uri:$}=await this.client.core.pairing.create();h=E,l=$}if(!h){const{message:E}=F("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(E)}const f=await this.client.core.crypto.generateKeyPair(),p=ge.wc_sessionPropose.req.ttl||U.FIVE_MINUTES,y=de(p),m=Te(se(se({requiredNamespaces:n,optionalNamespaces:o,relays:u??[{protocol:Vl}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:h},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),_=X("session_connect",m.id),{reject:b,resolve:I,done:A}=Gt(p,Su),C=({id:E})=>{E===m.id&&(this.client.events.off("proposal_expire",C),this.pendingSessions.delete(m.id),this.events.emit(_,{error:{message:Su,code:0}}))};return this.client.events.on("proposal_expire",C),this.events.once(_,({error:E,session:$})=>{this.client.events.off("proposal_expire",C),E?b(E):$&&I($)}),await this.sendRequest({topic:h,method:"wc_sessionPropose",params:m,throwOnFailedPublish:!0,clientRpcId:m.id}),await this.setProposal(m.id,m),{uri:l,approval:A}}),N(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(i){throw this.client.logger.error("pair() failed"),i}}),N(this,"approve",async t=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=t==null?void 0:t.id)==null?void 0:i.toString(),trace:[at.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(P){throw o.setError(Kt.no_internet_connection),P}try{await this.isValidProposalId(t==null?void 0:t.id)}catch(P){throw this.client.logger.error(`approve() -> proposal.get(${t==null?void 0:t.id}) failed`),o.setError(Kt.proposal_not_found),P}try{await this.isValidApprove(t)}catch(P){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Kt.session_approve_namespace_validation_failure),P}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:h,scopedProperties:l,sessionConfig:d}=t,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:y,requiredNamespaces:m,optionalNamespaces:_}=f;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:at.session_approve_started,properties:{topic:p,trace:[at.session_approve_started,at.session_namespaces_validation_success]}}));const I=await this.client.core.crypto.generateKeyPair(),A=y.publicKey,C=await this.client.core.crypto.generateSharedKey(I,A),E=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:I,metadata:this.client.metadata},expiry:de(br)},h&&{sessionProperties:h}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),$=ae.relay;b.addTrace(at.subscribing_session_topic);try{await this.client.core.relayer.subscribe(C,{transportType:$})}catch(P){throw b.setError(Kt.subscribe_session_topic_failure),P}b.addTrace(at.subscribe_session_topic_success);const S=Te(se({},E),{topic:C,requiredNamespaces:m,optionalNamespaces:_,pairingTopic:p,acknowledged:!1,self:E.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:I,transportType:ae.relay});await this.client.session.set(C,S),b.addTrace(at.store_session);try{b.addTrace(at.publishing_session_settle),await this.sendRequest({topic:C,method:"wc_sessionSettle",params:E,throwOnFailedPublish:!0}).catch(P=>{throw b==null||b.setError(Kt.session_settle_publish_failure),P}),b.addTrace(at.session_settle_publish_success),b.addTrace(at.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:I},throwOnFailedPublish:!0}).catch(P=>{throw b==null||b.setError(Kt.session_approve_publish_failure),P}),b.addTrace(at.session_approve_publish_success)}catch(P){throw this.client.logger.error(P),this.client.session.delete(C,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(C),P}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:y.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(C,de(br)),{topic:C,acknowledged:()=>Promise.resolve(this.client.session.get(C))}}),N(this,"reject",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(t)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=t;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:ge.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),N(this,"update",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(t)}catch(l){throw this.client.logger.error("update() -> isValidUpdate() failed"),l}const{topic:i,namespaces:s}=t,{done:n,resolve:o,reject:a}=Gt(),c=wt(),u=er().toString(),h=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:l})=>{l?a(l):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:u}).catch(l=>{this.client.logger.error(l),this.client.session.update(i,{namespaces:h}),a(l)}),{acknowledged:n}}),N(this,"extend",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(t)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=t,s=wt(),{done:n,resolve:o,reject:a}=Gt();return this.events.once(X("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,de(br)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),N(this,"request",async t=>{this.isInitialized();try{await this.isValidRequest(t)}catch(_){throw this.client.logger.error("request() -> isValidRequest() failed"),_}const{chainId:i,request:s,topic:n,expiry:o=ge.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ae.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),u=er().toString(),{done:h,resolve:l,reject:d}=Gt(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:_,result:b})=>{_?d(_):l(b)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:f,params:{request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(_=>d(_)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await h();const y={request:Te(se({},s),{expiryTimestamp:de(o)}),chainId:i},m=this.shouldSetTVF(f,y);return await Promise.all([new Promise(async _=>{await this.sendRequest(se({clientRpcId:c,relayRpcId:u,topic:n,method:f,params:y,expiry:o,throwOnFailedPublish:!0},m&&{tvf:this.getTVFParams(c,y)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),_()}),new Promise(async _=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const I=await ww(this.client.core.storage,$u);await gw({id:c,topic:n,wcDeepLink:I})}_()}),h()]).then(_=>_[2])}),N(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:i,response:s}=t,{id:n}=s,o=this.client.session.get(i);o.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);bt(s)?await this.sendResult({id:n,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:a}):tt(s)&&await this.sendError({id:n,topic:i,error:s.error,appLink:a}),this.cleanupAfterResponse(t)}),N(this,"ping",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(t)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=t;if(this.client.session.keys.includes(i)){const s=wt(),n=er().toString(),{done:o,resolve:a,reject:c}=Gt();this.events.once(X("session_ping",s),({error:u})=>{u?c(u):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}))}),N(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:i,event:s,chainId:n}=t,o=er().toString(),a=wt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),N(this,"disconnect",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(t);const{topic:i}=t;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("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}=F("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),N(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(i=>e1(i,t)))),N(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),N(this,"authenticate",async(t,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(t);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:u,domain:h,nonce:l,type:d,exp:f,nbf:p,methods:y=[],expiry:m}=t,_=[...t.resources||[]],{topic:b,uri:I}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:I}});const A=await this.client.core.crypto.generateKeyPair(),C=ss(A);if(await Promise.all([this.client.auth.authKeys.set(cs,{responseTopic:C,publicKey:A}),this.client.auth.pairingTopics.set(C,{topic:C,pairingTopic:b})]),await this.client.core.relayer.subscribe(C,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),y.length>0){const{namespace:D}=Br(a[0]);let R=hb(D,"request",y);is(_)&&(R=db(R,_.pop())),_.push(R)}const E=m&&m>ge.wc_sessionAuthenticate.req.ttl?m:ge.wc_sessionAuthenticate.req.ttl,$={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:h,version:"1",nonce:l,iat:new Date().toISOString(),exp:f,nbf:p,resources:_},requester:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(E)},S={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},P={requiredNamespaces:{},optionalNamespaces:S,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:A,metadata:this.client.metadata},expiryTimestamp:de(ge.wc_sessionPropose.req.ttl),id:wt()},{done:j,resolve:T,reject:B}=Gt(E,"Request expired"),k=wt(),g=X("session_connect",P.id),w=X("session_request",k),v=async({error:D,session:R})=>{this.events.off(w,O),D?B(D):R&&T({session:R})},O=async D=>{var R,q,L;if(await this.deletePendingAuthRequest(k,{message:"fulfilled",code:0}),D.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===Y.code?void 0:(this.events.off(g,v),B(D.error.message))}await this.deleteProposal(P.id),this.events.off(g,v);const{cacaos:M,responder:z}=D.result,V=[],H=[];for(const Y of M){await sc({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),B(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ae}=Y,Ee=is(Ae.resources),Ce=[Ln(Ae.iss)],Je=ds(Ae.iss);if(Ee){const Ze=nc(Ee),dr=oc(Ee);V.push(...Ze),Ce.push(...dr)}for(const Ze of Ce)H.push(`${Ze}:${Je}`)}const ne=await this.client.core.crypto.generateSharedKey(A,z.publicKey);let ee;V.length>0&&(ee={topic:ne,acknowledged:!0,self:{publicKey:A,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:de(br),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:Oc([...new Set(V)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(ne,{transportType:o}),await this.client.session.set(ne,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:z.metadata}),ee=this.client.session.get(ne)),(R=this.client.metadata.redirect)!=null&&R.linkMode&&(q=z.metadata.redirect)!=null&&q.linkMode&&(L=z.metadata.redirect)!=null&&L.universal&&i&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(ne,{transportType:ae.link_mode})),T({auths:M,session:ee})};this.events.once(g,v),this.events.once(w,O);let x;try{if(n){const D=kt("wc_sessionAuthenticate",$,k);this.client.core.history.set(b,D);const R=await this.client.core.crypto.encode("",D,{type:ji,encoding:qt});x=Wi(i,b,R)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:$,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:k}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:P,expiry:ge.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:P.id})])}catch(D){throw this.events.off(g,v),this.events.off(w,O),D}return await this.setProposal(P.id,P),await this.setAuthRequest(k,{request:Te(se({},$),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:x??I,response:j}}),N(this,"approveSessionAuthenticate",async t=>{const{id:i,auths:s}=t,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Wt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw n.setError(oi.no_internet_connection),m}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(oi.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,u=await this.client.core.crypto.generateKeyPair(),h=ss(c),l={type:Tt,receiverPublicKey:c,senderPublicKey:u},d=[],f=[];for(const m of s){if(!await sc({cacao:m,projectId:this.client.core.projectId})){n.setError(oi.invalid_cacao);const C=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:h,error:C,encodeOpts:l}),new Error(C.message)}n.addTrace(Wt.cacaos_verified);const{p:_}=m,b=is(_.resources),I=[Ln(_.iss)],A=ds(_.iss);if(b){const C=nc(b),E=oc(b);d.push(...C),I.push(...E)}for(const C of I)f.push(`${C}:${A}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);n.addTrace(Wt.create_authenticated_session_topic);let y;if((d==null?void 0:d.length)>0){y={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:de(br),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Oc([...new Set(d)],[...new Set(f)]),transportType:a},n.addTrace(Wt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(m){throw n.setError(oi.subscribe_authenticated_session_topic_failure),m}n.addTrace(Wt.subscribe_authenticated_session_topic_success),await this.client.session.set(p,y),n.addTrace(Wt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Wt.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:i,result:{cacaos:s,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(m){throw n.setError(oi.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}}),N(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:i,reason:s}=t,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=ss(o),u={type:Tt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:u,rpcOpts:ge.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),N(this,"formatAuthMessage",t=>{this.isInitialized();const{request:i,iss:s}=t;return ol(i,s)}),N(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const t=this.relayMessageCache.shift();t&&await this.onRelayMessage(t)}catch(t){this.client.logger.error(t)}},50)}),N(this,"cleanupDuplicatePairings",async t=>{if(t.pairingTopic)try{const i=this.client.core.pairing.pairings.get(t.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)===t.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)}}),N(this,"deleteSession",async t=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=t,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,te("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($u).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===s&&this.deletePendingSessionRequest(u.id,te("USER_DISCONNECTED"))}),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),N(this,"deleteProposal",async(t,i)=>{if(i)try{const s=this.client.proposal.get(t),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Kt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),N(this,"deletePendingSessionRequest",async(t,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==t),s&&(this.sessionRequestQueue.state=yt.idle,this.client.events.emit("session_request_expire",{id:t}))}),N(this,"deletePendingAuthRequest",async(t,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(t,i),s?Promise.resolve():this.client.core.expirer.del(t)])}),N(this,"setExpiry",async(t,i)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,i),await this.client.session.update(t,{expiry:i}))}),N(this,"setProposal",async(t,i)=>{this.client.core.expirer.set(t,de(ge.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,i)}),N(this,"setAuthRequest",async(t,i)=>{const{request:s,pairingTopic:n,transportType:o=ae.relay}=i;this.client.core.expirer.set(t,s.expiryTimestamp),await this.client.auth.requests.set(t,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:t,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),N(this,"setPendingSessionRequest",async t=>{const{id:i,topic:s,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||de(ge.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})}),N(this,"sendRequest",async t=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:h,tvf:l}=t,d=kt(s,n,c);let f;const p=!!h;try{const _=p?qt:ht;f=await this.client.core.crypto.encode(i,d,{encoding:_})}catch(_){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),_}let y;if(E$.includes(s)){const _=vt(JSON.stringify(d)),b=vt(f);y=await this.client.core.verify.register({id:b,decryptedId:_})}const m=ge[s].req;if(m.attestation=y,o&&(m.ttl=o),a&&(m.id=a),this.client.core.history.set(i,d),p){const _=Wi(h,i,f);await global.Linking.openURL(_,this.client.name)}else{const _=ge[s].req;o&&(_.ttl=o),a&&(_.id=a),_.tvf=Te(se({},l),{correlationId:d.id}),u?(_.internal=Te(se({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,_)):this.client.core.relayer.publish(i,f,_).catch(b=>this.client.logger.error(b))}return d.id}),N(this,"sendResult",async t=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,u=xs(i,n);let h;const l=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=l?qt:ht;h=await this.client.core.crypto.encode(s,u,Te(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,f;try{d=await this.client.core.history.get(s,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(i,p.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),p}if(l){const p=Wi(c,s,h);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,y=ge[p].res;y.tvf=Te(se({},f),{correlationId:i}),o?(y.internal=Te(se({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,y)):this.client.core.relayer.publish(s,h,y).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(u)}),N(this,"sendError",async t=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,u=Cs(i,n);let h;const l=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=l?qt:ht;h=await this.client.core.crypto.encode(s,u,Te(se({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),f}let d;try{d=await this.client.core.history.get(s,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),f}if(l){const f=Wi(c,s,h);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||ge[f].res;this.client.core.relayer.publish(s,h,p)}await this.client.core.history.resolve(u)}),N(this,"cleanup",async()=>{const t=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Ft(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&t.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Ft(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...t.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),N(this,"onProviderMessageEvent",async t=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(t):await this.onRelayMessage(t)}),N(this,"onRelayEventRequest",async t=>{this.requestQueue.queue.push(t),await this.processRequestsQueue()}),N(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===yt.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=yt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=yt.idle}),N(this,"processRequest",async t=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=t,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}`)}}),N(this,"onRelayEventResponse",async t=>{const{topic:i,payload:s,transportType:n}=t,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}`)}}),N(this,"onRelayEventUnknownPayload",t=>{const{topic:i}=t,{message:s}=F("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),N(this,"shouldIgnorePairingRequest",t=>{const{topic:i,requestMethod:s}=t,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),N(this,"onSessionProposeRequest",async t=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=t,{params:a,id:c}=s;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u==null||u.setError(Ot.proposal_listener_not_found)),this.isValidConnect(se({},s.params));const h=a.expiryTimestamp||de(ge.wc_sessionPropose.req.ttl),l=se({id:c,pairingTopic:i,expiryTimestamp:h},a);await this.setProposal(c,l);const d=await this.getVerifyContext({attestationId:n,hash:vt(JSON.stringify(s)),encryptedId:o,metadata:l.proposer.metadata});u==null||u.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:l,verifyContext:d})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:ge.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),N(this,"onSessionProposeResponse",async(t,i,s)=>{const{id:n}=i;if(bt(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 u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const h=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:t,proposalId:n,publicKey:c});const l=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:t})}else if(tt(i)){await this.client.proposal.delete(n,te("USER_DISCONNECTED"));const o=X("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})}}),N(this,"onSessionSettleRequest",async(t,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:h,scopedProperties:l,sessionConfig:d}=i.params,f=[...this.pendingSessions.values()].find(m=>m.sessionTopic===t);if(!f)return this.client.logger.error(`Pending session not found for topic ${t}`);const p=this.client.proposal.get(f.proposalId),y=Te(se(se(se({topic:t,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),{transportType:ae.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(X("session_connect",f.proposalId),{session:y}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:i.id,topic:t,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),N(this,"onSessionSettleResponse",async(t,i)=>{const{id:s}=i;bt(i)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(X("session_approve",s),{})):tt(i)&&(await this.client.session.delete(t,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",s),{error:i.error}))}),N(this,"onSessionUpdateRequest",async(t,i)=>{const{params:s,id:n}=i;try{const o=`${t}_session_update`,a=si.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:t,error:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:t},s));try{si.set(o,n),await this.client.session.update(t,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:t,result:!0,throwOnFailedPublish:!0})}catch(c){throw si.delete(o),c}this.client.events.emit("session_update",{id:n,topic:t,params:s})}catch(o){await this.sendError({id:n,topic:t,error:o}),this.client.logger.error(o)}}),N(this,"isRequestOutOfSync",(t,i)=>i.toString().slice(0,-3)<t.toString().slice(0,-3)),N(this,"onSessionUpdateResponse",(t,i)=>{const{id:s}=i,n=X("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_update",s),{}):tt(i)&&this.events.emit(X("session_update",s),{error:i.error})}),N(this,"onSessionExtendRequest",async(t,i)=>{const{id:s}=i;try{this.isValidExtend({topic:t}),await this.setExpiry(t,de(br)),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),N(this,"onSessionExtendResponse",(t,i)=>{const{id:s}=i,n=X("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_extend",s),{}):tt(i)&&this.events.emit(X("session_extend",s),{error:i.error})}),N(this,"onSessionPingRequest",async(t,i)=>{const{id:s}=i;try{this.isValidPing({topic:t}),await this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:t})}catch(n){await this.sendError({id:s,topic:t,error:n}),this.client.logger.error(n)}}),N(this,"onSessionPingResponse",(t,i)=>{const{id:s}=i,n=X("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);bt(i)?this.events.emit(X("session_ping",s),{}):tt(i)&&this.events.emit(X("session_ping",s),{error:i.error})},500)}),N(this,"onSessionDeleteRequest",async(t,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:t,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(we.publish,async()=>{n(await this.deleteSession({topic:t,id:s}))})}),this.sendResult({id:s,topic:t,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:t,error:te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),N(this,"onSessionRequest",async t=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:h}=t,{id:l,params:d}=a;try{await this.isValidRequest(se({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:vt(JSON.stringify(kt("wc_sessionRequest",d,l))),encryptedId:u,metadata:f.peer.metadata,transportType:h}),y={id:l,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(y),h===ae.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=f.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(f){await this.sendError({id:l,topic:o,error:f}),this.client.logger.error(f)}}),N(this,"onSessionRequestResponse",(t,i)=>{const{id:s}=i,n=X("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),N(this,"onSessionEventRequest",async(t,i)=>{const{id:s,params:n}=i;try{const o=`${t}_session_event_${n.event.name}`,a=si.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(se({topic:t},n)),this.client.events.emit("session_event",{id:s,topic:t,params:n}),si.set(o,s)}catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),N(this,"onSessionAuthenticateResponse",(t,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:i}),bt(i)?this.events.emit(X("session_request",s),{result:i.result}):tt(i)&&this.events.emit(X("session_request",s),{error:i.error})}),N(this,"onSessionAuthenticateRequest",async t=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:u,authPayload:h,expiryTimestamp:l}=n.params,d=await this.getVerifyContext({attestationId:o,hash:vt(JSON.stringify(n)),encryptedId:a,metadata:u.metadata,transportType:c}),f={requester:u,pairingTopic:s,id:n.id,authPayload:h,verifyContext:d,expiryTimestamp:l};await this.setAuthRequest(n.id,{request:f,pairingTopic:s,transportType:c}),c===ae.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(u){this.client.logger.error(u);const h=n.params.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:Tt,receiverPublicKey:h,senderPublicKey:l};await this.sendError({id:n.id,topic:s,error:u,encodeOpts:f,rpcOpts:ge.wc_sessionAuthenticate.autoReject,appLink:d})}}),N(this,"addSessionRequestToSessionRequestQueue",t=>{this.sessionRequestQueue.queue.push(t)}),N(this,"cleanupAfterResponse",t=>{this.deletePendingSessionRequest(t.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=yt.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))}),N(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===t&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",n.request.id),{error:i})})}),N(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===yt.active){this.client.logger.info("session request queue is already active.");return}const t=this.sessionRequestQueue.queue[0];if(!t){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=yt.active,this.emitSessionRequest(t)}catch(i){this.client.logger.error(i)}}),N(this,"emitSessionRequest",t=>{this.client.events.emit("session_request",t)}),N(this,"onPairingCreated",t=>{if(t.methods&&this.expectedPairingMethodMap.set(t.topic,t.methods),t.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===t.topic);i&&this.onSessionProposeRequest({topic:t.topic,payload:kt("wc_sessionPropose",Te(se({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),N(this,"isValidConnect",async t=>{if(!Fe(t)){const{message:u}=F("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(Se(i)||await this.isValidPairingTopic(i),!d1(c)){const{message:u}=F("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Se(s)&&Si(s)!==0&&this.validateNamespaces(s,"requiredNamespaces"),!Se(n)&&Si(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Se(o)||this.validateSessionProps(o,"sessionProperties"),!Se(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>u.includes(h)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),N(this,"validateNamespaces",(t,i)=>{const s=l1(t,"connect()",i);if(s)throw new Error(s.message)}),N(this,"isValidApprove",async t=>{if(!Fe(t))throw new Error(F("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=cn(s,"approve()");if(u)throw new Error(u.message);const h=Cc(c.requiredNamespaces,s,"approve()");if(h)throw new Error(h.message);if(!le(n,!0)){const{message:l}=F("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(l)}if(Se(o)||this.validateSessionProps(o,"sessionProperties"),!Se(a)){this.validateSessionProps(a,"scopedProperties");const l=new Set(Object.keys(s));if(!Object.keys(a).every(d=>l.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(l).join(", ")}`)}}),N(this,"isValidReject",async t=>{if(!Fe(t)){const{message:n}=F("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:i,reason:s}=t;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!f1(s)){const{message:n}=F("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),N(this,"isValidSessionSettleRequest",t=>{if(!Fe(t)){const{message:u}=F("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(u)}const{relay:i,controller:s,namespaces:n,expiry:o}=t;if(!Tl(i)){const{message:u}=F("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=n1(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=cn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Ft(o)){const{message:u}=F("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),N(this,"isValidUpdate",async t=>{if(!Fe(t)){const{message:c}=F("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:i,namespaces:s}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=cn(s,"update()");if(o)throw new Error(o.message);const a=Cc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),N(this,"isValidExtend",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(s)}const{topic:i}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),N(this,"isValidRequest",async t=>{if(!Fe(t)){const{message:c}=F("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!xc(a,n)){const{message:c}=F("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!g1(s)){const{message:c}=F("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!w1(a,n,s.method)){const{message:c}=F("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!_1(o,vn)){const{message:c}=F("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${vn.min} and ${vn.max}`);throw new Error(c)}}),N(this,"isValidRespond",async t=>{var i;if(!Fe(t)){const{message:o}=F("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:s,response:n}=t;try{await this.isValidSessionTopic(s)}catch(o){throw(i=t==null?void 0:t.response)!=null&&i.id&&this.cleanupAfterResponse(t),o}if(!y1(n)){const{message:o}=F("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),N(this,"isValidPing",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),N(this,"isValidEmit",async t=>{if(!Fe(t)){const{message:a}=F("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=t;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!xc(o,n)){const{message:a}=F("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!m1(s)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!b1(o,n,s.name)){const{message:a}=F("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),N(this,"isValidDisconnect",async t=>{if(!Fe(t)){const{message:s}=F("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(s)}const{topic:i}=t;await this.isValidSessionOrPairingTopic(i)}),N(this,"isValidAuthenticate",t=>{const{chains:i,uri:s,domain:n,nonce:o}=t;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!le(s,!1))throw new Error("uri is required parameter");if(!le(n,!1))throw new Error("domain is required parameter");if(!le(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Br(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Br(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),N(this,"getVerifyContext",async t=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||yi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ae.link_mode){const h=this.getAppLinkIfEnabled(o,a);return c.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),N(this,"validateSessionProps",(t,i)=>{Object.values(t).forEach((s,n)=>{if(s==null){const{message:o}=F("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}),N(this,"getPendingAuthRequest",t=>{const i=this.client.auth.requests.get(t);return typeof i=="object"?i:void 0}),N(this,"addToRecentlyDeleted",(t,i)=>{if(this.recentlyDeletedMap.set(t,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)}}}),N(this,"checkRecentlyDeleted",t=>{const i=this.recentlyDeletedMap.get(t);if(i){const{message:s}=F("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${t}`);throw new Error(s)}}),N(this,"isLinkModeEnabled",(t,i)=>{var s,n,o,a,c,u,h,l,d;return!t||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&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((h=t==null?void 0:t.redirect)==null?void 0:h.universal)!==void 0&&((l=t==null?void 0:t.redirect)==null?void 0:l.universal)!==""&&((d=t==null?void 0:t.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),N(this,"getAppLinkIfEnabled",(t,i)=>{var s;return this.isLinkModeEnabled(t,i)?(s=t==null?void 0:t.redirect)==null?void 0:s.universal:void 0}),N(this,"handleLinkModeMessage",({url:t})=>{if(!t||!t.includes("wc_ev")||!t.includes("topic"))return;const i=Ya(t,"topic")||"",s=decodeURIComponent(Ya(t,"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})}),N(this,"registerLinkModeListeners",async()=>{var t;if(Ao()||zt()&&(t=this.client.metadata.redirect)!=null&&t.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)}}}),N(this,"shouldSetTVF",(t,i)=>{if(!i||t!=="wc_sessionRequest")return!1;const{request:s}=i;return Object.keys(Du).includes(s.method)}),N(this,"getTVFParams",(t,i,s)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,s);return Te(se({correlationId:t,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),N(this,"isValidContractData",t=>{var i;if(!t)return!1;try{const s=(t==null?void 0:t.data)||((i=t==null?void 0:t[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}),N(this,"extractTxHashesFromResult",(t,i)=>{try{const s=Du[t];if(typeof i=="string")return[i];const n=i[s.key];if(lt(n))return t==="solana_signAllTransactions"?n.map(o=>Jw(o)):n;if(typeof n=="string")return[n]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(t))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("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=F("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(we.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(cs)?this.client.auth.authKeys.get(cs):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,i,{receiverPublicKey:o,encoding:n===ae.link_mode?qt:ht});Lo(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:s,transportType:n,encryptedId:vt(i)})):Ts(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}),this.client.core.history.delete(t,a.id)):await this.onRelayEventUnknownPayload({topic:t,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(t,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(et.expired,async e=>{const{topic:t,id:i}=Zh(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,F("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,F("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Zt.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Zt.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!le(e,!1)){const{message:t}=F("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Ft(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=F("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!le(e,!1)){const{message:t}=F("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Ft(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=F("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=F("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(le(e,!1)){const{message:t}=F("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=F("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!p1(e)){const{message:t}=F("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=F("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Ft(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=F("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class R$ extends hr{constructor(e,t){super(e,t,m$,ko),this.core=e,this.logger=t}}let N$=class extends hr{constructor(e,t){super(e,t,w$,ko),this.core=e,this.logger=t}};class j$ extends hr{constructor(e,t){super(e,t,v$,ko,i=>i.id),this.core=e,this.logger=t}}class B$ extends hr{constructor(e,t){super(e,t,$$,Ns,()=>cs),this.core=e,this.logger=t}}class U$ extends hr{constructor(e,t){super(e,t,S$,Ns),this.core=e,this.logger=t}}class F$ extends hr{constructor(e,t){super(e,t,D$,Ns,i=>i.id),this.core=e,this.logger=t}}var q$=Object.defineProperty,L$=(r,e,t)=>e in r?q$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,En=(r,e,t)=>L$(r,typeof e!="symbol"?e+"":e,t);class k${constructor(e,t){this.core=e,this.logger=t,En(this,"authKeys"),En(this,"pairingTopics"),En(this,"requests"),this.authKeys=new B$(this.core,this.logger),this.pairingTopics=new U$(this.core,this.logger),this.requests=new F$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var M$=Object.defineProperty,z$=(r,e,t)=>e in r?M$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,G=(r,e,t)=>z$(r,typeof e!="symbol"?e+"":e,t);let H$=class cd extends M0{constructor(e){super(e),G(this,"protocol",nd),G(this,"version",od),G(this,"name",bn.name),G(this,"metadata"),G(this,"core"),G(this,"logger"),G(this,"events",new Ye.EventEmitter),G(this,"engine"),G(this,"session"),G(this,"proposal"),G(this,"pendingRequest"),G(this,"auth"),G(this,"signConfig"),G(this,"on",(i,s)=>this.events.on(i,s)),G(this,"once",(i,s)=>this.events.once(i,s)),G(this,"off",(i,s)=>this.events.off(i,s)),G(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),G(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),G(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),G(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),G(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),G(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||bn.name,this.metadata=uw(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const t=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Ui(As({level:(e==null?void 0:e.logger)||bn.logger}));this.core=(e==null?void 0:e.core)||new y$(e),this.logger=Ne(t,this.name),this.session=new N$(this.core,this.logger),this.proposal=new R$(this.core,this.logger),this.pendingRequest=new j$(this.core,this.logger),this.engine=new T$(this),this.auth=new k$(this.core,this.logger)}static async init(e){const t=new cd(e);return await t.initialize(),t}get context(){return ke(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},U.toMiliseconds(U.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var di={exports:{}},V$=di.exports,Ou;function K$(){return Ou||(Ou=1,function(r,e){var t=typeof self<"u"?self:V$,i=function(){function n(){this.fetch=!1,this.DOMException=t.DOMException}return n.prototype=t,new n}();(function(n){(function(o){var a={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function c(g){return g&&DataView.prototype.isPrototypeOf(g)}if(a.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 l(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(g))throw new TypeError("Invalid character in header field name");return g.toLowerCase()}function d(g){return typeof g!="string"&&(g=String(g)),g}function f(g){var w={next:function(){var v=g.shift();return{done:v===void 0,value:v}}};return a.iterable&&(w[Symbol.iterator]=function(){return w}),w}function p(g){this.map={},g instanceof p?g.forEach(function(w,v){this.append(v,w)},this):Array.isArray(g)?g.forEach(function(w){this.append(w[0],w[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(w){this.append(w,g[w])},this)}p.prototype.append=function(g,w){g=l(g),w=d(w);var v=this.map[g];this.map[g]=v?v+", "+w:w},p.prototype.delete=function(g){delete this.map[l(g)]},p.prototype.get=function(g){return g=l(g),this.has(g)?this.map[g]:null},p.prototype.has=function(g){return this.map.hasOwnProperty(l(g))},p.prototype.set=function(g,w){this.map[l(g)]=d(w)},p.prototype.forEach=function(g,w){for(var v in this.map)this.map.hasOwnProperty(v)&&g.call(w,this.map[v],v,this)},p.prototype.keys=function(){var g=[];return this.forEach(function(w,v){g.push(v)}),f(g)},p.prototype.values=function(){var g=[];return this.forEach(function(w){g.push(w)}),f(g)},p.prototype.entries=function(){var g=[];return this.forEach(function(w,v){g.push([v,w])}),f(g)},a.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function y(g){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}function m(g){return new Promise(function(w,v){g.onload=function(){w(g.result)},g.onerror=function(){v(g.error)}})}function _(g){var w=new FileReader,v=m(w);return w.readAsArrayBuffer(g),v}function b(g){var w=new FileReader,v=m(w);return w.readAsText(g),v}function I(g){for(var w=new Uint8Array(g),v=new Array(w.length),O=0;O<w.length;O++)v[O]=String.fromCharCode(w[O]);return v.join("")}function A(g){if(g.slice)return g.slice(0);var w=new Uint8Array(g.byteLength);return w.set(new Uint8Array(g)),w.buffer}function C(){return this.bodyUsed=!1,this._initBody=function(g){this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:a.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:a.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():a.arrayBuffer&&a.blob&&c(g)?(this._bodyArrayBuffer=A(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||h(g))?this._bodyArrayBuffer=A(g):this._bodyText=g=Object.prototype.toString.call(g):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):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var g=y(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(){return this._bodyArrayBuffer?y(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(_)}),this.text=function(){var g=y(this);if(g)return g;if(this._bodyBlob)return b(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(I(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(P)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function $(g){var w=g.toUpperCase();return E.indexOf(w)>-1?w:g}function S(g,w){w=w||{};var v=w.body;if(g instanceof S){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,w.headers||(this.headers=new p(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!v&&g._bodyInit!=null&&(v=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 p(w.headers)),this.method=$(w.method||this.method||"GET"),this.mode=w.mode||this.mode||null,this.signal=w.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&v)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(v)}S.prototype.clone=function(){return new S(this,{body:this._bodyInit})};function P(g){var w=new FormData;return g.trim().split("&").forEach(function(v){if(v){var O=v.split("="),x=O.shift().replace(/\+/g," "),D=O.join("=").replace(/\+/g," ");w.append(decodeURIComponent(x),decodeURIComponent(D))}}),w}function j(g){var w=new p,v=g.replace(/\r?\n[\t ]+/g," ");return v.split(/\r?\n/).forEach(function(O){var x=O.split(":"),D=x.shift().trim();if(D){var R=x.join(":").trim();w.append(D,R)}}),w}C.call(S.prototype);function T(g,w){w||(w={}),this.type="default",this.status=w.status===void 0?200:w.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in w?w.statusText:"OK",this.headers=new p(w.headers),this.url=w.url||"",this._initBody(g)}C.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},T.error=function(){var g=new T(null,{status:0,statusText:""});return g.type="error",g};var B=[301,302,303,307,308];T.redirect=function(g,w){if(B.indexOf(w)===-1)throw new RangeError("Invalid status code");return new T(null,{status:w,headers:{location:g}})},o.DOMException=n.DOMException;try{new o.DOMException}catch{o.DOMException=function(w,v){this.message=w,this.name=v;var O=Error(w);this.stack=O.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function k(g,w){return new Promise(function(v,O){var x=new S(g,w);if(x.signal&&x.signal.aborted)return O(new o.DOMException("Aborted","AbortError"));var D=new XMLHttpRequest;function R(){D.abort()}D.onload=function(){var q={status:D.status,statusText:D.statusText,headers:j(D.getAllResponseHeaders()||"")};q.url="responseURL"in D?D.responseURL:q.headers.get("X-Request-URL");var L="response"in D?D.response:D.responseText;v(new T(L,q))},D.onerror=function(){O(new TypeError("Network request failed"))},D.ontimeout=function(){O(new TypeError("Network request failed"))},D.onabort=function(){O(new o.DOMException("Aborted","AbortError"))},D.open(x.method,x.url,!0),x.credentials==="include"?D.withCredentials=!0:x.credentials==="omit"&&(D.withCredentials=!1),"responseType"in D&&a.blob&&(D.responseType="blob"),x.headers.forEach(function(q,L){D.setRequestHeader(L,q)}),x.signal&&(x.signal.addEventListener("abort",R),D.onreadystatechange=function(){D.readyState===4&&x.signal.removeEventListener("abort",R)}),D.send(typeof x._bodyInit>"u"?null:x._bodyInit)})}return k.polyfill=!0,n.fetch||(n.fetch=k,n.Headers=p,n.Request=S,n.Response=T),o.Headers=p,o.Request=S,o.Response=T,o.fetch=k,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,r.exports=e}(di,di.exports)),di.exports}var W$=K$();const Au=wo(W$);var G$=Object.defineProperty,Y$=Object.defineProperties,J$=Object.getOwnPropertyDescriptors,xu=Object.getOwnPropertySymbols,Z$=Object.prototype.hasOwnProperty,Q$=Object.prototype.propertyIsEnumerable,Cu=(r,e,t)=>e in r?G$(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tu=(r,e)=>{for(var t in e)Z$.call(e,t)&&Cu(r,t,e[t]);if(xu)for(var t of xu(e))Q$.call(e,t)&&Cu(r,t,e[t]);return r},Ru=(r,e)=>Y$(r,J$(e));const X$={Accept:"application/json","Content-Type":"application/json"},eS="POST",Nu={headers:X$,method:eS},ju=10;class dt{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new Ye.EventEmitter,this.isAvailable=!1,this.registering=!1,!Jc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=t}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const t=Rt(e),i=await(await Au(this.url,Ru(Tu({},Nu),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Jc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const t=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=t||this.events.listenerCount("open")>=t)&&this.events.setMaxListeners(t+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 t=Rt({id:1,jsonrpc:"2.0",method:"test",params:[]});await Au(e,Ru(Tu({},Nu),{body:t}))}this.onOpen()}catch(t){const i=this.parseError(t);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 t=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=i.message||i.toString(),n=Cs(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return ql(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>ju&&this.events.setMaxListeners(ju)}}const Bu="error",tS="wss://relay.walletconnect.org",rS="wc",iS="universal_provider",Zi=`${rS}@2:${iS}:`,ud="https://rpc.walletconnect.org/v1/",Tr="generic",sS=`${ud}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function nS(){}function Mo(r){return r==null||typeof r!="object"&&typeof r!="function"}function zo(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function oS(r){if(Mo(r))return r;if(Array.isArray(r)||zo(r)||r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);const e=Object.getPrototypeOf(r),t=e.constructor;if(r instanceof Date||r instanceof Map||r instanceof Set)return new t(r);if(r instanceof RegExp){const i=new t(r);return i.lastIndex=r.lastIndex,i}if(r instanceof DataView)return new t(r.buffer.slice(0));if(r instanceof Error){const i=new t(r.message);return i.stack=r.stack,i.name=r.name,i.cause=r.cause,i}if(typeof File<"u"&&r instanceof File)return new t([r],r.name,{type:r.type,lastModified:r.lastModified});if(typeof r=="object"){const i=Object.create(e);return Object.assign(i,r)}return r}function Uu(r){return typeof r=="object"&&r!==null}function hd(r){return Object.getOwnPropertySymbols(r).filter(e=>Object.prototype.propertyIsEnumerable.call(r,e))}function ld(r){return r==null?r===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(r)}const aS="[object RegExp]",dd="[object String]",pd="[object Number]",fd="[object Boolean]",gd="[object Arguments]",cS="[object Symbol]",uS="[object Date]",hS="[object Map]",lS="[object Set]",dS="[object Array]",pS="[object ArrayBuffer]",fS="[object Object]",gS="[object DataView]",yS="[object Uint8Array]",mS="[object Uint8ClampedArray]",wS="[object Uint16Array]",bS="[object Uint32Array]",vS="[object Int8Array]",ES="[object Int16Array]",_S="[object Int32Array]",IS="[object Float32Array]",$S="[object Float64Array]";function SS(r,e){return jr(r,void 0,r,new Map,e)}function jr(r,e,t,i=new Map,s=void 0){const n=s==null?void 0:s(r,e,t,i);if(n!=null)return n;if(Mo(r))return r;if(i.has(r))return i.get(r);if(Array.isArray(r)){const o=new Array(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=jr(r[a],a,t,i,s);return Object.hasOwn(r,"index")&&(o.index=r.index),Object.hasOwn(r,"input")&&(o.input=r.input),o}if(r instanceof Date)return new Date(r.getTime());if(r instanceof RegExp){const o=new RegExp(r.source,r.flags);return o.lastIndex=r.lastIndex,o}if(r instanceof Map){const o=new Map;i.set(r,o);for(const[a,c]of r)o.set(a,jr(c,a,t,i,s));return o}if(r instanceof Set){const o=new Set;i.set(r,o);for(const a of r)o.add(jr(a,void 0,t,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(r))return r.subarray();if(zo(r)){const o=new(Object.getPrototypeOf(r)).constructor(r.length);i.set(r,o);for(let a=0;a<r.length;a++)o[a]=jr(r[a],a,t,i,s);return o}if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer)return r.slice(0);if(r instanceof DataView){const o=new DataView(r.buffer.slice(0),r.byteOffset,r.byteLength);return i.set(r,o),Qt(o,r,t,i,s),o}if(typeof File<"u"&&r instanceof File){const o=new File([r],r.name,{type:r.type});return i.set(r,o),Qt(o,r,t,i,s),o}if(r instanceof Blob){const o=new Blob([r],{type:r.type});return i.set(r,o),Qt(o,r,t,i,s),o}if(r instanceof Error){const o=new r.constructor;return i.set(r,o),o.message=r.message,o.name=r.name,o.stack=r.stack,o.cause=r.cause,Qt(o,r,t,i,s),o}if(typeof r=="object"&&DS(r)){const o=Object.create(Object.getPrototypeOf(r));return i.set(r,o),Qt(o,r,t,i,s),o}return r}function Qt(r,e,t=r,i,s){const n=[...Object.keys(e),...hd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(r,a);(c==null||c.writable)&&(r[a]=jr(e[a],a,t,i,s))}}function DS(r){switch(ld(r)){case gd:case dS:case pS:case gS:case fd:case uS:case IS:case $S:case vS:case ES:case _S:case hS:case pd:case fS:case aS:case lS:case dd:case cS:case yS:case mS:case wS:case bS:return!0;default:return!1}}function PS(r,e){return SS(r,(t,i,s,n)=>{if(typeof r=="object")switch(Object.prototype.toString.call(r)){case pd:case dd:case fd:{const o=new r.constructor(r==null?void 0:r.valueOf());return Qt(o,r),o}case gd:{const o={};return Qt(o,r),o.length=r.length,o[Symbol.iterator]=r[Symbol.iterator],o}default:return}})}function Fu(r){return PS(r)}function qu(r){return r!==null&&typeof r=="object"&&ld(r)==="[object Arguments]"}function OS(r){return zo(r)}function AS(r){var t;if(typeof r!="object"||r==null)return!1;if(Object.getPrototypeOf(r)===null)return!0;if(Object.prototype.toString.call(r)!=="[object Object]"){const i=r[Symbol.toStringTag];return i==null||!((t=Object.getOwnPropertyDescriptor(r,Symbol.toStringTag))!=null&&t.writable)?!1:r.toString()===`[object ${i}]`}let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}function xS(r,...e){const t=e.slice(0,-1),i=e[e.length-1];let s=r;for(let n=0;n<t.length;n++){const o=t[n];s=lo(s,o,i,new Map)}return s}function lo(r,e,t,i){if(Mo(r)&&(r=Object(r)),e==null||typeof e!="object")return r;if(i.has(e))return oS(i.get(e));if(i.set(e,r),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),...hd(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=r[o];if(qu(a)&&(a={...a}),qu(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=Fu(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const h=[],l=Reflect.ownKeys(c);for(let d=0;d<l.length;d++){const f=l[d];h[f]=c[f]}c=h}else c=[];const u=t(c,a,o,r,e,i);u!=null?r[o]=u:Array.isArray(a)||Uu(c)&&Uu(a)?r[o]=lo(c,a,t,i):c==null&&AS(a)?r[o]=lo({},a,t,i):c==null&&OS(a)?r[o]=Fu(a):(c===void 0||a!==void 0)&&(r[o]=a)}return r}function CS(r,...e){return xS(r,...e,nS)}var TS=Object.defineProperty,RS=Object.defineProperties,NS=Object.getOwnPropertyDescriptors,Lu=Object.getOwnPropertySymbols,jS=Object.prototype.hasOwnProperty,BS=Object.prototype.propertyIsEnumerable,ku=(r,e,t)=>e in r?TS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Qi=(r,e)=>{for(var t in e||(e={}))jS.call(e,t)&&ku(r,t,e[t]);if(Lu)for(var t of Lu(e))BS.call(e,t)&&ku(r,t,e[t]);return r},US=(r,e)=>RS(r,NS(e));function Ge(r,e,t){var i;const s=Br(r);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${ud}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function lr(r){return r.includes(":")?r.split(":")[1]:r}function yd(r){return r.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function FS(r,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(r));if(!t.length)return[];const i=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function _n(r={},e={}){const t=Mu(r),i=Mu(e);return CS(t,i)}function Mu(r){var e,t,i,s;const n={};if(!Si(r))return n;for(const[o,a]of Object.entries(r)){const c=Bo(o)?[o]:a.chains,u=a.methods||[],h=a.events||[],l=a.rpcMap||{},d=hi(o);n[d]=US(Qi(Qi({},n[d]),a),{chains:rs(c,(e=n[d])==null?void 0:e.chains),methods:rs(u,(t=n[d])==null?void 0:t.methods),events:rs(h,(i=n[d])==null?void 0:i.events),rpcMap:Qi(Qi({},l),(s=n[d])==null?void 0:s.rpcMap)})}return n}function zu(r){return r.includes(":")?r.split(":")[2]:r}function Hu(r){const e={};for(const[t,i]of Object.entries(r)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=Bo(t)?[t]:i.chains?i.chains:yd(i.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function In(r){return typeof r=="number"?r:r.includes("0x")?parseInt(r,16):(r=r.includes(":")?r.split(":")[1]:r,isNaN(Number(r))?r:Number(r))}const md={},Q=r=>md[r],$n=(r,e)=>{md[r]=e};var qS=Object.defineProperty,LS=(r,e,t)=>e in r?qS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vr=(r,e,t)=>LS(r,typeof e!="symbol"?e+"":e,t);class kS{constructor(e){vr(this,"name","polkadot"),vr(this,"client"),vr(this,"httpProviders"),vr(this,"events"),vr(this,"namespace"),vr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=lr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var MS=Object.defineProperty,zS=Object.defineProperties,HS=Object.getOwnPropertyDescriptors,Vu=Object.getOwnPropertySymbols,VS=Object.prototype.hasOwnProperty,KS=Object.prototype.propertyIsEnumerable,po=(r,e,t)=>e in r?MS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ku=(r,e)=>{for(var t in e||(e={}))VS.call(e,t)&&po(r,t,e[t]);if(Vu)for(var t of Vu(e))KS.call(e,t)&&po(r,t,e[t]);return r},Wu=(r,e)=>zS(r,HS(e)),Er=(r,e,t)=>po(r,typeof e!="symbol"?e+"":e,t);class WS{constructor(e){Er(this,"name","eip155"),Er(this,"client"),Er(this,"chainId"),Er(this,"namespace"),Er(this,"httpProviders"),Er(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,t){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=parseInt(lr(t));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}async handleSwitchChain(e){var t,i;let s=e.request.params?(t=e.request.params[0])==null?void 0:t.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 t,i,s;const n=(i=(t=e.request)==null?void 0:t.params)==null?void 0:i[0];if(!n)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const o=this.client.session.get(e.topic),a=((s=o==null?void 0:o.sessionProperties)==null?void 0:s.capabilities)||{};if(a!=null&&a[n])return a==null?void 0:a[n];const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Wu(Ku({},o.sessionProperties||{}),{capabilities:Wu(Ku({},a||{}),{[n]:c})})})}catch(u){console.warn("Failed to update session with capabilities",u)}return c}async getCallStatus(e){var t,i;const s=this.client.session.get(e.topic),n=(t=s.sessionProperties)==null?void 0:t.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(kt("eth_getUserOperationReceipt",[(i=t.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,t){return`${sS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var GS=Object.defineProperty,YS=(r,e,t)=>e in r?GS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_r=(r,e,t)=>YS(r,typeof e!="symbol"?e+"":e,t);class JS{constructor(e){_r(this,"name","solana"),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=lr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var ZS=Object.defineProperty,QS=(r,e,t)=>e in r?ZS(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ir=(r,e,t)=>QS(r,typeof e!="symbol"?e+"":e,t);class XS{constructor(e){Ir(this,"name","cosmos"),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=lr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var eD=Object.defineProperty,tD=(r,e,t)=>e in r?eD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$r=(r,e,t)=>tD(r,typeof e!="symbol"?e+"":e,t);class rD{constructor(e){$r(this,"name","algorand"),$r(this,"client"),$r(this,"httpProviders"),$r(this,"events"),$r(this,"namespace"),$r(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var iD=Object.defineProperty,sD=(r,e,t)=>e in r?iD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Sr=(r,e,t)=>sD(r,typeof e!="symbol"?e+"":e,t);class nD{constructor(e){Sr(this,"name","cip34"),Sr(this,"client"),Sr(this,"httpProviders"),Sr(this,"events"),Sr(this,"namespace"),Sr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{const i=this.getCardanoRPCUrl(t),s=lr(t);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}getCardanoRPCUrl(e){const t=this.namespace.rpcMap;if(t)return t[e]}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var oD=Object.defineProperty,aD=(r,e,t)=>e in r?oD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>aD(r,typeof e!="symbol"?e+"":e,t);class cD{constructor(e){Dr(this,"name","elrond"),Dr(this,"client"),Dr(this,"httpProviders"),Dr(this,"events"),Dr(this,"namespace"),Dr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=lr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var uD=Object.defineProperty,hD=(r,e,t)=>e in r?uD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e,t)=>hD(r,typeof e!="symbol"?e+"":e,t);class lD{constructor(e){Pr(this,"name","multiversx"),Pr(this,"client"),Pr(this,"httpProviders"),Pr(this,"events"),Pr(this,"namespace"),Pr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;const s=lr(t);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var dD=Object.defineProperty,pD=(r,e,t)=>e in r?dD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Or=(r,e,t)=>pD(r,typeof e!="symbol"?e+"":e,t);class fD{constructor(e){Or(this,"name","near"),Or(this,"client"),Or(this,"httpProviders"),Or(this,"events"),Or(this,"namespace"),Or(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var i;e[t]=this.createHttpProvider(t,(i=this.namespace.rpcMap)==null?void 0:i[t])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var gD=Object.defineProperty,yD=(r,e,t)=>e in r?gD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e,t)=>yD(r,typeof e!="symbol"?e+"":e,t);class mD{constructor(e){Ar(this,"name","tezos"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,t){if(this.chainId=e,!this.httpProviders[e]){const i=t||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{e[t]=this.createHttpProvider(t)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var wD=Object.defineProperty,bD=(r,e,t)=>e in r?wD(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xr=(r,e,t)=>bD(r,typeof e!="symbol"?e+"":e,t);class vD{constructor(e){xr(this,"name",Tr),xr(this,"client"),xr(this,"httpProviders"),xr(this,"events"),xr(this,"namespace"),xr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(t=>t.split(":")[1]===this.chainId.toString()).map(t=>t.split(":")[2]))]:[]}createHttpProviders(){var e,t;const i={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=Br(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const t=this.httpProviders[e];if(typeof t>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return t}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var ED=Object.defineProperty,_D=Object.defineProperties,ID=Object.getOwnPropertyDescriptors,Gu=Object.getOwnPropertySymbols,$D=Object.prototype.hasOwnProperty,SD=Object.prototype.propertyIsEnumerable,fo=(r,e,t)=>e in r?ED(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Xi=(r,e)=>{for(var t in e||(e={}))$D.call(e,t)&&fo(r,t,e[t]);if(Gu)for(var t of Gu(e))SD.call(e,t)&&fo(r,t,e[t]);return r},Sn=(r,e)=>_D(r,ID(e)),Xe=(r,e,t)=>fo(r,typeof e!="symbol"?e+"":e,t);let DD=class wd{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new bo),Xe(this,"rpcProviders",{}),Xe(this,"session"),Xe(this,"providerOpts"),Xe(this,"logger"),Xe(this,"uri"),Xe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Ui(As({level:(e==null?void 0:e.logger)||Bu})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const t=new wd(e);return await t.initialize(),t}async request(e,t,i){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:Xi({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>t(null,xs(n,o))).catch(o=>t(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,t);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Hu(this.session.namespaces);this.namespaces=_n(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const n=Hu(s.namespaces);return this.namespaces=_n(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Tr?n.setDefaultChain(`${i}:${s}`,t):n.setDefaultChain(s,t)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(lt(t)){for(const i of t)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${t.length}`)}}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,t;if(this.client=this.providerOpts.client||await H$.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Bu,relayUrl:this.providerOpts.relayUrl||tS,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("Failed to get session",i),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.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(t=>hi(t)))];$n("client",this.client),$n("events",this.events),$n("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const i=FS(t,this.session),s=yd(i),n=_n(this.namespaces,this.optionalNamespaces),o=Sn(Xi({},n[t]),{accounts:i,chains:s});switch(t){case"eip155":this.rpcProviders[t]=new WS({namespace:o});break;case"algorand":this.rpcProviders[t]=new rD({namespace:o});break;case"solana":this.rpcProviders[t]=new JS({namespace:o});break;case"cosmos":this.rpcProviders[t]=new XS({namespace:o});break;case"polkadot":this.rpcProviders[t]=new kS({namespace:o});break;case"cip34":this.rpcProviders[t]=new nD({namespace:o});break;case"elrond":this.rpcProviders[t]=new cD({namespace:o});break;case"multiversx":this.rpcProviders[t]=new lD({namespace:o});break;case"near":this.rpcProviders[t]=new fD({namespace:o});break;case"tezos":this.rpcProviders[t]=new mD({namespace:o});break;default:this.rpcProviders[Tr]?this.rpcProviders[Tr].updateNamespace(o):this.rpcProviders[Tr]=new vD({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var t;const{topic:i}=e;i===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:i,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&lt(o)&&this.events.emit("accountsChanged",o.map(zu))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=hi(o),u=In(o)!==In(a)?`${c}:${In(a)}`:o;this.onChainChanged(u)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Sn(Xi({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})}),this.client.on("session_delete",async e=>{var t;e.topic===((t=this.session)==null?void 0:t.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Sn(Xi({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Tr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var t;this.getProvider(e).updateNamespace((t=this.session)==null?void 0:t.namespaces[e])})}setNamespaces(e){const{namespaces:t,optionalNamespaces:i,sessionProperties:s,scopedProperties:n}=e;t&&Object.keys(t).length&&(this.namespaces=t),i&&Object.keys(i).length&&(this.optionalNamespaces=i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map(o=>hi(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=hi(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,t=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();t||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:i}){var s,n;try{if(t===i)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(`${i}:`)).map(zu);if(!lt(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${Zi}/${e}${s}`,t)}async getFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Zi}/${e}${i}`)}async deleteFromStore(e){var t;const i=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Zi}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const t=await this.client.core.storage.getKeys();for(const i of t)i.startsWith(Zi)&&await this.client.core.storage.removeItem(i)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const PD=DD,OD="wc",AD="ethereum_provider",xD=`${OD}@2:${AD}:`,CD="https://rpc.walletconnect.org/v1/",go=["eth_sendTransaction","personal_sign"],TD=["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"],yo=["chainChanged","accountsChanged"],RD=["chainChanged","accountsChanged","message","disconnect","connect"];var ND=Object.defineProperty,jD=Object.defineProperties,BD=Object.getOwnPropertyDescriptors,Yu=Object.getOwnPropertySymbols,UD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,mo=(r,e,t)=>e in r?ND(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rr=(r,e)=>{for(var t in e||(e={}))UD.call(e,t)&&mo(r,t,e[t]);if(Yu)for(var t of Yu(e))FD.call(e,t)&&mo(r,t,e[t]);return r},Dn=(r,e)=>jD(r,BD(e)),ze=(r,e,t)=>mo(r,typeof e!="symbol"?e+"":e,t);function ws(r){return Number(r[0].split(":")[1])}function es(r){return`0x${r.toString(16)}`}function qD(r){const{chains:e,optionalChains:t,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=r;if(!lt(e))throw new Error("Invalid chains");const c={chains:e,methods:i||go,events:n||yo,rpcMap:Rr({},e.length?{[ws(e)]:a[ws(e)]}:{})},u=n==null?void 0:n.filter(f=>!yo.includes(f)),h=i==null?void 0:i.filter(f=>!go.includes(f));if(!t&&!o&&!s&&!(u!=null&&u.length)&&!(h!=null&&h.length))return{required:e.length?c:void 0};const l=(u==null?void 0:u.length)&&(h==null?void 0:h.length)||!t,d={chains:[...new Set(l?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:TD))],events:[...new Set(c.events.concat(o!=null&&o.length?o:RD))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class Ho{constructor(){ze(this,"events",new Ye.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",xD),ze(this,"on",(e,t)=>(this.events.on(e,t),this)),ze(this,"once",(e,t)=>(this.events.once(e,t),this)),ze(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),ze(this,"off",(e,t)=>(this.events.off(e,t),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Ho;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!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){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=qD(this.rpc);try{const s=await new Promise(async(o,a)=>{var c;this.rpc.showQrModal&&((c=this.modal)==null||c.subscribeModal(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(Dn(Rr({namespaces:Rr({},t&&{[this.namespace]:t})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(h=>{o(h)}).catch(h=>{a(new Error(h.message))})});if(!s)return;const n=Ha(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:es(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{this.modal&&this.modal.closeModal()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const i=await new Promise(async(n,o)=>{var a;this.rpc.showQrModal&&((a=this.modal)==null||a.subscribeModal(c=>{!c.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),o(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(Dn(Rr({},e),{chains:this.rpc.chains}),t).then(c=>{n(c)}).catch(c=>{o(new Error(c.message))})}),s=i.session;if(s){const n=Ha(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:n),this.setAccounts(n),this.events.emit("connect",{chainId:es(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{this.modal&&this.modal.closeModal()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:i}=t;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 t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",es(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",Dn(Rr({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{var t,i;this.rpc.showQrModal&&((t=this.modal)==null||t.closeModal(),(i=this.modal)==null||i.openModal({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 t=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",es(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(t=>this.parseChainId(this.parseAccountId(t).chainId)===this.chainId).map(t=>this.parseAccountId(t).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var t,i;const s=(t=e==null?void 0:e.chains)!=null?t:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||go:[],c=s.length?(e==null?void 0:e.events)||yo:[],u=(e==null?void 0:e.optionalMethods)||[],h=(e==null?void 0:e.optionalEvents)||[],l=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:u,optionalEvents:h,rpcMap:l,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,t)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?ws(this.rpc.chains):ws(this.rpc.optionalChains),this.signer=await PD.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 t;try{const{WalletConnectModal:i}=await Zu(()=>import("./index-PreWv3wh.js").then(s=>s.i),__vite__mapDeps([0,1,2]));t=i}catch{throw new Error("To use QR modal, please install @walletconnect/modal package")}if(t)try{this.modal=new t(Rr({projectId:this.rpc.projectId},this.rpc.qrModalOptions))}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&lt(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&lt(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,t){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${CD}?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t==null?void 0:t.accounts),this.setAccounts(t==null?void 0:t.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(t=>this.signer.logger.warn(t))}}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(t=>this.parseAccount(t))}}const SP=Ho;export{SP as EthereumProvider,RD as OPTIONAL_EVENTS,TD as OPTIONAL_METHODS,yo as REQUIRED_EVENTS,go as REQUIRED_METHODS,Ho as default};