1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/core-CYyOml1y.js","assets/index-Chd_Wa1n.js","assets/index-BUUZxY2d.css","assets/index-BbP3371Q.js"])))=>i.map(i=>d[i]); 2import{e7 as rt,e8 as Ud,_ as eu,dz as ge,e9 as st,dB as tu,ea as mi,eb as yo}from"./index-Chd_Wa1n.js";import{g as H}from"./index-BbP3371Q.js";import{c as Ld,a as kd,k as Fd,d as qd,s as Md,g as Yo}from"./index-nibyPLVP.js";import{r as zd}from"./browser-ponyfill-CEp-GVeJ.js";var Jo=function(i,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,n;r<s;r++)(n||!(r in e))&&(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return i.concat(n||Array.prototype.slice.call(e))},Hd=(function(){function i(e,t,r){this.name=e,this.version=t,this.os=r,this.type="browser"}return i})(),Vd=(function(){function i(e){this.version=e,this.type="node",this.name="node",this.os=rt.platform}return i})(),Kd=(function(){function i(e,t,r,s){this.name=e,this.version=t,this.os=r,this.bot=s,this.type="bot-device"}return i})(),Wd=(function(){function i(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return i})(),Gd=(function(){function i(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return i})(),Yd=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Jd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Zo=3,Zd=[["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",Yd]],Qo=[["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 Qd(i){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Gd:typeof navigator<"u"?ep(navigator.userAgent):ip()}function Xd(i){return i!==""&&Zd.reduce(function(e,t){var r=t[0],s=t[1];if(e)return e;var n=s.exec(i);return!!n&&[r,n]},!1)}function ep(i){var e=Xd(i);if(!e)return null;var t=e[0],r=e[1];if(t==="searchbot")return new Wd;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length<Zo&&(s=Jo(Jo([],s,!0),rp(Zo-s.length),!0)):s=[];var n=s.join("."),o=tp(i),a=Jd.exec(i);return a&&a[1]?new Kd(t,n,o,a[1]):new Hd(t,n,o)}function tp(i){for(var e=0,t=Qo.length;e<t;e++){var r=Qo[e],s=r[0],n=r[1],o=n.exec(i);if(o)return s}return null}function ip(){var i=typeof rt<"u"&&rt.version;return i?new Vd(rt.version.slice(1)):null}function rp(i){for(var e=[],t=0;t<i;t++)e.push("0");return e}var ks={};
vendor: 5,223 bytes, line 2
2var Pn=function(i,e){return Pn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)r.hasOwnProperty(s)&&(t[s]=r[s])},Pn(i,e)};function sp(i,e){Pn(i,e);function t(){this.constructor=i}i.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var An=function(){return An=Object.assign||function(e){for(var t,r=1,s=arguments.length;r<s;r++){t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},An.apply(this,arguments)};function np(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t}function op(i,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(i,e,t,r);else for(var a=i.length-1;a>=0;a--)(o=i[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 ap(i,e){return function(t,r){e(t,r,i)}}function cp(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}function hp(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(u){try{h(r.next(u))}catch(l){o(l)}}function c(u){try{h(r.throw(u))}catch(l){o(l)}}function h(u){u.done?n(u.value):s(u.value).then(a,c)}h((r=r.apply(i,e||[])).next())})}function up(i,e){var t={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},r,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,s&&(n=h[0]&2?s.return:h[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,h[1])).done)return n;switch(s=0,n&&(h=[h[0]&2,n.value]),h[0]){case 0:case 1:n=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(n=t.trys,!(n=n.length>0&&n[n.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!n||h[1]>n[0]&&h[1]<n[3])){t.label=h[1];break}if(h[0]===6&&t.label<n[1]){t.label=n[1],n=h;break}if(n&&t.label<n[2]){t.label=n[2],t.ops.push(h);break}n[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(i,t)}catch(u){h=[6,u],s=0}finally{r=n=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function lp(i,e,t,r){r===void 0&&(r=t),i[r]=e[t]}function dp(i,e){for(var t in i)t!=="default"&&!e.hasOwnProperty(t)&&(e[t]=i[t])}function xn(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],r=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&r>=i.length&&(i=void 0),{value:i&&i[r++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function iu(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var r=t.call(i),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return n}function pp(){for(var i=[],e=0;e<arguments.length;e++)i=i.concat(iu(arguments[e]));return i}function fp(){for(var i=0,e=0,t=arguments.length;e<t;e++)i+=arguments[e].length;for(var r=Array(i),s=0,e=0;e<t;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)r[s]=n[o];return r}function _r(i){return this instanceof _r?(this.v=i,this):new _r(i)}function gp(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){r[d]&&(s[d]=function(f){return new Promise(function(p,g){n.push([d,f,p,g])>1||a(d,f)})})}function a(d,f){try{c(r[d](f))}catch(p){l(n[0][3],p)}}function c(d){d.value instanceof _r?Promise.resolve(d.value.v).then(h,u):l(n[0][2],d)}function h(d){a("next",d)}function u(d){a("throw",d)}function l(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function yp(i){var e,t;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,n){e[s]=i[s]?function(o){return(t=!t)?{value:_r(i[s](o)),done:s==="return"}:n?n(o):o}:n}}function mp(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof xn=="function"?xn(i):i[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=i[n]&&function(o){return new Promise(function(a,c){o=i[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(h){n({value:h,done:a})},o)}}function wp(i,e){return Object.defineProperty?Object.defineProperty(i,"raw",{value:e}):i.raw=e,i}function bp(i){if(i&&i.__esModule)return i;var e={};
2if(i!=null)for(var t in i)Object.hasOwnProperty.call(i,t)&&(e[t]=i[t]);return e.default=i,e}function vp(i){return i&&i.__esModule?i:{default:i}}function Ep(i,e){if(!e.has(i))throw new TypeError("attempted to get private field on non-instance");return e.get(i)}function _p(i,e,t){if(!e.has(i))throw new TypeError("attempted to set private field on non-instance");return e.set(i,t),t}const Ip=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return An},__asyncDelegator:yp,__asyncGenerator:gp,__asyncValues:mp,__await:_r,__awaiter:hp,__classPrivateFieldGet:Ep,__classPrivateFieldSet:_p,__createBinding:lp,__decorate:op,__exportStar:dp,__extends:sp,__generator:up,__importDefault:vp,__importStar:bp,__makeTemplateObject:wp,__metadata:cp,__param:ap,__read:iu,__rest:np,__spread:pp,__spreadArrays:fp,__values:xn},Symbol.toStringTag,{value:"Module"})),Ar=Ud(Ip);var Fs={},tr={},Xo;function $p(){if(Xo)return tr;Xo=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.delay=void 0;function i(e){return new Promise(t=>{setTimeout(()=>{t(!0)},e)})}return tr.delay=i,tr}var Yt={},qs={},Jt={},ea;function Sp(){return ea||(ea=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.ONE_THOUSAND=Jt.ONE_HUNDRED=void 0,Jt.ONE_HUNDRED=100,Jt.ONE_THOUSAND=1e3),Jt}var Ms={},ta;function Dp(){return ta||(ta=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.ONE_YEAR=i.FOUR_WEEKS=i.THREE_WEEKS=i.TWO_WEEKS=i.ONE_WEEK=i.THIRTY_DAYS=i.SEVEN_DAYS=i.FIVE_DAYS=i.THREE_DAYS=i.ONE_DAY=i.TWENTY_FOUR_HOURS=i.TWELVE_HOURS=i.SIX_HOURS=i.THREE_HOURS=i.ONE_HOUR=i.SIXTY_MINUTES=i.THIRTY_MINUTES=i.TEN_MINUTES=i.FIVE_MINUTES=i.ONE_MINUTE=i.SIXTY_SECONDS=i.THIRTY_SECONDS=i.TEN_SECONDS=i.FIVE_SECONDS=i.ONE_SECOND=void 0,i.ONE_SECOND=1,i.FIVE_SECONDS=5,i.TEN_SECONDS=10,i.THIRTY_SECONDS=30,i.SIXTY_SECONDS=60,i.ONE_MINUTE=i.SIXTY_SECONDS,i.FIVE_MINUTES=i.ONE_MINUTE*5,i.TEN_MINUTES=i.ONE_MINUTE*10,i.THIRTY_MINUTES=i.ONE_MINUTE*30,i.SIXTY_MINUTES=i.ONE_MINUTE*60,i.ONE_HOUR=i.SIXTY_MINUTES,i.THREE_HOURS=i.ONE_HOUR*3,i.SIX_HOURS=i.ONE_HOUR*6,i.TWELVE_HOURS=i.ONE_HOUR*12,i.TWENTY_FOUR_HOURS=i.ONE_HOUR*24,i.ONE_DAY=i.TWENTY_FOUR_HOURS,i.THREE_DAYS=i.ONE_DAY*3,i.FIVE_DAYS=i.ONE_DAY*5,i.SEVEN_DAYS=i.ONE_DAY*7,i.THIRTY_DAYS=i.ONE_DAY*30,i.ONE_WEEK=i.SEVEN_DAYS,i.TWO_WEEKS=i.ONE_WEEK*2,i.THREE_WEEKS=i.ONE_WEEK*3,i.FOUR_WEEKS=i.ONE_WEEK*4,i.ONE_YEAR=i.ONE_DAY*365})(Ms)),Ms}var ia;function ru(){return ia||(ia=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=Ar;e.__exportStar(Sp(),i),e.__exportStar(Dp(),i)})(qs)),qs}var ra;function Op(){if(ra)return Yt;ra=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.fromMiliseconds=Yt.toMiliseconds=void 0;const i=ru();function e(r){return r*i.ONE_THOUSAND}Yt.toMiliseconds=e;function t(r){return Math.floor(r/i.ONE_THOUSAND)}return Yt.fromMiliseconds=t,Yt}var sa;function Pp(){return sa||(sa=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=Ar;e.__exportStar($p(),i),e.__exportStar(Op(),i)})(Fs)),Fs}var wi={},na;function Ap(){if(na)return wi;na=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.Watch=void 0;class i{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 r=this.get(t);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${t}`);const s=Date.now()-r.started;this.timestamps.set(t,{started:r.started,elapsed:s})}get(t){const r=this.timestamps.get(t);if(typeof r>"u")throw new Error(`No timestamp found for label: ${t}`);return r}elapsed(t){const r=this.get(t);return r.elapsed||Date.now()-r.started}}return wi.Watch=i,wi.default=i,wi}var zs={},ir={},oa;function xp(){if(oa)return ir;oa=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.IWatch=void 0;class i{}return ir.IWatch=i,ir}var aa;function Cp(){return aa||(aa=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),Ar.__exportStar(xp(),i)})(zs)),zs}var ca;function Rp(){return ca||(ca=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=Ar;e.__exportStar(Pp(),i),e.__exportStar(Ap(),i),e.__exportStar(Cp(),i),e.__exportStar(ru(),i)})(ks)),ks}var U=Rp(),re={},ha;
2function su(){if(ha)return re;ha=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 i(d){let f;return typeof window<"u"&&typeof window[d]<"u"&&(f=window[d]),f}re.getFromWindow=i;function e(d){const f=i(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 r(){return i("document")}re.getDocument=r;function s(){return e("navigator")}re.getNavigatorOrThrow=s;function n(){return i("navigator")}re.getNavigator=n;function o(){return e("location")}re.getLocationOrThrow=o;function a(){return i("location")}re.getLocation=a;function c(){return e("crypto")}re.getCryptoOrThrow=c;function h(){return i("crypto")}re.getCrypto=h;function u(){return e("localStorage")}re.getLocalStorageOrThrow=u;function l(){return i("localStorage")}return re.getLocalStorage=l,re}var Ut=su(),rr={},ua;function Np(){if(ua)return rr;ua=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.getWindowMetadata=void 0;const i=su();function e(){let t,r;try{t=i.getDocumentOrThrow(),r=i.getLocationOrThrow()}catch{return null}function s(){const f=t.getElementsByTagName("link"),p=[];for(let g=0;g<f.length;g++){const y=f[g],b=y.getAttribute("rel");if(b&&b.toLowerCase().indexOf("icon")>-1){const m=y.getAttribute("href");if(m)if(m.toLowerCase().indexOf("https:")===-1&&m.toLowerCase().indexOf("http:")===-1&&m.indexOf("//")!==0){let v=r.protocol+"//"+r.host;if(m.indexOf("/")===0)v+=m;else{const O=r.pathname.split("/");O.pop();const x=O.join("/");v+=x+"/"+m}p.push(v)}else if(m.indexOf("//")===0){const v=r.protocol+m;p.push(v)}else p.push(m)}}return p}function n(...f){const p=t.getElementsByTagName("meta");for(let g=0;g<p.length;g++){const y=p[g],b=["itemprop","property","name"].map(m=>y.getAttribute(m)).filter(m=>m?f.includes(m):!1);if(b.length&&b){const m=y.getAttribute("content");if(m)return m}}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(),h=a(),u=r.origin,l=s();return{description:h,url:u,icons:l,name:c}}return rr.getWindowMetadata=e,rr}var Tp=Np();function Ir(i,{strict:e=!0}={}){return!i||typeof i!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(i):i.startsWith("0x")}function la(i){return Ir(i,{strict:!1})?Math.ceil((i.length-2)/2):i.length}const nu="2.23.2";let Hs={getDocsUrl:({docsBaseUrl:i,docsPath:e="",docsSlug:t})=>e?`${i??"https://viem.sh"}${e}${t?`#${t}`:""}`:void 0,version:`viem@${nu}`};class ci extends Error{constructor(e,t={}){const r=t.cause instanceof ci?t.cause.details:t.cause?.message?t.cause.message:t.details,s=t.cause instanceof ci&&t.cause.docsPath||t.docsPath,n=Hs.getDocsUrl?.({...t,docsPath:s}),o=[e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Hs.version?[`Version: ${Hs.version}`]:[]].join(` 3`);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=r,this.docsPath=s,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=nu}walk(e){return ou(this,e)}}function ou(i,e){return e?.(i)?i:i&&typeof i=="object"&&"cause"in i&&i.cause!==void 0?ou(i.cause,e):e?null:i}class au extends ci{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function Gi(i,{dir:e,size:t=32}={}){return typeof i=="string"?jp(i,{dir:e,size:t}):Bp(i,{dir:e,size:t})}function jp(i,{dir:e,size:t=32}={}){if(t===null)return i;const r=i.replace("0x","");if(r.length>t*2)throw new au({size:Math.ceil(r.length/2),targetSize:t,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](t*2,"0")}`}function Bp(i,{dir:e,size:t=32}={}){if(t===null)return i;if(i.length>t)throw new au({size:i.length,targetSize:t,type:"bytes"});
3const r=new Uint8Array(t);for(let s=0;s<t;s++){const n=e==="right";r[n?s:t-s-1]=i[n?s:i.length-s-1]}return r}class Up extends ci{constructor({max:e,min:t,signed:r,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class Lp extends ci{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Yi(i,{size:e}){if(la(i)>e)throw new Lp({givenSize:la(i),maxSize:e})}function Cn(i,e={}){const{signed:t}=e;e.size&&Yi(i,{size:e.size});const r=BigInt(i);if(!t)return r;const s=(i.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function kp(i,e={}){return Number(Cn(i,e))}const Fp=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Rn(i,e={}){return typeof i=="number"||typeof i=="bigint"?hu(i,e):typeof i=="string"?zp(i,e):typeof i=="boolean"?qp(i,e):cu(i,e)}function qp(i,e={}){const t=`0x${Number(i)}`;return typeof e.size=="number"?(Yi(t,{size:e.size}),Gi(t,{size:e.size})):t}function cu(i,e={}){let t="";for(let s=0;s<i.length;s++)t+=Fp[i[s]];const r=`0x${t}`;return typeof e.size=="number"?(Yi(r,{size:e.size}),Gi(r,{dir:"right",size:e.size})):r}function hu(i,e={}){const{signed:t,size:r}=e,s=BigInt(i);let n;r?t?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof i=="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 i=="bigint"?"n":"";throw new Up({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:t,size:r,value:`${i}${c}`})}const a=`0x${(t&&s<0?(1n<<BigInt(r*8))+BigInt(s):s).toString(16)}`;return r?Gi(a,{size:r}):a}const Mp=new TextEncoder;function zp(i,e={}){const t=Mp.encode(i);return cu(t,e)}const Hp=new TextEncoder;function Vp(i,e={}){return typeof i=="number"||typeof i=="bigint"?Wp(i,e):typeof i=="boolean"?Kp(i,e):Ir(i)?uu(i,e):lu(i,e)}function Kp(i,e={}){const t=new Uint8Array(1);return t[0]=Number(i),typeof e.size=="number"?(Yi(t,{size:e.size}),Gi(t,{size:e.size})):t}const Dt={zero:48,nine:57,A:65,F:70,a:97,f:102};function da(i){if(i>=Dt.zero&&i<=Dt.nine)return i-Dt.zero;if(i>=Dt.A&&i<=Dt.F)return i-(Dt.A-10);if(i>=Dt.a&&i<=Dt.f)return i-(Dt.a-10)}function uu(i,e={}){let t=i;e.size&&(Yi(t,{size:e.size}),t=Gi(t,{dir:"right",size:e.size}));let r=t.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=da(r.charCodeAt(a++)),h=da(r.charCodeAt(a++));if(c===void 0||h===void 0)throw new ci(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+h}return n}function Wp(i,e){const t=hu(i,e);return uu(t)}function lu(i,e={}){const t=Hp.encode(i);return typeof e.size=="number"?(Yi(t,{size:e.size}),Gi(t,{dir:"right",size:e.size})):t}function pa(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Gp(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function mo(i,...e){if(!Gp(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function fa(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Yp(i,e){mo(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const qr=BigInt(2**32-1),ga=BigInt(32);function Jp(i,e=!1){return e?{h:Number(i&qr),l:Number(i>>ga&qr)}:{h:Number(i>>ga&qr)|0,l:Number(i&qr)|0}}
3function Zp(i,e=!1){let t=new Uint32Array(i.length),r=new Uint32Array(i.length);for(let s=0;s<i.length;s++){const{h:n,l:o}=Jp(i[s],e);[t[s],r[s]]=[n,o]}return[t,r]}const Qp=(i,e,t)=>i<<t|e>>>32-t,Xp=(i,e,t)=>e<<t|i>>>32-t,ef=(i,e,t)=>e<<t-32|i>>>64-t,tf=(i,e,t)=>i<<t-32|e>>>64-t;function rf(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}const ya=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function sf(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function ma(i){for(let e=0;e<i.length;e++)i[e]=sf(i[e])}function nf(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function du(i){return typeof i=="string"&&(i=nf(i)),mo(i),i}class of{clone(){return this._cloneInto()}}function af(i){const e=r=>i().update(du(r)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}const pu=[],fu=[],gu=[],cf=BigInt(0),sr=BigInt(1),hf=BigInt(2),uf=BigInt(7),lf=BigInt(256),df=BigInt(113);for(let i=0,e=sr,t=1,r=0;i<24;i++){[t,r]=[r,(2*t+3*r)%5],pu.push(2*(5*r+t)),fu.push((i+1)*(i+2)/2%64);let s=cf;for(let n=0;n<7;n++)e=(e<<sr^(e>>uf)*df)%lf,e&hf&&(s^=sr<<(sr<<BigInt(n))-sr);gu.push(s)}const[pf,ff]=Zp(gu,!0),wa=(i,e,t)=>t>32?ef(i,e,t):Qp(i,e,t),ba=(i,e,t)=>t>32?tf(i,e,t):Xp(i,e,t);function gf(i,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],u=t[c+1],l=wa(h,u,1)^t[a],d=ba(h,u,1)^t[a+1];for(let f=0;f<50;f+=10)i[o+f]^=l,i[o+f+1]^=d}let s=i[2],n=i[3];for(let o=0;o<24;o++){const a=fu[o],c=wa(s,n,a),h=ba(s,n,a),u=pu[o];s=i[u],n=i[u+1],i[u]=c,i[u+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=pf[r],i[1]^=ff[r]}t.fill(0)}class wo extends of{constructor(e,t,r,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,pa(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=rf(this.state)}keccak(){ya||ma(this.state32),gf(this.state32,this.rounds),ya||ma(this.state32),this.posOut=0,this.pos=0}update(e){fa(this);const{blockLen:t,state:r}=this;e=du(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++)r[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:r,blockLen:s}=this;e[r]^=t,(t&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){fa(this,!1),mo(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(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 pa(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yp(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:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new wo(t,r,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const yf=(i,e,t)=>af(()=>new wo(e,i,t)),mf=yf(1,136,256/8);function yu(i,e){const t=e||"hex",r=mf(Ir(i,{strict:!1})?Vp(i):i);return t==="bytes"?r:Rn(r)}class wf 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 r=this.keys().next().value;r&&this.delete(r)}return this}}const Vs=new wf(8192);function bf(i,e){if(Vs.has(`${i}.${e}`))return Vs.get(`${i}.${e}`);const t=i.substring(2).toLowerCase(),r=yu(lu(t),"bytes"),s=t.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(r[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return Vs.set(`${i}.${e}`,n),n}function vf(i){const e=yu(`0x${i.substring(4)}`).substring(26);return bf(`0x${e}`)}async function Ef({hash:i,signature:e}){const t=Ir(i)?i:Rn(i),{secp256k1:r}=await eu(async()=>{const{secp256k1:o}=await import("./secp256k1-D7nWsfUE.js");return{secp256k1:o}},[]);return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:u,v:l,yParity:d}=e,f=Number(d??l),p=va(f);return new r.Signature(Cn(h),Cn(u)).addRecoveryBit(p)}const o=Ir(e)?e:Rn(e),a=kp(`0x${o.slice(130)}`),c=va(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(t.substring(2)).toHex(!1)}`}function va(i){if(i===0||i===1)return i;if(i===27)return 0;if(i===28)return 1;throw new Error("Invalid yParityOrV value")}async function _f({hash:i,signature:e}){return vf(await Ef({hash:i,signature:e}))}function If(i){if(i.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<i.length;h++){const u=i.charAt(h),l=u.charCodeAt(0);if(e[l]!==255)throw new TypeError(u+" is ambiguous");e[l]=h}const t=i.length,r=i.charAt(0),s=Math.log(t)/Math.log(256),n=Math.log(256)/Math.log(t);
3function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let u=0,l=0,d=0;const f=h.length;for(;d!==f&&h[d]===0;)d++,u++;const p=(f-d)*n+1>>>0,g=new Uint8Array(p);for(;d!==f;){let m=h[d],v=0;for(let O=p-1;(m!==0||v<l)&&O!==-1;O--,v++)m+=256*g[O]>>>0,g[O]=m%t>>>0,m=m/t>>>0;if(m!==0)throw new Error("Non-zero carry");l=v,d++}let y=p-l;for(;y!==p&&g[y]===0;)y++;let b=r.repeat(u);for(;y<p;++y)b+=i.charAt(g[y]);return b}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let u=0,l=0,d=0;for(;h[u]===r;)l++,u++;const f=(h.length-u)*s+1>>>0,p=new Uint8Array(f);for(;u<h.length;){const m=h.charCodeAt(u);if(m>255)return;let v=e[m];if(v===255)return;let O=0;for(let x=f-1;(v!==0||O<d)&&x!==-1;x--,O++)v+=t*p[x]>>>0,p[x]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");d=O,u++}let g=f-d;for(;g!==f&&p[g]===0;)g++;const y=new Uint8Array(l+(f-g));let b=l;for(;g!==f;)y[b++]=p[g++];return y}function c(h){const u=a(h);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var $f="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Sf=If($f);function Df(i){if(typeof i!="string")throw new Error(`Cannot safe json parse value of type ${typeof i}`);try{return JSON.parse(i)}catch{return i}}function Of(i){return typeof i=="string"?i:JSON.stringify(i)}function Pf(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function mu(i,...e){if(!Pf(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Ea(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Af(i,e){mu(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const bi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;const Ks=i=>new DataView(i.buffer,i.byteOffset,i.byteLength);function xf(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function wu(i){return typeof i=="string"&&(i=xf(i)),mu(i),i}let Cf=class{clone(){return this._cloneInto()}};function Rf(i){const e=r=>i().update(wu(r)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function bu(i=32){if(bi&&typeof bi.getRandomValues=="function")return bi.getRandomValues(new Uint8Array(i));if(bi&&typeof bi.randomBytes=="function")return bi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}function Nf(i,e,t,r){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=r?4:0,h=r?0:4;i.setUint32(e+c,o,r),i.setUint32(e+h,a,r)}let Tf=class extends Cf{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ks(this.buffer)}update(e){Ea(this);const{view:t,buffer:r,blockLen:s}=this;e=wu(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=Ks(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ea(this),Af(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)t[l]=0;Nf(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=Ks(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<h;l++)a.setUint32(4*l,u[l],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(r),e}};const Mr=BigInt(2**32-1),Nn=BigInt(32);function vu(i,e=!1){return e?{h:Number(i&Mr),l:Number(i>>Nn&Mr)}:{h:Number(i>>Nn&Mr)|0,l:Number(i&Mr)|0}}
3function jf(i,e=!1){let t=new Uint32Array(i.length),r=new Uint32Array(i.length);for(let s=0;s<i.length;s++){const{h:n,l:o}=vu(i[s],e);[t[s],r[s]]=[n,o]}return[t,r]}const Bf=(i,e)=>BigInt(i>>>0)<<Nn|BigInt(e>>>0),Uf=(i,e,t)=>i>>>t,Lf=(i,e,t)=>i<<32-t|e>>>t,kf=(i,e,t)=>i>>>t|e<<32-t,Ff=(i,e,t)=>i<<32-t|e>>>t,qf=(i,e,t)=>i<<64-t|e>>>t-32,Mf=(i,e,t)=>i>>>t-32|e<<64-t,zf=(i,e)=>e,Hf=(i,e)=>i,Vf=(i,e,t)=>i<<t|e>>>32-t,Kf=(i,e,t)=>e<<t|i>>>32-t,Wf=(i,e,t)=>e<<t-32|i>>>64-t,Gf=(i,e,t)=>i<<t-32|e>>>64-t;function Yf(i,e,t,r){const s=(e>>>0)+(r>>>0);return{h:i+t+(s/2**32|0)|0,l:s|0}}const Jf=(i,e,t)=>(i>>>0)+(e>>>0)+(t>>>0),Zf=(i,e,t,r)=>e+t+r+(i/2**32|0)|0,Qf=(i,e,t,r)=>(i>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Xf=(i,e,t,r,s)=>e+t+r+s+(i/2**32|0)|0,eg=(i,e,t,r,s)=>(i>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),tg=(i,e,t,r,s,n)=>e+t+r+s+n+(i/2**32|0)|0,W={fromBig:vu,split:jf,toBig:Bf,shrSH:Uf,shrSL:Lf,rotrSH:kf,rotrSL:Ff,rotrBH:qf,rotrBL:Mf,rotr32H:zf,rotr32L:Hf,rotlSH:Vf,rotlSL:Kf,rotlBH:Wf,rotlBL:Gf,add:Yf,add3L:Jf,add3H:Zf,add4L:Qf,add4H:Xf,add5H:tg,add5L:eg},[ig,rg]=W.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","0xf40e3585
35771202a","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(i=>BigInt(i))),Lt=new Uint32Array(80),kt=new Uint32Array(80);let sg=class extends Tf{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:r,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:h,El:u,Fh:l,Fl:d,Gh:f,Gl:p,Hh:g,Hl:y}=this;return[e,t,r,s,n,o,a,c,h,u,l,d,f,p,g,y]}set(e,t,r,s,n,o,a,c,h,u,l,d,f,p,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let v=0;v<16;v++,t+=4)Lt[v]=e.getUint32(t),kt[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){const O=Lt[v-15]|0,x=kt[v-15]|0,w=W.rotrSH(O,x,1)^W.rotrSH(O,x,8)^W.shrSH(O,x,7),_=W.rotrSL(O,x,1)^W.rotrSL(O,x,8)^W.shrSL(O,x,7),$=Lt[v-2]|0,I=kt[v-2]|0,j=W.rotrSH($,I,19)^W.rotrBH($,I,61)^W.shrSH($,I,6),T=W.rotrSL($,I,19)^W.rotrBL($,I,61)^W.shrSL($,I,6),B=W.add4L(_,T,kt[v-7],kt[v-16]),q=W.add4H(B,w,j,Lt[v-7],Lt[v-16]);Lt[v]=q|0,kt[v]=B|0}let{Ah:r,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:h,Dl:u,Eh:l,El:d,Fh:f,Fl:p,Gh:g,Gl:y,Hh:b,Hl:m}=this;for(let v=0;v<80;v++){const O=W.rotrSH(l,d,14)^W.rotrSH(l,d,18)^W.rotrBH(l,d,41),x=W.rotrSL(l,d,14)^W.rotrSL(l,d,18)^W.rotrBL(l,d,41),w=l&f^~l&g,_=d&p^~d&y,$=W.add5L(m,x,_,rg[v],kt[v]),I=W.add5H($,b,O,w,ig[v],Lt[v]),j=$|0,T=W.rotrSH(r,s,28)^W.rotrBH(r,s,34)^W.rotrBH(r,s,39),B=W.rotrSL(r,s,28)^W.rotrBL(r,s,34)^W.rotrBL(r,s,39),q=r&n^r&a^n&a,S=s&o^s&c^o&c;b=g|0,m=y|0,g=f|0,y=p|0,f=l|0,p=d|0,{h:l,l:d}=W.add(h|0,u|0,I|0,j|0),h=a|0,u=c|0,a=n|0,c=o|0,n=r|0,o=s|0;const D=W.add3L(j,B,S);r=W.add3H(D,I,T,q),s=D|0}({h:r,l:s}=W.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:n,l:o}=W.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=W.add(this.Ch|0,this.Cl|0,a|0,c|0),{h,l:u}=W.add(this.Dh|0,this.Dl|0,h|0,u|0),{h:l,l:d}=W.add(this.Eh|0,this.El|0,l|0,d|0),{h:f,l:p}=W.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:g,l:y}=W.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:b,l:m}=W.add(this.Hh|0,this.Hl|0,b|0,m|0),this.set(r,s,n,o,a,c,h,u,l,d,f,p,g,y,b,m)}roundClean(){Lt.fill(0),kt.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 ng=Rf(()=>new sg);const bo=BigInt(0),Eu=BigInt(1),og=BigInt(2);function vo(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Eo(i){if(!vo(i))throw new Error("Uint8Array expected")}function Ws(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const ag=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function _o(i){Eo(i);let e="";for(let t=0;t<i.length;t++)e+=ag[i[t]];return e}function _u(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?bo:BigInt("0x"+i)}const Ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function _a(i){if(i>=Ot._0&&i<=Ot._9)return i-Ot._0;if(i>=Ot.A&&i<=Ot.F)return i-(Ot.A-10);if(i>=Ot.a&&i<=Ot.f)return i-(Ot.a-10)}function Iu(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=_a(i.charCodeAt(n)),a=_a(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[s]=o*16+a}return r}function cg(i){return _u(_o(i))}function rs(i){return Eo(i),_u(_o(Uint8Array.from(i).reverse()))}function $u(i,e){return Iu(i.toString(16).padStart(e*2,"0"))}function Tn(i,e){return $u(i,e).reverse()}function Pt(i,e,t){let r;if(typeof e=="string")try{r=Iu(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(vo(e))r=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(i+" of length "+t+" expected, got "+s);return r}function Ia(...i){let e=0;for(let r=0;r<i.length;r++){const s=i[r];Eo(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<i.length;r++){const n=i[r];t.set(n,s),s+=n.length}return t}const Gs=i=>typeof i=="bigint"&&bo<=i;function hg(i,e,t){return Gs(i)&&Gs(e)&&Gs(t)&&e<=i&&i<t}function nr(i,e,t,r){if(!hg(e,t,r))throw new Error("expected valid "+i+": "+t+" <= n < "+r+", got "+e)}function ug(i){let e;for(e=0;i>bo;i>>=Eu,e+=1);return e}const lg=i=>(og<<BigInt(i-1))-Eu,dg={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||vo(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function Io(i,e,t={}){const r=(s,n,o)=>{const a=dg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[s];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(s)+" is invali
3d. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))r(s,n,!1);for(const[s,n]of Object.entries(t))r(s,n,!0);return i}function $a(i){const e=new WeakMap;return(t,...r)=>{const s=e.get(t);if(s!==void 0)return s;const n=i(t,...r);return e.set(t,n),n}}const Ee=BigInt(0),he=BigInt(1),ti=BigInt(2),pg=BigInt(3),jn=BigInt(4),Sa=BigInt(5),Da=BigInt(8);function fe(i,e){const t=i%e;return t>=Ee?t:e+t}function fg(i,e,t){if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(t<=Ee)throw new Error("invalid modulus");if(t===he)return Ee;let r=he;for(;e>Ee;)e&he&&(r=r*i%t),i=i*i%t,e>>=he;return r}function gt(i,e,t){let r=i;for(;e-- >Ee;)r*=r,r%=t;return r}function Oa(i,e){if(i===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let t=fe(i,e),r=e,s=Ee,n=he;for(;t!==Ee;){const o=r/t,a=r%t,c=s-n*o;r=t,t=a,s=n,n=c}if(r!==he)throw new Error("invert: does not exist");return fe(s,e)}function gg(i){const e=(i-he)/ti;let t,r,s;for(t=i-he,r=0;t%ti===Ee;t/=ti,r++);for(s=ti;s<i&&fg(s,e,i)!==i-he;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(i+he)/jn;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+he)/ti;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,h=o.pow(o.mul(o.ONE,s),t),u=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(h,he<<BigInt(c-d-1));h=o.sqr(f),u=o.mul(u,f),l=o.mul(l,h),c=d}return u}}function yg(i){if(i%jn===pg){const e=(i+he)/jn;return function(t,r){const s=t.pow(r,e);if(!t.eql(t.sqr(s),r))throw new Error("Cannot find square root");return s}}if(i%Da===Sa){const e=(i-Sa)/Da;return function(t,r){const s=t.mul(r,ti),n=t.pow(s,e),o=t.mul(r,n),a=t.mul(t.mul(o,ti),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),r))throw new Error("Cannot find square root");return c}}return gg(i)}const mg=(i,e)=>(fe(i,e)&he)===he,wg=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function bg(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=wg.reduce((r,s)=>(r[s]="function",r),e);return Io(i,t)}function vg(i,e,t){if(t<Ee)throw new Error("invalid exponent, negatives unsupported");if(t===Ee)return i.ONE;if(t===he)return e;let r=i.ONE,s=e;for(;t>Ee;)t&he&&(r=i.mul(r,s)),s=i.sqr(s),t>>=he;return r}function Eg(i,e){const t=new Array(e.length),r=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),s=i.inv(r);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),s),t}function Su(i,e){const t=e!==void 0?e:i.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Du(i,e,t=!1,r={}){if(i<=Ee)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:s,nByteLength:n}=Su(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:s,BYTES:n,MASK:lg(s),ZERO:Ee,ONE:he,create:c=>fe(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ee<=c&&c<i},is0:c=>c===Ee,isOdd:c=>(c&he)===he,neg:c=>fe(-c,i),eql:(c,h)=>c===h,sqr:c=>fe(c*c,i),add:(c,h)=>fe(c+h,i),sub:(c,h)=>fe(c-h,i),mul:(c,h)=>fe(c*h,i),pow:(c,h)=>vg(a,c,h),div:(c,h)=>fe(c*Oa(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Oa(c,i),sqrt:r.sqrt||(c=>(o||(o=yg(i)),o(a,c))),invertBatch:c=>Eg(a,c),cmov:(c,h,u)=>u?h:c,toBytes:c=>t?Tn(c,n):$u(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?rs(c):cg(c)}});return Object.freeze(a)}const Pa=BigInt(0),zr=BigInt(1);function Ys(i,e){const t=e.negate();return i?t:e}function Ou(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function Js(i,e){Ou(i,e);const t=Math.ceil(e/i)+1,r=2**(i-1);return{windows:t,windowSize:r}}function _g(i,e){if(!Array.isArray(i))throw new Error("array expected");
3i.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Ig(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}const Zs=new WeakMap,Pu=new WeakMap;function Qs(i){return Pu.get(i)||1}function $g(i,e){return{constTimeNegate:Ys,hasPrecomputes(t){return Qs(t)!==1},unsafeLadder(t,r,s=i.ZERO){let n=t;for(;r>Pa;)r&zr&&(s=s.add(n)),n=n.double(),r>>=zr;return s},precomputeWindow(t,r){const{windows:s,windowSize:n}=Js(r,e),o=[];let a=t,c=a;for(let h=0;h<s;h++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,r,s){const{windows:n,windowSize:o}=Js(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),u=2**t,l=BigInt(t);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&h);s>>=l,p>o&&(p-=u,s+=zr);const g=f,y=f+Math.abs(p)-1,b=d%2!==0,m=p<0;p===0?c=c.add(Ys(b,r[g])):a=a.add(Ys(m,r[y]))}return{p:a,f:c}},wNAFUnsafe(t,r,s,n=i.ZERO){const{windows:o,windowSize:a}=Js(t,e),c=BigInt(2**t-1),h=2**t,u=BigInt(t);for(let l=0;l<o;l++){const d=l*a;if(s===Pa)break;let f=Number(s&c);if(s>>=u,f>a&&(f-=h,s+=zr),f===0)continue;let p=r[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(t,r,s){let n=Zs.get(r);return n||(n=this.precomputeWindow(r,t),t!==1&&Zs.set(r,s(n))),n},wNAFCached(t,r,s){const n=Qs(t);return this.wNAF(n,this.getPrecomputes(n,t,s),r)},wNAFCachedUnsafe(t,r,s,n){const o=Qs(t);return o===1?this.unsafeLadder(t,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),r,n)},setWindowSize(t,r){Ou(r,e),Pu.set(t,r),Zs.delete(t)}}}function Sg(i,e,t,r){if(_g(t,i),Ig(r,e),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=i.ZERO,n=ug(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),h=Math.floor((e.BITS-1)/o)*o;let u=s;for(let l=h;l>=0;l-=o){c.fill(s);for(let f=0;f<r.length;f++){const p=r[f],g=Number(p>>BigInt(l)&BigInt(a));c[g]=c[g].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(u=u.add(d),l!==0)for(let f=0;f<o;f++)u=u.double()}return u}function Dg(i){return bg(i.Fp),Io(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Su(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}const at=BigInt(0),Ue=BigInt(1),Hr=BigInt(2),Og=BigInt(8),Pg={zip215:!0};function Ag(i){const e=Dg(i);return Io(i,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function xg(i){const e=Ag(i),{Fp:t,n:r,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,h=Hr<<BigInt(a*8)-Ue,u=t.create,l=Du(e.n,e.nBitLength),d=e.uvRatio||((D,E)=>{try{return{isValid:!0,value:t.sqrt(D*t.inv(E))}}catch{return{isValid:!1,value:at}}}),f=e.adjustScalarBytes||(D=>D),p=e.domain||((D,E,A)=>{if(Ws("phflag",A),E.length||A)throw new Error("Contexts/pre-hash are not supported");return D});function g(D,E){nr("coordinate "+D,E,at,h)}function y(D){if(!(D instanceof v))throw new Error("ExtendedPoint expected")}const b=$a((D,E)=>{const{ex:A,ey:C,ez:P}=D,R=D.is0();E==null&&(E=R?Og:t.inv(P));const k=u(A*E),F=u(C*E),M=u(P*E);if(R)return{x:at,y:Ue};if(M!==Ue)throw new Error("invZ was invalid");return{x:k,y:F}}),m=$a(D=>{const{a:E,d:A}=e;if(D.is0())throw new Error("bad point: ZERO");const{ex:C,ey:P,ez:R,et:k}=D,F=u(C*C),M=u(P*P),z=u(R*R),K=u(z*z),V=u(F*E),oe=u(z*u(V+M)),te=u(K+u(A*u(F*M)));if(oe!==te)throw new Error("bad point: equation left != right (1)");const J=u(C*P),Ce=u(R*k);if(J!==Ce)throw new Error("bad point: equation left != right (2)");return!0});class v{constructor(E,A,C,P){this.ex=E,this.ey=A,this.ez=C,this.et=P,g("x",E),g("y",A),g("z",C),g("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof v)throw new Error("extended point not allowed");const{x:A,y:C}=E||{};return g("x",A),g("y",C),new v(A,C,Ue,u(A*C))}static normalizeZ(E){const A=t.invertBatch(E.map(C=>C.ez));return E.map((C,P)=>C.toAffine(A[P])).map(v.fromAffine)}static msm(E,A){return Sg(v,l,E,A)}_setWindowSize(E){w.setWindowSize(this,E)}assertValidity(){m(this)}equals(E){y(E);const{ex:A,ey:C,ez:P}=this,{ex:R,ey:k,ez:F}=E,M=u(A*F),z=u(R*P),K=u(C*F),V=u(k*P);return M===z&&K===V}is0(){return this.equals(v.ZERO)}negate(){return new v(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:E}=e,{ex:A,ey:C,ez:P}=this,R=u(A*A),k=u(C*C),F=u(Hr*u(P*P)),M=u(E*R),z=A+C,K=u(u(z*z)-R-k),V=M+k,oe=V-F,te=M-k,J=u(K*oe),Ce=u(V*te),Ie=u(K*te),Ne=u(oe*V);return new v(J,Ce,Ne,Ie)}add(E){y(E);const{a:A,d:C}=e,{ex:P,ey:R,ez:k,et:F}=this,{ex:M,ey:z,ez:K,et:V}=E;if(A===BigInt(-1)){const Mo=u((R-P)*(z+M)),zo=u((R+P)*(z-M)),Ls=u(zo-Mo);if(Ls===at)return this.double();const Ho=u(k*Hr*V),Vo=u(F*Hr*K),Ko=Vo+Ho,Wo=zo+Mo,Go=Vo-Ho,Nd=u(Ko*Ls),Td=u(Wo*Go),jd=u(Ko*Go),Bd=u(Ls*Wo);return new v(Nd,Td,Bd,jd)}
3const oe=u(P*M),te=u(R*z),J=u(F*C*V),Ce=u(k*K),Ie=u((P+R)*(M+z)-oe-te),Ne=Ce-J,Ze=Ce+J,St=u(te-A*oe),yi=u(Ie*Ne),xd=u(Ze*St),Cd=u(Ie*St),Rd=u(Ne*Ze);return new v(yi,xd,Rd,Cd)}subtract(E){return this.add(E.negate())}wNAF(E){return w.wNAFCached(this,E,v.normalizeZ)}multiply(E){const A=E;nr("scalar",A,Ue,r);const{p:C,f:P}=this.wNAF(A);return v.normalizeZ([C,P])[0]}multiplyUnsafe(E,A=v.ZERO){const C=E;return nr("scalar",C,at,r),C===at?x:this.is0()||C===Ue?this:w.wNAFCachedUnsafe(this,C,v.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return w.unsafeLadder(this,r).is0()}toAffine(E){return b(this,E)}clearCofactor(){const{h:E}=e;return E===Ue?this:this.multiplyUnsafe(E)}static fromHex(E,A=!1){const{d:C,a:P}=e,R=t.BYTES;E=Pt("pointHex",E,R),Ws("zip215",A);const k=E.slice(),F=E[R-1];k[R-1]=F&-129;const M=rs(k),z=A?h:t.ORDER;nr("pointHex.y",M,at,z);const K=u(M*M),V=u(K-Ue),oe=u(C*K-P);let{isValid:te,value:J}=d(V,oe);if(!te)throw new Error("Point.fromHex: invalid y coordinate");const Ce=(J&Ue)===Ue,Ie=(F&128)!==0;if(!A&&J===at&&Ie)throw new Error("Point.fromHex: x=0 and x_0=1");return Ie!==Ce&&(J=u(-J)),v.fromAffine({x:J,y:M})}static fromPrivateKey(E){return I(E).point}toRawBytes(){const{x:E,y:A}=this.toAffine(),C=Tn(A,t.BYTES);return C[C.length-1]|=E&Ue?128:0,C}toHex(){return _o(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,Ue,u(e.Gx*e.Gy)),v.ZERO=new v(at,Ue,Ue,at);const{BASE:O,ZERO:x}=v,w=$g(v,a*8);function _(D){return fe(D,r)}function $(D){return _(rs(D))}function I(D){const E=t.BYTES;D=Pt("private key",D,E);const A=Pt("hashed private key",n(D),2*E),C=f(A.slice(0,E)),P=A.slice(E,2*E),R=$(C),k=O.multiply(R),F=k.toRawBytes();return{head:C,prefix:P,scalar:R,point:k,pointBytes:F}}function j(D){return I(D).pointBytes}function T(D=new Uint8Array,...E){const A=Ia(...E);return $(n(p(A,Pt("context",D),!!s)))}function B(D,E,A={}){D=Pt("message",D),s&&(D=s(D));const{prefix:C,scalar:P,pointBytes:R}=I(E),k=T(A.context,C,D),F=O.multiply(k).toRawBytes(),M=T(A.context,F,R,D),z=_(k+M*P);nr("signature.s",z,at,r);const K=Ia(F,Tn(z,t.BYTES));return Pt("result",K,t.BYTES*2)}const q=Pg;function S(D,E,A,C=q){const{context:P,zip215:R}=C,k=t.BYTES;D=Pt("signature",D,2*k),E=Pt("message",E),A=Pt("publicKey",A,k),R!==void 0&&Ws("zip215",R),s&&(E=s(E));const F=rs(D.slice(k,2*k));let M,z,K;try{M=v.fromHex(A,R),z=v.fromHex(D.slice(0,k),R),K=O.multiplyUnsafe(F)}catch{return!1}if(!R&&M.isSmallOrder())return!1;const V=T(P,z.toRawBytes(),M.toRawBytes(),E);return z.add(M.multiplyUnsafe(V)).subtract(K).clearCofactor().equals(v.ZERO)}return O._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:B,verify:S,ExtendedPoint:v,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>o(t.BYTES),precompute(D=8,E=v.BASE){return E._setWindowSize(D),E.multiply(BigInt(3)),E}}}}BigInt(0),BigInt(1);const $o=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Aa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Cg=BigInt(1),xa=BigInt(2);BigInt(3);const Rg=BigInt(5),Ng=BigInt(8);function Tg(i){const e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),n=$o,o=i*i%n*i%n,a=gt(o,xa,n)*o%n,c=gt(a,Cg,n)*i%n,h=gt(c,Rg,n)*c%n,u=gt(h,e,n)*h%n,l=gt(u,t,n)*u%n,d=gt(l,r,n)*l%n,f=gt(d,s,n)*d%n,p=gt(f,s,n)*d%n,g=gt(p,e,n)*h%n;return{pow_p_5_8:gt(g,xa,n)*i%n,b2:o}}function jg(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}function Bg(i,e){const t=$o,r=fe(e*e*e,t),s=fe(r*r*e,t),n=Tg(i*s).pow_p_5_8;let o=fe(i*r*n,t);const a=fe(e*o*o,t),c=o,h=fe(o*Aa,t),u=a===i,l=a===fe(-i,t),d=a===fe(-i*Aa,t);return u&&(o=c),(l||d)&&(o=h),mg(o,t)&&(o=fe(-o,t)),{isValid:u||l,value:o}}const Ug=Du($o,void 0,!0),Lg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ug,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ng,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ng,randomBytes:bu,adjustScalarBytes:jg,uvRatio:Bg},Au=xg(Lg),kg="EdDSA",Fg="JWT",us=".",_s="base64url",xu="utf8",Cu="utf8",qg=":",Mg="did",zg="key",Ca="base58btc",Hg="z",Vg="K36",Kg=32;function So(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function Ru(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?So(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}function Nu(i,e){e||(e=i.reduce((s,n)=>s+n.length,0));const t=Ru(e);let r=0;for(const s of i)t.set(s,r),r+=s.length;return So(t)}function Wg(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}
3var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),u=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 g=0,y=0,b=0,m=p.length;b!==m&&p[b]===0;)b++,g++;for(var v=(m-b)*u+1>>>0,O=new Uint8Array(v);b!==m;){for(var x=p[b],w=0,_=v-1;(x!==0||w<y)&&_!==-1;_--,w++)x+=256*O[_]>>>0,O[_]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=w,b++}for(var $=v-y;$!==v&&O[$]===0;)$++;for(var I=c.repeat(g);$<v;++$)I+=i.charAt(O[$]);return I}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,b=0;p[g]===c;)y++,g++;for(var m=(p.length-g)*h+1>>>0,v=new Uint8Array(m);p[g];){var O=t[p.charCodeAt(g)];if(O===255)return;for(var x=0,w=m-1;(O!==0||x<b)&&w!==-1;w--,x++)O+=a*v[w]>>>0,v[w]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,g++}if(p[g]!==" "){for(var _=m-b;_!==m&&v[_]===0;)_++;for(var $=new Uint8Array(y+(m-_)),I=y;_!==m;)$[I++]=v[_++];return $}}}function f(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var Gg=Wg,Yg=Gg;const Tu=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},Jg=i=>new TextEncoder().encode(i),Zg=i=>new TextDecoder().decode(i);let Qg=class{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Xg=class{constructor(e,t,r){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=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ju(this,e)}},ey=class{constructor(e){this.decoders=e}or(e){return ju(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const ju=(i,e)=>new ey({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});let ty=class{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new Qg(e,t,r),this.decoder=new Xg(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Is=({name:i,prefix:e,encode:t,decode:r})=>new ty(i,e,t,r),xr=({prefix:i,name:e,alphabet:t})=>{const{encode:r,decode:s}=Yg(t,e);return Is({prefix:i,name:e,encode:r,decode:n=>Tu(s(n))})},iy=(i,e,t,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[i[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},ry=(i,e,t)=>{const r=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),r)for(;n.length*t&7;)n+="=";return n},Pe=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>Is({prefix:e,name:i,encode(s){return ry(s,r,t)},decode(s){return iy(s,r,t,i)}}),sy=Is({prefix:"\0",name:"identity",encode:i=>Zg(i),decode:i=>Jg(i)});var ny=Object.freeze({__proto__:null,identity:sy});const oy=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ay=Object.freeze({__proto__:null,base2:oy});const cy=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hy=Object.freeze({__proto__:null,base8:cy});const uy=xr({prefix:"9",name:"base10",alphabet:"0123456789"});var ly=Object.freeze({__proto__:null,base10:uy});const dy=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),py=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fy=Object.freeze({__proto__:null,base16:dy,base16upper:py});const gy=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),yy=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),my=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wy=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),by=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vy=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ey=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),_y=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Iy=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $y=Object.freeze({__proto__:null,base32:gy,base32upper:yy,base32pad:my,base32padupper:wy,base32hex:by,base32hexupper:vy,base32hexpad:Ey,base32hexpadupper:_y,base32z:Iy});const Sy=xr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dy=xr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Oy=Object.freeze({__proto__:null,base36:Sy,base36upper:Dy});const Py=xr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ay=xr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xy=Object.freeze({__proto__:null,base58btc:Py,base58flickr:Ay});const Cy=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
3+/",bitsPerChar:6}),Ry=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ny=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ty=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jy=Object.freeze({__proto__:null,base64:Cy,base64pad:Ry,base64url:Ny,base64urlpad:Ty});const Bu=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),By=Bu.reduce((i,e,t)=>(i[t]=e,i),[]),Uy=Bu.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Ly(i){return i.reduce((e,t)=>(e+=By[t],e),"")}function ky(i){const e=[];for(const t of i){const r=Uy[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}const Fy=Is({prefix:"ð",name:"base256emoji",encode:Ly,decode:ky});var qy=Object.freeze({__proto__:null,base256emoji:Fy}),My=Uu,Ra=128,zy=-128,Hy=Math.pow(2,31);function Uu(i,e,t){e=e||[],t=t||0;for(var r=t;i>=Hy;)e[t++]=i&255|Ra,i/=128;for(;i&zy;)e[t++]=i&255|Ra,i>>>=7;return e[t]=i|0,Uu.bytes=t-r+1,e}var Vy=Bn,Ky=128,Na=127;function Bn(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw Bn.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&Na)<<s:(o&Na)*Math.pow(2,s),s+=7}while(o>=Ky);return Bn.bytes=n-r,t}var Wy=Math.pow(2,7),Gy=Math.pow(2,14),Yy=Math.pow(2,21),Jy=Math.pow(2,28),Zy=Math.pow(2,35),Qy=Math.pow(2,42),Xy=Math.pow(2,49),em=Math.pow(2,56),tm=Math.pow(2,63),im=function(i){return i<Wy?1:i<Gy?2:i<Yy?3:i<Jy?4:i<Zy?5:i<Qy?6:i<Xy?7:i<em?8:i<tm?9:10},rm={encode:My,decode:Vy,encodingLength:im},Lu=rm;const Ta=(i,e,t=0)=>(Lu.encode(i,e,t),e),ja=i=>Lu.encodingLength(i),Un=(i,e)=>{const t=e.byteLength,r=ja(i),s=r+ja(t),n=new Uint8Array(s+t);return Ta(i,n,0),Ta(t,n,r),n.set(e,s),new sm(i,t,e,n)};let sm=class{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}};const ku=({name:i,code:e,encode:t})=>new nm(i,e,t);let nm=class{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Un(this.code,t):t.then(r=>Un(this.code,r))}else throw Error("Unknown type, must be binary type")}};const Fu=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),om=ku({name:"sha2-256",code:18,encode:Fu("SHA-256")}),am=ku({name:"sha2-512",code:19,encode:Fu("SHA-512")});var cm=Object.freeze({__proto__:null,sha256:om,sha512:am});const qu=0,hm="identity",Mu=Tu,um=i=>Un(qu,Mu(i)),lm={code:qu,name:hm,encode:Mu,digest:um};var dm=Object.freeze({__proto__:null,identity:lm});new TextEncoder,new TextDecoder;const Ba={...ny,...ay,...hy,...ly,...fy,...$y,...Oy,...xy,...jy,...qy};({...cm,...dm});function zu(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}const Ua=zu("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),Xs=zu("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=Ru(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Hu={utf8:Ua,"utf-8":Ua,hex:Ba.base16,latin1:Xs,ascii:Xs,binary:Xs,...Ba};function $s(i,e="utf8"){const t=Hu[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(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}function Ji(i,e="utf8"){const t=Hu[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?So(globalThis.Buffer.from(i,"utf-8")):t.decoder.decode(`${t.prefix}${i}`)}function La(i){return Df($s(Ji(i,_s),xu))}function ls(i){return $s(Ji(Of(i),xu),_s)}function Vu(i){const e=Ji(Vg,Ca),t=Hg+$s(Nu([e,i]),Ca);return[Mg,zg,t].join(qg)}function pm(i){return $s(i,_s)}function fm(i){return Ji(i,_s)}function gm(i){return Ji([ls(i.header),ls(i.payload)].join(us),Cu)}function ym(i){return[ls(i.header),ls(i.payload),pm(i.signature)].join(us)}function Ln(i){const e=i.split(us),t=La(e[0]),r=La(e[1]),s=fm(e[2]),n=Ji(e.slice(0,2).join(us),Cu);return{header:t,payload:r,signature:s,data:n}}function ka(i=bu(Kg)){const e=Au.getPublicKey(i);return{secretKey:Nu([i,e]),publicKey:e}}async function mm(i,e,t,r,s=U.fromMiliseconds(Date.now())){const n={alg:kg,typ:Fg},o=Vu(r.publicKey),a=s+t,c={iss:o,sub:i,aud:e,iat:s,exp:a},h=gm({header:n,payload:c}),u=Au.sign(h,r.secretKey.slice(0,32));return ym({header:n,payload:c,signature:u})}function Ku(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function gr(i,e){e||(e=i.reduce((s,n)=>s+n.length,0));const t=Ku(e);let r=0;for(const s of i)t.set(s,r),r+=s.length;return t}function wm(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}
3var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),u=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 g=0,y=0,b=0,m=p.length;b!==m&&p[b]===0;)b++,g++;for(var v=(m-b)*u+1>>>0,O=new Uint8Array(v);b!==m;){for(var x=p[b],w=0,_=v-1;(x!==0||w<y)&&_!==-1;_--,w++)x+=256*O[_]>>>0,O[_]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=w,b++}for(var $=v-y;$!==v&&O[$]===0;)$++;for(var I=c.repeat(g);$<v;++$)I+=i.charAt(O[$]);return I}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,b=0;p[g]===c;)y++,g++;for(var m=(p.length-g)*h+1>>>0,v=new Uint8Array(m);p[g];){var O=t[p.charCodeAt(g)];if(O===255)return;for(var x=0,w=m-1;(O!==0||x<b)&&w!==-1;w--,x++)O+=a*v[w]>>>0,v[w]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,g++}if(p[g]!==" "){for(var _=m-b;_!==m&&v[_]===0;)_++;for(var $=new Uint8Array(y+(m-_)),I=y;_!==m;)$[I++]=v[_++];return $}}}function f(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var bm=wm,vm=bm;const Em=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},_m=i=>new TextEncoder().encode(i),Im=i=>new TextDecoder().decode(i);class $m{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Sm{constructor(e,t,r){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=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Wu(this,e)}}class Dm{constructor(e){this.decoders=e}or(e){return Wu(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Wu=(i,e)=>new Dm({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class Om{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new $m(e,t,r),this.decoder=new Sm(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ss=({name:i,prefix:e,encode:t,decode:r})=>new Om(i,e,t,r),Cr=({prefix:i,name:e,alphabet:t})=>{const{encode:r,decode:s}=vm(t,e);return Ss({prefix:i,name:e,encode:r,decode:n=>Em(s(n))})},Pm=(i,e,t,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[i[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Am=(i,e,t)=>{const r=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),r)for(;n.length*t&7;)n+="=";return n},Ae=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>Ss({prefix:e,name:i,encode(s){return Am(s,r,t)},decode(s){return Pm(s,r,t,i)}}),xm=Ss({prefix:"\0",name:"identity",encode:i=>Im(i),decode:i=>_m(i)}),Cm=Object.freeze(Object.defineProperty({__proto__:null,identity:xm},Symbol.toStringTag,{value:"Module"})),Rm=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base2:Rm},Symbol.toStringTag,{value:"Module"})),Tm=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),jm=Object.freeze(Object.defineProperty({__proto__:null,base8:Tm},Symbol.toStringTag,{value:"Module"})),Bm=Cr({prefix:"9",name:"base10",alphabet:"0123456789"}),Um=Object.freeze(Object.defineProperty({__proto__:null,base10:Bm},Symbol.toStringTag,{value:"Module"})),Lm=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),km=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Fm=Object.freeze(Object.defineProperty({__proto__:null,base16:Lm,base16upper:km},Symbol.toStringTag,{value:"Module"})),qm=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}
3),Mm=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zm=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hm=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vm=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Km=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wm=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gm=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ym=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Jm=Object.freeze(Object.defineProperty({__proto__:null,base32:qm,base32hex:Vm,base32hexpad:Wm,base32hexpadupper:Gm,base32hexupper:Km,base32pad:zm,base32padupper:Hm,base32upper:Mm,base32z:Ym},Symbol.toStringTag,{value:"Module"})),Zm=Cr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qm=Cr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base36:Zm,base36upper:Qm},Symbol.toStringTag,{value:"Module"})),ew=Cr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tw=Cr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),iw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:ew,base58flickr:tw},Symbol.toStringTag,{value:"Module"})),rw=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sw=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nw=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ow=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),aw=Object.freeze(Object.defineProperty({__proto__:null,base64:rw,base64pad:sw,base64url:nw,base64urlpad:ow},Symbol.toStringTag,{value:"Module"})),Gu=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),cw=Gu.reduce((i,e,t)=>(i[t]=e,i),[]),hw=Gu.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function uw(i){return i.reduce((e,t)=>(e+=cw[t],e),"")}function lw(i){const e=[];for(const t of i){const r=hw[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}const dw=Ss({prefix:"ð",name:"base256emoji",encode:uw,decode:lw}),pw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:dw},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Fa={...Cm,...Nm,...jm,...Um,...Fm,...Jm,...Xm,...iw,...aw,...pw};function Yu(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}const qa=Yu("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),en=Yu("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=Ku(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Ju={utf8:qa,"utf-8":qa,hex:Fa.base16,latin1:en,ascii:en,binary:en,...Fa};function it(i,e="utf8"){const t=Ju[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}function Me(i,e="utf8"){const t=Ju[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(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}const fw={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 gw={};const yw=":";function Fi(i){const[e,t]=i.split(yw);return{namespace:e,reference:t}}function Ma(i,e=[]){const t=[];
3return Object.keys(i).forEach(r=>{if(e.length&&!e.includes(r))return;const s=i[r];t.push(...s.accounts)}),t}function Zu(i,e){return i.includes(":")?[i]:e.chains||[]}var mw=Object.defineProperty,ww=Object.defineProperties,bw=Object.getOwnPropertyDescriptors,za=Object.getOwnPropertySymbols,vw=Object.prototype.hasOwnProperty,Ew=Object.prototype.propertyIsEnumerable,Ha=(i,e,t)=>e in i?mw(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Va=(i,e)=>{for(var t in e||(e={}))vw.call(e,t)&&Ha(i,t,e[t]);if(za)for(var t of za(e))Ew.call(e,t)&&Ha(i,t,e[t]);return i},_w=(i,e)=>ww(i,bw(e));const Iw="ReactNative",Ye={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},$w="js";function ds(){return typeof rt<"u"&&typeof rt.versions<"u"&&typeof rt.versions.node<"u"}function Gt(){return!Ut.getDocument()&&!!Ut.getNavigator()&&navigator.product===Iw}function Sw(){return Gt()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="android"}function Dw(){return Gt()&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"&&(H==null?void 0:H.Platform.OS)==="ios"}function Zi(){return!ds()&&!!Ut.getNavigator()&&!!Ut.getDocument()}function Rr(){return Gt()?Ye.reactNative:ds()?Ye.node:Zi()?Ye.browser:Ye.unknown}function Ka(){var i;try{return Gt()&&typeof H<"u"&&typeof(H==null?void 0:H.Application)<"u"?(i=H.Application)==null?void 0:i.applicationId:void 0}catch{return}}function Ow(i,e){const t=new URLSearchParams(i);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const s=e[r];s!==void 0&&t.set(r,s)}return t.toString()}function Pw(i){var e,t;const r=Qu();try{return i!=null&&i.url&&r.url&&new URL(i.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${i.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),i.url=r.url),(e=i?.icons)!=null&&e.length&&i.icons.length>0&&(i.icons=i.icons.filter(s=>s!=="")),_w(Va(Va({},r),i),{url:i?.url||r.url,name:i?.name||r.name,description:i?.description||r.description,icons:(t=i?.icons)!=null&&t.length&&i.icons.length>0?i.icons:r.icons})}catch(s){return console.warn("Error populating app metadata",s),i||r}}function Qu(){return Tp.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function Aw(){if(Rr()===Ye.reactNative&&typeof H<"u"&&typeof(H==null?void 0:H.Platform)<"u"){const{OS:t,Version:r}=H.Platform;return[t,r].join("-")}const i=Qd();if(i===null)return"unknown";const e=i.os?i.os.replace(" ","").toLowerCase():"unknown";return i.type==="browser"?[e,i.name,i.version].join("-"):[e,i.version].join("-")}function xw(){var i;const e=Rr();return e===Ye.browser?[e,((i=Ut.getLocation())==null?void 0:i.host)||"unknown"].join(":"):e}function Xu(i,e,t){const r=Aw(),s=xw();return[[i,e].join("-"),[$w,t].join("-"),r,s].join("/")}function Cw({protocol:i,version:e,relayUrl:t,sdkVersion:r,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=t.split("?"),u=Xu(i,e,r),l={auth:s,ua:u,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Ow(h[1]||"",l);return h[0]+"?"+d}function ni(i,e){return i.filter(t=>e.includes(t)).length===i.length}function kn(i){return Object.fromEntries(i.entries())}function Fn(i){return new Map(Object.entries(i))}function Xt(i=U.FIVE_MINUTES,e){const t=U.toMiliseconds(i||U.FIVE_MINUTES);let r,s,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},t),r=a,s=c})}}function Ht(i,e,t){return new Promise(async(r,s)=>{const n=setTimeout(()=>s(new Error(t)),e);try{const o=await i;r(o)}catch(o){s(o)}clearTimeout(n)})}function el(i,e){if(typeof e=="string"&&e.startsWith(`${i}:`))return e;if(i.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(i.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: ${i}`)}function Rw(i){return el("topic",i)}function Nw(i){return el("id",i)}function tl(i){const[e,t]=i.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof t=="string")r.topic=t;else if(e==="id"&&Number.isInteger(Number(t)))r.id=Number(t);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${t}`);return r}function pe(i,e){return U.fromMiliseconds(Date.now()+U.toMiliseconds(i))}function Mt(i){return Date.now()>=U.toMiliseconds(i)}function ee(i,e){return`${i}${e?`:${e}`:""}`}function It(i=[],e=[]){return[...new Set([...i,...e])]}async function Tw({id:i,topic:e,wcDeepLink:t}){var r;try{if(!t)return;const s=typeof t=="string"?JSON.parse(t):t,n=s?.href;
3if(typeof n!="string")return;const o=jw(n,i,e),a=Rr();if(a===Ye.browser){if(!((r=Ut.getDocument())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Bw(o)}else a===Ye.reactNative&&typeof(H==null?void 0:H.Linking)<"u"&&await H.Linking.openURL(o)}catch(s){console.error(s)}}function jw(i,e,t){const r=`requestId=${e}&sessionTopic=${t}`;i.endsWith("/")&&(i=i.slice(0,-1));let s=`${i}`;if(i.startsWith("https://t.me")){const n=i.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Fw(r,!0)}`}else s=`${s}/wc?${r}`;return s}function Bw(i){let e="_self";kw()?e="_top":(Lw()||i.startsWith("https://")||i.startsWith("http://"))&&(e="_blank"),window.open(i,e,"noreferrer noopener")}async function Uw(i,e){let t="";try{if(Zi()&&(t=localStorage.getItem(e),t))return t;t=await i.getItem(e)}catch(r){console.error(r)}return t}function Wa(i,e){if(!i.includes(e))return null;const t=i.split(/([&,?,=])/),r=t.indexOf(e);return t[r+2]}function Ga(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function Do(){return typeof rt<"u"&&gw.IS_VITEST==="true"}function Lw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function kw(){try{return window.self!==window.top}catch{return!1}}function Fw(i,e=!1){const t=ge.from(i).toString("base64");return e?t.replace(/[=]/g,""):t}function il(i){return ge.from(i,"base64").toString("utf-8")}function qw(i){return new Promise(e=>setTimeout(e,i))}function $r(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function Mw(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Nr(i,...e){if(!Mw(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function Oo(i){if(typeof i!="function"||typeof i.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");$r(i.outputLen),$r(i.blockLen)}function qi(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function rl(i,e){Nr(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const Vr=BigInt(2**32-1),Ya=BigInt(32);function zw(i,e=!1){return e?{h:Number(i&Vr),l:Number(i>>Ya&Vr)}:{h:Number(i>>Ya&Vr)|0,l:Number(i&Vr)|0}}
3function Hw(i,e=!1){let t=new Uint32Array(i.length),r=new Uint32Array(i.length);for(let s=0;s<i.length;s++){const{h:n,l:o}=zw(i[s],e);[t[s],r[s]]=[n,o]}return[t,r]}const Vw=(i,e,t)=>i<<t|e>>>32-t,Kw=(i,e,t)=>e<<t|i>>>32-t,Ww=(i,e,t)=>e<<t-32|i>>>64-t,Gw=(i,e,t)=>i<<t-32|e>>>64-t,vi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Yw(i){return new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4))}function tn(i){return new DataView(i.buffer,i.byteOffset,i.byteLength)}function yt(i,e){return i<<32-e|i>>>e}const Ja=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Jw(i){return i<<24&4278190080|i<<8&16711680|i>>>8&65280|i>>>24&255}function Za(i){for(let e=0;e<i.length;e++)i[e]=Jw(i[e])}function Zw(i){if(typeof i!="string")throw new Error("utf8ToBytes expected string, got "+typeof i);return new Uint8Array(new TextEncoder().encode(i))}function Mi(i){return typeof i=="string"&&(i=Zw(i)),Nr(i),i}function Qw(...i){let e=0;for(let r=0;r<i.length;r++){const s=i[r];Nr(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<i.length;r++){const n=i[r];t.set(n,s),s+=n.length}return t}let Po=class{clone(){return this._cloneInto()}};function sl(i){const e=r=>i().update(Mi(r)).digest(),t=i();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>i(),e}function Qi(i=32){if(vi&&typeof vi.getRandomValues=="function")return vi.getRandomValues(new Uint8Array(i));if(vi&&typeof vi.randomBytes=="function")return vi.randomBytes(i);throw new Error("crypto.getRandomValues must be defined")}const nl=[],ol=[],al=[],Xw=BigInt(0),or=BigInt(1),eb=BigInt(2),tb=BigInt(7),ib=BigInt(256),rb=BigInt(113);for(let i=0,e=or,t=1,r=0;i<24;i++){[t,r]=[r,(2*t+3*r)%5],nl.push(2*(5*r+t)),ol.push((i+1)*(i+2)/2%64);let s=Xw;for(let n=0;n<7;n++)e=(e<<or^(e>>tb)*rb)%ib,e&eb&&(s^=or<<(or<<BigInt(n))-or);al.push(s)}const[sb,nb]=Hw(al,!0),Qa=(i,e,t)=>t>32?Ww(i,e,t):Vw(i,e,t),Xa=(i,e,t)=>t>32?Gw(i,e,t):Kw(i,e,t);function ob(i,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)t[o]=i[o]^i[o+10]^i[o+20]^i[o+30]^i[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,h=t[c],u=t[c+1],l=Qa(h,u,1)^t[a],d=Xa(h,u,1)^t[a+1];for(let f=0;f<50;f+=10)i[o+f]^=l,i[o+f+1]^=d}let s=i[2],n=i[3];for(let o=0;o<24;o++){const a=ol[o],c=Qa(s,n,a),h=Xa(s,n,a),u=nl[o];s=i[u],n=i[u+1],i[u]=c,i[u+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)t[a]=i[o+a];for(let a=0;a<10;a++)i[o+a]^=~t[(a+2)%10]&t[(a+4)%10]}i[0]^=sb[r],i[1]^=nb[r]}t.fill(0)}let ab=class cl extends Po{constructor(e,t,r,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,$r(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Yw(this.state)}keccak(){Ja||Za(this.state32),ob(this.state32,this.rounds),Ja||Za(this.state32),this.posOut=0,this.pos=0}update(e){qi(this);const{blockLen:t,state:r}=this;e=Mi(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++)r[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:r,blockLen:s}=this;e[r]^=t,(t&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){qi(this,!1),Nr(e),this.finish();const t=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(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 $r(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(rl(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:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new cl(t,r,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const cb=(i,e,t)=>sl(()=>new ab(e,i,t)),hb=cb(1,136,256/8),ub="https://rpc.walletconnect.org/v1";function hl(i){const e=`�Ethereum Signed Message: 4${i.length}`,t=new TextEncoder().encode(e+i);return"0x"+ge.from(hb(t)).toString("hex")}async function lb(i,e,t,r,s,n){switch(t.t){case"eip191":return await db(i,e,t.s);case"eip1271":return await pb(i,e,t.s,r,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`)}}async function db(i,e,t){return(await _f({hash:hl(e),signature:t})).toLowerCase()===i.toLowerCase()}async function pb(i,e,t,r,s,n){const o=Fi(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",u=t.substring(2),l=hl(e).substring(2),d=a+l+c+h+u,f=await fetch(`${n||ub}/?chainId=${r}&projectId=${s}`,{method:"POST",body:JSON.stringify({id:fb(),jsonrpc:"2.0",method:"eth_call",params:[{to:i,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 fb(){return Date.now()+Math.floor(Math.random()*1e3)}function gb(i){const e=atob(i),t=new Uint8Array(e.length);for(let o=0;o<e.length;o++)t[o]=e.charCodeAt(o);const r=t[0];if(r===0)throw new Error("No signatures found");const s=1+r*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=ge.from(i,"base64").slice(1,65);return Sf.encode(n)}var yb=Object.defineProperty,mb=Object.defineProperties,wb=Object.getOwnPropertyDescriptors,ec=Object.getOwnPropertySymbols,bb=Object.prototype.hasOwnProperty,vb=Object.prototype.propertyIsEnumerable,tc=(i,e,t)=>e in i?yb(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Eb=(i,e)=>{for(var t in e||(e={}))bb.call(e,t)&&tc(i,t,e[t]);if(ec)for(var t of ec(e))vb.call(e,t)&&tc(i,t,e[t]);return i},_b=(i,e)=>mb(i,wb(e));const Ib="did:pkh:",Ao=i=>i?.split(":"),$b=i=>{const e=i&&Ao(i);if(e)return i.includes(Ib)?e[3]:e[1]},qn=i=>{const e=i&&Ao(i);if(e)return e[2]+":"+e[3]},ps=i=>{const e=i&&Ao(i);if(e)return e.pop()};async function ic(i){const{cacao:e,projectId:t}=i,{s:r,p:s}=e,n=ul(s,s.iss),o=ps(s.iss);return await lb(o,n,r,qn(s.iss),t)}const ul=(i,e)=>{const t=`${i.domain} wants you to sign in with your Ethereum account:`,r=ps(e);if(!i.aud&&!i.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=i.statement||void 0;const n=`URI: ${i.aud||i.uri}`,o=`Version: ${i.version}`,a=`Chain ID: ${$b(e)}`,c=`Nonce: ${i.nonce}`,h=`Issued At: ${i.iat}`,u=i.exp?`Expiration Time: ${i.exp}`:void 0,l=i.nbf?`Not Before: ${i.nbf}`:void 0,d=i.requestId?`Request ID: ${i.requestId}`:void 0,f=i.resources?`Resources:${i.resources.map(g=>` 5- ${g}`).join("")}`:void 0,p=ss(i.resources);if(p){const g=Sr(p);s=Nb(s,g)}return[t,r,"",s,"",n,o,a,c,h,u,l,d,f].filter(g=>g!=null).join(` 6`)};function Sb(i){return ge.from(JSON.stringify(i)).toString("base64")}function Db(i){return JSON.parse(ge.from(i,"base64").toString("utf-8"))}function hi(i){if(!i)throw new Error("No recap provided, value is undefined");if(!i.att)throw new Error("No `att` property found");const e=Object.keys(i.att);
6if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(t=>{const r=i.att[t];if(Array.isArray(r))throw new Error(`Resource must be an object: ${t}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(r).forEach(s=>{const n=r[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function Ob(i,e,t,r={}){return t?.sort((s,n)=>s.localeCompare(n)),{att:{[i]:Pb(e,t,r)}}}function Pb(i,e,t={}){e=e?.sort((s,n)=>s.localeCompare(n));const r=e.map(s=>({[`${i}/${s}`]:[t]}));return Object.assign({},...r)}function ll(i){return hi(i),`urn:recap:${Sb(i).replace(/=/g,"")}`}function Sr(i){const e=Db(i.replace("urn:recap:",""));return hi(e),e}function Ab(i,e,t){const r=Ob(i,e,t);return ll(r)}function xb(i){return i&&i.includes("urn:recap:")}function Cb(i,e){const t=Sr(i),r=Sr(e),s=Rb(t,r);return ll(s)}function Rb(i,e){hi(i),hi(e);const t=Object.keys(i.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),r={att:{}};return t.forEach(s=>{var n,o;Object.keys(((n=i.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;r.att[s]=_b(Eb({},r.att[s]),{[a]:((c=i.att[s])==null?void 0:c[a])||((h=e.att[s])==null?void 0:h[a])})})}),r}function Nb(i="",e){hi(e);const t="I further authorize the stated URI to perform the following actions on my behalf: ";if(i.includes(t))return i;const r=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(l=>({ability:l.split("/")[0],action:l.split("/")[1]}));c.sort((l,d)=>l.action.localeCompare(d.action));const h={};c.forEach(l=>{h[l.ability]||(h[l.ability]=[]),h[l.ability].push(l.action)});const u=Object.keys(h).map(l=>(s++,`(${s}) '${l}': '${h[l].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const n=r.join(" "),o=`${t}${n}`;return`${i?i+" ":""}${o}`}function rc(i){var e;const t=Sr(i);hi(t);const r=(e=t.att)==null?void 0:e.eip155;return r?Object.keys(r).map(s=>s.split("/")[1]):[]}function sc(i){const e=Sr(i);hi(e);const t=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{var n;(n=s?.[0])!=null&&n.chains&&t.push(s[0].chains)})}),[...new Set(t.flat())]}function ss(i){if(!i)return;const e=i?.[i.length-1];return xb(e)?e:void 0}function rn(i){if(!Number.isSafeInteger(i)||i<0)throw new Error("positive integer expected, got "+i)}function dl(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function Ge(i,...e){if(!dl(i))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(i.length))throw new Error("Uint8Array expected of length "+e+", got length="+i.length)}function nc(i,e=!0){if(i.destroyed)throw new Error("Hash instance has been destroyed");if(e&&i.finished)throw new Error("Hash#digest() has already been called")}function Tb(i,e){Ge(i);const t=e.outputLen;if(i.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function oc(i){if(typeof i!="boolean")throw new Error(`boolean expected, not ${i}`)}const Kt=i=>new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)),jb=i=>new DataView(i.buffer,i.byteOffset,i.byteLength),Bb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Bb)throw new Error("Non little-endian hardware is not supported");function Ub(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}function Mn(i){if(typeof i=="string")i=Ub(i);else if(dl(i))i=zn(i);else throw new Error("Uint8Array expected, got "+typeof i);return i}function Lb(i,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(i,e)}function kb(i,e){if(i.length!==e.length)return!1;let t=0;for(let r=0;r<i.length;r++)t|=i[r]^e[r];return t===0}const Fb=(i,e)=>{function t(r,...s){if(Ge(r),i.nonceLength!==void 0){const h=s[0];if(!h)throw new Error("nonce / iv required");i.varSizeNonce?Ge(h):Ge(h,i.nonceLength)}const n=i.tagLength;n&&s[1]!==void 0&&Ge(s[1]);const o=e(r,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ge(u)}};let c=!1;
6return{encrypt(h,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ge(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ge(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(h,u)}}}return Object.assign(t,i),t};function ac(i,e,t=!0){if(e===void 0)return new Uint8Array(i);if(e.length!==i)throw new Error("invalid output length, expected "+i+", got: "+e.length);if(t&&!qb(e))throw new Error("invalid output, must be aligned");return e}function cc(i,e,t,r){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n);i.setUint32(e+4,o,r),i.setUint32(e+0,a,r)}function qb(i){return i.byteOffset%4===0}function zn(i){return Uint8Array.from(i)}function zi(...i){for(let e=0;e<i.length;e++)i[e].fill(0)}const pl=i=>Uint8Array.from(i.split("").map(e=>e.charCodeAt(0))),Mb=pl("expand 16-byte k"),zb=pl("expand 32-byte k"),Hb=Kt(Mb),Vb=Kt(zb);function Z(i,e){return i<<e|i>>>32-e}function Hn(i){return i.byteOffset%4===0}const Kr=64,Kb=16,fl=2**32-1,hc=new Uint32Array;function Wb(i,e,t,r,s,n,o,a){const c=s.length,h=new Uint8Array(Kr),u=Kt(h),l=Hn(s)&&Hn(n),d=l?Kt(s):hc,f=l?Kt(n):hc;for(let p=0;p<c;o++){if(i(e,t,r,u,o,a),o>=fl)throw new Error("arx: counter overflow");const g=Math.min(Kr,c-p);if(l&&g===Kr){const y=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<Kb;b++)m=y+b,f[m]=d[m]^u[b];p+=Kr;continue}for(let y=0,b;y<g;y++)b=p+y,n[b]=s[b]^h[y];p+=g}}function Gb(i,e){const{allowShortKeys:t,extendNonceFn:r,counterLength:s,counterRight:n,rounds:o}=Lb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof i!="function")throw new Error("core must be a function");return rn(s),rn(o),oc(n),oc(t),(a,c,h,u,l=0)=>{Ge(a),Ge(c),Ge(h);const d=h.length;if(u===void 0&&(u=new Uint8Array(d)),Ge(u),rn(l),l<0||l>=fl)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);const f=[];let p=a.length,g,y;if(p===32)f.push(g=zn(a)),y=Vb;else if(p===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),y=Hb,f.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Hn(c)||f.push(c=zn(c));const b=Kt(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,b,Kt(c.subarray(0,16)),b),c=c.subarray(16)}const m=16-s;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const O=new Uint8Array(12);O.set(c,n?0:12-c.length),c=O,f.push(c)}const v=Kt(c);return Wb(i,y,b,v,h,u,l,o),zi(...f),u}}const $e=(i,e)=>i[e++]&255|(i[e++]&255)<<8;class Yb{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=Mn(e),Ge(e,32);const t=$e(e,0),r=$e(e,2),s=$e(e,4),n=$e(e,6),o=$e(e,8),a=$e(e,10),c=$e(e,12),h=$e(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let u=0;u<8;u++)this.pad[u]=$e(e,16+2*u)}process(e,t,r=!1){const s=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],u=o[3],l=o[4],d=o[5],f=o[6],p=o[7],g=o[8],y=o[9],b=$e(e,t+0),m=$e(e,t+2),v=$e(e,t+4),O=$e(e,t+6),x=$e(e,t+8),w=$e(e,t+10),_=$e(e,t+12),$=$e(e,t+14);let I=n[0]+(b&8191),j=n[1]+((b>>>13|m<<3)&8191),T=n[2]+((m>>>10|v<<6)&8191),B=n[3]+((v>>>7|O<<9)&8191),q=n[4]+((O>>>4|x<<12)&8191),S=n[5]+(x>>>1&8191),D=n[6]+((x>>>14|w<<2)&8191),E=n[7]+((w>>>11|_<<5)&8191),A=n[8]+((_>>>8|$<<8)&8191),C=n[9]+($>>>5|s),P=0,R=P+I*a+j*(5*y)+T*(5*g)+B*(5*p)+q*(5*f);P=R>>>13,R&=8191,R+=S*(5*d)+D*(5*l)+E*(5*u)+A*(5*h)+C*(5*c),P+=R>>>13,R&=8191;let k=P+I*c+j*a+T*(5*y)+B*(5*g)+q*(5*p);P=k>>>13,k&=8191,k+=S*(5*f)+D*(5*d)+E*(5*l)+A*(5*u)+C*(5*h),P+=k>>>13,k&=8191;let F=P+I*h+j*c+T*a+B*(5*y)+q*(5*g);P=F>>>13,F&=8191,F+=S*(5*p)+D*(5*f)+E*(5*d)+A*(5*l)+C*(5*u),P+=F>>>13,F&=8191;let M=P+I*u+j*h+T*c+B*a+q*(5*y);P=M>>>13,M&=8191,M+=S*(5*g)+D*(5*p)+E*(5*f)+A*(5*d)+C*(5*l),P+=M>>>13,M&=8191;let z=P+I*l+j*u+T*h+B*c+q*a;P=z>>>13,z&=8191,z+=S*(5*y)+D*(5*g)+E*(5*p)+A*(5*f)+C*(5*d),P+=z>>>13,z&=8191;let K=P+I*d+j*l+T*u+B*h+q*c;P=K>>>13,K&=8191,K+=S*a+D*(5*y)+E*(5*g)+A*(5*p)+C*(5*f),P+=K>>>13,K&=8191;let V=P+I*f+j*d+T*l+B*u+q*h;P=V>>>13,V&=8191,V+=S*c+D*a+E*(5*y)+A*(5*g)+C*(5*p),P+=V>>>13,V&=8191;let oe=P+I*p+j*f+T*d+B*l+q*u;P=oe>>>13,oe&=8191,oe+=S*h+D*c+E*a+A*(5*y)+C*(5*g),P+=oe>>>13,oe&=8191;let te=P+I*g+j*p+T*f+B*d+q*l;P=te>>>13,te&=8191,te+=S*u+D*h+E*c+A*a+C*(5*y),P+=te>>>13,te&=8191;let J=P+I*y+j*g+T*p+B*f+q*d;P=J>>>13,J&=8191,J+=S*l+D*u+E*h+A*c+C*a,P+=J>>>13,J&=8191,P=(P<<2)+P|0,P=P+R|0,R=P&8191,P=P>>>13,k+=P,n[0]=R,n[1]=k,n[2]=F,n[3]=M,n[4]=z,n[5]=K,n[6]=V,n[7]=oe,n[8]=te,n[9]=J}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+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;zi(r)}update(e){nc(this);const{buffer:t,blockLen:r}=this;e=Mn(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);if(o===r){for(;r<=s-n;n+=r)this.process(e,n);continue}t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){zi(this.h,this.r,this.buffer,this.pad)}digestInto(e){nc(this),Tb(e,this),this.finished=!0;const{buffer:t,h:r}=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++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}function Jb(i){const e=(r,s)=>i(s).update(Mn(r)).digest(),t=i(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>i(r),e}const Zb=Jb(i=>new Yb(i));function Qb(i,e,t,r,s,n=20){let o=i[0],a=i[1],c=i[2],h=i[3],u=e[0],l=e[1],d=e[2],f=e[3],p=e[4],g=e[5],y=e[6],b=e[7],m=s,v=t[0],O=t[1],x=t[2],w=o,_=a,$=c,I=h,j=u,T=l,B=d,q=f,S=p,D=g,E=y,A=b,C=m,P=v,R=O,k=x;for(let M=0;M<n;M+=2)w=w+j|0,C=Z(C^w,16),S=S+C|0,j=Z(j^S,12),w=w+j|0,C=Z(C^w,8),S=S+C|0,j=Z(j^S,7),_=_+T|0,P=Z(P^_,16),D=D+P|0,T=Z(T^D,12),_=_+T|0,P=Z(P^_,8),D=D+P|0,T=Z(T^D,7),$=$+B|0,R=Z(R^$,16),E=E+R|0,B=Z(B^E,12),$=$+B|0,R=Z(R^$,8),E=E+R|0,B=Z(B^E,7),I=I+q|0,k=Z(k^I,16),A=A+k|0,q=Z(q^A,12),I=I+q|0,k=Z(k^I,8),A=A+k|0,q=Z(q^A,7),w=w+T|0,k=Z(k^w,16),E=E+k|0,T=Z(T^E,12),w=w+T|0,k=Z(k^w,8),E=E+k|0,T=Z(T^E,7),_=_+B|0,C=Z(C^_,16),A=A+C|0,B=Z(B^A,12),_=_+B|0,C=Z(C^_,8),A=A+C|0,B=Z(B^A,7),$=$+q|0,P=Z(P^$,16),S=S+P|0,q=Z(q^S,12),$=$+q|0,P=Z(P^$,8),S=S+P|0,q=Z(q^S,7),I=I+j|0,R=Z(R^I,16),D=D+R|0,j=Z(j^D,12),I=I+j|0,R=Z(R^I,8),D=D+R|0,j=Z(j^D,7);let F=0;r[F++]=o+w|0,r[F++]=a+_|0,r[F++]=c+$|0,r[F++]=h+I|0,r[F++]=u+j|0,r[F++]=l+T|0,r[F++]=d+B|0,r[F++]=f+q|0,r[F++]=p+S|0,r[F++]=g+D|0,r[F++]=y+E|0,r[F++]=b+A|0,r[F++]=m+C|0,r[F++]=v+P|0,r[F++]=O+R|0,r[F++]=x+k|0}const Xb=Gb(Qb,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ev=new Uint8Array(16),uc=(i,e)=>{i.update(e);const t=e.length%16;t&&i.update(ev.subarray(t))},tv=new Uint8Array(32);function lc(i,e,t,r,s){const n=i(e,t,tv),o=Zb.create(n);s&&uc(o,s),uc(o,r);const a=new Uint8Array(16),c=jb(a);cc(c,0,BigInt(s?s.length:0),!0),cc(c,8,BigInt(r.length),!0),o.update(a);const h=o.digest();return zi(n,a),h}const iv=i=>(e,t,r)=>({encrypt(s,n){const o=s.length;n=ac(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);i(e,t,a,a,1);const c=lc(i,e,t,a,r);return n.set(c,o),zi(c),n},decrypt(s,n){n=ac(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=lc(i,e,t,o,r);if(!kb(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),i(e,t,n,n,1),zi(c),n}}),gl=Fb({blockSize:64,nonceLength:12,tagLength:16},iv(Xb));let yl=class extends Po{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Oo(e);const r=Mi(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(r.length>s?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return qi(this),this.iHash.update(e),this}digestInto(e){qi(this),Nr(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:r,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Ds=(i,e,t)=>new yl(i,e).update(t).digest();Ds.create=(i,e)=>new yl(i,e);function rv(i,e,t){return Oo(i),t===void 0&&(t=new Uint8Array(i.outputLen)),Ds(i,Mi(t),Mi(e))}const sn=new Uint8Array([0]),dc=new Uint8Array;function sv(i,e,t,r=32){if(Oo(i),$r(r),r>255*i.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i.outputLen);t===void 0&&(t=dc);const n=new Uint8Array(s*i.outputLen),o=Ds.create(i,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<s;h++)sn[0]=h+1,a.update(h===0?dc:c).update(t).update(sn).digestInto(c),n.set(c,i.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),sn.fill(0),n.slice(0,r)}const nv=(i,e,t,r,s)=>sv(i,rv(i,e,t),r,s);function ov(i,e,t,r){if(typeof i.setBigUint64=="function")return i.setBigUint64(e,t,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(t>>s&n),a=Number(t&n),c=r?4:0,h=r?0:4;i.setUint32(e+c,o,r),i.setUint32(e+h,a,r)}function av(i,e,t){return i&e^~i&t}function cv(i,e,t){return i&e^i&t^e&t}let hv=class extends Po{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=tn(this.buffer)}update(e){qi(this);const{view:t,buffer:r,blockLen:s}=this;e=Mi(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=tn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qi(this),rl(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;t[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)t[l]=0;ov(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=tn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,u=this.get();if(h>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<h;l++)a.setUint32(4*l,u[l],n)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%t&&e.buffer.set(r),e}};const uv=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,2756
6734187,3204031479,3329325298]),Ft=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt=new Uint32Array(64);class lv extends hv{constructor(){super(64,32,8,!1),this.A=Ft[0]|0,this.B=Ft[1]|0,this.C=Ft[2]|0,this.D=Ft[3]|0,this.E=Ft[4]|0,this.F=Ft[5]|0,this.G=Ft[6]|0,this.H=Ft[7]|0}get(){const{A:e,B:t,C:r,D:s,E:n,F:o,G:a,H:c}=this;return[e,t,r,s,n,o,a,c]}set(e,t,r,s,n,o,a,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,t){for(let l=0;l<16;l++,t+=4)qt[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){const d=qt[l-15],f=qt[l-2],p=yt(d,7)^yt(d,18)^d>>>3,g=yt(f,17)^yt(f,19)^f>>>10;qt[l]=g+qt[l-7]+p+qt[l-16]|0}let{A:r,B:s,C:n,D:o,E:a,F:c,G:h,H:u}=this;for(let l=0;l<64;l++){const d=yt(a,6)^yt(a,11)^yt(a,25),f=u+d+av(a,c,h)+uv[l]+qt[l]|0,p=(yt(r,2)^yt(r,13)^yt(r,22))+cv(r,s,n)|0;u=h,h=c,c=a,a=o+f|0,o=n,n=s,s=r,r=f+p|0}r=r+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,u=u+this.H|0,this.set(r,s,n,o,a,c,h,u)}roundClean(){qt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Tr=sl(()=>new lv);const Os=BigInt(0),Ps=BigInt(1),dv=BigInt(2);function ui(i){return i instanceof Uint8Array||ArrayBuffer.isView(i)&&i.constructor.name==="Uint8Array"}function jr(i){if(!ui(i))throw new Error("Uint8Array expected")}function Hi(i,e){if(typeof e!="boolean")throw new Error(i+" boolean expected, got "+e)}const pv=Array.from({length:256},(i,e)=>e.toString(16).padStart(2,"0"));function Vi(i){jr(i);let e="";for(let t=0;t<i.length;t++)e+=pv[i[t]];return e}function Ui(i){const e=i.toString(16);return e.length&1?"0"+e:e}function xo(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);return i===""?Os:BigInt("0x"+i)}const At={_0:48,_9:57,A:65,F:70,a:97,f:102};function pc(i){if(i>=At._0&&i<=At._9)return i-At._0;if(i>=At.A&&i<=At.F)return i-(At.A-10);if(i>=At.a&&i<=At.f)return i-(At.a-10)}function Ki(i){if(typeof i!="string")throw new Error("hex string expected, got "+typeof i);const e=i.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,n=0;s<t;s++,n+=2){const o=pc(i.charCodeAt(n)),a=pc(i.charCodeAt(n+1));if(o===void 0||a===void 0){const c=i[n]+i[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[s]=o*16+a}return r}function ai(i){return xo(Vi(i))}function Dr(i){return jr(i),xo(Vi(Uint8Array.from(i).reverse()))}function Wi(i,e){return Ki(i.toString(16).padStart(e*2,"0"))}function As(i,e){return Wi(i,e).reverse()}function fv(i){return Ki(Ui(i))}function We(i,e,t){let r;if(typeof e=="string")try{r=Ki(e)}catch(n){throw new Error(i+" must be hex string or Uint8Array, cause: "+n)}else if(ui(e))r=Uint8Array.from(e);else throw new Error(i+" must be hex string or Uint8Array");const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(i+" of length "+t+" expected, got "+s);return r}function Or(...i){let e=0;for(let r=0;r<i.length;r++){const s=i[r];jr(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<i.length;r++){const n=i[r];t.set(n,s),s+=n.length}return t}function gv(i,e){if(i.length!==e.length)return!1;let t=0;for(let r=0;r<i.length;r++)t|=i[r]^e[r];return t===0}function yv(i){if(typeof i!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(i))}const nn=i=>typeof i=="bigint"&&Os<=i;function xs(i,e,t){return nn(i)&&nn(e)&&nn(t)&&e<=i&&i<t}function jt(i,e,t,r){if(!xs(e,t,r))throw new Error("expected valid "+i+": "+t+" <= n < "+r+", got "+e)}function ml(i){let e;for(e=0;i>Os;i>>=Ps,e+=1);return e}function mv(i,e){return i>>BigInt(e)&Ps}function wv(i,e,t){return i|(t?Ps:Os)<<BigInt(e)}const Co=i=>(dv<<BigInt(i-1))-Ps,on=i=>new Uint8Array(i),fc=i=>Uint8Array.from(i);function wl(i,e,t){if(typeof i!="number"||i<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 r=on(i),s=on(i),n=0;const o=()=>{r.fill(1),s.fill(0),n=0},a=(...u)=>t(s,r,...u),c=(u=on())=>{s=a(fc([0]),u),r=a(),u.length!==0&&(s=a(fc([1]),u),r=a())},h=()=>
6{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const l=[];for(;u<e;){r=a();const d=r.slice();l.push(d),u+=r.length}return Or(...l)};return(u,l)=>{o(),c(u);let d;for(;!(d=l(h()));)c();return o(),d}}const bv={bigint:i=>typeof i=="bigint",function:i=>typeof i=="function",boolean:i=>typeof i=="boolean",string:i=>typeof i=="string",stringOrUint8Array:i=>typeof i=="string"||ui(i),isSafeInteger:i=>Number.isSafeInteger(i),array:i=>Array.isArray(i),field:(i,e)=>e.Fp.isValid(i),hash:i=>typeof i=="function"&&Number.isSafeInteger(i.outputLen)};function Xi(i,e,t={}){const r=(s,n,o)=>{const a=bv[n];if(typeof a!="function")throw new Error("invalid validator function");const c=i[s];if(!(o&&c===void 0)&&!a(c,i))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))r(s,n,!1);for(const[s,n]of Object.entries(t))r(s,n,!0);return i}const vv=()=>{throw new Error("not implemented")};function Vn(i){const e=new WeakMap;return(t,...r)=>{const s=e.get(t);if(s!==void 0)return s;const n=i(t,...r);return e.set(t,n),n}}var Ev=Object.freeze({__proto__:null,isBytes:ui,abytes:jr,abool:Hi,bytesToHex:Vi,numberToHexUnpadded:Ui,hexToNumber:xo,hexToBytes:Ki,bytesToNumberBE:ai,bytesToNumberLE:Dr,numberToBytesBE:Wi,numberToBytesLE:As,numberToVarBytesBE:fv,ensureBytes:We,concatBytes:Or,equalBytes:gv,utf8ToBytes:yv,inRange:xs,aInRange:jt,bitLen:ml,bitGet:mv,bitSet:wv,bitMask:Co,createHmacDrbg:wl,validateObject:Xi,notImplemented:vv,memoized:Vn});const _e=BigInt(0),ue=BigInt(1),ii=BigInt(2),_v=BigInt(3),Kn=BigInt(4),gc=BigInt(5),yc=BigInt(8);function qe(i,e){const t=i%e;return t>=_e?t:e+t}function bl(i,e,t){if(e<_e)throw new Error("invalid exponent, negatives unsupported");if(t<=_e)throw new Error("invalid modulus");if(t===ue)return _e;let r=ue;for(;e>_e;)e&ue&&(r=r*i%t),i=i*i%t,e>>=ue;return r}function lt(i,e,t){let r=i;for(;e-- >_e;)r*=r,r%=t;return r}function Wn(i,e){if(i===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let t=qe(i,e),r=e,s=_e,n=ue;for(;t!==_e;){const o=r/t,a=r%t,c=s-n*o;r=t,t=a,s=n,n=c}if(r!==ue)throw new Error("invert: does not exist");return qe(s,e)}function Iv(i){const e=(i-ue)/ii;let t,r,s;for(t=i-ue,r=0;t%ii===_e;t/=ii,r++);for(s=ii;s<i&&bl(s,e,i)!==i-ue;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(i+ue)/Kn;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(t+ue)/ii;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,h=o.pow(o.mul(o.ONE,s),t),u=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(h,ue<<BigInt(c-d-1));h=o.sqr(f),u=o.mul(u,f),l=o.mul(l,h),c=d}return u}}function $v(i){if(i%Kn===_v){const e=(i+ue)/Kn;return function(t,r){const s=t.pow(r,e);if(!t.eql(t.sqr(s),r))throw new Error("Cannot find square root");return s}}if(i%yc===gc){const e=(i-gc)/yc;return function(t,r){const s=t.mul(r,ii),n=t.pow(s,e),o=t.mul(r,n),a=t.mul(t.mul(o,ii),n),c=t.mul(o,t.sub(a,t.ONE));if(!t.eql(t.sqr(c),r))throw new Error("Cannot find square root");return c}}return Iv(i)}const Sv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dv(i){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Sv.reduce((r,s)=>(r[s]="function",r),e);return Xi(i,t)}function Ov(i,e,t){if(t<_e)throw new Error("invalid exponent, negatives unsupported");if(t===_e)return i.ONE;if(t===ue)return e;let r=i.ONE,s=e;for(;t>_e;)t&ue&&(r=i.mul(r,s)),s=i.sqr(s),t>>=ue;return r}function Pv(i,e){const t=new Array(e.length),r=e.reduce((n,o,a)=>i.is0(o)?n:(t[a]=n,i.mul(n,o)),i.ONE),s=i.inv(r);return e.reduceRight((n,o,a)=>i.is0(o)?n:(t[a]=i.mul(n,t[a]),i.mul(n,o)),s),t}function vl(i,e){const t=e!==void 0?e:i.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function El(i,e,t=!1,r={}){if(i<=_e)throw new Error("invalid field: expected ORDER > 0, got "+i);const{nBitLength:s,nByteLength:n}=vl(i,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:i,isLE:t,BITS:s,BYTES:n,MASK:Co(s),ZERO:_e,ONE:ue,create:c=>qe(c,i),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _e<=c&&c<i},is0:c=>c===_e,isOdd:c=>(c&ue)===ue,neg:c=>qe(-c,i),eql:(c,h)=>c===h,sqr:c=>qe(c*c,i),add:(c,h)=>qe(c+h,i),sub:(c,h)=>qe(c-h,i),mul:(c,h)=>qe(c*h,i),pow:(c,h)=>Ov(a,c,h),div:(c,h)=>qe(c*Wn(h,i),i),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Wn(c,i),sqrt:r.sqrt||(c=>
6(o||(o=$v(i)),o(a,c))),invertBatch:c=>Pv(a,c),cmov:(c,h,u)=>u?h:c,toBytes:c=>t?As(c,n):Wi(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return t?Dr(c):ai(c)}});return Object.freeze(a)}function _l(i){if(typeof i!="bigint")throw new Error("field order must be bigint");const e=i.toString(2).length;return Math.ceil(e/8)}function Il(i){const e=_l(i);return e+Math.ceil(e/2)}function Av(i,e,t=!1){const r=i.length,s=_l(e),n=Il(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=t?Dr(i):ai(i),a=qe(o,e-ue)+ue;return t?As(a,s):Wi(a,s)}const mc=BigInt(0),Wr=BigInt(1);function an(i,e){const t=e.negate();return i?t:e}function $l(i,e){if(!Number.isSafeInteger(i)||i<=0||i>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+i)}function cn(i,e){$l(i,e);const t=Math.ceil(e/i)+1,r=2**(i-1);return{windows:t,windowSize:r}}function xv(i,e){if(!Array.isArray(i))throw new Error("array expected");i.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function Cv(i,e){if(!Array.isArray(i))throw new Error("array of scalars expected");i.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}const hn=new WeakMap,Sl=new WeakMap;function un(i){return Sl.get(i)||1}function Rv(i,e){return{constTimeNegate:an,hasPrecomputes(t){return un(t)!==1},unsafeLadder(t,r,s=i.ZERO){let n=t;for(;r>mc;)r&Wr&&(s=s.add(n)),n=n.double(),r>>=Wr;return s},precomputeWindow(t,r){const{windows:s,windowSize:n}=cn(r,e),o=[];let a=t,c=a;for(let h=0;h<s;h++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(t,r,s){const{windows:n,windowSize:o}=cn(t,e);let a=i.ZERO,c=i.BASE;const h=BigInt(2**t-1),u=2**t,l=BigInt(t);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&h);s>>=l,p>o&&(p-=u,s+=Wr);const g=f,y=f+Math.abs(p)-1,b=d%2!==0,m=p<0;p===0?c=c.add(an(b,r[g])):a=a.add(an(m,r[y]))}return{p:a,f:c}},wNAFUnsafe(t,r,s,n=i.ZERO){const{windows:o,windowSize:a}=cn(t,e),c=BigInt(2**t-1),h=2**t,u=BigInt(t);for(let l=0;l<o;l++){const d=l*a;if(s===mc)break;let f=Number(s&c);if(s>>=u,f>a&&(f-=h,s+=Wr),f===0)continue;let p=r[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(t,r,s){let n=hn.get(r);return n||(n=this.precomputeWindow(r,t),t!==1&&hn.set(r,s(n))),n},wNAFCached(t,r,s){const n=un(t);return this.wNAF(n,this.getPrecomputes(n,t,s),r)},wNAFCachedUnsafe(t,r,s,n){const o=un(t);return o===1?this.unsafeLadder(t,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,t,s),r,n)},setWindowSize(t,r){$l(r,e),Sl.set(t,r),hn.delete(t)}}}function Nv(i,e,t,r){if(xv(t,i),Cv(r,e),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=i.ZERO,n=ml(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),h=Math.floor((e.BITS-1)/o)*o;let u=s;for(let l=h;l>=0;l-=o){c.fill(s);for(let f=0;f<r.length;f++){const p=r[f],g=Number(p>>BigInt(l)&BigInt(a));c[g]=c[g].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(u=u.add(d),l!==0)for(let f=0;f<o;f++)u=u.double()}return u}function Dl(i){return Dv(i.Fp),Xi(i,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vl(i.n,i.nBitLength),...i,p:i.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Ei=BigInt(0),ln=BigInt(1);function Tv(i){return Xi(i,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...i})}function jv(i){const e=Tv(i),{P:t}=e,r=m=>qe(m,t),s=e.montgomeryBits,n=Math.ceil(s/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>bl(m,t-BigInt(2),t));function h(m,v,O){const x=r(m*(v-O));return v=r(v-x),O=r(O+x),[v,O]}const u=(e.a-BigInt(2))/BigInt(4);function l(m,v){jt("u",m,Ei,t),jt("scalar",v,Ei,t);const O=v,x=m;let w=ln,_=Ei,$=m,I=ln,j=Ei,T;for(let q=BigInt(s-1);q>=Ei;q--){const S=O>>q&ln;j^=S,T=h(j,w,$),w=T[0],$=T[1],T=h(j,_,I),_=T[0],I=T[1],j=S;const D=w+_,E=r(D*D),A=w-_,C=r(A*A),P=E-C,R=$+I,k=$-I,F=r(k*D),M=r(R*A),z=F+M,K=F-M;$=r(z*z),I=r(x*r(K*K)),w=r(E*C),_=r(P*(E+r(u*P)))}T=h(j,w,$),w=T[0],$=T[1],T=h(j,_,I),_=T[0],I=T[1];const B=c(_);return r(w*B)}
6function d(m){return As(r(m),n)}function f(m){const v=We("u coordinate",m,n);return o===32&&(v[31]&=127),Dr(v)}function p(m){const v=We("scalar",m),O=v.length;if(O!==n&&O!==o){let x=""+n+" or "+o;throw new Error("invalid scalar, expected "+x+" bytes, got "+O)}return Dr(a(v))}function g(m,v){const O=f(v),x=p(m),w=l(O,x);if(w===Ei)throw new Error("invalid private or public key received");return d(w)}const y=d(e.Gu);function b(m){return g(m,y)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(m,v)=>g(m,v),getPublicKey:m=>b(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:y}}const Gn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const Bv=BigInt(1),wc=BigInt(2),Uv=BigInt(3),Lv=BigInt(5);BigInt(8);function kv(i){const e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),n=Gn,o=i*i%n*i%n,a=lt(o,wc,n)*o%n,c=lt(a,Bv,n)*i%n,h=lt(c,Lv,n)*c%n,u=lt(h,e,n)*h%n,l=lt(u,t,n)*u%n,d=lt(l,r,n)*l%n,f=lt(d,s,n)*d%n,p=lt(f,s,n)*d%n,g=lt(p,e,n)*h%n;return{pow_p_5_8:lt(g,wc,n)*i%n,b2:o}}function Fv(i){return i[0]&=248,i[31]&=127,i[31]|=64,i}const Yn=jv({P:Gn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:i=>{const e=Gn,{pow_p_5_8:t,b2:r}=kv(i);return qe(lt(t,Uv,e)*r,e)},adjustScalarBytes:Fv,randomBytes:Qi});function bc(i){i.lowS!==void 0&&Hi("lowS",i.lowS),i.prehash!==void 0&&Hi("prehash",i.prehash)}function qv(i){const e=Dl(i);Xi(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.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:Mv,hexToBytes:zv}=Ev;class Hv extends Error{constructor(e=""){super(e)}}const Nt={Err:Hv,_tlv:{encode:(i,e)=>{const{Err:t}=Nt;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,s=Ui(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const n=r>127?Ui(s.length/2|128):"";return Ui(i)+n+s+e},decode(i,e){const{Err:t}=Nt;let r=0;if(i<0||i>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==i)throw new t("tlv.decode: wrong tlv");const s=e[r++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const h=e.subarray(r,r+c);if(h.length!==c)throw new t("tlv.decode: length bytes not complete");if(h[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const u of h)o=o<<8|u;if(r+=c,o<128)throw new t("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(i){const{Err:e}=Nt;if(i<Tt)throw new e("integer: negative integers are not allowed");let t=Ui(i);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(i){const{Err:e}=Nt;if(i[0]&128)throw new e("invalid signature integer: negative");if(i[0]===0&&!(i[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Mv(i)}},toSig(i){const{Err:e,_int:t,_tlv:r}=Nt,s=typeof i=="string"?zv(i):i;jr(s);const{v:n,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:h,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(h)}},hexFromSig(i){const{_tlv:e,_int:t}=Nt,r=e.encode(2,t.encode(i.r)),s=e.encode(2,t.encode(i.s)),n=r+s;return e.encode(48,n)}},Tt=BigInt(0),be=BigInt(1);BigInt(2);const vc=BigInt(3);BigInt(4);function Vv(i){const e=qv(i),{Fp:t}=e,r=El(e.n,e.nBitLength),s=e.toBytes||((g,y,b)=>{const m=y.toAffine();return Or(Uint8Array.from([4]),t.toBytes(m.x),t.toBytes(m.y))}),n=e.fromBytes||(g=>{const y=g.subarray(1),b=t.fromBytes(y.subarray(0,t.BYTES)),m=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:b,y:m}});function o(g){const{a:y,b}=e,m=t.sqr(g),v=t.mul(m,g);return t.add(t.add(v,t.mul(g,y)),b)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return xs(g,be,e.n)}function c(g){const{allowedPrivateKeyLengths:y,nByteLength:b,wrapPrivateKey:m,n:v}=e;if(y&&typeof g!="bigint"){if(ui(g)&&(g=Vi(g)),typeof g!="string"||!y.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let O;try{O=typeof g=="bigint"?g:ai(We("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return m&&(O=qe(O,v)),jt("private key",O,be,v),O}function h(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}const u=Vn((g,y)=>{const{px:b,py:m,pz:v}=g;if(t.eql(v,t.ONE))return{x:b,y:m};const O=g.is0();y==null&&(y=O?t.ONE:t.inv(v));const x=t.mul(b,y),w=t.mul(m,y),_=t.mul(v,y);if(O)return{x:t.ZERO,y:t.ZERO};
6if(!t.eql(_,t.ONE))throw new Error("invZ was invalid");return{x,y:w}}),l=Vn(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=g.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not FE");const m=t.sqr(b),v=o(y);if(!t.eql(m,v))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,b,m){if(this.px=y,this.py=b,this.pz=m,y==null||!t.isValid(y))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(m==null||!t.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(y){const{x:b,y:m}=y||{};if(!y||!t.isValid(b)||!t.isValid(m))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");const v=O=>t.eql(O,t.ZERO);return v(b)&&v(m)?d.ZERO:new d(b,m,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){const b=t.invertBatch(y.map(m=>m.pz));return y.map((m,v)=>m.toAffine(b[v])).map(d.fromAffine)}static fromHex(y){const b=d.fromAffine(n(We("pointHex",y)));return b.assertValidity(),b}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,b){return Nv(d,r,y,b)}_setWindowSize(y){p.setWindowSize(this,y)}assertValidity(){l(this)}hasEvenY(){const{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){h(y);const{px:b,py:m,pz:v}=this,{px:O,py:x,pz:w}=y,_=t.eql(t.mul(b,w),t.mul(O,v)),$=t.eql(t.mul(m,w),t.mul(x,v));return _&&$}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){const{a:y,b}=e,m=t.mul(b,vc),{px:v,py:O,pz:x}=this;let w=t.ZERO,_=t.ZERO,$=t.ZERO,I=t.mul(v,v),j=t.mul(O,O),T=t.mul(x,x),B=t.mul(v,O);return B=t.add(B,B),$=t.mul(v,x),$=t.add($,$),w=t.mul(y,$),_=t.mul(m,T),_=t.add(w,_),w=t.sub(j,_),_=t.add(j,_),_=t.mul(w,_),w=t.mul(B,w),$=t.mul(m,$),T=t.mul(y,T),B=t.sub(I,T),B=t.mul(y,B),B=t.add(B,$),$=t.add(I,I),I=t.add($,I),I=t.add(I,T),I=t.mul(I,B),_=t.add(_,I),T=t.mul(O,x),T=t.add(T,T),I=t.mul(T,B),w=t.sub(w,I),$=t.mul(T,j),$=t.add($,$),$=t.add($,$),new d(w,_,$)}add(y){h(y);const{px:b,py:m,pz:v}=this,{px:O,py:x,pz:w}=y;let _=t.ZERO,$=t.ZERO,I=t.ZERO;const j=e.a,T=t.mul(e.b,vc);let B=t.mul(b,O),q=t.mul(m,x),S=t.mul(v,w),D=t.add(b,m),E=t.add(O,x);D=t.mul(D,E),E=t.add(B,q),D=t.sub(D,E),E=t.add(b,v);let A=t.add(O,w);return E=t.mul(E,A),A=t.add(B,S),E=t.sub(E,A),A=t.add(m,v),_=t.add(x,w),A=t.mul(A,_),_=t.add(q,S),A=t.sub(A,_),I=t.mul(j,E),_=t.mul(T,S),I=t.add(_,I),_=t.sub(q,I),I=t.add(q,I),$=t.mul(_,I),q=t.add(B,B),q=t.add(q,B),S=t.mul(j,S),E=t.mul(T,E),q=t.add(q,S),S=t.sub(B,S),S=t.mul(j,S),E=t.add(E,S),B=t.mul(q,E),$=t.add($,B),B=t.mul(A,E),_=t.mul(D,_),_=t.sub(_,B),B=t.mul(D,q),I=t.mul(A,I),I=t.add(I,B),new d(_,$,I)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return p.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){const{endo:b,n:m}=e;jt("scalar",y,Tt,m);const v=d.ZERO;if(y===Tt)return v;if(this.is0()||y===be)return this;if(!b||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,y,d.normalizeZ);let{k1neg:O,k1:x,k2neg:w,k2:_}=b.splitScalar(y),$=v,I=v,j=this;for(;x>Tt||_>Tt;)x&be&&($=$.add(j)),_&be&&(I=I.add(j)),j=j.double(),x>>=be,_>>=be;return O&&($=$.negate()),w&&(I=I.negate()),I=new d(t.mul(I.px,b.beta),I.py,I.pz),$.add(I)}multiply(y){const{endo:b,n:m}=e;jt("scalar",y,be,m);let v,O;if(b){const{k1neg:x,k1:w,k2neg:_,k2:$}=b.splitScalar(y);let{p:I,f:j}=this.wNAF(w),{p:T,f:B}=this.wNAF($);I=p.constTimeNegate(x,I),T=p.constTimeNegate(_,T),T=new d(t.mul(T.px,b.beta),T.py,T.pz),v=I.add(T),O=j.add(B)}else{const{p:x,f:w}=this.wNAF(y);v=x,O=w}return d.normalizeZ([v,O])[0]}multiplyAndAddUnsafe(y,b,m){const v=d.BASE,O=(w,_)=>_===Tt||_===be||!w.equals(v)?w.multiplyUnsafe(_):w.multiply(_),x=O(this,b).add(O(y,m));return x.is0()?void 0:x}toAffine(y){return u(this,y)}isTorsionFree(){const{h:y,isTorsionFree:b}=e;if(y===be)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:y,clearCofactor:b}=e;return y===be?this:b?b(d,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return Hi("isCompressed",y),this.assertValidity(),s(d,this,y)}toHex(y=!0){return Hi("isCompressed",y),Vi(this.toRawBytes(y))}}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=Rv(d,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Kv(i){const e=Dl(i);return Xi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Wv(i){const e=Kv(i),{Fp:t,n:r}=e,s=t.BYTES+1,n=2*t.BYTES+1;function o(S){return qe(S,r)}function a(S){return Wn(S,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:l}=Vv({...e,toBytes(S,D,E){const A=D.toAffine(),C=t.toBytes(A.x),P=Or;return Hi("isCompressed",E),E?P(Uint8Array.from([D.hasEvenY()?2:3]),C):P(Uint8Array.from([4]),C,t.toBytes(A.y))},fromBytes(S){const D=S.length,E=S[0],A=S.subarray(1);if(D===s&&(E===2||E===3)){const C=ai(A);if(!xs(C,be,t.ORDER))throw new Error("Point is not on curve");const P=u(C);let R;try{R=t.sqrt(P)}catch(F){const M=F instanceof Error?": "+F.message:"";throw new Error("Point is not on curve"+M)}const k=(R&be)===be;return(E&1)===1!==k&&(R=t.neg(R)),{x:C,y:R}}else if(D===n&&E===4){const C=t.fromBytes(A.subarray(0,t.BYTES)),P=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:C,y:P}}else{const C=s,P=n;throw new Error("invalid Point, expected length of "+C+", or uncompressed "+P+", got "+D)}}}),d=S=>Vi(Wi(S,e.nByteLength));function f(S){const D=r>>be;return S>D}function p(S){return f(S)?o(-S):S}const g=(S,D,E)=>ai(S.slice(D,E));class y{constructor(D,E,A){this.r=D,this.s=E,this.recovery=A,this.assertValidity()}static fromCompact(D){const E=e.nByteLength;return D=We("compactSignature",D,E*2),new y(g(D,0,E),g(D,E,2*E))}static fromDER(D){const{r:E,s:A}=Nt.toSig(We("DER",D));return new y(E,A)}assertValidity(){jt("r",this.r,be,r),jt("s",this.s,be,r)}addRecoveryBit(D){return new y(this.r,this.s,D)}recoverPublicKey(D){const{r:E,s:A,recovery:C}=this,P=w(We("msgHash",D));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const R=C===2||C===3?E+e.n:E;if(R>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(C&1)===0?"02":"03",F=c.fromHex(k+d(R)),M=a(R),z=o(-P*M),K=o(A*M),V=c.BASE.multiplyAndAddUnsafe(F,z,K);if(!V)throw new Error("point at infinify");return V.assertValidity(),V}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Ki(this.toDERHex())}toDERHex(){return Nt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ki(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const b={isValidPrivateKey(S){try{return h(S),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const S=Il(e.n);return Av(e.randomBytes(S),e.n)},precompute(S=8,D=c.BASE){return D._setWindowSize(S),D.multiply(BigInt(3)),D}};function m(S,D=!0){return c.fromPrivateKey(S).toRawBytes(D)}function v(S){const D=ui(S),E=typeof S=="string",A=(D||E)&&S.length;return D?A===s||A===n:E?A===2*s||A===2*n:S instanceof c}function O(S,D,E=!0){if(v(S))throw new Error("first arg must be private key");if(!v(D))throw new Error("second arg must be public key");return c.fromHex(D).multiply(h(S)).toRawBytes(E)}const x=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");
6const D=ai(S),E=S.length*8-e.nBitLength;return E>0?D>>BigInt(E):D},w=e.bits2int_modN||function(S){return o(x(S))},_=Co(e.nBitLength);function $(S){return jt("num < 2^"+e.nBitLength,S,Tt,_),Wi(S,e.nByteLength)}function I(S,D,E=j){if(["recovered","canonical"].some(te=>te in E))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:C}=e;let{lowS:P,prehash:R,extraEntropy:k}=E;P==null&&(P=!0),S=We("msgHash",S),bc(E),R&&(S=We("prehashed msgHash",A(S)));const F=w(S),M=h(D),z=[$(M),$(F)];if(k!=null&&k!==!1){const te=k===!0?C(t.BYTES):k;z.push(We("extraEntropy",te))}const K=Or(...z),V=F;function oe(te){const J=x(te);if(!l(J))return;const Ce=a(J),Ie=c.BASE.multiply(J).toAffine(),Ne=o(Ie.x);if(Ne===Tt)return;const Ze=o(Ce*o(V+Ne*M));if(Ze===Tt)return;let St=(Ie.x===Ne?0:2)|Number(Ie.y&be),yi=Ze;return P&&f(Ze)&&(yi=p(Ze),St^=1),new y(Ne,yi,St)}return{seed:K,k2sig:oe}}const j={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function B(S,D,E=j){const{seed:A,k2sig:C}=I(S,D,E),P=e;return wl(P.hash.outputLen,P.nByteLength,P.hmac)(A,C)}c.BASE._setWindowSize(8);function q(S,D,E,A=T){const C=S;D=We("msgHash",D),E=We("publicKey",E);const{lowS:P,prehash:R,format:k}=A;if(bc(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const F=typeof C=="string"||ui(C),M=!F&&!k&&typeof C=="object"&&C!==null&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!F&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let z,K;try{if(M&&(z=new y(C.r,C.s)),F){try{k!=="compact"&&(z=y.fromDER(C))}catch(Ze){if(!(Ze instanceof Nt.Err))throw Ze}!z&&k!=="der"&&(z=y.fromCompact(C))}K=c.fromHex(E)}catch{return!1}if(!z||P&&z.hasHighS())return!1;R&&(D=e.hash(D));const{r:V,s:oe}=z,te=w(D),J=a(oe),Ce=o(te*J),Ie=o(V*J),Ne=c.BASE.multiplyAndAddUnsafe(K,Ce,Ie)?.toAffine();return Ne?o(Ne.x)===V:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:O,sign:B,verify:q,ProjectivePoint:c,Signature:y,utils:b}}function Gv(i){return{hash:i,hmac:(e,...t)=>Ds(i,e,Qw(...t)),randomBytes:Qi}}function Yv(i,e){const t=r=>Wv({...i,...Gv(r)});return{...t(e),create:t}}const Ol=El(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Jv=Ol.create(BigInt("-3")),Zv=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Qv=Yv({a:Jv,b:Zv,Fp:Ol,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Tr),Pl="base10",je="base16",dt="base64pad",zt="base64url",Br="utf8",Al=0,Bt=1,Ur=2,Xv=0,Ec=1,yr=12,Ro=32;function e0(){const i=Yn.utils.randomPrivateKey(),e=Yn.getPublicKey(i);return{privateKey:Me(i,je),publicKey:Me(e,je)}}function Jn(){const i=Qi(Ro);return Me(i,je)}function t0(i,e){const t=Yn.getSharedSecret(it(i,je),it(e,je)),r=nv(Tr,t,void 0,void 0,Ro);return Me(r,je)}function ns(i){const e=Tr(it(i,je));return Me(e,je)}function _t(i){const e=Tr(it(i,Br));return Me(e,je)}function xl(i){return it(`${i}`,Pl)}function li(i){return Number(Me(i,Pl))}function Cl(i){return i.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Rl(i){const e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+"=".repeat(t)}function i0(i){const e=xl(typeof i.type<"u"?i.type:Al);if(li(e)===Bt&&typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const t=typeof i.senderPublicKey<"u"?it(i.senderPublicKey,je):void 0,r=typeof i.iv<"u"?it(i.iv,je):Qi(yr),s=it(i.symKey,je),n=gl(s,r).encrypt(it(i.message,Br)),o=Nl({type:e,sealed:n,iv:r,senderPublicKey:t});return i.encoding===zt?Cl(o):o}function r0(i){const e=it(i.symKey,je),{sealed:t,iv:r}=Pr({encoded:i.encoded,encoding:i.encoding}),s=gl(e,r).decrypt(t);if(s===null)throw new Error("Failed to decrypt");return Me(s,Br)}function s0(i,e){const t=xl(Ur),r=Qi(yr),s=it(i,Br),n=Nl({type:t,sealed:s,iv:r});return e===zt?Cl(n):n}function n0(i,e){const{sealed:t}=Pr({encoded:i,encoding:e});return Me(t,Br)}function Nl(i){if(li(i.type)===Ur)return Me(gr([i.type,i.sealed]),dt);if(li(i.type)===Bt){if(typeof i.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Me(gr([i.type,i.senderPublicKey,i.iv,i.sealed]),dt)}return Me(gr([i.type,i.iv,i.sealed]),dt)}function Pr(i){const e=(i.encoding||dt)===zt?Rl(i.encoded):i.encoded,t=it(e,dt),r=t.slice(Xv,Ec),s=Ec;if(li(r)===Bt){const c=s+Ro,h=c+yr,u=t.slice(s,c),l=t.slice(c,h),d=t.slice(h);return{type:r,sealed:d,iv:l,senderPublicKey:u}}if(li(r)===Ur){const c=t.slice(s),h=Qi(yr);return{type:r,sealed:c,iv:h}}const n=s+yr,o=t.slice(s,n),a=t.slice(n);return{type:r,sealed:a,iv:o}}function o0(i,e){const t=Pr({encoded:i,encoding:e?.encoding});return Tl({type:li(t.type),senderPublicKey:typeof t.senderPublicKey<"u"?Me(t.senderPublicKey,je):void 0,receiverPublicKey:e?.receiverPublicKey})}function Tl(i){const e=i?.type||Al;if(e===Bt){if(typeof i?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof i?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:i?.senderPublicKey,receiverPublicKey:i?.receiverPublicKey}}function _c(i){return i.type===Bt&&typeof i.senderPublicKey=="string"&&typeof i.receiverPublicKey=="string"}function Ic(i){return i.type===Ur}function a0(i){const e=ge.from(i.x,"base64"),t=ge.from(i.y,"base64");return gr([new Uint8Array([4]),e,t])}function c0(i,e){const[t,r,s]=i.split("."),n=ge.from(Rl(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");
6const o=n.slice(0,32),a=n.slice(32,64),c=`${t}.${r}`,h=Tr(c),u=a0(e);if(!Qv.verify(gr([o,a]),h,u))throw new Error("Invalid signature");return Ln(i).payload}const h0="irn";function fs(i){return i?.relay||{protocol:h0}}function pr(i){const e=fw[i];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${i}`);return e}function u0(i,e="-"){const t={},r="relay"+e;return Object.keys(i).forEach(s=>{if(s.startsWith(r)){const n=s.replace(r,""),o=i[s];t[n]=o}}),t}function $c(i){if(!i.includes("wc:")){const h=il(i);h!=null&&h.includes("wc:")&&(i=h)}i=i.includes("wc://")?i.replace("wc://",""):i,i=i.includes("wc:")?i.replace("wc:",""):i;const e=i.indexOf(":"),t=i.indexOf("?")!==-1?i.indexOf("?"):void 0,r=i.substring(0,e),s=i.substring(e+1,t).split("@"),n=typeof t<"u"?i.substring(t):"",o=new URLSearchParams(n),a={};o.forEach((h,u)=>{a[u]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:l0(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:u0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function l0(i){return i.startsWith("//")?i.substring(2):i}function d0(i,e="-"){const t="relay",r={};
6return Object.keys(i).forEach(s=>{const n=s,o=t+e+n;i[n]&&(r[o]=i[n])}),r}function Sc(i){const e=new URLSearchParams,t=d0(i.relay);Object.keys(t).sort().forEach(s=>{e.set(s,t[s])}),e.set("symKey",i.symKey),i.expiryTimestamp&&e.set("expiryTimestamp",i.expiryTimestamp.toString()),i.methods&&e.set("methods",i.methods.join(","));const r=e.toString();return`${i.protocol}:${i.topic}@${i.version}?${r}`}function Gr(i,e,t){return`${i}?wc_ev=${t}&topic=${e}`}var p0=Object.defineProperty,f0=Object.defineProperties,g0=Object.getOwnPropertyDescriptors,Dc=Object.getOwnPropertySymbols,y0=Object.prototype.hasOwnProperty,m0=Object.prototype.propertyIsEnumerable,Oc=(i,e,t)=>e in i?p0(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,w0=(i,e)=>{for(var t in e||(e={}))y0.call(e,t)&&Oc(i,t,e[t]);if(Dc)for(var t of Dc(e))m0.call(e,t)&&Oc(i,t,e[t]);return i},b0=(i,e)=>f0(i,g0(e));function er(i){const e=[];return i.forEach(t=>{const[r,s]=t.split(":");e.push(`${r}:${s}`)}),e}function v0(i){const e=[];return Object.values(i).forEac
6h(t=>{e.push(...er(t.accounts))}),e}function E0(i,e){const t=[];return Object.values(i).forEach(r=>{er(r.accounts).includes(e)&&t.push(...r.methods)}),t}function _0(i,e){const t=[];return Object.values(i).forEach(r=>{er(r.accounts).includes(e)&&t.push(...r.events)}),t}function Cs(i){return i.includes(":")}function Li(i){return Cs(i)?i.split(":")[0]:i}function Pc(i){var e,t,r;const s={};if(!Wt(i))return s;for(const[n,o]of Object.entries(i)){const a=Cs(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],u=Li(n);s[u]=b0(w0({},s[u]),{chains:It(a,(e=s[u])==null?void 0:e.chains),methods:It(c,(t=s[u])==null?void 0:t.methods),events:It(h,(r=s[u])==null?void 0:r.events)})}return s}function I0(i){const e={};return i?.forEach(t=>{var r;const[s,n]=t.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(t),(r=e[s].chains)==null||r.push(`${s}:${n}`)}),e}function Ac(i,e){e=e.map(r=>r.replace("did:pkh:",""));const t=I0(e);for(const[r,s]of Object.entries(t))s.methods?s.methods=It(s.methods,i):s.methods=i,s.events=["chainChanged","accountsChanged"];return t}function $0(i,e){var t,r,s,n,o,a;const c=Pc(i),h=Pc(e),u={},l=Object.keys(c).concat(Object.keys(h));for(const d of l)u[d]={chains:It((t=c[d])==null?void 0:t.chains,(r=h[d])==null?void 0:r.chains),methods:It((s=c[d])==null?void 0:s.methods,(n=h[d])==null?void 0:n.methods),events:It((o=c[d])==null?void 0:o.events,(a=h[d])==null?void 0:a.events)};return u}const S0={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}},D0={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 L(i,e){const{message:t,code:r}=D0[i];return{message:e?`${t} ${e}`:t,code:r}}function ie(i,e){const{message:t,code:r}=S0[i];return{message:e?`${t} ${e}`:t,code:r}}function pt(i,e){return!!Array.isArray(i)}function Wt(i){return Object.getPrototypeOf(i)===Object.prototype&&Object.keys(i).length}function Oe(i){return typeof i>"u"}function de(i,e){return e&&Oe(i)?!0:typeof i=="string"&&!!i.trim().length}function No(i,e){return e&&Oe(i)?!0:typeof i=="number"&&!isNaN(i)}function O0(i,e){const{requiredNamespaces:t}=e,r=Object.keys(i.namespaces),s=Object.keys(t);let n=!0;return ni(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:h}=i.namespaces[o],u=er(a),l=t[o];(!ni(Zu(o,l),u)||!ni(l.methods,c)||!ni(l.events,h))&&(n=!1)}),n):!1}function gs(i){return de(i,!1)&&i.includes(":")?i.split(":").length===2:!1}
6function P0(i){if(de(i,!1)&&i.includes(":")){const e=i.split(":");if(e.length===3){const t=e[0]+":"+e[1];return!!e[2]&&gs(t)}}return!1}function A0(i){function e(t){try{return typeof new URL(t)<"u"}catch{return!1}}try{if(de(i,!1)){if(e(i))return!0;const t=il(i);return e(t)}}catch{}return!1}function x0(i){var e;return(e=i?.proposer)==null?void 0:e.publicKey}function C0(i){return i?.topic}function R0(i,e){let t=null;return de(i?.publicKey,!1)||(t=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),t}function xc(i){let e=!0;return pt(i)?i.length&&(e=i.every(t=>de(t,!1))):e=!1,e}function N0(i,e,t){let r=null;return pt(e)&&e.length?e.forEach(s=>{r||gs(s)||(r=ie("UNSUPPORTED_CHAINS",`${t}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):gs(i)||(r=ie("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"] }`)),r}function T0(i,e,t){let r=null;return Object.entries(i).forEach(([s,n])=>{if(r)return;const o=N0(s,Zu(s,n),`${e} ${t}`);o&&(r=o)}),r}function j0(i,e){let t=null;return pt(i)?i.forEach(r=>{t||P0(r)||(t=ie("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):t=ie("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),t}function B0(i,e){let t=null;return Object.values(i).forEach(r=>{if(t)return;const s=j0(r?.accounts,`${e} namespace`);s&&(t=s)}),t}function U0(i,e){let t=null;return xc(i?.methods)?xc(i?.events)||(t=ie("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):t=ie("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),t}function jl(i,e){let t=null;return Object.values(i).forEach(r=>{if(t)return;const s=U0(r,`${e}, namespace`);s&&(t=s)}),t}function L0(i,e,t){let r=null;if(i&&Wt(i)){const s=jl(i,e);s&&(r=s);const n=T0(i,e,t);n&&(r=n)}else r=L("MISSING_OR_INVALID",`${e}, ${t} should be an object with data`);return r}function dn(i,e){let t=null;if(i&&Wt(i)){const r=jl(i,e);r&&(t=r);const s=B0(i,e);s&&(t=s)}else t=L("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return t}function Bl(i){return de(i.protocol,!0)}function k0(i,e){let t=!1;return i?i&&pt(i)&&i.length&&i.forEach(r=>{t=Bl(r)}):t=!0,t}function F0(i){return typeof i=="number"}function Fe(i){return typeof i<"u"&&typeof i!==null}function q0(i){return!(!i||typeof i!="object"||!i.code||!No(i.code,!1)||!i.message||!de(i.message,!1))}function M0(i){return!(Oe(i)||!de(i.method,!1))}function z0(i){return!(Oe(i)||Oe(i.result)&&Oe(i.error)||!No(i.id,!1)||!de(i.jsonrpc,!1))}function H0(i){return!(Oe(i)||!de(i.name,!1))}function Cc(i,e){return!(!gs(e)||!v0(i).includes(e))}function V0(i,e,t){return de(t,!1)?E0(i,e).includes(t):!1}function K0(i,e,t){return de(t,!1)?_0(i,e).includes(t):!1}function Rc(i,e,t){let r=null;const s=W0(i),n=G0(e),o=Object.keys(s),a=Object.keys(n),c=Nc(Object.keys(i)),h=Nc(Object.keys(e)),u=c.filter(l=>!h.includes(l));return u.length&&(r=L("NON_CONFORMING_NAMESPACES",`${t} namespaces keys don't satisfy requiredNamespaces. 7 Required: ${u.toString()} 8 Received: ${Object.keys(e).toString()}`)),ni(o,a)||(r=L("NON_CONFORMING_NAMESPACES",`${t} namespaces chains don't satisfy required namespaces. 9 Required: ${o.toString()} 10 Approved: ${a.toString()}`)),Object.keys(e).forEach(l=>{if(!l.includes(":")||r)return;const d=er(e[l].accounts);d.includes(l)||(r=L("NON_CONFORMING_NAMESPACES",`${t} namespaces accounts don't satisfy namespace accounts for ${l} 11 Required: ${l} 12 Approved: ${d.toString()}`))}),o.forEach(l=>{r||(ni(s[l].methods,n[l].methods)?ni(s[l].events,n[l].events)||(r=L("NON_CONFORMING_NAMESPACES",`${t} namespaces events don't satisfy namespace events for ${l}`)):r=L("NON_CONFORMING_NAMESPACES",`${t} namespaces methods don't satisfy namespace methods for ${l}`))}),r}function W0(i){const e={};
12return Object.keys(i).forEach(t=>{var r;t.includes(":")?e[t]=i[t]:(r=i[t].chains)==null||r.forEach(s=>{e[s]={methods:i[t].methods,events:i[t].events}})}),e}function Nc(i){return[...new Set(i.map(e=>e.includes(":")?e.split(":")[0]:e))]}function G0(i){const e={};return Object.keys(i).forEach(t=>{t.includes(":")?e[t]=i[t]:er(i[t].accounts)?.forEach(s=>{e[s]={accounts:i[t].accounts.filter(n=>n.includes(`${s}:`)),methods:i[t].methods,events:i[t].events}})}),e}function Y0(i,e){return No(i,!1)&&i<=e.max&&i>=e.min}function Tc(){const i=Rr();return new Promise(e=>{switch(i){case Ye.browser:e(J0());break;case Ye.reactNative:e(Z0());break;case Ye.node:e(Q0());break;default:e(!0)}})}function J0(){return Zi()&&navigator?.onLine}async function Z0(){return Gt()&&typeof H<"u"&&H!=null&&H.NetInfo?(await(H==null?void 0:H.NetInfo.fetch()))?.isConnected:!0}function Q0(){return!0}function X0(i){switch(Rr()){case Ye.browser:eE(i);break;case Ye.reactNative:tE(i);break}}function eE(i){!Gt()&&Zi()&&(window.addEventListener("online",()=>i(!0)),window.addEventListener("offline",()=>i(!1)))}function tE(i){Gt()&&typeof H<"u"&&H!=null&&H.NetInfo&&H?.NetInfo.addEventListener(e=>i(e?.isConnected))}function iE(){var i;return Zi()&&Ut.getDocument()?((i=Ut.getDocument())==null?void 0:i.visibilityState)==="visible":!0}const pn={};class ar{static get(e){return pn[e]}static set(e,t){pn[e]=t}static delete(e){delete pn[e]}}let di=class{},rE=class extends di{constructor(e){super()}};const jc=U.FIVE_SECONDS,pi={pulse:"heartbeat_pulse"};let sE=class Ul extends rE{constructor(e){super(e),this.events=new st.EventEmitter,this.interval=jc,this.interval=e?.interval||jc}static async init(e){const t=new Ul(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(pi.pulse)}};const nE=/"(?:_|\\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*:/,oE=/"(?: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*:/,aE=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function cE(i,e){if(i==="__proto__"||i==="constructor"&&e&&typeof e=="object"&&"prototype"in e){hE(i);return}return e}function hE(i){console.warn(`[destr] Dropping "${i}" key to prevent prototype pollution.`)}function Yr(i,e={}){if(typeof i!="string")return i;const t=i.trim();if(i[0]==='"'&&i.endsWith('"')&&!i.includes("\\"))return t.slice(1,-1);if(t.length<=9){const r=t.toLowerCase();if(r==="true")return!0;if(r==="false")return!1;if(r==="undefined")return;if(r==="null")return null;if(r==="nan")return Number.NaN;if(r==="infinity")return Number.POSITIVE_INFINITY;if(r==="-infinity")return Number.NEGATIVE_INFINITY}if(!aE.test(i)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return i}try{if(nE.test(i)||oE.test(i)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(i,cE)}return JSON.parse(i)}catch(r){if(e.strict)throw r;return i}}function uE(i){return!i||typeof i.then!="function"?Promise.resolve(i):i}function we(i,...e){try{return uE(i(...e))}catch(t){return Promise.reject(t)}}function lE(i){const e=typeof i;return i===null||e!=="object"&&e!=="function"}function dE(i){const e=Object.getPrototypeOf(i);return!e||e.isPrototypeOf(Object)}function os(i){if(lE(i))return String(i);if(dE(i)||Array.isArray(i))return JSON.stringify(i);if(typeof i.toJSON=="function")return os(i.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Ll(){if(typeof ge===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}const Zn="base64:";function pE(i){if(typeof i=="string")return i;Ll();const e=ge.from(i).toString("base64");return Zn+e}function fE(i){return typeof i!="string"||!i.startsWith(Zn)?i:(Ll(),ge.from(i.slice(Zn.length),"base64"))}function ke(i){return i?i.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function gE(...i){return ke(i.join(":"))}function Jr(i){return i=ke(i),i?i+":":""}const yE="memory",mE=()=>{const i=new Map;return{name:yE,options:{},hasItem(e){return i.has(e)},getItem(e){return i.get(e)??null},getItemRaw(e){return i.get(e)??null},setItem(e,t){i.set(e,t)},setItemRaw(e,t){i.set(e,t)},removeItem(e){i.delete(e)},getKeys(){return Array.from(i.keys())},clear(){i.clear()},dispose(){i.clear()}}};function wE(i={}){const e={mounts:{"":i.driver||mE()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}}
12,t=h=>{for(const u of e.mountpoints)if(h.startsWith(u))return{base:u,relativeKey:h.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:h,driver:e.mounts[""]}},r=(h,u)=>e.mountpoints.filter(l=>l.startsWith(h)||u&&h.startsWith(l)).map(l=>({relativeBase:h.length>l.length?h.slice(l.length):void 0,mountpoint:l,driver:e.mounts[l]})),s=(h,u)=>{if(e.watching){u=ke(u);for(const l of e.watchListeners)l(h,u)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await Bc(e.mounts[h],s,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,u,l)=>{const d=new Map,f=p=>{let g=d.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},d.set(p.base,g)),g};for(const p of h){const g=typeof p=="string",y=ke(g?p:p.key),b=g?void 0:p.value,m=g||!p.options?u:{...u,...p.options},v=t(y);f(v).items.push({key:y,value:b,relativeKey:v.relativeKey,options:m})}return Promise.all([...d.values()].map(p=>l(p))).then(p=>p.flat())},c={hasItem(h,u={}){h=ke(h);const{relativeKey:l,driver:d}=t(h);return we(d.hasItem,l,u)},getItem(h,u={}){h=ke(h);const{relativeKey:l,driver:d}=t(h);return we(d.getItem,l,u).then(f=>Yr(f))},getItems(h,u){return a(h,u,l=>l.driver.getItems?we(l.driver.getItems,l.items.map(d=>({key:d.relativeKey,options:d.options})),u).then(d=>d.map(f=>({key:gE(l.base,f.key),value:Yr(f.value)}))):Promise.all(l.items.map(d=>we(l.driver.getItem,d.relativeKey,d.options).then(f=>({key:d.key,value:Yr(f)})))))},getItemRaw(h,u={}){h=ke(h);const{relativeKey:l,driver:d}=t(h);return d.getItemRaw?we(d.getItemRaw,l,u):we(d.getItem,l,u).then(f=>fE(f))},async setItem(h,u,l={}){if(u===void 0)return c.removeItem(h);h=ke(h);const{relativeKey:d,driver:f}=t(h);f.setItem&&(await we(f.setItem,d,os(u),l),f.watch||s("update",h))},async setItems(h,u){await a(h,u,async l=>{if(l.driver.setItems)return we(l.driver.setItems,l.items.map(d=>({key:d.relativeKey,value:os(d.value),options:d.options})),u);l.driver.setItem&&await Promise.all(l.items.map(d=>we(l.driver.setItem,d.relativeKey,os(d.value),d.options)))})},async setItemRaw(h,u,l={}){if(u===void 0)return c.removeItem(h,l);h=ke(h);const{relativeKey:d,driver:f}=t(h);if(f.setItemRaw)await we(f.setItemRaw,d,u,l);else if(f.setItem)await we(f.setItem,d,pE(u),l);else return;f.watch||s("update",h)},async removeItem(h,u={}){typeof u=="boolean"&&(u={removeMeta:u}),h=ke(h);const{relativeKey:l,driver:d}=t(h);d.removeItem&&(await we(d.removeItem,l,u),(u.removeMeta||u.removeMata)&&await we(d.removeItem,l+"$",u),d.watch||s("remove",h))},async getMeta(h,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),h=ke(h);const{relativeKey:l,driver:d}=t(h),f=Object.create(null);if(d.getMeta&&Object.assign(f,await we(d.getMeta,l,u)),!u.nativeOnly){const p=await we(d.getItem,l+"$",u).then(g=>Yr(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(f,p))}return f},setMeta(h,u,l={}){return this.setItem(h+"$",u,l)},removeMeta(h,u={}){return this.removeItem(h+"$",u)},async getKeys(h,u={}){h=Jr(h);const l=r(h,!0);let d=[];const f=[];for(const p of l){const y=(await we(p.driver.getKeys,p.relativeBase,u)).map(b=>p.mountpoint+ke(b)).filter(b=>!d.some(m=>b.startsWith(m)));f.push(...y),d=[p.mountpoint,...d.filter(b=>!b.startsWith(p.mountpoint))]}return h?f.filter(p=>p.startsWith(h)&&!p.endsWith("$")):f.filter(p=>!p.endsWith("$"))},async clear(h,u={}){h=Jr(h),await Promise.all(r(h,!1).map(async l=>{if(l.driver.clear)return we(l.driver.clear,l.relativeBase,u);if(l.driver.removeItem){const d=await l.driver.getKeys(l.relativeBase||"",u);return Promise.all(d.map(f=>l.driver.removeItem(f,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>Uc(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,u){if(h=Jr(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((l,d)=>d.length-l.length)),e.mounts[h]=u,e.watching&&Promise.resolve(Bc(u,s,h)).then(l=>{e.unwatch[h]=l}).catch(console.error),c},async unmount(h,u=!0){h=Jr(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&(e.unwatch[h](),delete e.unwatch[h]),u&&await Uc(e.mounts[h]),e.mountpoints=e.mountpoints.filter(l=>l!==h),delete e.mounts[h])},getMount(h=""){h=ke(h)+":";const u=t(h);return{driver:u.driver,base:u.base}},getMounts(h="",u={}){return h=ke(h),r(h,u.parents).map(d=>({driver:d.driver,base:d.mountpoint}))}};return c}function Bc(i,e,t){return i.watch?i.watch((r,s)=>e(r,t+s)):()=>{}}async function Uc(i){typeof i.dispose=="function"&&await we(i.dispose)}
12function kl(i){if(typeof i!="string")throw new Error(`Cannot safe json parse value of type ${typeof i}`);try{return JSON.parse(i)}catch{return i}}function Fl(i){return typeof i=="string"?i:JSON.stringify(i)}const bE="idb-keyval";var vE=(i={})=>{const e=i.base&&i.base.length>0?`${i.base}:`:"",t=s=>e+s;let r;return i.dbName&&i.storeName&&(r=Ld(i.dbName,i.storeName)),{name:bE,options:i,async hasItem(s){return!(typeof await Yo(t(s),r)>"u")},async getItem(s){return await Yo(t(s),r)??null},setItem(s,n){return Md(t(s),n,r)},removeItem(s){return qd(t(s),r)},getKeys(){return Fd(r)},clear(){return kd(r)}}};const EE="WALLET_CONNECT_V2_INDEXED_DB",_E="keyvaluestorage";let IE=class{constructor(){this.indexedDb=wE({driver:vE({dbName:EE,storeName:_E})})}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,Fl(t))}async removeItem(e){await this.indexedDb.removeItem(e)}};var fn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof H<"u"?H:typeof self<"u"?self:{},as={exports:{}};(function(){let i;function e(){}i=e,i.prototype.getItem=function(t){return this.hasOwnProperty(t)?String(this[t]):null},i.prototype.setItem=function(t,r){this[t]=String(r)},i.prototype.removeItem=function(t){delete this[t]},i.prototype.clear=function(){const t=this;Object.keys(t).forEach(function(r){t[r]=void 0,delete t[r]})},i.prototype.key=function(t){return t=t||0,Object.keys(this)[t]},i.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof fn<"u"&&fn.localStorage?as.exports=fn.localStorage:typeof window<"u"&&window.localStorage?as.exports=window.localStorage:as.exports=new e})();function $E(i){var e;return[i[0],kl((e=i[1])!=null?e:"")]}let SE=class{constructor(){this.localStorage=as.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map($E)}async getItem(e){const t=this.localStorage.getItem(e);if(t!==null)return kl(t)}async setItem(e,t){this.localStorage.setItem(e,Fl(t))}async removeItem(e){this.localStorage.removeItem(e)}};const DE="wc_storage_version",Lc=1,OE=async(i,e,t)=>{const r=DE,s=await e.getItem(r);if(s&&s>=Lc){t(e);return}const n=await i.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 h=await i.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(r,Lc),t(e),PE(i,o)},PE=async(i,e)=>{e.length&&e.forEach(async t=>{await i.removeItem(t)})};let AE=class{constructor(){this.initialized=!1,this.setInitialized=t=>{this.storage=t,this.initialized=!0};const e=new SE;this.storage=e;try{const t=new IE;OE(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 gn,kc;function xE(){if(kc)return gn;kc=1;function i(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}gn=e;function e(t,r,s){var n=s&&s.stringify||i,o=1;if(typeof t=="object"&&t!==null){var a=r.length+o;if(a===1)return t;var c=new Array(a);c[0]=n(t);for(var h=1;h<a;h++)c[h]=n(r[h]);return c.join(" ")}if(typeof t!="string")return t;var u=r.length;if(u===0)return t;for(var l="",d=1-o,f=-1,p=t&&t.length||0,g=0;g<p;){if(t.charCodeAt(g)===37&&g+1<p){switch(f=f>-1?f:0,t.charCodeAt(g+1)){case 100:case 102:if(d>=u||r[d]==null)break;f<g&&(l+=t.slice(f,g)),l+=Number(r[d]),f=g+2,g++;break;case 105:if(d>=u||r[d]==null)break;f<g&&(l+=t.slice(f,g)),l+=Math.floor(Number(r[d])),f=g+2,g++;break;case 79:case 111:case 106:if(d>=u||r[d]===void 0)break;f<g&&(l+=t.slice(f,g));var y=typeof r[d];if(y==="string"){l+="'"+r[d]+"'",f=g+2,g++;break}if(y==="function"){l+=r[d].name||"<anonymous>",f=g+2,g++;break}l+=n(r[d]),f=g+2,g++;break;case 115:if(d>=u)break;f<g&&(l+=t.slice(f,g)),l+=String(r[d]),f=g+2,g++;break;case 37:f<g&&(l+=t.slice(f,g)),l+="%",f=g+2,g++,d--;break}++d}++g}return f===-1?t:(f<p&&(l+=t.slice(f)),l)}return gn}var yn,Fc;function CE(){if(Fc)return yn;Fc=1;const i=xE();yn=s;const e=x().console||{},t={mapHttpRequest:p,mapHttpResponse:p,wrapRequestSerializer:g,wrapResponseSerializer:g,wrapErrorSerializer:g,req:p,res:p,err:d};function r(w,_){return Array.isArray(w)?w.filter(function(I){return I!=="!stdSerializers.err"}):w===!0?Object.keys(_):!1}function s(w){w=w||{},w.browser=w.browser||{};const _=w.browser.transmit;if(_&&typeof _.send!="function")throw Error("pino: transmit option must have a send function");const $=w.browser.write||e;w.browser.write&&(w.browser.asObject=!0);const I=w.serializers||{},j=r(w.browser.serialize,I);let T=w.browser.serialize;Array.isArray(w.browser.serialize)&&w.browser.serialize.indexOf("!stdSerializers.err")>-1&&(T=!1);const B=["error","fatal","warn","info","debug","trace"];typeof $=="function"&&($.error=$.fatal=$.warn=$.info=$.debug=$.trace=$),w.enabled===!1&&(w.level="silent");const q=w.level||"info",S=Object.create($);S.log||(S.log=y),Object.defineProperty(S,"levelVal",{get:E}),Object.defineProperty(S,"level",{get:A,set:C}
12);const D={transmit:_,serialize:j,asObject:w.browser.asObject,levels:B,timestamp:f(w)};S.levels=s.levels,S.level=q,S.setMaxListeners=S.getMaxListeners=S.emit=S.addListener=S.on=S.prependListener=S.once=S.prependOnceListener=S.removeListener=S.removeAllListeners=S.listeners=S.listenerCount=S.eventNames=S.write=S.flush=y,S.serializers=I,S._serialize=j,S._stdErrSerialize=T,S.child=P,_&&(S._logEvent=l());function E(){return this.level==="silent"?1/0:this.levels.values[this.level]}function A(){return this._level}function C(R){if(R!=="silent"&&!this.levels.values[R])throw Error("unknown level "+R);this._level=R,n(D,S,"error","log"),n(D,S,"fatal","error"),n(D,S,"warn","error"),n(D,S,"info","log"),n(D,S,"debug","log"),n(D,S,"trace","log")}function P(R,k){if(!R)throw new Error("missing bindings for child Pino");k=k||{},j&&R.serializers&&(k.serializers=R.serializers);const F=k.serializers;if(j&&F){var M=Object.assign({},I,F),z=w.browser.serialize===!0?Object.keys(M):j;delete R.serializers,c([R],z,M,this._stdErrSerialize)}function K(V){this._childLevel=(V._childLevel|0)+1,this.error=h(V,R,"error"),this.fatal=h(V,R,"fatal"),this.warn=h(V,R,"warn"),this.info=h(V,R,"info"),this.debug=h(V,R,"debug"),this.trace=h(V,R,"trace"),M&&(this.serializers=M,this._serialize=z),_&&(this._logEvent=l([].concat(V._logEvent.bindings,R)))}return K.prototype=this,new K(this)}return S}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:b,epochTime:m,unixTime:v,isoTime:O});function n(w,_,$,I){const j=Object.getPrototypeOf(_);_[$]=_.levelVal>_.levels.values[$]?y:j[$]?j[$]:e[$]||e[I]||y,o(w,_,$)}function o(w,_,$){!w.transmit&&_[$]===y||(_[$]=(function(I){return function(){const T=w.timestamp(),B=new Array(arguments.length),q=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var S=0;S<B.length;S++)B[S]=arguments[S];if(w.serialize&&!w.asObject&&c(B,this._serialize,this.serializers,this._stdErrSerialize),w.asObject?I.call(q,a(this,$,B,T)):I.apply(q,B),w.transmit){const D=w.transmit.level||_.level,E=s.levels.values[D],A=s.levels.values[$];if(A<E)return;u(this,{ts:T,methodLevel:$,methodValue:A,transmitValue:s.levels.values[w.transmit.level||_.level],send:w.transmit.send,val:_.levelVal},B)}}})(_[$]))}function a(w,_,$,I){w._serialize&&c($,w._serialize,w.serializers,w._stdErrSerialize);const j=$.slice();let T=j[0];const B={};I&&(B.time=I),B.level=s.levels.values[_];let q=(w._childLevel|0)+1;if(q<1&&(q=1),T!==null&&typeof T=="object"){for(;q--&&typeof j[0]=="object";)Object.assign(B,j.shift());T=j.length?i(j.shift(),j):void 0}else typeof T=="string"&&(T=i(j.shift(),j));return T!==void 0&&(B.msg=T),B}function c(w,_,$,I){for(const j in w)if(I&&w[j]instanceof Error)w[j]=s.stdSerializers.err(w[j]);else if(typeof w[j]=="object"&&!Array.isArray(w[j]))for(const T in w[j])_&&_.indexOf(T)>-1&&T in $&&(w[j][T]=$[T](w[j][T]))}function h(w,_,$){return function(){const I=new Array(1+arguments.length);I[0]=_;for(var j=1;j<I.length;j++)I[j]=arguments[j-1];return w[$].apply(this,I)}}function u(w,_,$){const I=_.send,j=_.ts,T=_.methodLevel,B=_.methodValue,q=_.val,S=w._logEvent.bindings;c($,w._serialize||Object.keys(w.serializers),w.serializers,w._stdErrSerialize===void 0?!0:w._stdErrSerialize),w._logEvent.ts=j,w._logEvent.messages=$.filter(function(D){return S.indexOf(D)===-1}),w._logEvent.level.label=T,w._logEvent.level.value=B,I(T,w._logEvent,q),w._logEvent=l(S)}function l(w){return{ts:0,messages:[],bindings:w||[],level:{label:"",value:0}}}function d(w){const _={type:w.constructor.name,msg:w.message,stack:w.stack};for(const $ in w)_[$]===void 0&&(_[$]=w[$]);return _}function f(w){return typeof w.timestamp=="function"?w.timestamp:w.timestamp===!1?b:m}function p(){return{}}function g(w){return w}function y(){}function b(){return!1}function m(){return Date.now()}function v(){return Math.round(Date.now()/1e3)}function O(){return new Date(Date.now()).toISOString()}function x(){function w(_){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 w(self)||w(window)||w(this)||{}}}return yn}var ji=CE();const Lr=tu(ji),RE=i=>JSON.stringify(i,(e,t)=>typeof t=="bigint"?t.toString()+"n":t),NE=i=>{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=i.replace(e,'$1"$2n"$3');return JSON.parse(t,(r,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};
12function Qn(i){if(typeof i!="string")throw new Error(`Cannot safe json parse value of type ${typeof i}`);try{return NE(i)}catch{return i}}function ys(i){return typeof i=="string"?i:RE(i)||""}const TE={level:"info"},kr="custom_context",To=1e3*1024;let jE=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}},qc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new jE(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}}}}},ql=class{constructor(e,t=To){this.level=e??"error",this.levelValue=ji.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new qc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===ji.levels.values.error?console.error(e):t===ji.levels.values.warn?console.warn(e):t===ji.levels.values.debug?console.debug(e):t===ji.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(ys({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 qc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(ys({extraMetadata:e})),new Blob(t,{type:"application/json"})}},BE=class{constructor(e,t=To){this.baseChunkLogger=new ql(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)),r=document.createElement("a");r.href=t,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(t)}},UE=class{constructor(e,t=To){this.baseChunkLogger=new ql(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 LE=Object.defineProperty,kE=Object.defineProperties,FE=Object.getOwnPropertyDescriptors,Mc=Object.getOwnPropertySymbols,qE=Object.prototype.hasOwnProperty,ME=Object.prototype.propertyIsEnumerable,zc=(i,e,t)=>e in i?LE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ms=(i,e)=>{for(var t in e||(e={}))qE.call(e,t)&&zc(i,t,e[t]);if(Mc)for(var t of Mc(e))ME.call(e,t)&&zc(i,t,e[t]);return i},ws=(i,e)=>kE(i,FE(e));function Rs(i){return ws(ms({},i),{level:i?.level||TE.level})}function zE(i,e=kr){return i[e]||""}function HE(i,e,t=kr){return i[t]=e,i}function ze(i,e=kr){let t="";return typeof i.bindings>"u"?t=zE(i,e):t=i.bindings().context||"",t}function VE(i,e,t=kr){const r=ze(i,t);return r.trim()?`${r}/${e}`:e}function Be(i,e,t=kr){const r=VE(i,e,t),s=i.child({context:r});return HE(s,r,t)}function KE(i){var e,t;const r=new BE((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:Lr(ws(ms({},i.opts),{level:"trace",browser:ws(ms({},(t=i.opts)==null?void 0:t.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function WE(i){var e;const t=new UE((e=i.opts)==null?void 0:e.level,i.maxSizeInBytes);return{logger:Lr(ws(ms({},i.opts),{level:"trace"}),t),chunkLoggerController:t}}function GE(i){return typeof i.loggerOverride<"u"&&typeof i.loggerOverride!="string"?{logger:i.loggerOverride,chunkLoggerController:null}:typeof window<"u"?KE(i):WE(i)}var YE=Object.defineProperty,JE=(i,e,t)=>e in i?YE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Hc=(i,e,t)=>JE(i,typeof e!="symbol"?e+"":e,t);let ZE=class extends di{constructor(e){super(),this.opts=e,Hc(this,"protocol","wc"),Hc(this,"version",2)}};var QE=Object.defineProperty,XE=(i,e,t)=>e in i?QE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,e1=(i,e,t)=>XE(i,e+"",t);let t1=class extends di{constructor(e,t){super(),this.core=e,this.logger=t,e1(this,"records",new Map)}},i1=class{constructor(e,t){this.logger=e,this.core=t}};class r1 extends di{constructor(e,t){super(),this.relayer=e,this.logger=t}}let s1=class extends di{constructor(e){super()}},n1=class{constructor(e,t,r,s){this.core=e,this.logger=t,this.name=r}},o1=class extends di{constructor(e,t){super(),this.relayer=e,this.logger=t}},a1=class extends di{constructor(e,t){super(),this.core=e,this.logger=t}},c1=class{constructor(e,t,r){this.core=e,this.logger=t,this.store=r}},h1=class{constructor(e,t){this.projectId=e,this.logger=t}},u1=class{constructor(e,t,r){this.core=e,this.logger=t,this.telemetryEnabled=r}};const l1="PARSE_ERROR",d1="INVALID_REQUEST",p1="METHOD_NOT_FOUND",f1="INVALID_PARAMS",Ml="INT
12ERNAL_ERROR",jo="SERVER_ERROR",g1=[-32700,-32600,-32601,-32602,-32603],mr={[l1]:{code:-32700,message:"Parse error"},[d1]:{code:-32600,message:"Invalid Request"},[p1]:{code:-32601,message:"Method not found"},[f1]:{code:-32602,message:"Invalid params"},[Ml]:{code:-32603,message:"Internal error"},[jo]:{code:-32e3,message:"Server error"}},zl=jo;function y1(i){return g1.includes(i)}function Vc(i){return Object.keys(mr).includes(i)?mr[i]:mr[zl]}function m1(i){const e=Object.values(mr).find(t=>t.code===i);return e||mr[zl]}var mn={},xt={},Kc;function w1(){if(Kc)return xt;Kc=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.isBrowserCryptoAvailable=xt.getSubtleCrypto=xt.getBrowerCrypto=void 0;function i(){return(mi===null||mi===void 0?void 0:mi.crypto)||(mi===null||mi===void 0?void 0:mi.msCrypto)||{}}xt.getBrowerCrypto=i;function e(){const r=i();return r.subtle||r.webkitSubtle}xt.getSubtleCrypto=e;function t(){return!!i()&&!!e()}return xt.isBrowserCryptoAvailable=t,xt}var Ct={},Wc;function b1(){if(Wc)return Ct;Wc=1,Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.isBrowser=Ct.isNode=Ct.isReactNative=void 0;function i(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ct.isReactNative=i;function e(){return typeof rt<"u"&&typeof rt.versions<"u"&&typeof rt.versions.node<"u"}Ct.isNode=e;function t(){return!i()&&!e()}return Ct.isBrowser=t,Ct}var Gc;function v1(){return Gc||(Gc=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0});const e=Ar;e.__exportStar(w1(),i),e.__exportStar(b1(),i)})(mn)),mn}var E1=v1();function vt(i=3){const e=Date.now()*Math.pow(10,i),t=Math.floor(Math.random()*Math.pow(10,i));return e+t}function oi(i=6){return BigInt(vt(i))}function Vt(i,e,t){return{id:t||vt(),jsonrpc:"2.0",method:i,params:e}}function Ns(i,e){return{id:i,jsonrpc:"2.0",result:e}}function Hl(i,e,t){return{id:i,jsonrpc:"2.0",error:_1(e)}}function _1(i,e){return typeof i>"u"?Vc(Ml):(typeof i=="string"&&(i=Object.assign(Object.assign({},Vc(jo)),{message:i})),y1(i.code)&&(i=m1(i.code)),i)}class I1{}class $1 extends I1{constructor(){super()}}class S1 extends $1{constructor(e){super()}}function Vl(i){return typeof i=="object"&&"id"in i&&"jsonrpc"in i&&i.jsonrpc==="2.0"}function Bo(i){return Vl(i)&&"method"in i}function Ts(i){return Vl(i)&&(Et(i)||tt(i))}function Et(i){return"result"in i}function tt(i){return"error"in i}let nt=class extends S1{constructor(e){super(e),this.events=new st.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,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(Vt(e.method,e.params||[],e.id||oi().toString()),t)}async requestStrict(e,t){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{tt(n)?s(n.error):r(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 D1="PARSE_ERROR",O1="INVALID_REQUEST",P1="METHOD_NOT_FOUND",A1="INVALID_PARAMS",Kl="INTERNAL_ERROR",Uo="SERVER_ERROR",x1=[-32700,-32600,-32601,-32602,-32603],wr={[D1]:{code:-32700,message:"Parse error"},[O1]:{code:-32600,message:"Invalid Request"},[P1]:{code:-32601,message:"Method not found"},[A1]:{code:-32602,message:"Invalid params"},[Kl]:{code:-32603,message:"Internal error"},[Uo]:{code:-32e3,message:"Server error"}},Wl=Uo;function C1(i){return x1.includes(i)}function Yc(i){return Object.keys(wr).includes(i)?wr[i]:wr[Wl]}function R1(i){const e=Object.values(wr).find(t=>t.code===i);return e||wr[Wl]}function N1(i,e,t){return i.message.includes("getaddrinfo ENOTFOUND")||i.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):i}function T1(i,e,t){return{id:i,jsonrpc:"2.0",error:j1(e)}}function j1(i,e){return typeof i>"u"?Yc(Kl):(typeof i=="string"&&(i=Object.assign(Object.assign({},Yc(Uo)),{message:i})),C1(i.code)&&(i=R1(i.code)),i)}const B1="^wss?:";function U1(i){const e=i.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function L1(i,e){const t=U1(i);return typeof t>"u"?!1:new RegExp(e).test(t)}
12function Jc(i){return L1(i,B1)}function k1(i){return new RegExp("wss?://localhost(:d{2,5})?").test(i)}const F1=()=>typeof WebSocket<"u"?WebSocket:typeof H<"u"&&typeof H.WebSocket<"u"?H.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),q1=()=>typeof WebSocket<"u"||typeof H<"u"&&typeof H.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Zc=i=>i.split("?")[0],Qc=10,M1=F1();let z1=class{constructor(e){if(this.url=e,this.events=new st.EventEmitter,this.registering=!1,!Jc(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=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ys(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Jc(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((r,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((t,r)=>{const s=E1.isReactNative()?void 0:{rejectUnauthorized:!k1(e)},n=new M1(e,[],s);q1()?n.onerror=o=>{const a=o;r(this.emitError(a.error))}:n.on("error",o=>{r(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"?Qn(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const r=this.parseError(t),s=r.message||r.toString(),n=T1(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return N1(e,Zc(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Qc&&this.events.setMaxListeners(Qc)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Zc(this.url)}`));return this.events.emit("register_error",t),t}};var H1={};const Gl="wc",Yl=2,Xn="core",$t=`${Gl}@2:${Xn}:`,V1={logger:"error"},K1={database:":memory:"},W1="crypto",Xc="client_ed25519_seed",G1=U.ONE_DAY,Y1="keychain",J1="0.3",Z1="messages",Q1="0.3",eh=U.SIX_HOURS,X1="publisher",Jl="irn",e_="error",Zl="wss://relay.walletconnect.org",t_="relayer",ve={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"},i_="_subscription",Qe={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},r_=.1,eo="2.21.1",ce={link_mode:"link_mode",relay:"relay"},cs={inbound:"inbound",outbound:"outbound"},s_="0.3",n_="WALLETCONNECT_CLIENT_ID",th="WALLETCONNECT_LINK_MODE_APPS",Ke={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},o_="subscription",a_="0.3",c_="pairing",h_="0.3",cr={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}}},ri={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ct={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},u_="history",l_="0.3",d_="expirer",et={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},p_="0.3",f_="verify-api",g_="https://verify.walletconnect.com",Ql="https://verify.walletconnect.org",br=Ql,y_=`${br}/v3`,m_=[g_,Ql],w_="echo",b_="https://echo.walletconnect.com",bt={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"},Rt={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"},ht={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"},Zt={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"},Qt={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"}
12,hr={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},v_=.1,E_="event-client",__=86400,I_="https://pulse.walletconnect.org/batch";function $_(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),u=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 g=0,y=0,b=0,m=p.length;b!==m&&p[b]===0;)b++,g++;for(var v=(m-b)*u+1>>>0,O=new Uint8Array(v);b!==m;){for(var x=p[b],w=0,_=v-1;(x!==0||w<y)&&_!==-1;_--,w++)x+=256*O[_]>>>0,O[_]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=w,b++}for(var $=v-y;$!==v&&O[$]===0;)$++;for(var I=c.repeat(g);$<v;++$)I+=i.charAt(O[$]);return I}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,b=0;p[g]===c;)y++,g++;for(var m=(p.length-g)*h+1>>>0,v=new Uint8Array(m);p[g];){var O=t[p.charCodeAt(g)];if(O===255)return;for(var x=0,w=m-1;(O!==0||x<b)&&w!==-1;w--,x++)O+=a*v[w]>>>0,v[w]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");b=x,g++}if(p[g]!==" "){for(var _=m-b;_!==m&&v[_]===0;)_++;for(var $=new Uint8Array(y+(m-_)),I=y;_!==m;)$[I++]=v[_++];return $}}}function f(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:f}}var S_=$_,D_=S_;const Xl=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")},O_=i=>new TextEncoder().encode(i),P_=i=>new TextDecoder().decode(i);class A_{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class x_{constructor(e,t,r){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=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ed(this,e)}}class C_{constructor(e){this.decoders=e}or(e){return ed(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ed=(i,e)=>new C_({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}});class R_{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new A_(e,t,r),this.decoder=new x_(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const js=({name:i,prefix:e,encode:t,decode:r})=>new R_(i,e,t,r),Fr=({prefix:i,name:e,alphabet:t})=>{const{encode:r,decode:s}=D_(t,e);return js({prefix:i,name:e,encode:r,decode:n=>Xl(s(n))})},N_=(i,e,t,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=i.length;for(;i[n-1]==="=";)--n;const o=new Uint8Array(n*t/8|0);let a=0,c=0,h=0;for(let u=0;u<n;++u){const l=s[i[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},T_=(i,e,t)=>{const r=e[e.length-1]==="=",s=(1<<t)-1;let n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),r)for(;n.length*t&7;)n+="=";return n},xe=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>js({prefix:e,name:i,encode(s){return T_(s,r,t)},decode(s){return N_(s,r,t,i)}}),j_=js({prefix:"\0",name:"identity",encode:i=>P_(i),decode:i=>O_(i)});var B_=Object.freeze({__proto__:null,identity:j_});const U_=xe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var L_=Object.freeze({__proto__:null,base2:U_});const k_=xe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var F_=Object.freeze({__proto__:null,base8:k_});const q_=Fr({prefix:"9",name:"base10",alphabet:"0123456789"});var M_=Object.freeze({__proto__:null,base10:q_});const z_=xe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),H_=xe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var V_=Object.freeze({__proto__:null,base16:z_,base16upper:H_});const K_=xe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),W_=xe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G_=xe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Y_=xe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),J_=xe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Z_=xe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q_=xe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),X_=xe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eI=xe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var tI=Object.freeze({__proto__:null,base32:K_,base32upper:W_,base32pad:G_,base32padupper:Y_,base32hex:J_,base32hexupper:Z_,base32hexpad:Q_,base32hexpadupper:X_,base32z:eI});const iI=Fr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),rI=Fr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sI=Object.freeze({__proto__:null,base36:iI,base36upper:rI});const nI=Fr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oI=Fr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var aI=Object.freeze({__proto__:null,base58btc:nI,base58flickr:oI});const cI=xe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
12+/",bitsPerChar:6}),hI=xe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uI=xe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lI=xe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dI=Object.freeze({__proto__:null,base64:cI,base64pad:hI,base64url:uI,base64urlpad:lI});const td=Array.from("ððªâð°ðððððððððððððâð»ð¥ð¾ð¿ðâ¤ðð¤£ððððððð
ððð¥ð¥°ðððð¢ð¤ðððªðâºðð¤ððððð¹ð¤¦ððââ¨ð¤·ð±ðð¸ððððððððð¤©ððð¤ðð¯ððð¶ðð¤â£ððððªðð¥ððð©ð¡ð¤ªðð¥³ð¥ð¤¤ððð³âððð´ðð¬ððð·ð»ðââ
ð¥ºððð¤ð¦âð£ððâ¹ððð âððºðð»ððððð¹ð£ð«ðððµð¤ðð´ð¤ð¼ð«â½ð¤âðð¤«ðð®ðð»ðð¶ðð²ð¿ð§¡ðâ¡ððââðð°ð¤¨ð¶ð¤ð¶ð°ðð¢ð¤ðð¨ð¨ð¤¬âððºð¤ððð±ðð¶ð¥´â¶â¡âðð¸â¬ð¨ðð¦ð·ðºâ ð
ððµðð¤²ð¤ ð¤§ððµð
ð§ð¾ððð¤ðð¤¯ð·âð§ð¯ððð¤ððâð´ð£ð¸ððð¥ð¤¢ð
ð¡ð©ðð¸ð»ð¤ð¤®ð¼ð¥µð©ððð¼ðð£ð¥"),pI=td.reduce((i,e,t)=>(i[t]=e,i),[]),fI=td.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function gI(i){return i.reduce((e,t)=>(e+=pI[t],e),"")}function yI(i){const e=[];for(const t of i){const r=fI[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}const mI=js({prefix:"ð",name:"base256emoji",encode:gI,decode:yI});var wI=Object.freeze({__proto__:null,base256emoji:mI}),bI=id,ih=128,vI=-128,EI=Math.pow(2,31);function id(i,e,t){e=e||[],t=t||0;for(var r=t;i>=EI;)e[t++]=i&255|ih,i/=128;for(;i&vI;)e[t++]=i&255|ih,i>>>=7;return e[t]=i|0,id.bytes=t-r+1,e}var _I=to,II=128,rh=127;function to(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw to.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&rh)<<s:(o&rh)*Math.pow(2,s),s+=7}while(o>=II);return to.bytes=n-r,t}var $I=Math.pow(2,7),SI=Math.pow(2,14),DI=Math.pow(2,21),OI=Math.pow(2,28),PI=Math.pow(2,35),AI=Math.pow(2,42),xI=Math.pow(2,49),CI=Math.pow(2,56),RI=Math.pow(2,63),NI=function(i){return i<$I?1:i<SI?2:i<DI?3:i<OI?4:i<PI?5:i<AI?6:i<xI?7:i<CI?8:i<RI?9:10},TI={encode:bI,decode:_I,encodingLength:NI},rd=TI;const sh=(i,e,t=0)=>(rd.encode(i,e,t),e),nh=i=>rd.encodingLength(i),io=(i,e)=>{const t=e.byteLength,r=nh(i),s=r+nh(t),n=new Uint8Array(s+t);return sh(i,n,0),sh(t,n,r),n.set(e,s),new jI(i,t,e,n)};class jI{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}}const sd=({name:i,code:e,encode:t})=>new BI(i,e,t);class BI{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?io(this.code,t):t.then(r=>io(this.code,r))}else throw Error("Unknown type, must be binary type")}}const nd=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),UI=sd({name:"sha2-256",code:18,encode:nd("SHA-256")}),LI=sd({name:"sha2-512",code:19,encode:nd("SHA-512")});var kI=Object.freeze({__proto__:null,sha256:UI,sha512:LI});const od=0,FI="identity",ad=Xl,qI=i=>io(od,ad(i)),MI={code:od,name:FI,encode:ad,digest:qI};var zI=Object.freeze({__proto__:null,identity:MI});new TextEncoder,new TextDecoder;const oh={...B_,...L_,...F_,...M_,...V_,...tI,...sI,...aI,...dI,...wI};({...kI,...zI});function HI(i=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(i):new Uint8Array(i)}function cd(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}const ah=cd("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),wn=cd("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);const e=HI(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),VI={utf8:ah,"utf-8":ah,hex:oh.base16,latin1:wn,ascii:wn,binary:wn,...oh};function KI(i,e="utf8"){const t=VI[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(i,"utf8"):t.decoder.decode(`${t.prefix}${i}`)}var WI=Object.defineProperty,GI=(i,e,t)=>e in i?WI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,mt=(i,e,t)=>GI(i,typeof e!="symbol"?e+"":e,t);class YI{constructor(e,t){this.core=e,this.logger=t,mt(this,"keychain",new Map),mt(this,"name",Y1),mt(this,"version",J1),mt(this,"initialized",!1),mt(this,"storagePrefix",$t),mt(this,"init",async()=>
12{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),mt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),mt(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),mt(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return s}),mt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Be(t,this.name)}get context(){return ze(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,kn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JI=Object.defineProperty,ZI=(i,e,t)=>e in i?JI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Se=(i,e,t)=>ZI(i,typeof e!="symbol"?e+"":e,t);class QI{constructor(e,t,r){this.core=e,this.logger=t,Se(this,"name",W1),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Jn()),Se(this,"initialized",!1),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Se(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=ka(s);return Vu(n.publicKey)}),Se(this,"generateKeyPair",()=>{this.isInitialized();const s=e0();return this.setPrivateKey(s.publicKey,s.privateKey)}),Se(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=ka(n),a=this.randomSessionIdentifier;return await mm(a,s,G1,o)}),Se(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=t0(a,n);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||ns(s);return await this.keychain.set(o,s),o}),Se(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Se(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Se(this,"encode",async(s,n,o)=>{this.isInitialized();const a=Tl(o),c=ys(n);if(Ic(a))return s0(c,o?.encoding);if(_c(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;s=await this.generateSharedKey(d,f)}const h=this.getSymKey(s),{type:u,senderPublicKey:l}=a;return i0({type:u,symKey:h,message:c,senderPublicKey:l,encoding:o?.encoding})}),Se(this,"decode",async(s,n,o)=>{this.isInitialized();const a=o0(n,o);if(Ic(a)){const c=n0(n,o?.encoding);return Qn(c)}if(_c(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;s=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(s),h=r0({symKey:c,encoded:n,encoding:o?.encoding});return Qn(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(s,n=dt)=>{const o=Pr({encoded:s,encoding:n});return li(o.type)}),Se(this,"getPayloadSenderPublicKey",(s,n=dt)=>{const o=Pr({encoded:s,encoding:n});return o.senderPublicKey?Me(o.senderPublicKey,je):void 0}),this.core=e,this.logger=Be(t,this.name),this.keychain=r||new YI(this.core,this.logger)}get context(){return ze(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(Xc)}catch{e=Jn(),await this.keychain.set(Xc,e)}return KI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XI=Object.defineProperty,e2=Object.defineProperties,t2=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,i2=Object.prototype.hasOwnProperty,r2=Object.prototype.propertyIsEnumerable,ro=(i,e,t)=>e in i?XI(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,s2=(i,e)=>{for(var t in e||(e={}))i2.call(e,t)&&ro(i,t,e[t]);if(ch)for(var t of ch(e))r2.call(e,t)&&ro(i,t,e[t]);return i},n2=(i,e)=>e2(i,t2(e)),He=(i,e,t)=>ro(i,typeof e!="symbol"?e+"":e,t);class o2 extends i1{constructor(e,t){super(e,t),this.logger=e,this.core=t,He(this,"messages",new Map),He(this,"messagesWithoutClientAck",new Map),He(this,"name",Z1),He(this,"version",Q1),He(this,"initialized",!1),He(this,"storagePrefix",$t),He(this,"init",async()=>
12{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),He(this,"set",async(r,s,n)=>{this.isInitialized();const o=_t(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),n===cs.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,n2(s2({},c),{[o]:s}))}return await this.persist(),o}),He(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),He(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),He(this,"has",(r,s)=>{this.isInitialized();const n=this.get(r),o=_t(s);return typeof n[o]<"u"}),He(this,"ack",async(r,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=_t(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),He(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Be(e,this.name),this.core=t}get context(){return ze(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,kn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,kn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Fn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var a2=Object.defineProperty,c2=Object.defineProperties,h2=Object.getOwnPropertyDescriptors,hh=Object.getOwnPropertySymbols,u2=Object.prototype.hasOwnProperty,l2=Object.prototype.propertyIsEnumerable,so=(i,e,t)=>e in i?a2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Zr=(i,e)=>{for(var t in e||(e={}))u2.call(e,t)&&so(i,t,e[t]);if(hh)for(var t of hh(e))l2.call(e,t)&&so(i,t,e[t]);return i},bn=(i,e)=>c2(i,h2(e)),ut=(i,e,t)=>so(i,typeof e!="symbol"?e+"":e,t);class d2 extends r1{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,ut(this,"events",new st.EventEmitter),ut(this,"name",X1),ut(this,"queue",new Map),ut(this,"publishTimeout",U.toMiliseconds(U.ONE_MINUTE)),ut(this,"initialPublishTimeout",U.toMiliseconds(U.ONE_SECOND*15)),ut(this,"needsTransportRestart",!1),ut(this,"publish",async(r,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:n}});const a=n?.ttl||eh,c=fs(n),h=n?.prompt||!1,u=n?.tag||0,l=n?.id||oi().toString(),d={topic:r,message:s,opts:{ttl:a,relay:c,prompt:h,tag:u,id:l,attestation:n?.attestation,tvf:n?.tvf}},f=`Failed to publish payload, please try again. id:${l} tag:${u}`;try{const p=new Promise(async g=>{const y=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(ve.publish,y),g(d))};this.relayer.events.on(ve.publish,y);const b=Ht(new Promise((m,v)=>{this.rpcPublish({topic:r,message:s,ttl:a,prompt:h,tag:u,id:l,attestation:n?.attestation,tvf:n?.tvf}).then(m).catch(O=>{this.logger.warn(O,O?.message),v(O)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${l} tag:${u}`);try{await b,this.events.removeListener(ve.publish,y)}catch(m){this.queue.set(l,bn(Zr({},d),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,topic:r,message:s,opts:n}}),await Ht(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(l)}}),ut(this,"on",(r,s)=>{this.events.on(r,s)}),ut(this,"once",(r,s)=>{this.events.once(r,s)}),ut(this,"off",(r,s)=>{this.events.off(r,s)}),ut(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=e,this.logger=Be(t,this.name),this.registerEventListeners()}get context(){return ze(this.logger)}async rpcPublish(e){var t,r,s,n;const{topic:o,message:a,ttl:c=eh,prompt:h,tag:u,id:l,attestation:d,tvf:f}=e,p={method:pr(fs().protocol).publish,params:Zr({topic:o,message:a,ttl:c,prompt:h,tag:u,attestation:d},f),id:l};Oe((t=p.params)==null?void 0:t.prompt)&&((r=p.params)==null||delete r.prompt),Oe((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 g=await this.relayer.request(p);return this.relayer.events.emit(ve.publish,e),this.logger.debug("Successfully Published Payload"),g}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,t)=>{const r=e.attempt+1;this.queue.set(t,bn(Zr({},e),{attempt:r}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(bn(Zr({},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(pi.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ve.connection_stalled);return}this.checkQueue()}),this.relayer.on(ve.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var p2=Object.defineProperty,f2=(i,e,t)=>e in i?p2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_i=(i,e,t)=>f2(i,typeof e!="symbol"?e+"":e,t);class g2{constructor(){_i(this,"map",new Map),_i(this,"set",(e,t)=>{const r=this.get(e);this.exists(e,t)||this.map.set(e,[...r,t])}),_i(this,"get",e=>this.map.get(e)||[]),_i(this,"exists",(e,t)=>this.get(e).includes(t)),_i(this,"delete",(e,t)=>{if(typeof t>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,t))return;const s=r.filter(n=>n!==t);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),_i(this,"clear",()=>{this.map.clear()})}
12get topics(){return Array.from(this.map.keys())}}var y2=Object.defineProperty,m2=Object.defineProperties,w2=Object.getOwnPropertyDescriptors,uh=Object.getOwnPropertySymbols,b2=Object.prototype.hasOwnProperty,v2=Object.prototype.propertyIsEnumerable,no=(i,e,t)=>e in i?y2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ur=(i,e)=>{for(var t in e||(e={}))b2.call(e,t)&&no(i,t,e[t]);if(uh)for(var t of uh(e))v2.call(e,t)&&no(i,t,e[t]);return i},vn=(i,e)=>m2(i,w2(e)),se=(i,e,t)=>no(i,typeof e!="symbol"?e+"":e,t);class E2 extends o1{constructor(e,t){super(e,t),this.relayer=e,this.logger=t,se(this,"subscriptions",new Map),se(this,"topicMap",new g2),se(this,"events",new st.EventEmitter),se(this,"name",o_),se(this,"version",a_),se(this,"pending",new Map),se(this,"cached",[]),se(this,"initialized",!1),se(this,"storagePrefix",$t),se(this,"subscribeTimeout",U.toMiliseconds(U.ONE_MINUTE)),se(this,"initialSubscribeTimeout",U.toMiliseconds(U.ONE_SECOND*15)),se(this,"clientId"),se(this,"batchSubscribeTopicsLimit",500),se(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),se(this,"subscribe",async(r,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const n=fs(s),o={topic:r,relay:n,transportType:s?.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),se(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),se(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),se(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),se(this,"on",(r,s)=>{this.events.on(r,s)}),se(this,"once",(r,s)=>{this.events.once(r,s)}),se(this,"off",(r,s)=>{this.events.off(r,s)}),se(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),se(this,"start",async()=>{await this.onConnect()}),se(this,"stop",async()=>{await this.onDisconnect()}),se(this,"restart",async()=>{await this.restore(),await this.onRestart()}),se(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),se(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(pi.pulse,async()=>{await this.checkPending()}),this.events.on(Ke.created,async r=>{const s=Ke.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(Ke.deleted,async r=>{const s=Ke.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=e,this.logger=Be(t,this.name),this.clientId=""}get context(){return ze(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 r=!1;try{r=this.getSubscription(e).topic===t}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,t){const r=this.topicMap.get(e);await Promise.all(r.map(async s=>await this.unsubscribeById(e,s,t)))}async unsubscribeById(e,t,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:r}});try{const s=fs(r);await this.restartToComplete({topic:e,id:t,relay:s}
12),await this.rpcUnsubscribe(e,t,s);const n=ie("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:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,t,r){var s;(!r||r?.transportType===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const n={method:pr(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(r?.transportType===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},U.toMiliseconds(U.ONE_SECOND)),a;const c=new Promise(async u=>{const l=d=>{d.topic===e&&(this.events.removeListener(Ke.created,l),u(d.id))};this.events.on(Ke.created,l);try{const d=await Ht(new Promise((f,p)=>{this.relayer.request(n).catch(g=>{this.logger.warn(g,g?.message),p(g)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ke.created,l),u(d)}catch{}}),h=await Ht(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ve.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const t=e[0].relay,r={method:pr(t.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Ht(new Promise(s=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ve.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const t=e[0].relay,r={method:pr(t.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await Ht(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ve.connection_stalled)}return s}rpcUnsubscribe(e,t,r){const s={method:pr(r.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,vn(ur({},t),{id:e})),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach(t=>{this.setSubscription(t.id,ur({},t)),this.pending.delete(t.topic)})}async onUnsubscribe(e,t,r){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,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,ur({},t)),this.topicMap.set(t.topic,e),this.events.emit(Ke.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:r}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const r=this.getSubscription(e);
12this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Ke.deleted,vn(ur({},r),{reason:t}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ke.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<t;r++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(Ke.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:t}=L("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=>vn(ur({}
12,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 qw(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}=L("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 _t(e+await this.getClientId())}}var _2=Object.defineProperty,lh=Object.getOwnPropertySymbols,I2=Object.prototype.hasOwnProperty,$2=Object.prototype.propertyIsEnumerable,oo=(i,e,t)=>e in i?_2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,dh=(i,e)=>{for(var t in e||(e={}))I2.call(e,t)&&oo(i,t,e[t]);if(lh)for(var t of lh(e))$2.call(e,t)&&oo(i,t,e[t]);return i},Q=(i,e,t)=>oo(i,typeof e!="symbol"?e+"":e,t);class S2 extends s1{constructor(e){super(e),Q(this,"protocol","wc"),Q(this,"version",2),Q(this,"core"),Q(this,"logger"),Q(this,"events",new st.EventEmitter),Q(this,"provider"),Q(this,"messages"),Q(this,"subscriber"),Q(this,"publisher"),Q(this,"name",t_),Q(this,"transportExplicitlyClosed",!1),Q(this,"initialized",!1),Q(this,"connectionAttemptInProgress",!1),Q(this,"relayUrl"),Q(this,"projectId"),Q(this,"packageName"),Q(this,"bundleId"),Q(this,"hasExperiencedNetworkDisruption",!1),Q(this,"pingTimeout"),Q(this,"heartBeatTimeout",U.toMiliseconds(U.THIRTY_SECONDS+U.FIVE_SECONDS)),Q(this,"reconnectTimeout"),Q(this,"connectPromise"),Q(this,"reconnectInProgress",!1),Q(this,"requestsInFlight",[]),Q(this,"connectTimeout",U.toMiliseconds(U.ONE_SECOND*15)),Q(this,"request",async t=>{var r,s;this.logger.debug("Publishing Request Payload");const n=t.id||oi().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:t.method,topic:(r=t.params)==null?void 0:r.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}}),Q(this,"resetPingTimeout",()=>{ds()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var t,r,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(r=(t=this.provider)==null?void 0:t.connection)==null?void 0:r.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),Q(this,"onPayloadHandler",t=>{this.onProviderPayload(t),this.resetPingTimeout()}),Q(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected ð"),this.startPingTimeout(),this.events.emit(ve.connect)}),Q(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected ð"),this.requestsInFlight=[],this.onProviderDisconnect()}),Q(this,"onProviderErrorHandler",t=>{this.logger.fatal(`Fatal socket error: ${t.message}`),this.events.emit(ve.error,t),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Q(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"?Be(e.logger,this.name):Lr(Rs({level:e.logger||e_})),this.messages=new o2(this.logger,e.core),this.subscriber=new E2(this,this.logger),this.publisher=new d2(this,this.logger),this.relayUrl=e?.relayUrl||Zl,this.projectId=e.projectId,Sw()?this.packageName=Ka():Dw()&&(this.bundleId=Ka()),this.provider={}}
12async 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?.message)}}get context(){return ze(this.logger)}get connected(){var e,t,r;return((r=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,t,r;return((r=(t=(e=this.provider)==null?void 0:e.connection)==null?void 0:t.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,t,r){this.isInitialized(),await this.publisher.publish(e,t,r),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:ce.relay},cs.outbound)}async subscribe(e,t){var r,s,n;this.isInitialized(),(!(t!=null&&t.transportType)||t?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=t?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=t?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=u=>{u.topic===e&&(this.subscriber.off(Ke.created,h),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(Ke.created,h)}),new Promise(async(u,l)=>{a=await this.subscriber.subscribe(e,dh({internal:{throwOnFailedPublish:o}},t)).catch(d=>{o&&l(d)})||a,u()})]),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 Ht(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,r)=>{await this.connect(e).then(t).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Tc())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const t=e.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${t.length} message events sorted`);for(const r of t)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:r}=e;if(!t.sessionExists){const s=pe(U.FIVE_MINUTES),n={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(ve.message,e),await this.recordMessageEvent(e,cs.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(r,s)=>{const n=()=>
12{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Qe.disconnect,n),await Ht(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,r()})}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise(r=>setTimeout(r,U.toMiliseconds(t*1))),t++}}startPingTimeout(){var e,t,r,s,n;if(ds())try{(t=(e=this.provider)==null?void 0:e.connection)!=null&&t.socket&&((n=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new nt(new z1(Cw({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:r,message:s}=e;await this.messages.set(r,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Bo(e)){if(!e.method.endsWith(i_))return;const t=e.params,{topic:r,message:s,publishedAt:n,attestation:o}=t.data,a={topic:r,message:s,publishedAt:n,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(dh({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(ve.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,cs.inbound),this.events.emit(ve.message,e))}async acknowledgePayload(e){const t=Ns(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 Tc();X0(async t=>{e!==t&&(e=t,t?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(pi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&iE())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(t){this.logger.warn(t,t?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ve.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},U.toMiliseconds(r_)))))}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function D2(){}function ph(i){if(!i||typeof i!="object")return!1;const e=Object.getPrototypeOf(i);
12return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(i)==="[object Object]":!1}function fh(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}function gh(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const O2="[object RegExp]",P2="[object String]",A2="[object Number]",x2="[object Boolean]",yh="[object Arguments]",C2="[object Symbol]",R2="[object Date]",N2="[object Map]",T2="[object Set]",j2="[object Array]",B2="[object Function]",U2="[object ArrayBuffer]",En="[object Object]",L2="[object Error]",k2="[object DataView]",F2="[object Uint8Array]",q2="[object Uint8ClampedArray]",M2="[object Uint16Array]",z2="[object Uint32Array]",H2="[object BigUint64Array]",V2="[object Int8Array]",K2="[object Int16Array]",W2="[object Int32Array]",G2="[object BigInt64Array]",Y2="[object Float32Array]",J2="[object Float64Array]";function Z2(i,e){return i===e||Number.isNaN(i)&&Number.isNaN(e)}function Q2(i,e,t){return fr(i,e,void 0,void 0,void 0,void 0,t)}function fr(i,e,t,r,s,n,o){const a=o(i,e,t,r,s,n);if(a!==void 0)return a;if(typeof i==typeof e)switch(typeof i){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return i===e;case"number":return i===e||Object.is(i,e);case"function":return i===e;case"object":return vr(i,e,n,o)}return vr(i,e,n,o)}function vr(i,e,t,r){if(Object.is(i,e))return!0;let s=gh(i),n=gh(e);if(s===yh&&(s=En),n===yh&&(n=En),s!==n)return!1;switch(s){case P2:return i.toString()===e.toString();case A2:{const c=i.valueOf(),h=e.valueOf();return Z2(c,h)}case x2:case R2:case C2:return Object.is(i.valueOf(),e.valueOf());case O2:return i.source===e.source&&i.flags===e.flags;case B2:return i===e}t=t??new Map;const o=t.get(i),a=t.get(e);if(o!=null&&a!=null)return o===e;t.set(i,e),t.set(e,i);try{switch(s){case N2:{if(i.size!==e.size)return!1;for(const[c,h]of i.entries())if(!e.has(c)||!fr(h,e.get(c),c,i,e,t,r))return!1;return!0}case T2:{if(i.size!==e.size)return!1;const c=Array.from(i.values()),h=Array.from(e.values());for(let u=0;u<c.length;u++){const l=c[u],d=h.findIndex(f=>fr(l,f,void 0,i,e,t,r));if(d===-1)return!1;h.splice(d,1)}return!0}case j2:case F2:case q2:case M2:case z2:case H2:case V2:case K2:case W2:case G2:case Y2:case J2:{if(typeof ge<"u"&&ge.isBuffer(i)!==ge.isBuffer(e)||i.length!==e.length)return!1;for(let c=0;c<i.length;c++)if(!fr(i[c],e[c],c,i,e,t,r))return!1;return!0}case U2:return i.byteLength!==e.byteLength?!1:vr(new Uint8Array(i),new Uint8Array(e),t,r);case k2:return i.byteLength!==e.byteLength||i.byteOffset!==e.byteOffset?!1:vr(new Uint8Array(i),new Uint8Array(e),t,r);case L2:return i.name===e.name&&i.message===e.message;case En:{if(!(vr(i.constructor,e.constructor,t,r)||ph(i)&&ph(e)))return!1;const c=[...Object.keys(i),...fh(i)],h=[...Object.keys(e),...fh(e)];if(c.length!==h.length)return!1;for(let u=0;u<c.length;u++){const l=c[u],d=i[l];if(!Object.hasOwn(e,l))return!1;const f=e[l];if(!fr(d,f,l,i,e,t,r))return!1}return!0}default:return!1}}finally{t.delete(i),t.delete(e)}}function X2(i,e){return Q2(i,e,D2)}var e$=Object.defineProperty,mh=Object.getOwnPropertySymbols,t$=Object.prototype.hasOwnProperty,i$=Object.prototype.propertyIsEnumerable,ao=(i,e,t)=>e in i?e$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,wh=(i,e)=>{for(var t in e||(e={}))t$.call(e,t)&&ao(i,t,e[t]);if(mh)for(var t of mh(e))i$.call(e,t)&&ao(i,t,e[t]);return i},Le=(i,e,t)=>ao(i,typeof e!="symbol"?e+"":e,t);class fi extends n1{constructor(e,t,r,s=$t,n=void 0){super(e,t,r,s),this.core=e,this.logger=t,this.name=r,Le(this,"map",new Map),Le(this,"version",s_),Le(this,"cached",[]),Le(this,"initialized",!1),Le(this,"getKey"),Le(this,"storagePrefix",$t),Le(this,"recentlyDeleted",[]),Le(this,"recentlyDeletedLimit",200),Le(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Oe(o)?this.map.set(this.getKey(o),o):x0(o)?this.map.set(o.id,o):C0(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Le(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())}),Le(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Le(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>X2(a[c],o[c]))):this.values)),Le(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=wh(wh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Le(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",ke
12y:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Be(t,this.name),this.storagePrefix=s,this.getKey=n}get context(){return ze(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}=L("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}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}=L("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}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var r$=Object.defineProperty,s$=(i,e,t)=>e in i?r$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,G=(i,e,t)=>s$(i,typeof e!="symbol"?e+"":e,t);class n${constructor(e,t){this.core=e,this.logger=t,G(this,"name",c_),G(this,"version",h_),G(this,"events",new yo),G(this,"pairings"),G(this,"initialized",!1),G(this,"storagePrefix",$t),G(this,"ignoredPayloadTypes",[Bt]),G(this,"registeredMethods",[]),G(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),G(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),G(this,"create",async r=>{this.isInitialized();const s=Jn(),n=await this.core.crypto.setSymKey(s),o=pe(U.FIVE_MINUTES),a={protocol:Jl},c={topic:n,expiry:o,relay:a,active:!1,methods:r?.methods},h=Sc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(ri.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r?.transportType}),{topic:n,uri:h}}),G(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[bt.pairing_started]}});this.isValidPair(r,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=$c(r.uri);s.props.properties.topic=n,s.addTrace(bt.pairing_uri_validation_success),s.addTrace(bt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),s.addTrace(bt.existing_pairing),u.active)throw s.setError(Rt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(bt.pairing_not_expired)}const l=c||pe(U.FIVE_MINUTES),d={topic:n,relay:a,expiry:l,active:!1,methods:h};this.core.expirer.set(n,l),await this.pairings.set(n,d),s.addTrace(bt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(ri.create,d),s.addTrace(bt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(bt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Rt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw s.setError(Rt.subscribe_pairing_topic_failure),f}return s.addTrace(bt.subscribe_pairing_topic_success),d}),G(this,"activate",async({topic:r})=>{this.isInitialized();const s=pe(U.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),G(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Xt();this.events.once(ee("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),G(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),G(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),G(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),G(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",ie("USER_DISCONNECTED")),await this.deletePairing(s))}),G(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Sc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),G(this,"sendRequest",async(r,s,n)=>{const o=Vt(s,n),a=await this.core.crypto.encode(r,o),c=cr[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),G(this,"sendResult",async(r,s,n)=>{const o=Ns(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,h=cr[c].res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),G(this,"sendError",async(r,s,n)=>{const o=Hl(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,h=cr[c]?cr[c].res:cr.unregistered_method.res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),G(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ie("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),G(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>Mt(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),G(this,"onRelayEventRequest",async r=>{const{topic:s,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),G(this,"onRelayEventResponse",async r=>{const{topic:s,payload:n}=r,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),G(this,"onPairingPingRequest",async(r,s)=>{const{id:n}=s;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(ri.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),G(this,"onPairingPingResponse",(r,s)=>{const{id:n}=s;setTimeout(()=>{Et(s)?this.events.emit(ee("pairing_ping",n),{}):tt(s)&&this.events.emit(ee("pairing_ping",n),{error:s.error})},500)}),G(this,"onPairingDeleteRequest",async(r,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(ri.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),G(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=ie("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),G(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ie("WC_METHOD_UNSUPPORTED",r))}),G(this,"isValidPair",(r,s)=>{var n;if(!Fe(r)){const{message:a}=L("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(!A0(r.uri)){const{message:a}=L("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(Rt.malformed_pairing_uri),new Error(a)}const o=$c(r?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Rt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&U.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(Rt.pairing_expired);const{message:a}=L("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),G(this,"isValidPing",async r=>{if(!Fe(r)){const{message:n}=L("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),G(this,"isValidDisconnect",async r=>{if(!Fe(r)){const{message:n}=L("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),G(this,"isValidPairingTopic",async r=>{if(!de(r,!1)){const{message:s}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(Mt(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=L("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=e,this.logger=Be(t,this.name),this.pairings=new fi(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ze(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ve.message,async e=>{const{topic:t,message:r,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(t,r);Bo(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,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(et.expired,async e=>{const{topic:t}=tl(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(ri.expire,{topic:t}))})}}var o$=Object.defineProperty,a$=(i,e,t)=>e in i?o$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,De=(i,e,t)=>a$(i,typeof e!="symbol"?e+"":e,t);class c$ extends t1{constructor(e,t){super(e,t),this.core=e,this.logger=t,De(this,"records",new Map),De(this,"events",new st.EventEmitter),De(this,"name",u_),De(this,"version",l_),De(this,"cac
12hed",[]),De(this,"initialized",!1),De(this,"storagePrefix",$t),De(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),De(this,"set",(r,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:n,expiry:pe(U.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ct.created,o)}),De(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=tt(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(ct.updated,s))}),De(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),De(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===r){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(ct.deleted,n)}}),this.persist()}),De(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),De(this,"on",(r,s)=>{this.events.on(r,s)}),De(this,"once",(r,s)=>{this.events.once(r,s)}),De(this,"off",(r,s)=>{this.events.off(r,s)}),De(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=Be(t,this.name)}get context(){return ze(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 r={topic:t.topic,request:Vt(t.request.method,t.request.params,t.id),chainId:t.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const t=this.records.get(e);if(!t){const{message:r}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ct.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:t}=L("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(ct.created,e=>{const t=ct.created;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ct.updated,e=>{const t=ct.updated;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.events.on(ct.deleted,e=>{const t=ct.deleted;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})}),this.core.heartbeat.on(pi.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(ct.deleted,t,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var h$=Object.defineProperty,u$=(i,e,t)=>e in i?h$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Re=(i,e,t)=>u$(i,typeof e!="symbol"?e+"":e,t);class l$ extends a1{constructor(e,t){super(e,t),this.core=e,this.logger=t,Re(this,"expirations",new Map),Re(this,"events",new st.EventEmitter),Re(this,"name",d_),Re(this,"version",p_),Re(this,"cac
12hed",[]),Re(this,"initialized",!1),Re(this,"storagePrefix",$t),Re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Re(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Re(this,"set",(r,s)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(et.created,{target:n,expiration:o})}),Re(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),Re(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(et.deleted,{target:s,expiration:n})}}),Re(this,"on",(r,s)=>{this.events.on(r,s)}),Re(this,"once",(r,s)=>{this.events.once(r,s)}),Re(this,"off",(r,s)=>{this.events.off(r,s)}),Re(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=Be(t,this.name)}get context(){return ze(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 Rw(e);if(typeof e=="number")return Nw(e);const{message:t}=L("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}=L("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:r}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return t}checkExpiry(e,t){const{expiry:r}=t;U.toMiliseconds(r)-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(pi.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}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var d$=Object.defineProperty,p$=(i,e,t)=>e in i?d$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,le=(i,e,t)=>p$(i,typeof e!="symbol"?e+"":e,t);class f$ extends c1{constructor(e,t,r){super(e,t,r),this.core=e,this.logger=t,this.store=r,le(this,"name",f_),le(this,"abortController"),le(this,"isDevEnv"),le(this,"verifyUrlV3",y_),le(this,"storagePrefix",$t),le(this,"version",Yl),le(this,"publicKey"),le(this,"fetchPromise"),le(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()))}),le(this,"register",async s=>{if(!Zi()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const h=Ut.getDocument(),u=this.startAbortTimer(U.ONE_SECOND*5),l=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",y),h.body.removeChild(g),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=h.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=b=>
12{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(Ln(m.attestation).payload.id!==o)return;clearInterval(u),h.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};h.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",l),l}catch(h){this.logger.warn(h)}return""}),le(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(Ln(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)}),le(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}),le(this,"getVerifyUrl",s=>{let n=s||br;return m_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${br}`),n=br),n}),le(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)}}),le(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),le(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),le(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")}}),le(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),le(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}),le(this,"validateAttestation",(s,n)=>{const o=c0(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=Be(t,this.name),this.abortController=new AbortController,this.isDevEnv=Do(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ze(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),U.toMiliseconds(e))}}var g$=Object.defineProperty,y$=(i,e,t)=>e in i?g$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bh=(i,e,t)=>y$(i,typeof e!="symbol"?e+"":e,t);class m$ extends h1{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,bh(this,"context",w_),bh(this,"registerDeviceToken",async r=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${b_}/${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=Be(t,this.context)}}var w$=Object.defineProperty,vh=Object.getOwnPropertySymbols,b$=Object.prototype.hasOwnProperty,v$=Object.prototype.propertyIsEnumerable,co=(i,e,t)=>e in i?w$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,lr=(i,e)=>{for(var t in e||(e={}))b$.call(e,t)&&co(i,t,e[t]);if(vh)for(var t of vh(e))v$.call(e,t)&&co(i,t,e[t]);return i},ye=(i,e,t)=>co(i,typeof e!="symbol"?e+"":e,t);class E$ extends u1{constructor(e,t,r=!0){super(e,t,r),this.core=e,this.logger=t,ye(this,"context",E_),ye(this,"storagePrefix",$t),ye(this,"storageVersion",v_),ye(this,"events",new Map),ye(this,"shouldPersist",!1),ye(this,"init",async()=>
12{if(!Do())try{const s={eventId:Ga(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Xu(this.core.relayer.protocol,this.core.relayer.version,eo)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),ye(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,h=Ga(),u=this.core.projectId||"",l=Date.now(),d=lr({eventId:h,timestamp:l,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,d),this.shouldPersist=!0),d}),ye(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 lr(lr({},a),this.setMethods(a.eventId))}),ye(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),ye(this,"setEventListeners",()=>{this.core.heartbeat.on(pi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{U.fromMiliseconds(Date.now())-U.fromMiliseconds(s.timestamp)>__&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),ye(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),ye(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)}),ye(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)}),ye(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ye(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,lr(lr({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),ye(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)}}),ye(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${I_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${eo}${n}`,{method:"POST",body:JSON.stringify(s)})}),ye(this,"getAppDomain",()=>Qu().url),this.logger=Be(t,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var _$=Object.defineProperty,Eh=Object.getOwnPropertySymbols,I$=Object.prototype.hasOwnProperty,$$=Object.prototype.propertyIsEnumerable,ho=(i,e,t)=>e in i?_$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,_h=(i,e)=>{for(var t in e||(e={}))I$.call(e,t)&&ho(i,t,e[t]);if(Eh)for(var t of Eh(e))$$.call(e,t)&&ho(i,t,e[t]);return i},ae=(i,e,t)=>ho(i,typeof e!="symbol"?e+"":e,t);let S$=class hd extends ZE{constructor(e){var t;super(e),ae(this,"protocol",Gl),ae(this,"version",Yl),ae(this,"name",Xn),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new st.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:ce.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:h})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Zl,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Rs({level:typeof e?.logger=="string"&&e.logger?e.logger:V1.logger,name:Xn}),{logger:n,chunkLoggerController:o}=GE({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride: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=Be(n,this.name),this.heartbeat=new sE,this.crypto=new QI(this,this.logger,e?.keychain),this.history=new c$(this,this.logger),this.expirer=new l$(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new AE(_h(_h({},K1),e?.storageOptions)),this.relayer=new S2({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new n$(this,this.logger),this.verify=new f$(this,this.logger,this.storage),this.echoClient=new m$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new E$(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const t=new hd(e);await t.initialize();const r=await t.crypto.getClientId();return await t.storage.setItem(n_,r),t}get context(){return ze(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(th,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(
12),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(th)||[],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}`,r=`${t}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[t]}catch(t){console.warn("Failed to get global WalletConnect core",t);return}}setGlobalCore(e){var t;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((t=e.opts)==null?void 0:t.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof rt<"u"&&H1.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const D$=S$;var O$=Object.defineProperty,P$=(i,e,t)=>e in i?O$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ih=(i,e,t)=>P$(i,typeof e!="symbol"?e+"":e,t);let A$=class{constructor(e){this.opts=e,Ih(this,"protocol","wc"),Ih(this,"version",2)}},x$=class{constructor(e){this.client=e}};const ud="wc",ld=2,dd="client",Lo=`${ud}@${ld}:${dd}:`,_n={name:dd,logger:"error"},$h="WALLETCONNECT_DEEPLINK_CHOICE",C$="proposal",Sh="Proposal expired",R$="session",Ii=U.SEVEN_DAYS,N$="engine",me={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}}},In={min:U.FIVE_MINUTES,max:U.SEVEN_DAYS},wt={idle:"IDLE",active:"ACTIVE"},Dh={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},T$="request",j$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],B$="wc",U$="auth",L$="authKeys",k$="pairingTopics",F$="requests",Bs=`${B$}@${1.5}:${U$}:`,hs=`${Bs}:PUB_KEY`;var q$=Object.defineProperty,M$=Object.defineProperties,z$=Object.getOwnPropertyDescriptors,Oh=Object.getOwnPropertySymbols,H$=Object.prototype.hasOwnProperty,V$=Object.prototype.propertyIsEnumerable,uo=(i,e,t)=>e in i?q$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ne=(i,e)=>{for(var t in e||(e={}))H$.call(e,t)&&uo(i,t,e[t]);if(Oh)for(var t of Oh(e))V$.call(e,t)&&uo(i,t,e[t]);return i},Te=(i,e)=>M$(i,z$(e)),N=(i,e,t)=>uo(i,typeof e!="symbol"?e+"":e,t);class K$ extends x${constructor(e){super(e),N(this,"name",N$),N(this,"events",new yo),N(this,"initialized",!1),N(this,"requestQueue",{state:wt.idle,queue:[]}),N(this,"sessionRequestQueue",{state:wt.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(me)}),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 r=Te(ne({},t),{requiredNamespaces:t.requiredNamespaces||{},optionalNamespaces:t.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=$0(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=r;let u=s,l,d=!1;try{if(u){const w=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=w.active}}catch(w){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),w}if(!u||!d){const{topic:w,uri:_}=await this.client.core.pairing.create();u=w,l=_}if(!u){const{message:w}=L("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(w)}const f=await this.client.core.crypto.generateKeyPair(),p=me.wc_sessionPropose.req.ttl||U.FIVE_MINUTES,g=pe(p),y=Te(ne(ne({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Jl}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:vt()}),b=ee("session_connect",y.id),{reject:m,resolve:v,done:O}=Xt(p,Sh),x=({id:w})=>{w===y.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(y.id),this.events.emit(b,{error:{message:Sh,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(b,({error:w,session:_})=>{this.client.events.off("proposal_expire",x),w?m(w):_&&v(_)}
12),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:y,throwOnFailedPublish:!0,clientRpcId:y.id}),await this.setProposal(y.id,y),{uri:l,approval:O}}),N(this,"pair",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(t)}catch(r){throw this.client.logger.error("pair() failed"),r}}),N(this,"approve",async t=>{var r,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=t?.id)==null?void 0:r.toString(),trace:[ht.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(I){throw o.setError(Zt.no_internet_connection),I}try{await this.isValidProposalId(t?.id)}catch(I){throw this.client.logger.error(`approve() -> proposal.get(${t?.id}) failed`),o.setError(Zt.proposal_not_found),I}try{await this.isValidApprove(t)}catch(I){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Zt.session_approve_namespace_validation_failure),I}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:u,scopedProperties:l,sessionConfig:d}=t,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:y,optionalNamespaces:b}=f;let m=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});m||(m=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:ht.session_approve_started,properties:{topic:p,trace:[ht.session_approve_started,ht.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),O=g.publicKey,x=await this.client.core.crypto.generateSharedKey(v,O),w=ne(ne(ne({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:v,metadata:this.client.metadata},expiry:pe(Ii)},u&&{sessionProperties:u}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),_=ce.relay;m.addTrace(ht.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:_})}catch(I){throw m.setError(Zt.subscribe_session_topic_failure),I}m.addTrace(ht.subscribe_session_topic_success);const $=Te(ne({},w),{topic:x,requiredNamespaces:y,optionalNamespaces:b,pairingTopic:p,acknowledged:!1,self:w.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:v,transportType:ce.relay});await this.client.session.set(x,$),m.addTrace(ht.store_session);try{m.addTrace(ht.publishing_session_settle),await this.sendRequest({topic:x,method:"wc_sessionSettle",params:w,throwOnFailedPublish:!0}).catch(I=>{throw m?.setError(Zt.session_settle_publish_failure),I}),m.addTrace(ht.session_settle_publish_success),m.addTrace(ht.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(I=>{throw m?.setError(Zt.session_approve_publish_failure),I}),m.addTrace(ht.session_approve_publish_success)}catch(I){throw this.client.logger.error(I),this.client.session.delete(x,ie("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),I}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.client.proposal.delete(a,ie("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(x,pe(Ii)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),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:r,reason:s}=t;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&(await this.sendError({id:r,topic:n,error:s,rpcOpts:me.wc_sessionPropose.reject}),await this.client.proposal.delete(r,ie("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:r,namespaces:s}=t,{done:n,resolve:o,reject:a}=Xt(),c=vt(),h=oi().toString(),u=this.client.session.get(r).namespaces;return this.events.once(ee("session_update",c),({error:l})=>{l?a(l):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(l=>{this.client.logger.error(l),this.client.session.update(r,{namespaces:u}),a(l)}),{acknowledged:n}}),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:r}=t,s=vt(),{done:n,resolve:o,reject:a}=Xt();return this.events.once(ee("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,pe(Ii)),this.sendRequest({topic:r,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(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:r,request:s,topic:n,expiry:o=me.wc_sessionRequest.req.ttl}=t,a=this.client.session.get(n);a?.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const c=vt(),h=oi().toString(),{done:u,resolve:l,reject:d}=Xt(o,"Request expired. Please try again.");this.events.once(ee("session_request",c),({error:b,result:m})=>{b?d(b):l(m)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:f,params:{request:Te(ne({},s),{expiryTimestamp:pe(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),await u();const g={request:Te(ne({},s),{expiryTimestamp:pe(o)}),chainId:r},y=this.shouldSetTVF(f,g);return await Promise.all([new Promise(async b=>{await this.sendRequest(ne({clientRpcId:c,relayRpcId:h,topic:n,method:f,params:g,expiry:o,throwOnFailedPublish:!0},y&&{tvf:this.getTVFParams(c,g)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),b()}),new Promise(async b=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const v=await Uw(this.client.core.storage,$h);await Tw({id:c,topic:n,wcDeepLink:v})}b()}),u()]).then(b=>b[2])}),N(this,"respond",async t=>{this.isInitialized(),await this.isValidRespond(t);const{topic:r,response:s}=t,{id:n}=s,o=this.client.session.get(r);o.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Et(s)?await this.sendResult({id:n,topic:r,result:s.result,throwOnFailedPublish:!0,appLink:a}
12):tt(s)&&await this.sendError({id:n,topic:r,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:r}=t;if(this.client.session.keys.includes(r)){const s=vt(),n=oi().toString(),{done:o,resolve:a,reject:c}=Xt();this.events.once(ee("session_ping",s),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),N(this,"emit",async t=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(t);const{topic:r,event:s,chainId:n}=t,o=oi().toString(),a=vt();await this.sendRequest({topic:r,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:r}=t;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:ie("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=L("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),N(this,"find",t=>(this.isInitialized(),this.client.session.getAll().filter(r=>O0(r,t)))),N(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),N(this,"authenticate",async(t,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(t);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:u,nonce:l,type:d,exp:f,nbf:p,methods:g=[],expiry:y}=t,b=[...t.resources||[]],{topic:m,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:v}});const O=await this.client.core.crypto.generateKeyPair(),x=ns(O);if(await Promise.all([this.client.auth.authKeys.set(hs,{responseTopic:x,publicKey:O}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:m})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),g.length>0){const{namespace:P}=Fi(a[0]);let R=Ab(P,"request",g);ss(b)&&(R=Cb(R,b.pop())),b.push(R)}const w=y&&y>me.wc_sessionAuthenticate.req.ttl?y:me.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:d??"caip122",chains:a,statement:c,aud:h,domain:u,version:"1",nonce:l,iat:new Date().toISOString(),exp:f,nbf:p,resources:b},requester:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:pe(w)},$={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},I={requiredNamespaces:{},optionalNamespaces:$,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:pe(me.wc_sessionPropose.req.ttl),id:vt()},{done:j,resolve:T,reject:B}=Xt(w,"Request expired"),q=vt(),S=ee("session_connect",I.id),D=ee("session_request",q),E=async({error:P,session:R})=>{this.events.off(D,A),P?B(P):R&&T({session:R})},A=async P=>{var R,k,F;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),P.error){const J=ie("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===J.code?void 0:(this.events.off(S,E),B(P.error.message))}await this.deleteProposal(I.id),this.events.off(S,E);const{cacaos:M,responder:z}=P.result,K=[],V=[];for(const J of M){await ic({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),B(ie("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ce}=J,Ie=ss(Ce.resources),Ne=[qn(Ce.iss)],Ze=ps(Ce.iss);if(Ie){const St=rc(Ie),yi=sc(Ie);K.push(...St),Ne.push(...yi)}for(const St of Ne)V.push(`${St}:${Ze}`)}const oe=await this.client.core.crypto.generateSharedKey(O,z.publicKey);let te;K.length>0&&(te={topic:oe,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:pe(Ii),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:Ac([...new Set(K)],[...new Set(V)]),transportType:o},await this.client.core.relayer.subscribe(oe,{transportType:o}),await this.client.session.set(oe,te),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:z.metadata}),te=this.client.session.get(oe)),(R=this.client.metadata.redirect)!=null&&R.linkMode&&(k=z.metadata.redirect)!=null&&k.linkMode&&(F=z.metadata.redirect)!=null&&F.universal&&r&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(oe,{transportType:ce.link_mode})),T({auths:M,session:te})};this.events.once(S,E),this.events.once(D,A);let C;try{if(n){const P=Vt("wc_sessionAuthenticate",_,q);this.client.core.history.set(m,P);const R=await this.client.core.crypto.encode("",P,{type:Ur,encoding:zt});C=Gr(r,m,R)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:_,expiry:t.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:I,expiry:me.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:I.id})])}catch(P){throw this.events.off(S,E),this.events.off(D,A),P}return await this.setProposal(I.id,I),await this.setAuthRequest(q,{request:Te(ne({},_),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:C??v,response:j}}),N(this,"approveSessionAuthenticate",async t=>{const{id:r,auths:s}=t,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Qt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(hr.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(hr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),u=ns(c),l={type:Bt,receiverPublicKey:c,senderPublicKey:h},d=[],f=[];for(const y of s){if(!await ic({cacao:y,projectId:this.client.core.projectId}
12)){n.setError(hr.invalid_cacao);const x=ie("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:x,encodeOpts:l}),new Error(x.message)}n.addTrace(Qt.cacaos_verified);const{p:b}=y,m=ss(b.resources),v=[qn(b.iss)],O=ps(b.iss);if(m){const x=rc(m),w=sc(m);d.push(...x),v.push(...w)}for(const x of v)f.push(`${x}:${O}`)}const p=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Qt.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:pe(Ii),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Ac([...new Set(d)],[...new Set(f)]),transportType:a},n.addTrace(Qt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw n.setError(hr.subscribe_authenticated_session_topic_failure),y}n.addTrace(Qt.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),n.addTrace(Qt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Qt.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(hr.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:g}}),N(this,"rejectSessionAuthenticate",async t=>{this.isInitialized();const{id:r,reason:s}=t,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ns(o),h={type:Bt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:h,rpcOpts:me.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.client.proposal.delete(r,ie("USER_DISCONNECTED"))}),N(this,"formatAuthMessage",t=>{this.isInitialized();const{request:r,iss:s}=t;return ul(r,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 r=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!==r.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),N(this,"deleteSession",async t=>{var r;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,ie("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($h).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEac
12h(h=>{h.topic===s&&this.deletePendingSessionRequest(h.id,ie("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=wt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),N(this,"deleteProposal",async(t,r)=>{if(r)try{const s=this.client.proposal.get(t);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(Zt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(t,ie("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(t)]),this.addToRecentlyDeleted(t,"proposal")}),N(this,"deletePendingSessionRequest",async(t,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(t,r),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=wt.idle,this.client.events.emit("session_request_expire",{id:t}))}),N(this,"deletePendingAuthRequest",async(t,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(t,r),s?Promise.resolve():this.client.core.expirer.del(t)])}),N(this,"setExpiry",async(t,r)=>{this.client.session.keys.includes(t)&&(this.client.core.expirer.set(t,r),await this.client.session.update(t,{expiry:r}))}),N(this,"setProposal",async(t,r)=>{this.client.core.expirer.set(t,pe(me.wc_sessionPropose.req.ttl)),await this.client.proposal.set(t,r)}),N(this,"setAuthRequest",async(t,r)=>{const{request:s,pairingTopic:n,transportType:o=ce.relay}=r;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:r,topic:s,params:n,verifyContext:o}=t,a=n.request.expiryTimestamp||pe(me.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:n,verifyContext:o})}),N(this,"sendRequest",async t=>{const{topic:r,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:u,tvf:l}=t,d=Vt(s,n,c);let f;const p=!!u;try{const b=p?zt:dt;f=await this.client.core.crypto.encode(r,d,{encoding:b})}catch(b){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),b}let g;if(j$.includes(s)){const b=_t(JSON.stringify(d)),m=_t(f);g=await this.client.core.verify.register({id:m,decryptedId:b})}const y=me[s].req;if(y.attestation=g,o&&(y.ttl=o),a&&(y.id=a),this.client.core.history.set(r,d),p){const b=Gr(u,r,f);await H.Linking.openURL(b,this.client.name)}else{const b=me[s].req;o&&(b.ttl=o),a&&(b.id=a),b.tvf=Te(ne({},l),{correlationId:d.id}),h?(b.internal=Te(ne({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,f,b)):this.client.core.relayer.publish(r,f,b).catch(m=>this.client.logger.error(m))}return d.id}),N(this,"sendResult",async t=>{const{id:r,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=t,h=Ns(r,n);let u;const l=c&&typeof(H==null?void 0:H.Linking)<"u";try{const p=l?zt:dt;u=await this.client.core.crypto.encode(s,h,Te(ne({},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,r);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(r,p.params,n))}catch(g){this.client.logger.warn("sendResult() -> getTVFParams() failed",g)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),p}if(l){const p=Gr(c,s,u);await H.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=me[p].res;g.tvf=Te(ne({},f),{correlationId:r}),o?(g.internal=Te(ne({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(h)}),N(this,"sendError",async t=>{const{id:r,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=t,h=Hl(r,n);let u;const l=c&&typeof(H==null?void 0:H.Linking)<"u";try{const f=l?zt:dt;u=await this.client.core.crypto.encode(s,h,Te(ne({},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,r)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),f}if(l){const f=Gr(c,s,u);await H.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||me[f].res;this.client.core.relayer.publish(s,u,p)}await this.client.core.history.resolve(h)}),N(this,"cleanup",async()=>{const t=[],r=[];
12this.client.session.getAll().forEach(s=>{let n=!1;Mt(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=>{Mt(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...t.map(s=>this.deleteSession({topic:s})),...r.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===wt.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=wt.active;const t=this.requestQueue.queue.shift();if(t)try{await this.processRequest(t)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=wt.idle}),N(this,"processRequest",async t=>{const{topic:r,payload:s,attestation:n,transportType:o,encryptedId:a}=t,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest
12({topic:r,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),N(this,"onRelayEventResponse",async t=>{const{topic:r,payload:s,transportType:n}=t,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),N(this,"onRelayEventUnknownPayload",t=>{const{topic:r}=t,{message:s}=L("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),N(this,"shouldIgnorePairingRequest",t=>{const{topic:r,requestMethod:s}=t,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),N(this,"onSessionProposeRequest",async t=>{const{topic:r,payload:s,attestation:n,encryptedId:o}=t,{params:a,id:c}=s;try{const h=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h?.setError(Rt.proposal_listener_not_found)),this.isValidConnect(ne({},s.params));const u=a.expiryTimestamp||pe(me.wc_sessionPropose.req.ttl),l=ne({id:c,pairingTopic:r,expiryTimestamp:u},a);await this.setProposal(c,l);const d=await this.getVerifyContext({attestationId:n,hash:_t(JSON.stringify(s)),encryptedId:o,metadata:l.proposer.metadata});h?.addTrace(bt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:l,verifyContext:d})}catch(h){await this.sendError({id:c,topic:r,error:h,rpcOpts:me.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),N(this,"onSessionProposeResponse",async(t,r,s)=>{const{id:n}=r;if(Et(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const u=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:t,proposalId:n,publicKey:c});const l=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:t})}else if(tt(r)){await this.client.proposal.delete(n,ie("USER_DISCONNECTED"));const o=ee("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),N(this,"onSessionSettleRequest",async(t,r)=>{const{id:s,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:u,scopedProperties:l,sessionConfig:d}=r.params,f=[...this.pendingSessions.values()].find(y=>y.sessionTopic===t);if(!f)return this.client.logger.error(`Pending session not found for topic ${t}`);const p=this.client.proposal.get(f.proposalId),g=Te(ne(ne(ne({topic:t,relay:o,expiry:c,namespaces:h,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}},u&&{sessionProperties:u}),l&&{scopedProperties:l}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ee("session_connect",f.proposalId),{session:g}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDupl
12icatePairings(g),await this.sendResult({id:r.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,r)=>{const{id:s}=r;Et(r)?(await this.client.session.update(t,{acknowledged:!0}),this.events.emit(ee("session_approve",s),{})):tt(r)&&(await this.client.session.delete(t,ie("USER_DISCONNECTED")),this.events.emit(ee("session_approve",s),{error:r.error}))}),N(this,"onSessionUpdateRequest",async(t,r)=>{const{params:s,id:n}=r;try{const o=`${t}_session_update`,a=ar.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:ie("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ne({topic:t},s));try{ar.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 ar.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,r)=>r.toString().slice(0,-3)<t.toString().slice(0,-3)),N(this,"onSessionUpdateResponse",(t,r)=>{const{id:s}=r,n=ee("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Et(r)?this.events.emit(ee("session_update",s),{}):tt(r)&&this.events.emit(ee("session_update",s),{error:r.error})}),N(this,"onSessionExtendRequest",async(t,r)=>{const{id:s}=r;try{this.isValidExtend({topic:t}),await this.setExpiry(t,pe(Ii)),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,r)=>{const{id:s}=r,n=ee("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Et(r)?this.events.emit(ee("session_extend",s),{}):tt(r)&&this.events.emit(ee("session_extend",s),{error:r.error})}),N(this,"onSessionPingRequest",async(t,r)=>{const{id:s}=r;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,r)=>{const{id:s}=r,n=ee("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);Et(r)?this.events.emit(ee("session_ping",s),{}):tt(r)&&this.events.emit(ee("session_ping",s),{error:r.error})},500)}),N(this,"onSessionDeleteRequest",async(t,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:t,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(ve.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:ie("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),N(this,"onSessionRequest",async t=>{var r,s,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:u}=t,{id:l,params:d}=a;try{await this.isValidRequest(ne({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:_t(JSON.stringify(Vt("wc_sessionRequest",d,l))),encryptedId:h,metadata:f.peer.metadata,transportType:u}),g={id:l,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),u===ce.link_mode&&(r=f.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=f.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(f){await this.sendError({id:l,topic:o,error:f}),this.client.logger.error(f)}}),N(this,"onSessionRequestResponse",(t,r)=>{const{id:s}=r,n=ee("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Et(r)?this.events.emit(ee("session_request",s),{result:r.result}):tt(r)&&this.events.emit(ee("session_request",s),{error:r.error})}),N(this,"onSessionEventRequest",async(t,r)=>{const{id:s,params:n}=r;try{const o=`${t}_session_event_${n.event.name}`,a=ar.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(ne({topic:t},n)),this.client.events.emit("session_event",{id:s,topic:t,params:n}),ar.set(o,s)}
12catch(o){await this.sendError({id:s,topic:t,error:o}),this.client.logger.error(o)}}),N(this,"onSessionAuthenticateResponse",(t,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:t,payload:r}),Et(r)?this.events.emit(ee("session_request",s),{result:r.result}):tt(r)&&this.events.emit(ee("session_request",s),{error:r.error})}),N(this,"onSessionAuthenticateRequest",async t=>{var r;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=t;try{const{requester:h,authPayload:u,expiryTimestamp:l}=n.params,d=await this.getVerifyContext({attestationId:o,hash:_t(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),f={requester:h,pairingTopic:s,id:n.id,authPayload:u,verifyContext:d,expiryTimestamp:l};await this.setAuthRequest(n.id,{request:f,pairingTopic:s,transportType:c}),c===ce.link_mode&&(r=h.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(h){this.client.logger.error(h);const u=n.params.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:Bt,receiverPublicKey:u,senderPublicKey:l};await this.sendError({id:n.id,topic:s,error:h,encodeOpts:f,rpcOpts:me.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=wt.idle,this.processSessionRequestQueue()},U.toMiliseconds(this.requestQueueDelay))}),N(this,"cleanupPendingSentRequestsForTopic",({topic:t,error:r})=>{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=ee("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ee("session_request",n.request.id),{error:r})})}),N(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===wt.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=wt.active,this.emitSessionRequest(t)}catch(r){this.client.logger.error(r)}}),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 r=this.client.proposal.getAll().find(s=>s.pairingTopic===t.topic);
12r&&this.onSessionProposeRequest({topic:t.topic,payload:Vt("wc_sessionPropose",Te(ne({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id)})}),N(this,"isValidConnect",async t=>{if(!Fe(t)){const{message:h}=L("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(t)}`);throw new Error(h)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=t;if(Oe(r)||await this.isValidPairingTopic(r),!k0(c)){const{message:h}=L("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!Oe(s)&&Wt(s)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(s,"requiredNamespaces")}if(!Oe(n)&&Wt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>h.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),N(this,"validateNamespaces",(t,r)=>{const s=L0(t,"connect()",r);if(s)throw new Error(s.message)}),N(this,"isValidApprove",async t=>{if(!Fe(t))throw new Error(L("MISSING_OR_INVALID",`approve() params: ${t}`).message);const{id:r,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=t;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),h=dn(s,"approve()");if(h)throw new Error(h.message);const u=Rc(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!de(n,!0)){const{message:l}=L("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(l)}if(Oe(o)||this.validateSessionProps(o,"sessionProperties"),!Oe(a)){this.validateSessionProps(a,"scopedProperties");const l=new Set(Object.keys(s));if(!Object.keys(a).every(d=>l.has(d)))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}=L("MISSING_OR_INVALID",`reject() params: ${t}`);throw new Error(n)}const{id:r,reason:s}=t;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!q0(s)){const{message:n}=L("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),N(this,"isValidSessionSettleRequest",t=>{if(!Fe(t)){const{message:h}=L("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${t}`);throw new Error(h)}const{relay:r,controller:s,namespaces:n,expiry:o}=t;if(!Bl(r)){const{message:h}=L("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=R0(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=dn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Mt(o)){const{message:h}=L("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),N(this,"isValidUpdate",async t=>{if(!Fe(t)){const{message:c}=L("MISSING_OR_INVALID",`update() params: ${t}`);throw new Error(c)}const{topic:r,namespaces:s}=t;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=dn(s,"update()");if(o)throw new Error(o.message);const a=Rc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),N(this,"isValidExtend",async t=>{if(!Fe(t)){const{message:s}=L("MISSING_OR_INVALID",`extend() params: ${t}`);throw new Error(s)}const{topic:r}=t;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),N(this,"isValidRequest",async t=>{if(!Fe(t)){const{message:c}=L("MISSING_OR_INVALID",`request() params: ${t}`);throw new Error(c)}const{topic:r,request:s,chainId:n,expiry:o}=t;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Cc(a,n)){const{message:c}=L("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!M0(s)){const{message:c}=L("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!V0(a,n,s.method)){const{message:c}=L("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!Y0(o,In)){const{message:c}=L("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${In.min} and ${In.max}`);throw new Error(c)}}),N(this,"isValidRespond",async t=>{var r;if(!Fe(t)){const{message:o}=L("MISSING_OR_INVALID",`respond() params: ${t}`);throw new Error(o)}const{topic:s,response:n}=t;try{await this.isValidSessionTopic(s)}catch(o){throw(r=t?.response)!=null&&r.id&&this.cleanupAfterResponse(t),o}if(!z0(n)){const{message:o}=L("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),N(this,"isValidPing",async t=>{if(!Fe(t)){const{message:s}=L("MISSING_OR_INVALID",`ping() params: ${t}`);throw new Error(s)}const{topic:r}=t;await this.isValidSessionOrPairingTopic(r)}),N(this,"isValidEmit",async t=>{if(!Fe(t)){const{message:a}=L("MISSING_OR_INVALID",`emit() params: ${t}`);throw new Error(a)}const{topic:r,event:s,chainId:n}=t;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Cc(o,n)){const{message:a}=L("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!H0(s)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!K0(o,n,s.name)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),N(this,"isValidDisconnect",async t=>{if(!Fe(t)){const{message:s}=L("MISSING_OR_INVALID",`disconnect() params: ${t}`);throw new Error(s)}const{topic:r}=t;await this.isValidSessionOrPairingTopic(r)}),N(this,"isValidAuthenticate",t=>{const{chains:r,uri:s,domain:n,nonce:o}=t;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!de(s,!1))throw new Error("uri is required parameter");if(!de(n,!1))throw new Error("domain is required parameter");if(!de(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Fi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Fi(r[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:r,hash:s,encryptedId:n,metadata:o,transportType:a}=t,c={verified:{verifyUrl:o.verifyUrl||br,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),N(this,"validateSessionProps",(t,r)=>{Object.values(t).forEach((s,n)=>{if(s==null){const{message:o}=L("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(t)[n]}`);throw new Error(o)}})}
12),N(this,"getPendingAuthRequest",t=>{const r=this.client.auth.requests.get(t);return typeof r=="object"?r:void 0}),N(this,"addToRecentlyDeleted",(t,r)=>{if(this.recentlyDeletedMap.set(t,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),N(this,"checkRecentlyDeleted",t=>{const r=this.recentlyDeletedMap.get(t);if(r){const{message:s}=L("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${t}`);throw new Error(s)}}),N(this,"isLinkModeEnabled",(t,r)=>{var s,n,o,a,c,h,u,l,d;return!t||r!==ce.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((u=t?.redirect)==null?void 0:u.universal)!==void 0&&((l=t?.redirect)==null?void 0:l.universal)!==""&&((d=t?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(t.redirect.universal)&&typeof(H==null?void 0:H.Linking)<"u"}),N(this,"getAppLinkIfEnabled",(t,r)=>{var s;return this.isLinkModeEnabled(t,r)?(s=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 r=Wa(t,"topic")||"",s=decodeURIComponent(Wa(t,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:n})}),N(this,"registerLinkModeListeners",async()=>{var t;if(Do()||Gt()&&(t=this.client.metadata.redirect)!=null&&t.linkMode){const r=H==null?void 0:H.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),N(this,"shouldSetTVF",(t,r)=>{if(!r||t!=="wc_sessionRequest")return!1;const{request:s}=r;return Object.keys(Dh).includes(s.method)}),N(this,"getTVFParams",(t,r,s)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,s);return Te(ne({correlationId:t,rpcMethods:[a],chainId:r.chainId},this.isValidContractData(r.request.params)&&{contractAddresses:[(o=(n=r.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 r;if(!t)return!1;try{const s=t?.data||((r=t?.[0])==null?void 0:r.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),N(this,"extractTxHashesFromResult",(t,r)=>{try{const s=Dh[t];if(typeof r=="string")return[r];const n=r[s.key];if(pt(n))return t==="solana_signAllTransactions"?n.map(o=>gb(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[r,s]of Object.entries(t))for(const n of s)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ve.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:t,message:r,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(hs)?this.client.auth.authKeys.get(hs):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(t,r,{receiverPublicKey:o,encoding:n===ce.link_mode?zt:dt});Bo(a)?(this.client.core.history.set(t,a),await this.onRelayEventRequest({topic:t,payload:a,attestation:s,transportType:n,encryptedId:_t(r)})):Ts(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:t,payload:a,transportType:n}
12),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,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(et.expired,async e=>{const{topic:t,id:r}=tl(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,L("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,L("EXPIRED"),!0);t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(ri.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ri.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!de(e,!1)){const{message:t}=L("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}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(Mt(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=L("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!de(e,!1)){const{message:t}=L("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}=L("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(Mt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=L("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=L("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(de(e,!1)){const{message:t}=L("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}else{const{message:t}=L("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}async isValidProposalId(e){if(!F0(e)){const{message:t}=L("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=L("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(Mt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=L("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}}class W$ extends fi{constructor(e,t){super(e,t,C$,Lo),this.core=e,this.logger=t}}let G$=class extends fi{constructor(e,t){super(e,t,R$,Lo),this.core=e,this.logger=t}};class Y$ extends fi{constructor(e,t){super(e,t,T$,Lo,r=>r.id),this.core=e,this.logger=t}}class J$ extends fi{constructor(e,t){super(e,t,L$,Bs,()=>hs),this.core=e,this.logger=t}}class Z$ extends fi{constructor(e,t){super(e,t,k$,Bs),this.core=e,this.logger=t}}class Q$ extends fi{constructor(e,t){super(e,t,F$,Bs,r=>r.id),this.core=e,this.logger=t}}var X$=Object.defineProperty,eS=(i,e,t)=>e in i?X$(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,$n=(i,e,t)=>eS(i,typeof e!="symbol"?e+"":e,t);class tS{constructor(e,t){this.core=e,this.logger=t,$n(this,"authKeys"),$n(this,"pairingTopics"),$n(this,"requests"),this.authKeys=new J$(this.core,this.logger),this.pairingTopics=new Z$(this.core,this.logger),this.requests=new Q$(this.core,this.logger)}
12async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var iS=Object.defineProperty,rS=(i,e,t)=>e in i?iS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Y=(i,e,t)=>rS(i,typeof e!="symbol"?e+"":e,t);let sS=class pd extends A${constructor(e){super(e),Y(this,"protocol",ud),Y(this,"version",ld),Y(this,"name",_n.name),Y(this,"metadata"),Y(this,"core"),Y(this,"logger"),Y(this,"events",new st.EventEmitter),Y(this,"engine"),Y(this,"session"),Y(this,"proposal"),Y(this,"pendingRequest"),Y(this,"auth"),Y(this,"signConfig"),Y(this,"on",(r,s)=>this.events.on(r,s)),Y(this,"once",(r,s)=>this.events.once(r,s)),Y(this,"off",(r,s)=>this.events.off(r,s)),Y(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),Y(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),Y(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),Y(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(n){throw this.logger.error(n.message),n}}),Y(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),Y(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=e?.name||_n.name,this.metadata=Pw(e?.metadata),this.signConfig=e?.signConfig;const t=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Lr(Rs({level:e?.logger||_n.logger}));this.core=e?.core||new D$(e),this.logger=Be(t,this.name),this.session=new G$(this.core,this.logger),this.proposal=new W$(this.core,this.logger),this.pendingRequest=new Y$(this.core,this.logger),this.engine=new K$(this),this.auth=new tS(this.core,this.logger)}static async init(e){const t=new pd(e);return await t.initialize(),t}get context(){return ze(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 nS=zd();const Ph=tu(nS);function oS(i){if(typeof i!="string")throw new Error(`Cannot safe json parse value of type ${typeof i}`);try{return JSON.parse(i)}catch{return i}}function Ah(i){return typeof i=="string"?i:JSON.stringify(i)}const aS="PARSE_ERROR",cS="INVALID_REQUEST",hS="METHOD_NOT_FOUND",uS="INVALID_PARAMS",fd="INTERNAL_ERROR",ko="SERVER_ERROR",lS=[-32700,-32600,-32601,-32602,-32603],Er={[aS]:{code:-32700,message:"Parse error"},[cS]:{code:-32600,message:"Invalid Request"},[hS]:{code:-32601,message:"Method not found"},[uS]:{code:-32602,message:"Invalid params"},[fd]:{code:-32603,message:"Internal error"},[ko]:{code:-32e3,message:"Server error"}},gd=ko;function dS(i){return lS.includes(i)}function xh(i){return Object.keys(Er).includes(i)?Er[i]:Er[gd]}function pS(i){const e=Object.values(Er).find(t=>t.code===i);return e||Er[gd]}function fS(i,e,t){return i.message.includes("getaddrinfo ENOTFOUND")||i.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${t} RPC url at ${e}`):i}function gS(i,e,t){return{id:i,jsonrpc:"2.0",error:yS(e)}}function yS(i,e){return typeof i>"u"?xh(fd):(typeof i=="string"&&(i=Object.assign(Object.assign({},xh(ko)),{message:i}
12)),dS(i.code)&&(i=pS(i.code)),i)}const mS="^https?:";function wS(i){const e=i.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function bS(i,e){const t=wS(i);return typeof t>"u"?!1:new RegExp(e).test(t)}function Ch(i){return bS(i,mS)}var vS=Object.defineProperty,ES=Object.defineProperties,_S=Object.getOwnPropertyDescriptors,Rh=Object.getOwnPropertySymbols,IS=Object.prototype.hasOwnProperty,$S=Object.prototype.propertyIsEnumerable,Nh=(i,e,t)=>e in i?vS(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Th=(i,e)=>{for(var t in e||(e={}))IS.call(e,t)&&Nh(i,t,e[t]);if(Rh)for(var t of Rh(e))$S.call(e,t)&&Nh(i,t,e[t]);return i},jh=(i,e)=>ES(i,_S(e));const SS={Accept:"application/json","Content-Type":"application/json"},DS="POST",Bh={headers:SS,method:DS},Uh=10;let ft=class{constructor(e,t=!1){if(this.url=e,this.disableProviderPing=t,this.events=new st.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=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=Ah(e),r=await(await Ph(this.url,jh(Th({},Bh),{body:t}))).json();this.onPayload({data:r})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!Ch(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((r,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=Ah({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ph(e,jh(Th({},Bh),{body:t}))}this.onOpen()}catch(t){const r=this.parseError(t);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const t=typeof e.data=="string"?oS(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const r=this.parseError(t),s=r.message||r.toString(),n=gS(e,s);this.events.emit("payload",n)}parseError(e,t=this.url){return fS(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Uh&&this.events.setMaxListeners(Uh)}};const Lh="error",OS="wss://relay.walletconnect.org",PS="wc",AS="universal_provider",Qr=`${PS}@2:${AS}:`,yd="https://rpc.walletconnect.org/v1/",Bi="generic",xS=`${yd}bundler`,ot={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function CS(){}function Fo(i){return i==null||typeof i!="object"&&typeof i!="function"}function qo(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function RS(i){if(Fo(i))return i;if(Array.isArray(i)||qo(i)||i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);const e=Object.getPrototypeOf(i),t=e.constructor;if(i instanceof Date||i instanceof Map||i instanceof Set)return new t(i);if(i instanceof RegExp){const r=new t(i);return r.lastIndex=i.lastIndex,r}if(i instanceof DataView)return new t(i.buffer.slice(0));if(i instanceof Error){const r=new t(i.message);return r.stack=i.stack,r.name=i.name,r.cause=i.cause,r}if(typeof File<"u"&&i instanceof File)return new t([i],i.name,{type:i.type,lastModified:i.lastModified});if(typeof i=="object"){const r=Object.create(e);return Object.assign(r,i)}return i}function kh(i){return typeof i=="object"&&i!==null}function md(i){return Object.getOwnPropertySymbols(i).filter(e=>Object.prototype.propertyIsEnumerable.call(i,e))}
12function wd(i){return i==null?i===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(i)}const NS="[object RegExp]",bd="[object String]",vd="[object Number]",Ed="[object Boolean]",_d="[object Arguments]",TS="[object Symbol]",jS="[object Date]",BS="[object Map]",US="[object Set]",LS="[object Array]",kS="[object ArrayBuffer]",FS="[object Object]",qS="[object DataView]",MS="[object Uint8Array]",zS="[object Uint8ClampedArray]",HS="[object Uint16Array]",VS="[object Uint32Array]",KS="[object Int8Array]",WS="[object Int16Array]",GS="[object Int32Array]",YS="[object Float32Array]",JS="[object Float64Array]";function ZS(i,e){return ki(i,void 0,i,new Map,e)}function ki(i,e,t,r=new Map,s=void 0){const n=s?.(i,e,t,r);if(n!=null)return n;if(Fo(i))return i;if(r.has(i))return r.get(i);if(Array.isArray(i)){const o=new Array(i.length);r.set(i,o);for(let a=0;a<i.length;a++)o[a]=ki(i[a],a,t,r,s);return Object.hasOwn(i,"index")&&(o.index=i.index),Object.hasOwn(i,"input")&&(o.input=i.input),o}if(i instanceof Date)return new Date(i.getTime());if(i instanceof RegExp){const o=new RegExp(i.source,i.flags);return o.lastIndex=i.lastIndex,o}if(i instanceof Map){const o=new Map;r.set(i,o);for(const[a,c]of i)o.set(a,ki(c,a,t,r,s));return o}if(i instanceof Set){const o=new Set;r.set(i,o);for(const a of i)o.add(ki(a,void 0,t,r,s));return o}if(typeof ge<"u"&&ge.isBuffer(i))return i.subarray();if(qo(i)){const o=new(Object.getPrototypeOf(i)).constructor(i.length);r.set(i,o);for(let a=0;a<i.length;a++)o[a]=ki(i[a],a,t,r,s);return o}if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer)return i.slice(0);if(i instanceof DataView){const o=new DataView(i.buffer.slice(0),i.byteOffset,i.byteLength);return r.set(i,o),si(o,i,t,r,s),o}if(typeof File<"u"&&i instanceof File){const o=new File([i],i.name,{type:i.type});return r.set(i,o),si(o,i,t,r,s),o}if(i instanceof Blob){const o=new Blob([i],{type:i.type});return r.set(i,o),si(o,i,t,r,s),o}if(i instanceof Error){const o=new i.constructor;return r.set(i,o),o.message=i.message,o.name=i.name,o.stack=i.stack,o.cause=i.cause,si(o,i,t,r,s),o}if(typeof i=="object"&&QS(i)){const o=Object.create(Object.getPrototypeOf(i));return r.set(i,o),si(o,i,t,r,s),o}return i}function si(i,e,t=i,r,s){const n=[...Object.keys(e),...md(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(i,a);(c==null||c.writable)&&(i[a]=ki(e[a],a,t,r,s))}}function QS(i){switch(wd(i)){case _d:case LS:case kS:case qS:case Ed:case jS:case YS:case JS:case KS:case WS:case GS:case BS:case vd:case FS:case NS:case US:case bd:case TS:case MS:case zS:case HS:case VS:return!0;default:return!1}}function XS(i,e){return ZS(i,(t,r,s,n)=>{if(typeof i=="object")switch(Object.prototype.toString.call(i)){case vd:case bd:case Ed:{const o=new i.constructor(i?.valueOf());return si(o,i),o}case _d:{const o={};return si(o,i),o.length=i.length,o[Symbol.iterator]=i[Symbol.iterator],o}default:return}})}function Fh(i){return XS(i)}function qh(i){return i!==null&&typeof i=="object"&&wd(i)==="[object Arguments]"}function eD(i){return qo(i)}function tD(i){if(typeof i!="object"||i==null)return!1;if(Object.getPrototypeOf(i)===null)return!0;if(Object.prototype.toString.call(i)!=="[object Object]"){const t=i[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(i,Symbol.toStringTag)?.writable?!1:i.toString()===`[object ${t}]`}let e=i;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(i)===e}function iD(i,...e){const t=e.slice(0,-1),r=e[e.length-1];let s=i;for(let n=0;n<t.length;n++){const o=t[n];s=lo(s,o,r,new Map)}return s}function lo(i,e,t,r){if(Fo(i)&&(i=Object(i)),e==null||typeof e!="object")return i;if(r.has(e))return RS(r.get(e));if(r.set(e,i),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),...md(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=i[o];if(qh(a)&&(a={...a}),qh(c)&&(c={...c}),typeof ge<"u"&&ge.isBuffer(a)&&(a=Fh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],l=Reflect.ownKeys(c);for(let d=0;d<l.length;d++){const f=l[d];u[f]=c[f]}c=u}else c=[];const h=t(c,a,o,i,e,r);h!=null?i[o]=h:Array.isArray(a)||kh(c)&&kh(a)?i[o]=lo(c,a,t,r):c==null&&tD(a)?i[o]=lo({},a,t,r):c==null&&eD(a)?i[o]=Fh(a):(c===void 0||a!==void 0)&&(i[o]=a)}return i}function rD(i,...e){return iD(i,...e,CS)}var sD=Object.defineProperty,nD=Object.defineProperties,oD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,aD=Object.prototype.hasOwnProperty,cD=Object.prototype.propertyIsEnumerable,zh=(i,e,t)=>e in i?sD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xr=(i,e)=>{for(var t in e||(e={}))aD.call(e,t)&&zh(i,t,e[t]);if(Mh)for(var t of Mh(e))cD.call(e,t)&&zh(i,t,e[t]);return i},hD=(i,e)=>nD(i,oD(e));function Je(i,e,t){var r;const s=Fi(i);return((r=e.rpcMap)==null?void 0:r[s.reference])||`${yd}?chainId=${s.namespace}:${s.reference}&projectId=${t}`}function gi(i){return i.includes(":")?i.split(":")[1]:i}function Id(i){return i.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function uD(i,e){const t=Object.keys(e.namespaces).filter(s=>s.includes(i));if(!t.length)return[];const r=[];return t.forEach(s=>{const n=e.namespaces[s].accounts;
12r.push(...n)}),r}function es(i={},e={}){const t=Hh(i),r=Hh(e);return rD(t,r)}function Hh(i){var e,t,r,s,n;const o={};if(!Wt(i))return o;for(const[a,c]of Object.entries(i)){const h=Cs(a)?[a]:c.chains,u=c.methods||[],l=c.events||[],d=c.rpcMap||{},f=Li(a);o[f]=hD(Xr(Xr({},o[f]),c),{chains:It(h,(e=o[f])==null?void 0:e.chains),methods:It(u,(t=o[f])==null?void 0:t.methods),events:It(l,(r=o[f])==null?void 0:r.events)}),(Wt(d)||Wt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=Xr(Xr({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Vh(i){return i.includes(":")?i.split(":")[2]:i}function Kh(i){const e={};for(const[t,r]of Object.entries(i)){const s=r.methods||[],n=r.events||[],o=r.accounts||[],a=Cs(t)?[t]:r.chains?r.chains:Id(r.accounts);e[t]={chains:a,methods:s,events:n,accounts:o}}return e}function Sn(i){return typeof i=="number"?i:i.includes("0x")?parseInt(i,16):(i=i.includes(":")?i.split(":")[1]:i,isNaN(Number(i))?i:Number(i))}const $d={},X=i=>$d[i],Dn=(i,e)=>{$d[i]=e};var lD=Object.defineProperty,dD=(i,e,t)=>e in i?lD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,$i=(i,e,t)=>dD(i,typeof e!="symbol"?e+"":e,t);class pD{constructor(e){$i(this,"name","polkadot"),$i(this,"client"),$i(this,"httpProviders"),$i(this,"events"),$i(this,"namespace"),$i(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r;const s=gi(t);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var fD=Object.defineProperty,gD=Object.defineProperties,yD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,mD=Object.prototype.hasOwnProperty,wD=Object.prototype.propertyIsEnumerable,po=(i,e,t)=>e in i?fD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Gh=(i,e)=>{for(var t in e||(e={}))mD.call(e,t)&&po(i,t,e[t]);if(Wh)for(var t of Wh(e))wD.call(e,t)&&po(i,t,e[t]);return i},Yh=(i,e)=>gD(i,yD(e)),Si=(i,e,t)=>po(i,typeof e!="symbol"?e+"":e,t);class bD{constructor(e){Si(this,"name","eip155"),Si(this,"client"),Si(this,"chainId"),Si(this,"namespace"),Si(this,"httpProviders"),Si(this,"events"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r=t||Je(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}setHttpProvider(e,t){const r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(t=>{var r;const s=parseInt(gi(t));e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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,r;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:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var t,r,s,n,o;const a=(r=(t=e.request)==null?void 0:t.params)==null?void 0:r[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),l=((o=u?.sessionProperties)==null?void 0:o.capabilities)||{};if(l!=null&&l[h])return l?.[h];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Yh(Gh({},u.sessionProperties||{}),{capabilities:Yh(Gh({},l||{}),{[h]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var t,r;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=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,t){var r;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Vt("eth_getUserOperationReceipt",[(r=t.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}
12getBundlerUrl(e,t){return`${xS}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}}var vD=Object.defineProperty,ED=(i,e,t)=>e in i?vD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Di=(i,e,t)=>ED(i,typeof e!="symbol"?e+"":e,t);class _D{constructor(e){Di(this,"name","solana"),Di(this,"client"),Di(this,"httpProviders"),Di(this,"events"),Di(this,"namespace"),Di(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r;const s=gi(t);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var ID=Object.defineProperty,$D=(i,e,t)=>e in i?ID(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Oi=(i,e,t)=>$D(i,typeof e!="symbol"?e+"":e,t);class SD{constructor(e){Oi(this,"name","cosmos"),Oi(this,"client"),Oi(this,"httpProviders"),Oi(this,"events"),Oi(this,"namespace"),Oi(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r;const s=gi(t);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var DD=Object.defineProperty,OD=(i,e,t)=>e in i?DD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Pi=(i,e,t)=>OD(i,typeof e!="symbol"?e+"":e,t);class PD{constructor(e){Pi(this,"name","algorand"),Pi(this,"client"),Pi(this,"httpProviders"),Pi(this,"events"),Pi(this,"namespace"),Pi(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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 r=t||Je(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(ot.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 r;e[t]=this.createHttpProvider(t,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new nt(new ft(r,X("disableProviderPing")))}}var AD=Object.defineProperty,xD=(i,e,t)=>e in i?AD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ai=(i,e,t)=>xD(i,typeof e!="symbol"?e+"":e,t);class CD{constructor(e){Ai(this,"name","cip34"),Ai(this,"client"),Ai(this,"httpProviders"),Ai(this,"events"),Ai(this,"namespace"),Ai(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r=this.getCardanoRPCUrl(t),s=gi(t);e[s]=this.createHttpProvider(s,r)}),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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var RD=Object.defineProperty,ND=(i,e,t)=>e in i?RD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,xi=(i,e,t)=>ND(i,typeof e!="symbol"?e+"":e,t);class TD{constructor(e){xi(this,"name","elrond"),xi(this,"client"),xi(this,"httpProviders"),xi(this,"events"),xi(this,"namespace"),xi(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r;const s=gi(t);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var jD=Object.defineProperty,BD=(i,e,t)=>e in i?jD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ci=(i,e,t)=>BD(i,typeof e!="symbol"?e+"":e,t);class UD{constructor(e){Ci(this,"name","multiversx"),Ci(this,"client"),Ci(this,"httpProviders"),Ci(this,"events"),Ci(this,"namespace"),Ci(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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 r;const s=gi(t);e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var LD=Object.defineProperty,kD=(i,e,t)=>e in i?LD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ri=(i,e,t)=>kD(i,typeof e!="symbol"?e+"":e,t);class FD{constructor(e){Ri(this,"name","near"),Ri(this,"client"),Ri(this,"httpProviders"),Ri(this,"events"),Ri(this,"namespace"),Ri(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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 r=t||Je(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(ot.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 r;e[t]=this.createHttpProvider(t,(r=this.namespace.rpcMap)==null?void 0:r[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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace);return typeof r>"u"?void 0:new nt(new ft(r,X("disableProviderPing")))}}var qD=Object.defineProperty,MD=(i,e,t)=>e in i?qD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ni=(i,e,t)=>MD(i,typeof e!="symbol"?e+"":e,t);class zD{constructor(e){Ni(this,"name","tezos"),Ni(this,"client"),Ni(this,"httpProviders"),Ni(this,"events"),Ni(this,"namespace"),Ni(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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 r=t||Je(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(ot.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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace);return typeof r>"u"?void 0:new nt(new ft(r))}}var HD=Object.defineProperty,VD=(i,e,t)=>e in i?HD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ti=(i,e,t)=>VD(i,typeof e!="symbol"?e+"":e,t);class KD{constructor(e){Ti(this,"name",Bi),Ti(this,"client"),Ti(this,"httpProviders"),Ti(this,"events"),Ti(this,"namespace"),Ti(this,"chainId"),this.namespace=e.namespace,this.events=X("events"),this.client=X("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(ot.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.c
12hains[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 r={};return(t=(e=this.namespace)==null?void 0:e.accounts)==null||t.forEach(s=>{const n=Fi(s);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),r}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 r=this.createHttpProvider(e,t);r&&(this.httpProviders[e]=r)}createHttpProvider(e,t){const r=t||Je(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new nt(new ft(r,X("disableProviderPing")))}}var WD=Object.defineProperty,GD=Object.defineProperties,YD=Object.getOwnPropertyDescriptors,Jh=Object.getOwnPropertySymbols,JD=Object.prototype.hasOwnProperty,ZD=Object.prototype.propertyIsEnumerable,fo=(i,e,t)=>e in i?WD(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ts=(i,e)=>{for(var t in e||(e={}))JD.call(e,t)&&fo(i,t,e[t]);if(Jh)for(var t of Jh(e))ZD.call(e,t)&&fo(i,t,e[t]);return i},On=(i,e)=>GD(i,YD(e)),Xe=(i,e,t)=>fo(i,typeof e!="symbol"?e+"":e,t);let QD=class Sd{constructor(e){Xe(this,"client"),Xe(this,"namespaces"),Xe(this,"optionalNamespaces"),Xe(this,"sessionProperties"),Xe(this,"scopedProperties"),Xe(this,"events",new yo),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?.logger<"u"&&typeof e?.logger!="string"?e.logger:Lr(Rs({level:e?.logger||Lh})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const t=new Sd(e);return await t.initialize(),t}async request(e,t,r){const[s,n]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:ts({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,t,r,s){const n=new Date().getTime();this.request(e,r,s).then(o=>t(null,Ns(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:ie("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:r,response:s}=await this.client.authenticate(e,t);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await s();if(this.session=n.session,this.session){const o=Kh(this.session.namespaces);this.namespaces=es(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:r}=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 r();this.session=s;const n=Kh(s.namespaces);return this.namespaces=es(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[r,s]=this.validateChain(e),n=this.getProvider(r);n.name===Bi?n.setDefaultChain(`${r}:${s}`,t):n.setDefaultChain(s,t)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(pt(t)){for(const r of t)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${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 sS.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Lh,relayUrl:this.providerOpts.relayUrl||OS,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(t=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:t.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(t=>Li(t)))];Dn("client",this.client),Dn("events",this.events),Dn("disableProviderPing",this.disableProviderPing),e.forEach(t=>{if(!this.session)return;const r=uD(t,this.session),s=Id(r),n=es(this.namespaces,this.optionalNamespaces),o=On(ts({},n[t]),{accounts:r,chains:s});
12switch(t){case"eip155":this.rpcProviders[t]=new bD({namespace:o});break;case"algorand":this.rpcProviders[t]=new PD({namespace:o});break;case"solana":this.rpcProviders[t]=new _D({namespace:o});break;case"cosmos":this.rpcProviders[t]=new SD({namespace:o});break;case"polkadot":this.rpcProviders[t]=new pD({namespace:o});break;case"cip34":this.rpcProviders[t]=new CD({namespace:o});break;case"elrond":this.rpcProviders[t]=new TD({namespace:o});break;case"multiversx":this.rpcProviders[t]=new UD({namespace:o});break;case"near":this.rpcProviders[t]=new FD({namespace:o});break;case"tezos":this.rpcProviders[t]=new zD({namespace:o});break;default:this.rpcProviders[Bi]?this.rpcProviders[Bi].updateNamespace(o):this.rpcProviders[Bi]=new KD({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:r}=e;r===((t=this.session)==null?void 0:t.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var t;const{params:r,topic:s}=e;if(s!==((t=this.session)==null?void 0:t.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&pt(o)&&this.events.emit("accountsChanged",o.map(Vh))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Li(o),h=Sn(o)!==Sn(a)?`${c}:${Sn(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:t})=>{var r,s;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=t,o=(s=this.client)==null?void 0:s.session.get(e);this.session=On(ts({},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",On(ts({},ie("USER_DISCONNECTED")),{data:e.topic})))}),this.on(ot.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Bi]}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:r={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=es(t,r),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[t,r]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,r];if(t&&!Object.keys(this.namespaces||{}).map(o=>Li(o)).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&r)return[t,r];const s=Li(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[r,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(r,s),this.events.emit("chainChanged",s);const n=this.getProvider(r).getDefaultChain();t||this.getProvider(r).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:t,newChainId:r}){var s,n;try{if(t===r)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(Vh);if(!pt(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 r=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=t):this.namespaces[r]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){var r;const s=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${Qr}/${e}${s}`,t)}async getFromStore(e){var t;const r=((t=this.session)==null?void 0:t.topic)||"";return await this.client.core.storage.getItem(`${Qr}/${e}${r}`)}async deleteFromStore(e){var t;const r=((t=this.session)==null?void 0:t.topic)||"";await this.client.core.storage.removeItem(`${Qr}/${e}${r}`)}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 r of t)r.startsWith(Qr)&&await this.client.core.storage.removeItem(r)}catch(t){this.logger.warn("Failed to cleanup storage",t)}}};const XD=QD,eO="wc",tO="ethereum_provider",iO=`${eO}@2:${tO}:`,rO="https://rpc.walletconnect.org/v1/",bs=["eth_sendTransaction","personal_sign"],Dd=["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"],vs=["chainChanged","accountsChanged"],Od=["chainChanged","accountsChanged","message","disconnect","connect"],sO=async()=>{const{createAppKit:i}=await eu(()=>import("./core-CYyOml1y.js").then(e=>e.G),__vite__mapDeps([0,1,2,3]));return i};var nO=Object.defineProperty,oO=Object.defineProperties,aO=Object.getOwnPropertyDescriptors,Zh=Object.getOwnPropertySymbols,cO=Object.prototype.hasOwnProperty,hO=Object.prototype.propertyIsEnumerable,go=(i,e,t)=>e in i?nO(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,ei=(i,e)=>{for(var t in e||(e={}))cO.call(e,t)&&go(i,t,e[t]);if(Zh)for(var t of Zh(e))hO.call(e,t)&&go(i,t,e[t]);return i},dr=(i,e)=>oO(i,aO(e)),Ve=(i,e,t)=>go(i,typeof e!="symbol"?e+"":e,t);function Es(i){return Number(i[0].split(":")[1])}function is(i){return`0x${i.toString(16)}`}function uO(i){const{chains:e,optionalChains:t,methods:r,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=i;if(!pt(e))throw new Error("Invalid chains");const c={chains:e,methods:r||bs,events:n||vs,rpcMap:ei({},e.length?{[Es(e)]:a[Es(e)]}:{})},h=n?.filter(f=>!vs.includes(f)),u=r?.filter(f=>!bs.includes(f));if(!t&&!o&&!s&&!(h!=null&&h.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const l=h?.length&&u?.length||!t,d={chains:[...new Set(l?c.chains.concat(t||[]):t)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Dd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Od))],rpcMap:a};return{required:e.length?c:void 0,optional:t.length?d:void 0}}class Us{constructor(){Ve(this,"events",new st.EventEmitter),Ve(this,"namespace","eip155"),Ve(this,"accounts",[]),Ve(this,"signer"),Ve(this,"chainId",1),Ve(this,"modal"),Ve(this,"rpc"),Ve(this,"STORAGE_KEY",iO),Ve(this,"on",(e,t)=>(this.events.on(e,t),this)),Ve(this,"once",(e,t)=>(this.events.once(e,t),this)),Ve(this,"removeListener",(e,t)=>(this.events.removeListener(e,t),this)),Ve(this,"off",(e,t)=>(this.events.off(e,t),this)),Ve(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const t=new Us;return await t.initialize(e),t}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,r){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),r)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var t;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:s}=uO(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,u;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(u=this.modal)==null||u.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const l=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(dr(ei({namespaces:ei({},r&&{[this.namespace]:r})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e?.pairingTopic,scopedProperties:l})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Ma(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:is(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(t=this.modal)==null||t.close()}}async authenticate(e,t){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const s=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(dr(ei({},e),{chains:this.rpc.chains}),t).then(u=>{o(u)}).catch(u=>{var l;(l=this.modal)==null||l.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),n=s.session;if(n){const o=Ma(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:is(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(r=this.modal)==null||r.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:t}=e,{event:r}=t;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",is(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",dr(ei({},ie("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",is(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,r,s]=e.split(":");return{chainId:`${t}:${r}`,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,r;const s=(t=e?.chains)!=null?t:[],n=(r=e?.optionalChains)!=null?r:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?e?.methods||bs:[],c=s.length?e?.events||vs:[],h=e?.optionalMethods||[],u=e?.optionalEvents||[],l=e?.rpcMap||this.buildRpcMap(o,e.projectId),d=e?.qrModalOptions||void 0;return{chains:s?.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:h,optionalEvents:u,rpcMap:l,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const r={};return e.forEach(s=>{r[s]=this.getRpcUrl(s,t)}),r}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Es(this.rpc.chains):Es(this.rpc.optionalChains),this.signer=await XD.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 r=await sO(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return EO}),n=s(dr(ei({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");t=r(dr(ei({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(r){throw console.warn(r),new Error("To use QR modal, please install @reown/appkit package")}if(t)try{this.modal=t}catch(r){throw this.signer.logger.error(r),new Error("Could not generate WalletConnectMod
12al Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:r,rpcMap:s}=e;t&&pt(t)&&(this.rpc.chains=t.map(n=>this.formatChainId(n)),t.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)})),r&&pt(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r?.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=s?.[n]||this.getRpcUrl(n)}))}getRpcUrl(e,t){var r;return((r=this.rpc.rpcMap)==null?void 0:r[e])||`${rO}?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?.accounts),this.setAccounts(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 lO=Us;var dO=Object.defineProperty,pO=Object.defineProperties,fO=Object.getOwnPropertyDescriptors,Qh=Object.getOwnPropertySymbols,gO=Object.prototype.hasOwnProperty,yO=Object.prototype.propertyIsEnumerable,Xh=(i,e,t)=>e in i?dO(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Pd=(i,e)=>{for(var t in e||(e={}))gO.call(e,t)&&Xh(i,t,e[t]);if(Qh)for(var t of Qh(e))yO.call(e,t)&&Xh(i,t,e[t]);return i},mO=(i,e)=>pO(i,fO(e));function wO(i){if(i)return{"--w3m-font-family":i["--wcm-font-family"],"--w3m-accent":i["--wcm-accent-color"],"--w3m-color-mix":i["--wcm-background-color"],"--w3m-z-index":i["--wcm-z-index"]?Number(i["--wcm-z-index"]):void 0,"--w3m-qr-color":i["--wcm-accent-color"],"--w3m-font-size-master":i["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":i["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const bO=i=>{const[e,t]=i.split(":");return Ad({id:t,caipNetworkId:i,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function vO(i){var e,t,r,s,n,o,a;const c=(e=i.chains)==null?void 0:e.map(bO).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(l=>{var d;return l.id===((d=i.defaultChain)==null?void 0:d.id)}),u={projectId:i.projectId,networks:c,themeMode:i.themeMode,themeVariables:wO(i.themeVariables),chainImages:i.chainImages,connectorImages:i.walletImages,defaultNetwork:h,metadata:mO(Pd({},i.metadata),{name:((t=i.metadata)==null?void 0:t.name)||"WalletConnect",description:((r=i.metadata)==null?void 0:r.description)||"Connect to WalletConnect-compatible wallets",url:((s=i.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=i.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:i.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(i.explorerRecommendedWalletIds)?i.explorerRecommendedWalletIds:[],excludeWalletIds:i.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(i.explorerExcludedWalletIds)?i.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=i.mobileWallets)!=null&&o.length||(a=i.desktopWallets)!=null&&a.length){const l=[...(i.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(i.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],f=l.filter(p=>!d.includes(p.id));f.length&&(u.customWallets=f)}return u}function Ad(i){return Pd({formatters:void 0,fees:void 0,serializers:void 0},i)}var EO=Object.freeze({__proto__:null,convertWCMToAppKitOptions:vO,defineChain:Ad});const uP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:lO,OPTIONAL_EVENTS:Od,OPTIONAL_METHODS:Dd,REQUIRED_EVENTS:vs,REQUIRED_METHODS:bs,default:Us},Symbol.toStringTag,{value:"Module"}));
12export{GE as A,vt as B,fw as C,ft as D,Be as E,uP as F,di as I,Lr as O,ka as P,Vu as Q,U as a,Ut as b,Tp as c,Qd as d,gr as e,it as f,Vt as g,AE as h,sE as i,z1 as j,Rs as k,Bo as l,Ts as m,Ns as n,nt as o,mm as p,ys as q,pi as r,Ln as s,Me as t,Qn as u,oi as v,Hl as w,Et as x,ze as y,tt as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.